var rcs = temprcs;            // Rate Calculators
var vrcs = tempvrcs;          // Valid Rate Calculators
var rcsups = temprcsups;      // Rate Calculators to suppliers
var rcdts = temprcdts;        // Rate Calculators to pickup dates
var plsups = tempplsups;      // Pickup Locations to Suppliers
var dlsups = tempdlsups;      // Drop off Locations to Suppliers
var supsages = tempsupsages;  // Suppliers minimum drivers ages
var coo = tempcoo;            // Countries of origin - not sure if needed!!
var rcc = temprcc;            // Rate Calculator allowed Countries
var supsc = tempsupsc;        // Suppliers to countries allowed into
var locs = templocs;          // List of Location id's and their names
var cos = tempcos;            // List of Country id's and their names
var maxAge = tempmaxAge;      // max age allowed
var minAge = tempminAge;      // min age allowed

var locspro = templocspro;    // locations ids to province ids
var provs = tempprovs;        // List of province and country names

var selectedPickupLocation = -1;
var selectedDropOffDay = -1;
var selectedDropOffMonth = -1;
var selectedDropOffYear = -1;
var selectedDropOffHour = -1;
var selectedDropOffLocation = -1;
//var selectedDobDay = -1;
//var selectedDobMonth = -1;
//var selectedDobYear = -1;
var selectedAgeGroup = -1;
var selectedCountryOfOrigin = -1;
var selectedCountriesIntoArray = new Array();
var millisecondsInAYear = 1000*60*60*24*365.242199;

function setup()
{
    disable("pickupLocation");
    //disableOrEnableAnchor("dropoffCalendarAnchor", true);
    
    disable("dropOffHour");
    disable("dropOffLocation");
    //disableOrEnableAnchor("dobCalendarAnchor", true);
    
    disable("countryOfOrigin");
    //disable("countriesInto");
    vrcs = rcs;
    //toggleJavascriptFunctionalityOn();
    defaultDates();
    return checkValues();
}

function defaultDates()
{
	var todayDate = ""
	var year = ""
	var month = ""
	var day = ""
	
    if (document.getElementById("fromDate").value == "")
    {
      todayDate = new Date()
	  year = todayDate.getFullYear() + ""
	  month = todayDate.getMonth()+1 + ""
	  day = todayDate.getDate() + ""
	
	  if (month.length == 1)
	  {
	    month = "0" + month
	  }
	  if (day.length == 1)
	  {
	    day = "0" + day
	  }
	
	  document.getElementById("fromDate").value = year + "-" + month +  "-" + day
    }
	if (document.getElementById("toDate").value == "")
	{
		document.getElementById("toDate").value = year + "-" + month +  "-" + day
	}
}

function disableOrEnableAnchor(elementName, disable)
{
  var obj = document.getElementById(elementName);
  if(disable)
  {
    var href = obj.getAttribute("href");
    var onclick = obj.getAttribute("onclick");
    if(href && href != "" && href != null)
    {
      obj.setAttribute('href_bak', href);
    }
    if(onclick != null)
    {
      obj.setAttribute('onclick_bak', onclick);
      obj.setAttribute('onclick', "void(0);");
    }
    obj.removeAttribute('href');
  }
  else
  {
    if(obj.attributes['onclick_bak']!=null)
    {
      obj.setAttribute('onclick', obj.attributes['onclick_bak'].nodeValue);
    }
    if(obj.attributes['href_bak']!=null)
    {
      obj.setAttribute('href', obj.attributes['href_bak'].nodeValue);
    }
  }
}

function toggleJavascriptFunctionalityOn()
{
    document.getElementById("pickupCalendarDiv").style.display = "inline";
    document.getElementById("dropoffCalendarDiv").style.display = "inline";
    document.getElementById("dobCalendarDiv").style.display = "inline";
}

function checkValues()
{
    return valueChangedEvent();
}

function resetCountriesClicked()
{
    document.getElementById("countriesInto").selectedIndex = -1;
    valueChangedEvent("countriesInto");
}

function valueChangedEvent(elementName)
{
	//alert("valueChangedEvent : elementName = " + elementName);
    
    // pickup date section
    
    
    if (/*(document.getElementById("pickupDay").selectedIndex == 0) ||
    	(document.getElementById("pickupMonth").selectedIndex == 0) ||
    	(document.getElementById("pickupYear").selectedIndex == 0) ||*/
    	(document.getElementById("fromDate").value == "") ||
    	(document.getElementById("fromDate").length != 10) ||
    	(document.getElementById("pickupHour").selectedIndex == 0))
    {
        disable("pickupLocation");
        //disable("dropOffDay");
        //disable("dropOffMonth");
        //disable("dropOffYear");
        disable("dropOffHour");
        disable("dropOffLocation");
        //disable("dobDay");
        //disable("dobMonth");
        //disable("dobYear");
        disable("ageGroup");
        disable("countryOfOrigin");
        //disable("countriesInto");
        
        return (true);
    }
    else
    {
        storePlaceHolders();
        enable("pickupLocation");
        vrcs = rcs;
        
        var fromDate =  document.getElementById("fromDate").value;
        if (fromDate.length() != 10)
    	{
        	return (false);
    	}
        var pickupDayVal = parseInt(fromDate.substring(0, 4),10); //parseInt(document.getElementById("pickupDay").value);
        var pickupMonthVal = parseInt(fromDate.substring(5, 7),10); //parseInt(document.getElementById("pickupMonth").value);
        var pickupYearVal = parseInt(fromDate.substring(8, 10),10); //parseInt(document.getElementById("pickupYear").value);
        	
        //var pickupDayVal = parseInt(document.getElementById("pickupDay").value,10);
        //var pickupMonthVal = parseInt(document.getElementById("pickupMonth").value,10);
        //var pickupYearVal = parseInt(document.getElementById("pickupYear").value,10);
        
        /*year, month, day, hour, minutes, seconds, - milliseconds*/
        var pickupDate = new Date(pickupYearVal, pickupMonthVal-1, pickupDayVal, 0, 0, 0, 0);
        var trcs = new Array();
        var count = 0;
        
        for (var i=0; i<vrcs.length; i++)
        {
            for (var j=0; j<rcdts.length; j++)
            {
                if (vrcs[i] == rcdts[j][0])
                {
                    var startDate = new Date(rcdts[j][1]);
                    var endDate = new Date(rcdts[j][2]);
                    if ((pickupDate.getTime() >= startDate.getTime()) && (pickupDate.getTime() <= endDate.getTime()))
                    {
                        trcs[count++] = vrcs[i];
                    }
                }
            }
        }
        
        vrcs = trcs;
        
        if ((elementName != "pickupLocation") &&
        //(elementName != "dropOffDay") &&
        //(elementName != "dropOffMonth") &&
        //(elementName != "dropOffYear") &&
        (elementName != "toDate") &&
        (elementName != "dropOffHour") &&
        (elementName != "dropOffLocation") &&
        //(elementName != "dobDay") &&
        //(elementName != "dobMonth") &&
        //(elementName != "dobYear") &&
        (elementName != "ageGroup") &&
        //(elementName != "countriesInto") &&
        (elementName != "countryOfOrigin"))
        {
            if (buildLocationValues(plsups, "Please select a pickup location", "pickupLocation"))
            {
                return true;
            }
        }
        
        lookForValueAndReSelect("pickupLocation", selectedPickupLocation);
    }
    
    
    // pickup location
    
    
    if (document.getElementById("pickupLocation").selectedIndex == 0)
    {
        //disable("dropOffDay");
        //disable("dropOffMonth");
        //disable("dropOffYear");
    	disable("toDate");
    	disable("dropOffYear");
        disable("dropOffHour");
        disable("dropOffLocation");
        //disable("dobDay");
        //disable("dobMonth");
        //disable("dobYear");
        disable("ageGroup");
        disable("countryOfOrigin");
        //disable("countriesInto");
        return (true);
    }
    else
    {
        //enable("dropOffDay");
        //enable("dropOffMonth");
        //enable("dropOffYear");
    	enable("toDate");
        enable("dropOffHour");
        disableOrEnableAnchor("dropoffCalendarAnchor", false);
        
        locationSelectedNarrowValidRCS(plsups);
        
        //lookForValueAndReSelect("dropOffDay", selectedDropOffDay);
        //lookForValueAndReSelect("dropOffMonth", selectedDropOffMonth);
        //lookForValueAndReSelect("dropOffYear", selectedDropOffYear);
        lookForValueAndReSelect("toDate", selectedDropOffYear);
        lookForValueAndReSelect("dropOffHour", selectedDropOffHour);
    }
    
    
    // drop-off date section
    
    
    if (//(document.getElementById("dropOffDay").selectedIndex == 0) ||
    	//(document.getElementById("dropOffMonth").selectedIndex == 0) ||
    	//(document.getElementById("dropOffYear").selectedIndex == 0) ||
    	(document.getElementById("toDate").value == "") ||
    	(document.getElementById("toDate").length != 10) ||
    	(document.getElementById("dropOffHour").selectedIndex == 0))
    {
        disable("dropOffLocation");
        //disable("dobDay");
        //disable("dobMonth");
        //disable("dobYear");
        disable("ageGroup");
        disable("countryOfOrigin");
        //disable("countriesInto");
        return (true);
    }
    else
    {
        enable("dropOffLocation");
        
        if ((elementName != "dropOffLocation") &&
        //(elementName != "dobDay") &&
        //(elementName != "dobMonth") &&
        //(elementName != "dobYear") &&
        (elementName != "ageGroup") &&	
        //(elementName != "countriesInto") &&
        (elementName != "countryOfOrigin"))
        {
            buildLocationValues(dlsups, "Please select a drop-off location", "dropOffLocation");
        }
        
        lookForValueAndReSelect("dropOffLocation", selectedDropOffLocation);
    }
    
    
    // drop-off location
    
    
    if (document.getElementById("dropOffLocation").selectedIndex == 0)
    {
        //disable("dobDay");
        //disable("dobMonth");
        //disable("dobYear");
    	disable("ageGroup");
        disable("countryOfOrigin");
        //disable("countriesInto");
        return (true);
    }
    else
    {
        //enable("dobDay");
        //enable("dobMonth");
        //enable("dobYear");
    	enable("ageGroup");
        disableOrEnableAnchor("dobCalendarAnchor", false);
        
        locationSelectedNarrowValidRCS(dlsups);
        
        if (//(elementName != "dobDay") &&
        //(elementName != "dobMonth") &&
        //(elementName != "dobYear") &&
        (elementName != "ageGroup") &&
        //(elementName != "countriesInto") &&
        (elementName != "countryOfOrigin"))
        {
            buildDOBYearValues();
        }
        
        //lookForValueAndReSelect("dobDay", selectedDobDay);
        //lookForValueAndReSelect("dobMonth", selectedDobMonth);
        //lookForValueAndReSelect("dobYear", selectedDobYear);
        lookForValueAndReSelect("ageGroup", selectedAgeGroup);
    }
    
    
    // Date of Birth
    
    
    if ((document.getElementById("ageGroup").selectedIndex == 0))
    //(document.getElementById("dobDay").selectedIndex == 0) ||
    //(document.getElementById("dobMonth").selectedIndex == 0) ||
    //(document.getElementById("dobYear").selectedIndex == 0)
    {
        disable("countryOfOrigin");
        //disable("countriesInto");
        return (true);
    }
    else
    {
        enable("countryOfOrigin");
        
        if (dobYearSelectedNarrowValidRCS() == false)
        {
            lookForValueAndReSelect("countryOfOrigin", selectedCountryOfOrigin);
            lookForMultipleValuesAndReSelect();
            return (false);
        }
        
        if (//(elementName != "countriesInto") &&
        (elementName != "countryOfOrigin"))
        {
            //currently not required
        }
        
        lookForValueAndReSelect("countryOfOrigin", selectedCountryOfOrigin);
    }
    
    
    // Country of Origin
    
    
    if (document.getElementById("countryOfOrigin").selectedIndex == 0)
    {
        //disable("countriesInto");
        return (true);
    }
    else
    {
        //enable("countriesInto");
        
        buildCountriesValues();
        
    }
    lookForMultipleValuesAndReSelect();
}

function valueChangedCountries()
{
    //getMultipleSelectedValues("countriesInto");
    
    if (document.getElementById("countriesInto").selectedIndex == 0)
    {
        if (selectedCountriesIntoArray.length == 1)
        {
            if ((selectedCountriesIntoArray[0] == 0) || (selectedCountriesIntoArray[0] == -1))
            {
                if (resetCountriesClicked())
                {
                    document.getElementById("countriesInto").selectedIndex = 0;
                    return (true);
                }
            }
        }
        var tempArray = new Array();
        var count = 0;
        var found = false;
        for (var i=0; i<selectedCountriesIntoArray.length; i++)
        {
            if ((selectedCountriesIntoArray[i] != 0) && (selectedCountriesIntoArray[i] != -1))
            {
                tempArray[count++] = selectedCountriesIntoArray[i];
            }
        }
        selectedCountriesIntoArray = tempArray;
    }
    
    var trcs = new Array();
    var count = 0;
    
    if (vrcs.length != 0)
    {
        countriesSelectedNarrowValidRCS();
        
        buildCountriesValues();
        
        lookForMultipleValuesAndReSelect();
    }
    else
    {
        // This should never happen or be called as the list will be rebuilt
        return (true);
    }
}

function valueChangedCountriesList()
{
    if (document.getElementById("countriesInto").selectedIndex == 0)
    {
        document.getElementById("countriesInto").selectedIndex = 0;
    }
    
    if (document.getElementById("countriesInto").selectedIndex == -1)
    {
        document.getElementById("countriesInto").selectedIndex = 0;
    }
    
}

function buildDOBYearValues()
{
    var locations = new Array();
    var count = 0;
    var minAge = 100;
    
    if (vrcs.length != 0)
    {
        for (var p=0; p<vrcs.length; p++) // step through valid RateTables
        {
            for (var k=0; k<rcsups.length; k++) // step through rateTable TO suppliers Array
            {
                if (vrcs[p] == rcsups[k][0]) // find the supplier for the valid rateTable
                {
                    for (var i=0; i<supsages.length; i++) // step through suppliers minimum ages
                    {
                        if (supsages[i][0] == rcsups[k][1]) // we have found the minimum age allowed by the supplier
                        {
                            if (supsages[i][1] <= minAge)
                            {
                                minAge = supsages[i][1];
                            }
                            break;
                        }
                    }
                    break;
                }
            }
        }
        
        //var today = new Date();
        
        var dobYears = new Array();
        var dobYearValues = new Array();
        
        dobYears[0] = "Year";
        dobYearValues[0] = "-1";
        
        //(get milliseconds since 1/1/1970 / calc milliseconds in a year) find the years since 1970 then add 1970 to get current year
        //var pickupDateYear = parseInt((pickupDate.getTime() / millisecondsInAYear) + 1970,10);
        var pickupDateYear = parseInt(document.getElementById("pickupYear").value,10);
        pickupDateYear = pickupDateYear - minAge;
        
        for (var i=1; i<((maxAge - minAge) + 2); i++)
        {
            dobYears[i] = pickupDateYear;
            dobYearValues[i] = pickupDateYear;
            pickupDateYear--;
        }
        
        clearListBoxItems("dobYear");
        for (var i=0; i<dobYears.length; i++)
        {
            addListBoxItem("dobYear", dobYears[i], dobYearValues[i]);
        }
    }
    else
    {
        unSelect("pickupLocation");
        //unSelect("dropOffDay");
        //unSelect("dropOffMonth");
        //unSelect("dropOffYear");
        /*
         * do i need to do something for toDate????
         */
        unSelect("dropOffHour");
        unSelect("dropOffLocation");
        //unSelect("dobDay");
        //unSelect("dobMonth");
        //unSelect("dobYear");
        unSelect("ageGroup");
        unSelect("countryOfOrigin");
        unSelectMulti("countriesInto");
        disable("pickupLocation");
        //disable("dropOffDay");
        //disable("dropOffMonth");
        //disable("dropOffYear");
        disable("dropOffHour");
        disable("dropOffLocation");
        //disable("dobDay");
        //disable("dobMonth");
        //disable("dobYear");
        disable("ageGroup");
        disable("countryOfOrigin");
        disable("countriesInto");
        alert("Unfortunately we do not have rates for your pickup date. Please change your date and try again.");
        return (true);
    }
}

function buildLocationValues(locsToSupsArrayName, firstRowString, comboBoxName)
{
    var locations = new Array();
    var provinces = new Array();
    
    var countLocs = 0;
    var countPros = 0;
    var foundLoc = false;
    var foundPro = false;
    
    var tempProviceId = 0;
    var tempLocations = new Array();
    
    if (vrcs.length != 0)
    {
        for (var p=0; p<vrcs.length; p++) // step through valid RateTables
        {
            for (var k=0; k<rcsups.length; k++) // step through rateTable TO suppliers Array
            {
                if (vrcs[p] == rcsups[k][0]) // find the supplier for the valid rateTable
                {
                    for (var q=0; q<locsToSupsArrayName.length; q++) // step through pickupLocations or dropoffLocations TO suppliers Array entries //format locID, [supplierID, supplierID]
                    {
                        // skipped second level loop as array has fixed length (1 location to 1..* suppliers)
                        // and we know only suppliers could be more than 1
                        for (var n=0; n<locsToSupsArrayName[q][1].length; n++) // step through suppliers for each location
                        {
                            if (rcsups[k][1] == locsToSupsArrayName[q][1][n]) // find the supplier that matches the valid rateTable supplier
                            {
                            	
                                for (var i=0; i<locspro.length; i++) // step through the (location ids -> province ids) list
                                {
                                    if (locspro[i][0] == locsToSupsArrayName[q][0]) // confirm that both locations ids match
                                    {
                                        tempProviceId = locspro[i][1];
                                        for (var l=0; l<provinces.length; l++) // step through the province list
                                        {
                                            if (locspro[i][1] == provinces[l][0]) // see if temp province array contains province already
                                            {
                                                foundPro = true;
                                                break;
                                            }
                                        }
                                        if (!foundPro) // if not found then add it
                                        {
                                            for (var j=0; j<provs.length; j++) // step through the provinces array
                                            {
                                                if (provs[j][0] == tempProviceId) // if the provinceID is the same we now have its name
                                                {
                                                    provinces[countPros++] = new Array(provs[j][0], provs[j][1]);
                                                    foundPro = false;
                                                    break;
                                                }
                                            }
                                        }
                                        foundPro = false;
                                    }
                                }
                                
                                for (var i=0; i<locations.length; i++) // check if this location has already been added to locations SET
                                {
                                    if (locations[i][0] == locsToSupsArrayName[q][0])
                                    {
                                        foundLoc = true;
                                        break;
                                    }
                                }
                                if (!foundLoc) // if not found then add it
                                {
                                    for (var j=0; j<locs.length; j++) // step through the locations array
                                    {
                                        if (locs[j][0] == locsToSupsArrayName[q][0]) // if the locationID is the same we now have its name
                                        {
                                            locations[countLocs++] = new Array(locs[j][0], locs[j][1]);
                                            foundLoc = false;
                                            break;
                                        }
                                    }
                                }
                                foundLoc = false;
                            }
                        }
                    }
                    break;
                }
            }
        }
        
        clearListBoxGroupsAndItems(comboBoxName);
        provinces.sort(sortByName);
        
        var boxName = document.getElementById(comboBoxName);
        var tempHTML = "";
        var tempCount = 0;
        
        addListBoxItem(comboBoxName, firstRowString, -1);
        
        for (var l=0; l<provinces.length; l++) // step through the just built provinces list
        {
        	for (var i=0; i<locspro.length; i++) // step through the (location ids -> province ids) list
	        {
	        	if (provinces[l][0] == locspro[i][1]) // if province ids match, this is a possible location
	        	{
	        		for (var p=0; p<locations.length; p++) // step through previously build locations array
                    {
                    	if (locations[p][0] == locspro[i][0]) // check for location in previously build locations array
                    	{
                    		tempLocations[tempCount++] = new Array(locations[p][0], locations[p][1]);
                    	}
                    }
	        	}
	        }
	        
	        tempLocations.sort(sortByName);
	        
            tempCount = 0;
            addListBoxGroupAndItems(comboBoxName, provinces[l][1], tempLocations);
            tempLocations = new Array();
        }
    }
    else
    {
        if (comboBoxName == "pickupLocation")
        {
            unSelect("pickupLocation");
            //unSelect("dropOffDay");
            //unSelect("dropOffMonth");
            //unSelect("dropOffYear");
            unSelect("dropOffHour");
            unSelect("dropOffLocation");
            //unSelect("dobDay");
            //unSelect("dobMonth");
            //unSelect("dobYear");
            unSelect("ageGroup");
            unSelect("countryOfOrigin");
            unSelectMulti("countriesInto");
            disable("pickupLocation");
            //disable("dropOffDay");
            //disable("dropOffMonth");
            //disable("dropOffYear");
            disable("dropOffHour");
            disable("dropOffLocation");
            //disable("dobDay");
            //disable("dobMonth");
            //disable("dobYear");
            disable("ageGroup");
            disable("countryOfOrigin");
            disable("countriesInto");
            alert("Unfortunately we do not have rates for your pickup date. Please change your date and try again.");
        }
        else
        {
            disable("dropOffLocation");
            //disable("dobDay");
            //disable("dobMonth");
            //disable("dobYear");
            disable("ageGroup");
            disable("countryOfOrigin");
            disable("countriesInto");
            alert("Unfortunately we do not have rates for your selection. Please change your selection and try again.");
        }
        return (true);
    }
}

function buildCountriesValues()
{
    var countries = new Array();
    var count = 0;
    var found = false;
    
    if (vrcs.length != 0)
    {
        for (var p=0; p<vrcs.length; p++) // step through valid RateTables
        {
            for (var k=0; k<rcsups.length; k++) // step through rateTable TO suppliers Array
            {
                if (vrcs[p] == rcsups[k][0]) // find the supplier for the valid rateTable
                {
                    for (var q=0; q<supsc.length; q++) // step through suppliers TO countries taking cars into Array
                    {
                        // skipped second level loop as array has fixed length (1 location to 1..* suppliers)
                        // and we know only suppliers could be more than 1
                        if (supsc[q][0] == rcsups[k][1]) // found the suppliers countries allowed into for this supplier
                        {
                            for (var n=0; n<supsc[q][1].length; n++) // step through each country in sups to countries array
                            {
                                for (var m=0; m<countries.length; m++) // step through the countries set
                                {
                                    if (countries[m][0] == supsc[q][1][n])
                                    {
                                        found = true;
                                        break;
                                    }
                                }
                                if (!found) // if not found then add it
                                {
                                    for (var j=0; j<cos.length; j++) // step through the countries allowed into array
                                    {
                                        if (cos[j][0] == supsc[q][1][n]) // if the locationID is the same we now have its name
                                        {
                                            countries [count++] = new Array(cos[j][0], cos[j][1]);
                                            found = false;
                                            break;
                                        }
                                    }
                                }
                                found = false;
                            }
                            break;
                        }
                    }
                    break;
                }
            }
        }
        
        countries.sort(sortByName);
        
        var tempArray = new Array();
        
        tempArray[0] = new Array(-1, "Not Leaving the Country");
        for (var i=0; i<countries.length; i++)
        {
            tempArray[i+1] = new Array(countries[i][0], countries[i][1]);
        }
        
        //TODO replace below function call with just a length=0
        clearListBoxItems("countriesInto");
        for (var i=0; i<tempArray.length; i++)
        {
            addListBoxItem("countriesInto", tempArray[i][1], tempArray[i][0]);
        }
    }
}

function countriesSelectedNarrowValidRCS()
{
    var trcs = new Array();
    var count = 0;
    var foundAll = false;
    var found = false;
    
    for (var i=0; i<vrcs.length; i++) // step through all valid rateTables
    {
        for (var j=0; j<rcsups.length; j++) // step through all ratetalbe to suppliers
        {
            if (vrcs[i] == rcsups[j][0]) // if ratetable the same ... we found our supplier [j][1]
            {
                for (var m=0; m<supsc.length; m++) // step through suppliers to countries allowed to take vehicle into array
                {
                    if (supsc[m][0] == rcsups[j][1]) // if we find the supplier we have the countries list countries
                    {
                        for (var p=0; p<selectedCountriesIntoArray.length; p++) // step through all clients selected countries so far
                        {
                            for (var n=0; n<supsc[m][1].length; n++) // step through all the suppliers countries
                            {
                                if (supsc[m][1][n] == selectedCountriesIntoArray[p])
                                {
                                    //trcs[count++] = vrcs[i];
                                    //foundAll = true;
                                    found = true;
                                    break;
                                }
                            }
                            if (found)
                            {
                                foundAll = true;
                                found = false;
                            }
                            else
                            {
                                foundAll = false;
                                break; // break because this supplier has failed in catering for all selected countries
                            }
                        }
                        if (foundAll)
                        {
                            trcs[count++] = vrcs[i];
                        }
                        else
                        {
                            
                        }
                    }
                }
            }
        }
    }
    vrcs = trcs;
}

function locationSelectedNarrowValidRCS(locsToSupsArrayName)
{
    var trcs = new Array();
    var count = 0;
    
    for (var i=0; i<vrcs.length; i++) // step through all valid rateTables
    {
        for (var j=0; j<rcsups.length; j++) // step through all ratetalbe to suppliers
        {
            if (vrcs[i] == rcsups[j][0]) // if ratetable the same ... we found our supplier [j][1]
            {
                for (var m=0; m<locsToSupsArrayName.length; m++) // step through all the pickuplocations to suppliers
                {
                    if (locsToSupsArrayName[m][0] == selectedPickupLocation) // if we find the location the client selected
                    {
                        for (var n=0; n<locsToSupsArrayName[m][1].length; n++) //then step through all the pickuplocations suppliers to see if the valid ratetable still applies
                        {
                            if (locsToSupsArrayName[m][1][n] == rcsups[j][1])
                            {
                                trcs[count++] = vrcs[i];
                            }
                        }
                    }
                }
            }
        }
    }
    vrcs = trcs;
}

function dobYearSelectedNarrowValidRCS()
{
    var trcs = new Array();
    count = 0;
    
    //var selectedDay = getSelectedValue("dobDay");
    //var selectedMonth = getSelectedValue("dobMonth");
    //var selectedYear = getSelectedValue("dobYear");
    var ageGroup = getSelectedValue("ageGroup");
    
    //var dateOfBirth = new Date(selectedYear, selectedMonth-1, selectedDay, 0, 0, 0, 0);
    
    var pickupDayVal = parseInt(document.getElementById("pickupDay").value,10);
    var pickupMonthVal = parseInt(document.getElementById("pickupMonth").value,10);
    var pickupYearVal = parseInt(document.getElementById("pickupYear").value,10);
    
    var pickupDate = new Date(pickupYearVal, pickupMonthVal-1, pickupDayVal, 0, 0, 0, 0);
    
    //var dobTemp = (dateOfBirth.getTime() / millisecondsInAYear) + 1970;
    //var pickupDateTemp = (pickupDate.getTime() / millisecondsInAYear) + 1970;
    //var clientAge = parseInt((pickupDateTemp - dobTemp),10);
    var clientAge = ageGroup.substring(0,2);
    
    for (var i=0; i<vrcs.length; i++) // step through all valid rateTables
    {
        for (var j=0; j<rcsups.length; j++) // step through all ratetalbe to suppliers
        {
            if (vrcs[i] == rcsups[j][0]) // if ratetable the same ... we found our supplier [j][1]
            {
                for (var m=0; m<supsages.length; m++) // step through all suppliers to min ages
                {
                    if (supsages[m][0] == rcsups[j][1]) // if supplier the same ... we found our min Age [m][1]
                    {
                        if (clientAge >= supsages[m][1]) //if clientAge > than the minimum allowed suppliers age then RateTable is Valid
                        {
                            trcs[count++] = vrcs[i];
                        }
                    }
                }
            }
        }
    }
    
    vrcs = trcs;
    
    if (vrcs.length != 0)
    {
        return (true);
    }
    else
    {
        unSelect("countryOfOrigin");
        unSelectMulti("countriesInto");
        disable("countryOfOrigin");
        disable("countriesInto");
        alert("Unfortunately we do not have rates for the requested age group.");
        return (false);
    }
}

function storePlaceHolders()
{
    selectedPickupLocation = getSelectedValue("pickupLocation");
    selectedDropOffLocation = getSelectedValue("dropOffLocation");
    //selectedDobDay = getSelectedValue("dobDay");
    //selectedDobMonth = getSelectedValue("dobMonth");
    //selectedDobYear = getSelectedValue("dobYear");
    selectedageGroup = getSelectedValue("ageGroup");
    selectedCountryOfOrigin = getSelectedValue("countryOfOrigin");
    getMultipleSelectedValues("countriesInto");
}

function lookForValueAndReSelect(elementName, storedValue)
{
    if (storedValue != -1)
    {
        var pl = document.getElementById(elementName)
        for (var i=0; i<pl.length; i++)
        {
            if (pl.options[i].value == storedValue)
            {
                pl.selectedIndex = i;
            }
        }
    }
}

function lookForMultipleValuesAndReSelect()
{
    for (var j=0; j<selectedCountriesIntoArray.length; j++)
    {
        if (selectedCountriesIntoArray[j] != -1)
        {
            var pl = document.getElementById("countriesInto")
            for (var i=0; i<pl.length; i++)
            {
                if (pl.options[i].value == selectedCountriesIntoArray[j])
                {
                    pl.options[i].selected = true;
                }
            }
        }
    }
}

function getSelectedValue(name)
{
    var ele = document.getElementById(name);
    if (ele.length != 0)
    {
        return ele.options[ele.selectedIndex].value;
    }
}

function getMultipleSelectedValues(name)
{
    selectedCountriesIntoArray = new Array();
    var count = 0;
    
    var ele = document.getElementById(name);
    for (var i=0; i<ele.options.length; i++)
    {
        if (ele.options[i].selected)
        {
            selectedCountriesIntoArray[count++] = ele.options[i].value;
        }
    }
}

/*
 * Method has been reversed, basically making it null and void.
 * Reason: I just don't want to go and remove all the hard work and then oneday
 * have to put it all back. 
 */
function disable(elementName)
{
    //document.getElementById(elementName).disabled=true;
    document.getElementById(elementName).disabled=false;
}

function enable(elementName)
{
    document.getElementById(elementName).disabled=false;
}

function unSelect(elementName)
{
    document.getElementById(elementName).selectedIndex = 0;
}

function unSelectMulti(elementName)
{
    document.getElementById(elementName).selectedIndex = -1;
}

function addListBoxItem(listBoxName, sName, sValue)
{
    var listBox = document.getElementById(listBoxName);
    listBox.options[listBox.length] = new Option(sName, sValue);
}

function addListBoxGroupAndItems(listBoxName, groupName, itemNames)
{
    var listBox = document.getElementById(listBoxName);
    var optGroup = document.createElement('optgroup'); // maybe should be 'OPTGROUP'
    var objOption;
    
    optGroup.label = groupName;
    listBox.appendChild(optGroup);
    for (var q=0; q<itemNames.length; q++)
    {
    	objOption = document.createElement("option");
        objOption.innerHTML = itemNames[q][1];
        objOption.value = itemNames[q][0];
        optGroup.appendChild(objOption);
    }
}

function clearListBoxItems(listBoxName)
{
    var listBox = document.getElementById(listBoxName);
    listBox.length = 0;
}

function clearListBoxGroupsAndItems(listBoxName)
{
	var locsList = document.getElementById(listBoxName);
	locsList.innerHTML = "";
}

function sortByName(a, b)
{
    if (a[1]<b[1]) return -1;
    if (a[1]>b[1]) return 1;
    return 0;
}
