//The following will get a start date of 01/05/04 to build the drop downs.
//var startDate = ""
var daysinmonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var startDate = new Date(2003,10,1);
var minDate04 = new Date(2004,4,1);
var maxDate04 = new Date(2004,10,31);
var minDate05 = new Date(2005,4,1);
var maxDate05 = new Date(2005,10,31);

function drawDays()
{
	//alert(startDate.toGMTString());
	var selected = "";
	var padDate = "";
	var tempDate = new Date();
	if (startDate != "" && startDate > tempDate)
	{
		var tempDate = startDate;
		var date = tempDate.getDate();
	}
	else
	{
		var date = tempDate.getDate();
		date += 3;
		tempDate.setDate(date);
	}
	date = tempDate.getDate();

	for (var i=1; i<32; i++)
	{
		padDate = i;
		padDate = padDate.toString();
		if(padDate.length == 1){padDate = "0" + padDate;}
		if(i == date){selected = "selected";}
		document.write('<option value="'+padDate+'" '+ selected +'>'+padDate+'</option>');
		selected = '';
	}
}

function drawMonths()
{
	var selected = '';
	var armonths=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	var curDate = new Date();
	//curDate.setDate(1);
	var tempDate = new Date();
	if (startDate != "" && startDate > tempDate)
	{
		var tempDate = startDate;
		curDate = startDate;
	}
	else
	{
		var date = tempDate.getDate();
		var testdate = tempDate.getDate();
		var testmonth = tempDate.getMonth();
		date += 3;

		if(date > daysinmonth[testmonth])
		{
			date = 3-(daysinmonth[testmonth]-tempDate.getDate());
		}

		// Check If Month Rolled Over
		if(testdate>date)
		{
			tempDate.setDate(date);
			if(tempDate.getMonth()==11)
			{
				tempDate.setMonth(0);
			}
			else
			{
				tempDate.setMonth(tempDate.getMonth() + 1);
			}

			// Check If Year Rolled Around
			if(testmonth>tempDate.getMonth())
			{
				tempDate.setYear(tempDate.getYear() + 1);
			}
			curDate = tempDate;
		}
		else
		{
			tempDate.setDate(date);
		}

	}
	var tempMonth = tempDate.getMonth();
	var tempYear = tempDate.getYear();
	for (var i=0; i<15; i++)
	{
		var curMonth = curDate.getMonth();
		var curMonthStr = curMonth + 1;
		curMonthStr = curMonthStr.toString();
		if(curMonthStr.length == 1){curMonthStr = "0" + curMonthStr;}
		var curYear = curDate.getFullYear();
		curYear = curYear.toString();
		var curYearStr = curYear;
		//alert("curYear="+curYear+",tempYear="+tempYear+",CurMonth="+curMonth+", tempMonth="+tempMonth);
		if(curYear == tempYear && curMonth == tempMonth)
		{
			selected = 'selected';
		}
		if (armonths[curMonth]!="XXX")
		{
			document.write('<option value="'+curMonthStr+'-'+curYear+'" ' + selected + '>'+armonths[curMonth]+' '+curYearStr+'</option>');
		}
		curDate.setMonth(curDate.getMonth() + 1);
		selected = '';
	}
}

//funtion to add days to any date
Date.prototype.addDays=function(num)
{
    return new Date((new Number(this)) + (num * 60 * 60 * 24 * 1000))
}

function resetScreen()
{
    document.CriteriaForm.HolType[0].checked = false;
    document.CriteriaForm.HolType[1].checked = true;
}

function pad(str, desiredStrLen, padChar)
{
var str = str.toString();
var strLen = str.length;
while(strLen < desiredStrLen)
{
    str = padChar + str;
    strLen = str.length;
}
return str;
}

function GetOut()
{
    var objDep = $("Dep");

    var objDay = $("Day");
    var objMonYear = $("Month");
    var objResort = $("Resort");
    var objArr = $("FOAirport");
    var objDuration=$("duration");

    var tdaysinmonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    var ttempDate = new Date();
    var tdate = ttempDate.getDate();
    var ttestdate = ttempDate.getDate();
    var ttestmonth = ttempDate.getMonth();
    var bvalid = true;
    tdate += 2;


    if(tdate > tdaysinmonth[ttestmonth])
    {
	    tdate = 3-(tdaysinmonth[ttestmonth]-ttempDate.getDate());
    }

    // Check If Month Rolled Over
    if(ttestdate>tdate)
    {
	    ttempDate.setDate(tdate);
	    if(ttempDate.getMonth()==11)
	    {
		    ttempDate.setMonth(0);
	    }
	    else
	    {
		    ttempDate.setMonth(ttempDate.getMonth() + 1);
	    }
	    // Check If Year Rolled Around
	    if(ttestmonth>ttempDate.getMonth())
	    {
		    ttempDate.setYear(ttempDate.getYear() + 1);
	    }
    }
    else
    {
	    ttempDate.setDate(tdate);
    }

    var tearliestdeparturedate = new Date(ttempDate.getYear(), ttempDate.getMonth(), ttempDate.getDate());


    var day_depart=objDay.options[objDay.selectedIndex].value;
    var monthYear = objMonYear.options[objMonYear.selectedIndex].value;
    var tempArr = monthYear.split(" ");
    var month_depart;
    switch (tempArr[0])
    {
	    case "Jan":
		    month_depart="01";
		    break;
	    case "Feb":
		    month_depart="02"
		    break;
	    case "Mar":
		    month_depart="03";
		    break;
	    case "Apr":
		    month_depart="04";
		    break;
	    case "May":
		    month_depart="05";
		    break;
	    case "Jun":
		    month_depart="06";
		    break;

	    case "Jul":
		    month_depart="07";
		    break;
	    case "Aug":
		    month_depart="08";
		    break;

	    case "Sep":
		    month_depart="09";
		    break;

	    case "Oct":
		    month_depart="10";
		    break;

	    case "Nov":
		    month_depart="11";
		    break;

	    case "Dec":
		    month_depart="12";
		    break;
    }


    var year_depart = tempArr[1];

    var tempDate = new Date(year_depart, month_depart-1, day_depart);

//	if(tearliestdeparturedate>tempDate)
//	{
//		alert('Please select a departure date greater than, or on, '+tearliestdeparturedate);
//		bvalid = false;
//	}

    var duration = objDuration.options[objDuration.selectedIndex].value;
    //alert(duration);

    duration = Number(duration);

    tempDate = tempDate.addDays(duration);

    var day_return = tempDate.getDate();

    day_return = pad(day_return, 2, "0");
    var month_return = tempDate.getMonth()+1;

    month_return = pad(month_return, 2, "0");
    var year_return = tempDate.getFullYear();

    $("OutDepDate").value = day_depart + "/" + month_depart + "/" + year_depart;

    $("RetDepDate").value = day_return + "/" + month_return + "/" + year_return;


    //Departure
    $('Departure1').value = objDep.options[objDep.selectedIndex].value;
    $('OutDepAir').value = objDep.options[objDep.selectedIndex].value;


    if (objDep.options[objDep.selectedIndex].value =="")
    {
	    alert('Please select a Departure Airport');
	    bvalid = false;
    }

    //Destination

    $('OutArrAir').value = objArr.options[objArr.selectedIndex].value;


/* FO Removed as per Adriatics request 01-Mar-2010 (was HolType[2]) */
    //if (!(document.forms[0].HolType[1].checked))
    //{
	    if (objArr.options[objArr.selectedIndex].value=="")
	    {
		    alert('Please select a Destination');
		    bvalid = false;
	    }
    //}


    if (!(objResort.options[objResort.selectedIndex].value==""))
    {
	    var rawDest = objResort.options[objResort.selectedIndex].value.split(',');
	    $('AccomLocation').value = rawDest[1];
	    $('OutArrAir').value = rawDest[0];
	    $('AccomResort').value = rawDest[2];

    }
    else
    {
	    $('OutArrAir').value = objArr.options[objArr.selectedIndex].value;
	    $('AccomResort').value = "";
    }

    //CompCode

    var dest = objArr.options[objArr.selectedIndex].value
    if (dest=="XX1"||dest=="XX2"||dest=="XX3"||dest=="X10")
    {
	    $('CompCode').value = "I";
    }
    else if (dest=="XX4"||dest=="XX5"||dest=="XX6")
    {
	    $('CompCode').value = "B";
    }
    else if (dest=="XX7"||dest=="XX8"||dest=="XX9"||dest=="XX0")
    {
	    $('CompCode').value = "C";
    }

    $('BranchCode').value = $('CompCode').value +'IN';

    //Set External Data
    var t = /AniteNextPage.asp/g;
    var domain="..\/..\/..\/.."
    var imgDir= /media/g;
    var scrDir = /javascript/g;
    var fixedImages= /images/g;

    //scripts
    //Declare the header html for Booking templates and change to absolute url
    if ( $("AllHeader") != null ) {
   		var ExternalData001 = $('ExternalData001');
   		if ( ExternalData001 != null ) {
			ExternalData001.value = $('AllHeader').innerHTML;
			ExternalData001.value = ExternalData001.value.replace( t, domain + "\/AniteNextPage.asp" );
			ExternalData001.value = ExternalData001.value.replace( imgDir,domain + "\/media");
			//ExternalData001.value = ExternalData001.value.replace( fixedImages,domain + "\/Images" );
			ExternalData001.value = ExternalData001.value.replace( scrDir,domain + "\/javascript" );
			var i=ExternalData001.value.indexOf( '<!-- DynamicBlockStart -->' );
			var j=ExternalData001.value.indexOf( '<!-- DynamicBlockEnd -->' );
			ExternalData001.value = ExternalData001.value.substr( 0, i ) + ExternalData001.value.substr( j, ExternalData001.value.substr( 0, i ) + ExternalData001.value.length );
		}
	}

    //Pass through the URL
    $('ExternalData002').value = SITE.domain;

    if($('InfantPax').value > $('AdultPax').value)
    {
	    alert('You cannot book more infants than adults through our website.  Please either amend your details or contact our call centre.');
	    bvalid = false;
    }

    if (bvalid)
    {
	/* FO Removed as per Adriatics request 01-Mar-2010
	    if ($('FOHolType').checked)
	    {
		    $('CriteriaForm').action = SITE.Booking.urls.fo;
		    $('CompCode').value = "F";
	    }
	    else */
	    if ($('INCHolType').checked)
	    {
		    $('CriteriaForm').action = SITE.Booking.urls.inc;
	    }
	    else
	    {
		    $('CriteriaForm').action = SITE.Booking.urls.ao;
		    $('CompCode').value ="";
	    }
	    $('CriteriaForm').submit();
    }
}


//################# ISU Inpage stuff ######################

    var req;
    var isIE = false;
    var reset = false;
    var MonthChange = "No";

    function Toggle()
    {
        if(document.forms[0].HolType[0].checked)
        {
            $("resdiv").style.display="none";
            $("destdiv").style.display="inline";
            //$("durationRow1").style.display="inline";
            //$("durationRow2").style.display="inline";

        }
        /* FO Removed as per Adriatics request 01-Mar-2010
        else if ( document.forms[0].HolType[2].checked)
        {
            $("resdiv").style.display="none";
            $("destdiv").style.display="none";
            //$("durationRow1").style.display="none";
            //$("durationRow2").style.display="none";
        }*/

        else

        {
            $("resdiv").style.display="inline";
            $("destdiv").style.display="inline";
            //$("durationRow1").style.display="inline";
            //$("durationRow2").style.display="inline";
        }
    }

    function InitRoutes()
    {
        reset = true;
        GetRoutes('','','');
    //	MonthChange = "No";
    }

    function reqInit()
    {
        if(window.XMLHttpRequest)
        {
            req=new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            try
            {
                req=new ActiveXObject("Msxml2.XMLHTTP");
                isIE = true;
            }
            catch(e)
            {
                try
                {
                    req=new ActiveXObject("Microsoft.XMLHTTP");
                    isIE = true;
                }
                catch(oc)
                {
                    req=null;
                }
            }
        }
    }

    function GetRoutes(DepDate,DepAir,ArrAir)
    {

        reqInit();

        var url="/AniteRoutes.aspx?q=3|"+DepDate+"|"+DepAir+"|"+ArrAir;

        if(req!=null)
        {
            req.onreadystatechange = Process;
            req.open("GET", url, true);
                req.send(null);
        }
        //setTimeout('setResortDD()', 1000)
    }

    function setResortDD() {

		for (var i = 0; i < document.CriteriaForm.Resort.options.length; i++)
		{
			if (document.CriteriaForm.Resort.options[i].value == SITE.Booking.selectedResort )
			{
				document.CriteriaForm.Resort.options[i].selected = true;
			}
		 	//alert('inside ='+document.CriteriaForm.Resort.options.length);
		}
    }

    function Process()
    {
        if (req.readyState == 4) {
            if (req.status == 200) {
                if(req.responseText=="")
                    alert("No response");
                else {
                    //alert(req.responseText);
                    LoadRoutes();
                }
            }
            else {
                alert("Error "+req.status);
            }
        }
    }

    function LoadRoutes()
    {
        var preMonth = '("' + $("Month").value + '"';

        var items = req.responseText.split("|");
        if (items.length == 6)
        {
            LoadVal("Month",eval("new Array"+items[1]),"","");
            LoadVal("Day",eval("new Array"+items[4]),"!","");
            LoadVal("Dep",eval("new Array"+items[2]),"!","Select departure                      ");
            LoadVal("FOAirport",eval("new Array"+items[3]),"!","Select destination                    ");
            LoadVal("Resort",eval("new Array"+items[5]),"!","Any resort                               ");
        }
        reset = false;

        var test = items[1].split(",");
        var postMonth = test[0].split(",");

        if (MonthChange == "Yes")
        {
            if (preMonth != postMonth)
            {
                dd = $("Day");
                mmyy = $("Month");
                dep = $("Dep");
                arr = $("FOAirport");
                MonthChange = "No";
                GetRoutes(dd[dd.selectedIndex].value+' '+mmyy[mmyy.selectedIndex].value,dep[dep.selectedIndex].value,arr[arr.selectedIndex].value);
            }
        }
    }

    function LoadVal(id,val,sep,seltxt)
    {
        var obj = $(id);
        var key = "";
        var newind = -1;
        if (obj.selectedIndex && !reset)
        {
            //key = obj[obj.selectedIndex].value;
            key = obj[obj.selectedIndex].text;
            newind = -1;
        }
        obj.options.length=0;
        var j = -1;
        if (seltxt != '')
        {
            j++;
            obj.options[j] = new Option(seltxt,'');
        }
        var cnt = 0;
        for (var i=0;i<val.length;i++)
        {
            j++;
            if (val[i] != '') {
                cnt++;
                if (sep == '') {
                    obj.options[j] = new Option(val[i],val[i]);
                    if (key == val[i]) newind = j;
                }
                else {
                    var s = val[i].split(sep);
                    obj.options[j] = new Option(s[1],s[0]);
                    //if (key == s[0]) newind = j;
                    if (key == s[1]) newind = j;
                }
            }
        }
        if (newind >= 0) obj.selectedIndex = newind;
        if (cnt == 1) obj.selectedIndex = j;
    }

    function Change(obj)
    {
        MonthChange = "Yes";

        dd = $("Day");
        mmyy = $("Month");
        dep = $("Dep");
        arr = $("FOAirport");
        GetRoutes(dd[dd.selectedIndex].value+' '+mmyy[mmyy.selectedIndex].value,dep[dep.selectedIndex].value,arr[arr.selectedIndex].value);
    }

    function setISU()
    {
//        <WC@IF NAME="//RESPONSE/IATGEOG3/IATGEOG2" COMPARISON="NOTBLANK">
//            $("FOAirport").value = '<WC@TAG NAME="//RESPONSE/IATGEOG3/IATGEOG2/AIRPORTCODE"></WC@TAG>';
//            Change($("FOAirport"));
//        </WC@IF>

        if ( SITE.Booking.FOAirport != "" ) {
			var FOAirportElem = $("FOAirport")
            FOAirportElem.value = SITE.Booking.FOAirport;
            Change( FOAirportElem );
		}

//        <WC@IF NAME="//RESPONSE/IATGEOG3" COMPARISON="NOTBLANK">
//            setTimeout("setResort();",300);
//	    </WC@IF>

		if ( SITE.isResort ) {
            setTimeout( "setResort();", 300 );
		}

//	    <WC@IF NAME="//RESPONSE/IATOFFERS" COMPARISON="NOTBLANK">
//
//            $("duration").value = <WC@TAG NAME="//RESPONSE/IATOFFERS/DURATION"></WC@TAG>;
//            $("Dep").value = '<WC@TAG NAME="//RESPONSE/IATOFFERS/IATAIRPORT/CODE"></WC@TAG>';
//
//            var DateString = '<WC@TAG NAME="//RESPONSE/IATOFFERS/DEPTDATE" />';
//            var DateShort = DateString.split("-");
//
//            $("Month").value = DateShort[1]+" "+DateShort[2];
//            setTimeout("setDay(" + DateShort[0] + ");",300);
//	    </WC@IF>

		if ( SITE.Booking.hasOffers ) {
            $("duration").value = SITE.Booking.duration;
            $("Dep").value = SITE.Booking.depAirportCode;

            var DateString = SITE.Booking.depDate;
            var DateShort = DateString.split("-");

            $("Month").value = DateShort[1]+" "+DateShort[2];
            setTimeout("setDay(" + DateShort[0] + ");",300);
		}
    }

    function setDay(theDay) {
        if (theDay < 10)
            theDay = '0'+theDay;
        $("Day").value = theDay;
    }

    function setResort() {
        var elOptions = $("Resort").options;
        for(i = 0; i < elOptions.length; i++) {
	        if(elOptions[i].text == SITE.resortName ) {
		        elOptions.selectedIndex = i;
		        break;
	        }
        }
    }

window.addEvent( "domready", function() {
	if ( $("CriteriaForm") ) {
		InitRoutes();
		setTimeout( "setISU();", 1000 );
	}
});
