/**
* Browser check
*/
var ie4 = (document.all) ? true : false;
var validBrowser = (document.getElementById) ? true : false;
var formSubmitted = false;

/**
* Visar ett div lager.
*/
function showLayer(layerName)
{
	if (document.getElementById(layerName))
	{
		document.getElementById(layerName).style.display = "block";
	}
}

//

function hideLayer(layerName)
{
	if (document.getElementById(layerName))
	{
		document.getElementById(layerName).style.display = "none";
	}
}

//

function isLayerVisible(layerName)
{
	if (document.getElementById(layerName).style.display == "block")
		return true;
	else
		return false;
}

function updateDropDown()
{
	var objValue = document.getElementById("countrylist").value;
	var countrycodeValue = document.getElementById("countrycode").value;

	arrcountry=objValue.split(';');
	arrcountrycode=countrycodeValue.split(';');

	var stationlistValue = document.getElementById("stationlist").value;
	var stationcodeValue = document.getElementById("stationcode").value;

	arrstation=stationlistValue.split(';');
	arrstationcode=stationcodeValue.split(';');



	for(x=0;x<arrcountry.length;x++)
		{
			var w = arrcountry[x];

			if(x==0)
			{
				document.getElementById('pickup-country').options[x] = new Option(arrcountry[x], arrcountrycode[x], true, false);
			}
			else
			{
				document.getElementById('pickup-country').options[x] = new Option(arrcountry[x], arrcountrycode[x], false, false);
			}

		}




	for(x=0;x<arrstation.length;x++)
		{
			var w = arrstation[x];

			if(x==0)
			{
				document.getElementById('pickup-station').options[x] = new Option(arrstation[x], arrstationcode[x], true, false);
			}
			else
			{
				document.getElementById('pickup-station').options[x] = new Option(arrstation[x], arrstationcode[x], false, false);
			}

		}
}

/**
* Används vid post i componenter for att visa progressbar.
*/
function submitWithProgress()
{
	self.scrollTo(0, 0);
	showLayer("progress");
	return true;
}

/**
* Shows the progress bar when loading on the Confirm page. Also disables the Book- and Back-button
*/
function submitWithProgressConfirm()
{
	hideInputs('hide-on-nav');
	self.scrollTo(0, 0);
	showLayer("progress");
	return true;
}

function hideInputs(className)
{
	var allInputTags = document.getElementsByTagName("input");

	for (i = 0; i < allInputTags.length; i++)
	{
		if (allInputTags[i].className == className)
		{
			allInputTags[i].style.display = 'none';
		}
	}
}

/***
 * This function should only be called from rentalcar.com on step 1.
 * This is to make sure that we have actually selected something in the word wheel.
 */
function submitFormStep1(formId_)
{
	topItem = document.getElementById('autocomplete_item_0');
	if(topItem != null && topItem.className == 'autocomplete_item_highlighted')
	{
		FO_SetValueToHiddenInput(topItem.innerHTML);
	}
	submitForm(formId_);
}

function submitForm(formId_)
{
	form = document.getElementById(formId_);
	form.submit();
}

function showLoader(loaderHTML_)
{
	loaderHTML = loaderHTML_.replace(/DELIMIT/g, '"');
	progressDiv = document.getElementById('progress');
	progressDiv.innerHTML = loaderHTML;
	progressDiv.style.display = 'block';
}

/**
* Används tillsammans med writeJSToggleButton i GlobalJs.
*/
function toggleDiv(divId, showButtonHtml, hideButtonHtml, firstTime)
{
	if (validBrowser)
	{
		if (isLayerVisible("firstDiv"+divId) || firstTime)
		{
			newHTML = '&nbsp;<a href="javascript:toggleDiv(\''+divId+'\', \''+showButtonHtml+'\', \''+hideButtonHtml+'\', false)">'+showButtonHtml+'</a>';

			hideLayer("firstDiv"+divId);
			showLayer("secondDiv"+divId);
		}
		else
		{
			newHTML = '&nbsp;<a href="javascript:toggleDiv(\''+divId+'\', \''+showButtonHtml+'\', \''+hideButtonHtml+'\', false)">'+hideButtonHtml+'</a>';

			showLayer("firstDiv"+divId);
			hideLayer("secondDiv"+divId);
		}
		document.getElementById("buttonDiv"+divId).innerHTML = newHTML;
	}
}

function toggleDivButton(divId, showButtonHtml, hideButtonHtml, firstTime)
{
	if (validBrowser)
	{
		if (firstTime)
		{
			newHTML = '&nbsp;<a href="javascript:toggleDiv(\''+divId+'\', \''+showButtonHtml+'\', \''+hideButtonHtml+'\', false)">'+showButtonHtml+'</a>';
		}
		else
		{
			newHTML = '&nbsp;<a href="javascript:toggleDiv(\''+divId+'\', \''+showButtonHtml+'\', \''+hideButtonHtml+'\', false)">'+hideButtonHtml+'</a>';
		}
		document.getElementById("buttonDiv"+divId).innerHTML = newHTML;
	}
}


/**
* Aktiverar print kommandot som finns under file->print.
*/
function printPage()
{
	if (window.print)
		window.print()
	else
		alert("Din webbläsare stöder inte det här kommandot.");
}

/**
* Sätter focus på första redigerbara controllen på webbsidan.
*/
function setElementFocus()
{
	if (document.forms.length > 0)
	{
		var field;

		if (typeof(document.standard) != 'undefined')
			field = document.standard;
		else
			field = document.forms[0];

		for (i = 0; i < field.length; i++)
		{
			if ((field.elements[i].type == "select-one") || (field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type == "checkbox"))
			{
				field.elements[i].focus();
				break;
			}
		}
	}
}

/**
*	Används för att via en anchor kunna göra en post istället för en get.
*
*	Example:
* <code>
* 	<a href="javascript:doPostOnLink(\''.$queryStr.'\', \'\');">
*	</code>
*/
function doPostOnLink(query, target)
{
	var postTarget, postAction, postMethod;

	postTarget = document.forms[0].target;
	postAction = document.forms[0].action;
	postMethod = document.forms[0].method;

	if (query != '')
		document.forms[0].action = postAction+"?"+query;

	if (target != '')
		document.forms[0].target = target;

	document.forms[0].method = 'post';
	document.forms[0].submit();

	document.forms[0].target = postTarget;
	document.forms[0].action = postAction;
	document.forms[0].method = postMethod;
}

/**
* Används för att "disabla" en redigerbar kontroll. Det är inte en riktig
* disable, utan den bara ändrar färg på controllen, så att det ser ut som
* att den inte går att använda.
*/
function setElementEnabled(element, state)
{
	var bcolor;
	var fcolor;

	if (state == "false")
	{
		bcolor='#CCCCCC';
		fcolor='#AAAAAA';
	}
	else
	{
		bcolor='#FFFFFF';
		fcolor='#000000';
	}

	element.style.backgroundColor=bcolor;
	element.style.color=fcolor;
}

/**
* Sätter focus på en controll med ett visst id.
*/
function setIdFocus(id)
{
	document.getElementById(id).focus();
}

/**
* Scrollar till översta postionen på sidan.
*/
function scrollToTop()
{
	self.scrollTo(0, 0);
}

/**
* Handler för click på dateNav
*/
function dateOutboundNavClick(clickedDate)
{
	document.getElementById('date_outbound_nav_clicked_value').value = clickedDate;
	document.forms[0].onSubmit = submitWithProgress();
	document.forms[0].submit();
}

/**
* Handler för click på dateNav
*/
function dateInboundNavClick(clickedDate)
{
	document.getElementById('date_inbound_nav_clicked_value').value = clickedDate;
	document.forms[0].onSubmit = submitWithProgress();
	document.forms[0].submit();
}


/*
* Functions for displaying the correct Credit Card input fields depending on the selected credit card
****/

function toggleExtraCreditCardFields()
{
	list = document.getElementById('card_type_list');
	selectedCreditCard = list.options[list.selectedIndex].value;

	if (selectedCreditCard == 'maestro' || selectedCreditCard == 'solo')
	{
		updateCreditCardInputFields(false);
	}
	else
	{
		//'VISA/MASTERCARD/AMEX';
		updateCreditCardInputFields(true);
	}

}

function updateCreditCardInputFields(disabled)
{
	fields = ['issue_number_field', 'start_month_field', 'start_year_field']

	for (var i in fields)
	{
		var el = document.getElementById(fields[i]);
		if (el != null)
		{
			el.disabled = disabled;
		}
	}
}

/**
 * Copy credit card function for Step 3
 */

function copyAddresses()
{
  document.getElementById('paymentFirstName').value = document.getElementById('firstName').value;
  document.getElementById('paymentLastName').value = document.getElementById('lastName').value;
  document.getElementById('paymentAddress').value = document.getElementById('address').value;
  document.getElementById('paymentZipCode').value = document.getElementById('zip_code').value;
  document.getElementById('paymentCountry').value = document.getElementById('country').value;
}

/**
 * This Section contains input validation for the booking engines across the sites.
 */

/**
 * Global variables for input validation
 */
var validationOk;

var monthStringToIntMap = {"jan": 0, "feb": 1, "mar": 2, "apr": 3, "may": 4, "jun": 5, "jul": 6, "aug": 7, "sep": 8, "oct": 9, "nov": 10, "dec": 11};
var hardMsgs = {"must-agree": "Text needs to be confirmed","invalid-email": "E-mail is invalid","required" : "This field is required", "date-reset" : "Date selected is not valid, we have reset the date for your convenience"}

/**
 * Start of validation functions.
 */

function validateStep1(e)
{
    //Remove any existing error messages
    clearErrors();

		var errorBox = $('.message-error');
		errorBox.hide();
		errorBox.html('');

    validationOk = true;

    //Validate all required fields
    var pickupCountry = document.getElementById('pickup-country');
    var pickupStation = document.getElementById('pickup-station');
    var dropoffCountry = document.getElementById('dropoff-country');
    var dropoffStation = document.getElementById('dropoff-station');

		validateEmeraldClubFields(e);

    validateElementStep1(pickupCountry, ['0'], e);
    validateElementStep1(pickupStation, ['0'], e);
    validateElementStep1(dropoffCountry, ['0'], e);
    validateElementStep1(dropoffStation, ['0'], e);

    validateGenericRequiredFields(e);

    return validationOk;
}

function validateElementStep1(element, disallowedValues, e)
{
    for (var i = 0; i < disallowedValues.length; i++)
    {
        if (element.value == disallowedValues[i])
        {
            showRequiredTextDefaultStep1(element);
            failValidation(e);
            break;
        }
        else if (element.type != null && element.type.toLowerCase() == 'checkbox' && element.checked == disallowedValues[i])
        {
            showRequiredTextDefaultStep1(element);
            failValidation(e);
            break;
        }
    }
}

function showRequiredTextDefaultStep1(element, errorText)
{
    var li = document.createElement('li');
		if (errorText == null)
    {
        li.innerHTML = getText('required');
    }
    else
    {
        li.innerHTML = errorText;
    }

    var ul = document.createElement('ul');
    ul.appendChild(li)


    var errDiv = document.createElement('span');
    errDiv.setAttribute('className', 'message-error') || errDiv.setAttribute('class', 'message-error');
		errDiv.appendChild(ul);

    element.parentNode.parentNode.appendChild(errDiv);
}

function validateEmeraldClubFields(e)
{
	var emeraldCheckbox = $('#emerald-boolean');
	if (emeraldCheckbox != null && emeraldCheckbox.is(':checked'))
	{
		var errors = new Array();
		if ($('#emerald-number').val() == "")
		{
			errors.push("Emerald club number field is empty.");
		}

		if ($('#emerald-name').val() == "")
		{
			errors.push("First name field is empty.");
		}

		if ($('#emerald-surname').val() == "")
		{
			errors.push("Last name field is empty.");
		}

		if (errors.length > 0)
		{
			var ul = document.createElement('ul');

			for (var i = 0; i < errors.length; i++)
			{
				var li = document.createElement('li');
				li.innerHTML = errors[i];
				ul.appendChild(li)
			}

			var errDiv = document.createElement('span');
			errDiv.setAttribute('className', 'message-error') || errDiv.setAttribute('class', 'message-error');
			errDiv.appendChild(ul);

			document.getElementById('emerald-content').appendChild(errDiv);

			failValidation(e);
		}
	}
}

function validateStep3(e)
{
    //Remove any existing error messages
    clearErrors();

    validationOk = true;

    //Validate all required fields
    validateTermsAndConditions();
    validateEmail(e);
    validateCCExpiration(e);
    validateGenericRequiredFields(e);



    return validationOk;
}

function clearErrors()
{
    var errorContainers = document.getElementsByName('js-val-container');

    var i = 0;
    while (errorContainers.length > 0)
    {
        var errCont = errorContainers[0];
        var parent = errCont.parentNode;
        parent.removeChild(errCont);
        i++;
    }

}

function validateElement(element, disallowedValues, e)
{
    for (var i = 0; i < disallowedValues.length; i++)
    {
        if (element.value == disallowedValues[i])
        {
            showRequiredText(element);
            failValidation(e);
            break;
        }
        else if (element.type != null && element.type.toLowerCase() == 'checkbox' && element.checked == disallowedValues[i])
        {
            showRequiredText(element);
            failValidation(e);
            break;
        }
    }
}

function showRequiredText(element, errorText)
{
    //If is checkbox and description in seperate column
    if (element.parentNode.className.indexOf('no-message-allowed') >= 0)
    {
        showRequiredTextInMarkedColumn(element, errorText);
    }
    else
    {
        showRequiredTextDefault(element, errorText);
    }


}

function showRequiredTextInMarkedColumn(element, errorText)
{
    //Find tr
    var currEl = element;

    while (currEl.tagName != null && currEl.tagName.toLowerCase() != "tr")
    {
        currEl = currEl.parentNode;
        if (currEl == null)
        {
            return;
        }
    }

    //Use td marked as "message-holder"
    var children = currEl.childNodes;
    for (i = 0; i < children.length; i++)
    {
        if (children[i].className.indexOf("message-holder") >= 0)
        {
            showRequiredTextDefault(children[i].firstChild);
            break;
        }
    }
}

function showRequiredTextDefault(element, errorText)
{
    var errDiv = document.createElement('div');
    errDiv.setAttribute('className', 'cssError') || errDiv.setAttribute('class', 'cssError');
    if (errorText == null)
    {
        errDiv.innerHTML = getText('required');
    }
    else
    {
        errDiv.innerHTML = errorText;
    }

    var li = document.createElement('li');
    li.appendChild(errDiv);

    var ul = document.createElement('ul');
    ul.setAttribute('style', 'margin-top : 5px; margin-left: 16px; margin-bottom: 5px;');
    ul.setAttribute('name', 'js-val-container');
    ul.setAttribute('className', 'js-val-container') || ul.setAttribute('class', 'js-val-container');
    ul.appendChild(li)

    element.parentNode.appendChild(ul);
}

function getText(type)
{

    var value;
    //Try getting localized texts as printed by the system to the localizedMsgs array

    if (localizedMsgs != null)
    {
        value = localizedMsgs[type];
    }

    //Else fall back to hardcoded english language values
    if (value == null)
    {
        value = hardMsgs[type];
    }

    return value;
}

function validateGenericRequiredFields(e)
{
    var allSpans = document.getElementsByTagName('span');

    for (var i = 0; i < allSpans.length; i++)
    {
        if (allSpans[i].className == null || allSpans[i].className != 'cssLabelRequired')
        {
            //This span is not of interest, go to next
            continue;
        }

        //else
        //Find out which column we are currently in
        var column = calculateNearestColumn(allSpans[i]);

        //The input box is always (hopefully) on the next row, so get that
        var element = getInputElement(allSpans[i], column);

        if (element == null)
        {
            //Silent fail
        }
        else if (element.tagName.toLowerCase() == 'select')
        {
            validateElement(element, ['', '0'], e);
        }
        else if (element.type.toLowerCase() == 'text')
        {
            validateElement(element, ['', ' '], e);
        }
        else if (element.type.toLowerCase() == 'checkbox')
        {
            validateElement(element, [false], e);
        }
        else
        {
            //Silent fail 2
        }
    }
}

function validateTermsAndConditions(e)
{
    var allInputs = document.getElementsByTagName('input');

    for (var i = 0; i < allInputs.length; i++)
    {
        if (allInputs[i].name == 'formCriterion[information_to_confirm]' &&
            allInputs[i].type.toLowerCase() == 'checkbox')
        {
            if (!allInputs[i].checked)
            {
                showRequiredText(allInputs[i], getText('must-agree'));
                failValidation(e);
            }
        }
    }
}

/**
 * Calculates which column the current element is in for the nearest
 * table in the hierarchy.
 */
function calculateNearestColumn(element)
{
    var tdEl = element;
    while (tdEl.tagName.toLowerCase() != 'td')
    {

        tdEl = tdEl.parentNode;
        if (tdEl == null)
        {
            return 0; //Fallback
        }
    }

    //Find out which child this element is
    var children = tdEl.parentNode.childNodes;
    for (var i = 0; i < children.length; i++)
    {
        if (children[i] == tdEl)
        {
            return i;
        }
    }

    return -1; //An error ocurred
}

function getInputElement(span, column)
{
    //Most elements on next row, get those first
    var element = getInputElementFromNextRow(span, column);

    if (element != null)
    {
        return element;
    }

    //if getting input from next row failed, try first column
    //Search until we get the first tr.
    var trEl = span;
    while (trEl.tagName.toLowerCase() != 'tr')
    {
        trEl = trEl.parentNode;
        if (trEl == null)
        {
            return null; //Fallback
        }
    }

    //Check if second child is a checkbox
    var tdEl = trEl.getElementsByTagName('td')[0];
    if (tdEl.childNodes[1].type.toLowerCase() == 'checkbox')
    {
        return tdEl.childNodes[1];
    }

    return null;

}

function getInputElementFromNextRow(element, column)
{
    //Search until we get the first tr.
    var trEl = element;
    while (trEl.tagName.toLowerCase() != 'tr')
    {
        trEl = trEl.parentNode;
        if (trEl == null)
        {
            return null; //Fallback
        }
    }

    //Get next tr.
    //Find out which child this element is
    var children = trEl.parentNode.childNodes;
    var nextTr;
    for (var i = 0; i < children.length; i++)
    {
        if (children[i] == trEl)
        {
            nextTr =  children[i + 1];
        }
    }

    if (nextTr == null)
    {
        return null;
    }

    //Get specified column on row
    var tdEl = nextTr.children[column];
    if (tdEl == null)
    {
        return null;
    }
    var input = tdEl.firstChild;
    while (input.tagName.toLowerCase() != 'input' &&
           input.tagName.toLowerCase() != 'select')
    {
        input = input.firstChild;
    }

    //First child should be input
    return input;

}

function fixDateSelection() {

    var pickupDay = document.getElementById('pickup-day');
    var pickupMonth = document.getElementById('pickup-month');
    var dropoffDay = document.getElementById('dropoff-day');
    var dropoffMonth = document.getElementById('dropoff-month');

    //Validate pickup
    var pDay = parseInt(pickupDay.value);
    var pMonth = getMonthAsInt(pickupMonth.value);

    var pDim = daysInMonth(pMonth);
    if (pDay > pDim) {
        pickupDay.value = '' + pDim;
        alert(getText('date-reset'));
    }

    //Validate dropoff
    var dDay = parseInt(dropoffDay.value);
    var dMonth = getMonthAsInt(dropoffMonth.value);

    var dDim = daysInMonth(dMonth);
    if (dDay > dDim) {
        dropoffDay.value = '' + dDim;
        alert(getText('date-reset'));
    }

}

function getMonthAsInt(dateStr)
{
    if (dateStr.length != 7)
    {
        //Unexpected month format, ignore
        return null;
    }

    //Only keep first 3 chars which is the month representation
    var monthStr = dateStr.substr(0, 3);

    return monthStringToIntMap[monthStr];
}

function validateEmail(e)
{
    var emailEl = document.getElementById('email');

    //clear existing error
    if (emailEl.parentNode.childNodes.length > 1)
    {
        var children = emailEl.parentNode.childNodes;

        for (var i = 0; i < children.length; i++)
        {
            if (children[i].className == 'js-val-container')
            {
                emailEl.parentNode.removeChild(children[i]);
            }
        }

    }

    if (emailEl.value != '')
    {
        if(!isValidEmail(emailEl.value))
        {
            showRequiredText(emailEl, getText('invalid-email'));
            failValidation(e);
            return;
        }
    }
}

function validateCCExpiration(e)
{
    var month = document.getElementsByName('formCriterion[payment][creditCardInformation][expire_month]')[0];
    var monthAsInt = parseInt(month.value, 10) - 1; //Months are base 0 in js & need radix when starts with 0
    var year = document.getElementsByName('formCriterion[payment][creditCardInformation][expire_year]')[0];
    var yearAsInt = parseInt(year.value);

    //clear existing error
    if (month.parentNode.childNodes.length > 2)
    {
        var children = month.parentNode.childNodes;

        for (var i = 0; i < children.length; i++)
        {
            if (children[i].className == 'js-val-container')
            {
                month.parentNode.removeChild(children[i]);
            }
        }
    }

    var d = new Date();
    if (
            yearAsInt < d.getFullYear() ||
            (
                yearAsInt == d.getFullYear() &&
                monthAsInt < d.getMonth()
            )
       )
   {
        showRequiredText(month, 'Expiry date in the past');
        failValidation(e);
   }

}

function failValidation(e)
{
	if (e != null && e.preventDefault)
	{
		e.preventDefault();
	}

    validationOk = false;
}

function attachEvents()
{

    //Determine which step we are on

    var stepEl = document.getElementById('portalsearchcar_alamo_dialog');

    var component = null;
    if (stepEl != null)
    {
        component = stepEl.value;
    }

    if (component == 'pscCriterionComponent')
    {
        //Step 1
        var searchButtons = document.getElementsByName('formButton[psccriterioncomponent][Search]');

        for (var i = 0; i < searchButtons.length; i++)
        {
        	addEventHandler(searchButtons[i], 'click', validateStep1);
        }

        var pickupDay = document.getElementById('pickup-day');
        var pickupMonth = document.getElementById('pickup-month');
        var dropoffDay = document.getElementById('dropoff-day');
        var dropoffMonth = document.getElementById('dropoff-month');

        addEventHandler(pickupDay, 'change', fixDateSelection);
        addEventHandler(pickupMonth, 'change', fixDateSelection);
        addEventHandler(dropoffDay, 'change', fixDateSelection);
        addEventHandler(dropoffMonth, 'change', fixDateSelection);

    }

    if (component == 'pscPassengersComponent')
    {
        //Step 3
        var buttons = document.getElementsByName('formButton[pscpassengerscomponent][Next]');

        for (i = 0; i < buttons.length; i++)
        {
        	addEventHandler(buttons[i], 'click', validateStep3);
        }

        var emailEl = document.getElementById('email');
        addEventHandler(emailEl, 'change', validateEmail);

        var months = document.getElementsByName('formCriterion[payment][creditCardInformation][expire_month]');

        for (i = 0; i < months.length; i++)
        {
            addEventHandler(months[i], 'change', validateCCExpiration);
        }

        var years = document.getElementsByName('formCriterion[payment][creditCardInformation][expire_year]');

        for (i = 0; i < years.length; i++)
        {
        	addEventHandler(years[i], 'change', validateCCExpiration);
        }

    }

}

//Add onload event that attaches events
addEventHandler(window, 'load', attachEvents);

/**
 * Utilities
 */

function addEventHandler(target, eventName, handlerName)
{
    if ( target.addEventListener )
	{
		target.addEventListener(eventName, handlerName, false);
	}
    else if ( target.attachEvent )
	{
    	target.attachEvent("on" + eventName, handlerName);
	}
    else
	{
    	target["on" + eventName] = handlerName;
	}
}

function daysInMonth(month)
{
    //Determine year
    var d = new Date();
    var currMonth = d.getMonth();

    var year = 2011;
    if (month < currMonth)
    {
        year++;
    }

	return 32 - new Date(year, month, 32).getDate();
}

function isValidEmail(email)
{
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(email);
}


