Event.observe(window, 'load', handlePageLoad);

function handlePageLoad() {
   showCorrectStates();
   if(typeof(areAddressLinesToBeEnabled)!="undefined")
   {
		enableAddressLines(isAddressToBeEnabledOnLoad()); 
   }
   hideOrShowPostCodeLookup(getCountryDropDown().getValue());
}

function isAddressToBeEnabledOnLoad() {
    var isAddressToBeEnabledOnLoad = areAddressLinesToBeEnabled.pop();
    if(isAddressToBeEnabledOnLoad == "True") {
        return true; 
    } else if(isAddressToBeEnabledOnLoad == "False") {
        return false;
    }
	var countryListDropDown = getCountryDropDown();
	return !isPostCodeSupported(countryListDropDown.getValue());
}

function getCountryDropDown() {
    var selectElements = $$('select');
	return getElementWithIdLike(selectElements,addressCountryList[0]);
}

function showCorrectStates() {
    var selectElements = $$('select');
	var stateListDropDown = getElementWithIdLike(selectElements,addressStateList[0]);
	if(stateListDropDown.visible()) {
	    var selectedState = stateListDropDown.getValue();
	    var country = getElementWithIdLike(selectElements, addressCountryList[0]).getValue();
	    populateStatesForCountry(country);
	    stateListDropDown.setValue(selectedState);
	}
}

function handleCountryChange(country) {
    enableOrDisableAddressLines(country);
    hideOrShowStateAndCity(country);
    hideOrShowPostCodeLookup(country);
}

function enableOrDisableAddressLines(country) {
	var shouldAddressLinesBeEnabled = true;
	for(var i=0; i< postcodeSupportingCountries.length; i++) {
		if(postcodeSupportingCountries[i] == country) {
			shouldAddressLinesBeEnabled = false;
			break;
		}
	}
	enableAddressLines(shouldAddressLinesBeEnabled);
}

function hideOrShowStateAndCity(country) {
	var shouldCityStateBeVisible = false;
	for(var i=0; i< countriesHavingStates.length; i++) {
		if(countriesHavingStates[i] == country) {
			shouldCityStateBeVisible = true;
			break;
		}
	}
	showCityAndStateAndHideAddressLine5(shouldCityStateBeVisible, country);
}

function enableAddressLines(shouldAddressLinesBeEnabled) {
	var inputElements = $$('input');

	if (!(typeof(isPostCodeSearchMandatory)=="undefined" || isPostCodeSearchMandatory[0] == 'True')) {
	    shouldAddressLinesBeEnabled = true;
	}
	/* Deciding whether we need to enable or disable the address lines. */
	var methodToCall = "disable";
	if(shouldAddressLinesBeEnabled) {
	    methodToCall = "enable";
	}
	invokeDesiredMethodonElements(inputElements, methodToCall, addressFieldsIds);
}

function showCityAndStateAndHideAddressLine5(shouldCityStateBeVisible, country) {
    var imgElements = $$('img');
    var spanElements = $$('span');
    var labelElements = $$('label');
    var selectElements = $$('select');
    var inputElements = $$('input');
    
    var methodToCall = "hide";
    var reverseMethodToCall = "show";
	if(shouldCityStateBeVisible) {
	    methodToCall = "show";
	    reverseMethodToCall = "hide";
	    populateStatesForCountry(country);
	} 
	invokeDesiredMethodonElements(imgElements, methodToCall, cityStateElementIds);       
	invokeDesiredMethodonElements(spanElements, methodToCall, cityStateElementIds);       
	invokeDesiredMethodonElements(labelElements, methodToCall, cityStateElementIds);       
	invokeDesiredMethodonElements(selectElements, methodToCall, cityStateElementIds);
	invokeDesiredMethodonElements(inputElements, reverseMethodToCall, addressElementIdsToHideWhenCityStateIsShown);
	invokeDesiredMethodonElements(labelElements, reverseMethodToCall, addressElementIdsToHideWhenCityStateIsShown);
}

function invokeDesiredMethodonElements(elements, methodToCall, idArray) {
	for(var i=0; i<idArray.length; i++) {
	    var inputElement = getElementWithIdLike(elements, idArray[i]);
	    if(inputElement) {
	        inputElement[methodToCall]();
	    }
    }
}

function invokeDesiredMethodonElementsUsingClientId(elements, methodToCall, id) {
    for(var i=0; i<elements.length; i++) {
        if(getElementClientID(elements[i].id) == getElementClientID(id)) {
            elements[i][methodToCall]();
        }
    }
}

function getElementWithIdLike(elements, idLike) {
	for(var i=0; i< elements.length; i++) {
        if(elements[i].id.indexOf(idLike) >= 0) {
            return elements[i];
        }
	}
}

function populateStatesForCountry(country) {
    var stateSelectElement = getElementWithIdLike($$('select'), addressStateList[0]);
    stateSelectElement.length = 0;
    stateSelectElement.clear();
    stateSelectElement.options.add(new Option("Please Select", ""));
    var statesForCountry = countriesStateHash[country];
    for(var i=0; i < statesForCountry.length; i++) {
        stateSelectElement.options.add(new Option(statesForCountry[i], statesForCountry[i]));
    }
}

function isPostCodeSupported(country) {
    var isPostCodeSupportedCountry = false;
	for(var i=0; i< postcodeSupportingCountries.length; i++) {
		if(postcodeSupportingCountries[i] == country) {
			isPostCodeSupportedCountry = true;
			break;
		}
	} 
	return isPostCodeSupportedCountry;  
}

function hideOrShowPostCodeLookup(country)
{
    var isPostCodeSupportedCountry = isPostCodeSupported(country);
    var methodToInvoke = "hide";
    var reverseMethodToInvoke = "show";
    if(isPostCodeSupportedCountry) {
        methodToInvoke = "show";
        reverseMethodToInvoke = "hide";
    }
    var inputElements = $$('input');
	var labelElements = $$('label');	 
	var idsOfInputElementsToHide = new Array(postCodeFieldIds[0], postCodeFieldIds[1]);
    invokeDesiredMethodonElements(inputElements, methodToInvoke, idsOfInputElementsToHide);
    invokeDesiredMethodonElementsUsingClientId(labelElements, methodToInvoke, postCodeFieldIds[2]);
    invokeDesiredMethodonElementsUsingClientId(labelElements, reverseMethodToInvoke, postCodeFieldIds[3]);    

    //Special handling for portals that have parent span to which style is applied.  For e.g. TheTrainline   
    hideTheParentSpans(inputElements, methodToInvoke, idsOfInputElementsToHide);    
}

function hideTheParentSpans(inputElements, methodToInvoke, idsOfInputElementsToHide) {

    for(var i=0;i<idsOfInputElementsToHide.length; i++) {
        var imageElement = getElementWithIdLike(inputElements, idsOfInputElementsToHide[i]);
        if(imageElement != null) {
            var imageParent = imageElement.parentNode;
            if (imageParent != null && imageParent.tagName == "SPAN") {
                imageParent = $(imageParent);
                imageParent[methodToInvoke]();
            }
        }
    }
}

function getElementClientID(elementID)
{
    if (elementID == "")
        return "";    
    var elements = elementID.split("_");
    return elements[elements.length - 1];
}

function lookupAddressOnEnterKeyPressed(e,elem){
		//Hack method find another way to do post code lookup
		var keynum;
		if(window.event) {
			keynum = e.keyCode;
		} else if(e.which){
			keynum = e.which;
		}
		if(keynum == 13){
			var button = $(elem).next();	
			if(isPostCodeSupported(getCountryDropDown().getValue())) button.click();
			return false;
		}
		return true;
}
