var bookNowForm = -1;
var curAnimation ;
var selectedItems = [];
var dOfficeIsDT = false;
var pOfficeIsDT = false;
var driverPreviusAge = 0;
var count = 0;
var quickPickOffice = "";

function pickRegion_onChange(){
   if(dijit.byId("selPickRegion").validate()){
        var regionid = dijit.byId("selPickRegion");
        var officeStore = new dojo.data.ItemFileReadStore({url: "/ajaxcalls/getchoffices?rid="+regionid});
        dijit.byId("selPickOffice").setDisabled(true);
        dijit.byId("selDropOffice").setDisabled(true);
        dijit.byId("selPickOffice").attr("displayedValue", "Loading...");
        officeStore.fetch({
            onBegin: function(){
                dijit.byId("selPickOffice").attr("displayedValue", "Loading...");
            },
            onComplete: function(items) {
                for(var i=0;i<items.length;i++){
                    selectedItems[i] = {'abrev':items[i].abbreviation,'location':items[i].location,'name':items[i].name};
                }                
                dijit.byId("selPickOffice").setDisabled(false);
                dijit.byId("selDropOffice").setDisabled(false);
                dijit.byId("selDropOffice").store = dijit.byId("selPickOffice").store = officeStore;
                if(quickPickOffice == ""){
                    var selectedItem = items[1].name;
                    dijit.byId("selPickOffice").attr("displayedValue", selectedItem.toString());
                }else{
                    dijit.byId("selPickOffice").attr("displayedValue", quickPickOffice);
                    quickPickOffice = ""
                }                
                if(dijit.byId("selPickRegion").value == "6717"){
                    dijit.byId("selPickOffice").attr("displayedValue","Orlando Intl Airport");
                }               
            }
        });
    }
    initCalendars();
}

function pickOffice_onChange(){        
    for(var i=0;i<selectedItems.length;i++){
        if(selectedItems[i]['abrev'] == dijit.byId("selPickOffice").value){
            //(selectedItems[i]['location'] == "dt") ? pOfficeIsDT = true : pOfficeIsDT = false;
           // alert(selectedItems[i]['name']);
            dijit.byId("selDropOffice").attr("displayedValue", selectedItems[i]['name'].toString());
        }
    }
}

function dropOffice_onChange(){
//    for(var i=0;i<selectedItems.length;i++){
//        if(selectedItems[i]['abrev'] == dijit.byId("selDropOffice").value){
//            (selectedItems[i]['location'] == "dt") ? dOfficeIsDT = true : dOfficeIsDT = false;
//        }
//    }
}

function validDownTownTimes(){
    var pTime = new Date(dijit.byId("pickTime").value);
    var dTime = new Date(dijit.byId("dropTime").value);
    var returnValue = 4;
    
//    if((pOfficeIsDT==true) && (pTime.getHours() < 9 || pTime.getHours() > 17)){
//            returnValue = 1; //Downtown picko-up office will be closed
//    }else if((dOfficeIsDT==true) && (dTime.getHours() < 9 || dTime.getHours() > 17)){
//            returnValue = 2; //Downtown drop-off office will be closed
//    }else
    if(pTime.getHours() > dTime.getHours()){
        returnValue = 3;//Can not send form invalid times
    }
    return returnValue;
}

function btnCarHireSearch_onClick(){
//    var nodelist = dijit.byId("selPickRegion")._popupWidget.getItems();
//    alert(nodelist[1].innerHTML);

    var pOfficeItem = dijit.byId("selPickOffice").value
    var dOfficeItem = dijit.byId("selDropOffice").value
	/*
    var pickdate = new Date(dijit.byId("pickDate").value);
    var dropdate = new Date(dijit.byId("dropDate").value);
    var tmstpTo = Date.UTC(dropdate.getFullYear(),dropdate.getMonth(),dropdate.getDate(), 0, 0, 0, 0);
    var tmstpFrom = Date.UTC(pickdate.getFullYear(),pickdate.getMonth(),pickdate.getDate(), 0, 0, 0, 0);
    var isValidDate = tmstpTo - tmstpFrom;
	*/
    if(dijit.byId("selPickOffice").value != ""){
	if(dijit.byId("selDropOffice").value != ""){
	    if(dijit.byId("driverAge").value != "0"){
		if(pOfficeItem == "group1" || pOfficeItem == "group2"){
		    dijit.byId("selPickOffice").attr("displayedValue", "");
		}else if(dOfficeItem == "group1" || dOfficeItem == "group2"){
		    dijit.byId("selDropOffice").attr("displayedValue", "");
		}else{
		    dojo.byId("pickRegionName").value = dijit.byId("selPickRegion").getDisplayedValue();
		    dojo.byId("pickRegion").value = dijit.byId("selPickRegion");
		    dojo.byId("pickOfficeName").value = dijit.byId("selPickOffice").getDisplayedValue();
		    dojo.byId("pickOffice").value = dijit.byId("selPickOffice");
		    dojo.byId("dropOfficeName").value = dijit.byId("selDropOffice").getDisplayedValue();
		    dojo.byId("dropOffice").value = dijit.byId("selDropOffice");
		    dijit.byId("frmCarHireSearch").submit()
		    dijit.byId("messagebox").show();
		}
	    }else{
		dijit.byId("driverAge").displayMessage("Driver must be over 21 to book");
	    }
	}else{
	    dijit.byId("selDropOffice").displayMessage("Please select a pick-up office");
	}
    }else{
	dijit.byId("selPickOffice").displayMessage("Please select a drop-off office");
    }
}

function btnBookNow_onClick(i){
    if(dijit.byId("driverAge").validate()){
        dojo.byId("bookNowDriverAge"+i).value = dijit.byId("driverAge").value;
        dijit.byId("messagebox").show();
        dojo.byId("frmBookNow"+i).submit();
    }else{
        bookNowForm = i;
        window.scrollTo(0, 330);
        dijit.byId("driverAge").focus();
    }
}

function checkForBookNow(){
    if(bookNowForm > -1){
        btnBookNow_onClick(bookNowForm);
    }
}

function updatecarPrice(chkbox,price){
   var curvalue = parseFloat(dojo.byId("hirePrice").value);
   price = parseFloat(price);
   var newval = 0;

   if(chkbox.checked){
        newval = (curvalue + price).toFixed(2);
		chkbox.value = price;
   }else{
       newval = (curvalue - price).toFixed(2);
	   chkbox.value = 0;
   }
   dojo.byId("hirePrice").value = newval;
   dojo.byId("carpricetag").innerHTML = newval;
}

function btnConfirmBooking_onClick(){
    var cardInput = dijit.byId("cardNumber1");
    var cardnumber = cardInput.value;
    var endMonth = dijit.byId("endMonth").value;
    var endYear = dijit.byId("endYear").value;
    var startYear = dijit.byId("startYear").value;
    var startMonth = dijit.byId("startMonth").value;
    var today = new Date();

    var curDate = Date.UTC(today.getFullYear(), today.getMonth(), 1, 0, 0, 0, 0);
    var endDate = Date.UTC(Math.abs(endYear), Math.abs(endMonth)-1, 1, 0, 0, 0, 0);
    var startDate = Date.UTC(Math.abs(startYear), Math.abs(startMonth)-1, 1, 0, 0, 0, 0);

    if(dijit.byId("frmBookingStep3").validate()){ //CHECK TO SEE IF FORM FIELDS ARE VALID
        if((cardnumber.length < 16 || cardnumber.length > 20) && (cardInput.required)){
            //MAKE SURE USER HAS ENTERED A VALID CREDIT CARD NUMBER
	    //dijit.byId("messagebox").hide();
            dojo.byId("cardNumber1").focus();
            dijit.byId("cardNumber1").displayMessage("The card number you entered does not seem to be valid!");
        }else if((startDate > curDate) && (cardInput.required)){
	    //dijit.byId("messagebox").hide();
            dojo.byId("startYear").focus();
            dijit.byId("startYear").displayMessage("Invalid start date!");
        }else if((endDate < curDate) && (cardInput.required)){
	    //dijit.byId("messagebox").hide();
            dojo.byId("endYear").focus();
            dijit.byId("endYear").displayMessage("Invalid end date!");
        }else if(!dojo.byId("cbTerms").checked){ //USER MUST CHECK THE TERMS & CONDITIONS
	    //dijit.byId("messagebox").hide();
            dojo.byId("cbTerms").focus();
			alert('Please confirm you have read and agreed to the terms and conditions');
        }else{//ALL GOOD! SEND THE FORM
	    dijit.byId("messagebox").show();
            dojo.byId("frmBookingStep3").submit();
        }
    }
}

function btnContact_onClick(){
    if(dijit.byId("frmContact").validate()){
        dojo.byId("frmContact").submit();
    }
}

function showTerms(){
    dijit.byId("dlgTerms").show();
}

function setDestination(office,officeid,country,countryid){
    quickPickOffice = office;
    var countryname = country.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    if(countryid == dijit.byId("selPickRegion")){
        dijit.byId("selPickOffice").attr("displayedValue", office);
    }else{
        dijit.byId("selPickRegion").attr("displayedValue", countryname);    
    }    
}

function hideAll(){
    var i = 0;
    var answers = dojo.byId("answersList").childNodes.length;
    for(i=0;i<answers;i++){
        var nodeid = "a"+i;
        currAnimation = dojo.fadeOut({node: nodeid,duration: 1});
        currAnimation.play();
    }
}

function fadeInAnswer(div){
    currAnimation = dojo.fadeOut({node: currAnswer,duration: 1000});
    currAnimation.play();
    currAnimation = dojo.fadeIn({node: div,duration: 1000});
    currAnimation.play();
    currAnswer = div;
}

function checkSatNav(sat) {
	if(sat) {
		updatecarPrice(dojo.byId("selSATExtra"),selSATExtraPrice);
	} else {
		updatecarPrice(dojo.byId("selYDPExtra"),selYDPExtraPrice);
	}
	if ((dojo.byId("selYDPExtra").checked)&&(dojo.byId("selSATExtra").checked)) {
		if(sat) {
			if (dojo.byId("selYDPExtra").checked) {
				dojo.byId("selYDPExtra").checked = false;
				updatecarPrice(dojo.byId("selYDPExtra"),selYDPExtraPrice);
			}
		} else {
			if (dojo.byId("selSATExtra").checked) {
				dojo.byId("selSATExtra").checked = false;
				updatecarPrice(dojo.byId("selSATExtra"),selSATExtraPrice);
			}
		}
	}
}
/*
function updateDropOffDate() {
    var pickdate = new Date(dijit.byId("pickDate").value);
	var dt = new Date();
	dt.setTime(Date.UTC(pickdate.getFullYear(),pickdate.getMonth(),pickdate.getDate()+7, 0, 0, 0, 0));
	dijit.byId("dropDate").attr("value",dt);
}
*/
function isGoldPackage(){
	if ((isUSA == "1")&&(dojo.byId("carCover").value == "Gold")) {
		return true;
	} else {
		return false;
	}
}

function checkDriversAge(){
    if (count == 0)
		driverPreviusAge = dojo.byId("driverAge").value;
	if ((isGoldPackage())&&(dojo.byId("driverAge").value < 25)) {
		dojo.byId("btnContinue").disabled = true;
		dojo.byId("btnContinue").className = "btnContinueDisabled";
		dijit.byId("driverAges").displayMessage("The driver must be over 24 to book a Gold Package,please re-sumbit search.");

	} else {
		dojo.byId("btnContinue").disabled = false;
		dojo.byId("btnContinue").className = "btnContinue";
		dijit.byId("driverAges").displayMessage("");
	}
    if (dojo.byId("selYDPExtra")) {
		if (dojo.byId("YDP").style.display != "none") {
			if (dojo.byId("driverAge").value < 25) {
				if (!dojo.byId("selYDPExtra").checked) {
					dojo.byId("selYDPExtra").checked = true;
					updatecarPrice(dojo.byId("selYDPExtra"),selYDPExtraPrice);
				}
				// SAT NAV
				dojo.byId("selSATExtra").disabled = true;
				if(dojo.byId("selSATExtra").checked) {
					dojo.byId("selSATExtra").checked = false;
					updatecarPrice(dojo.byId("selSATExtra"),selSATExtraPrice);
				}
				dojo.byId("selYDPExtra").disabled = true;
				driverPreviusAge = dojo.byId("driverAge").value;
			} else if (count > 0) {
				if (!((driverPreviusAge >= 25)&&(dojo.byId("selYDPExtra").checked))) {
					dojo.byId("selYDPExtra").disabled = false;
					dojo.byId("selYDPExtra").checked = false;
					dojo.byId("selSATExtra").disabled = false;
					if (driverPreviusAge < 25) {
						updatecarPrice(dojo.byId("selYDPExtra"),selYDPExtraPrice);
					}
				}
				driverPreviusAge = dojo.byId("driverAge").value;
			}
		}
    }
	count++;
}

function btnContinue_onClick(url){
    dojo.byId("seatBab").value = dijit.byId("numBabSeat");
    dojo.byId("seatTod").value = dijit.byId("numTodSeat");
    dojo.byId("seatBst").value = dijit.byId("numBstSeat");
    dojo.byId("cpiExtra").value = dojo.byId("selCPIExtra").value;
    dojo.byId("derExtra").value = dojo.byId("selDERExtra").value;
    dojo.byId("satExtra").value = dojo.byId("selSATExtra").value;
    dojo.byId("ydpExtra").value = dojo.byId("selYDPExtra").value;
    dojo.byId("frmCarHireSearch").setAttribute("action", url+"/bookingstep3") ;
    dojo.byId("frmCarHireSearch").submit();
}

function btnCancelBooking_onClick(url){
    window.location = "/"+url+"/home";
}

function clearText(elemid){
    dojo.byId(elemid).select();
}

function paymentOptions_onChange(type){
    var req = "";    
    if(type == "Credit Card"){
        dojo.byId("paymentDetails").style.display = "block";
        req = true;
    }else{
        dojo.byId("paymentDetails").style.display = "none";
        req = false;
    }
    dijit.byId("cardName").attr("required", req);
    dijit.byId("houseNumber").attr("required", req);
    dijit.byId("addressLine1").attr("required", req);
    dijit.byId("townCity").attr("required", req);
    dijit.byId("country").attr("required", req);
    dijit.byId("postCode").attr("required", req);
    dijit.byId("telNumber").attr("required", req);
    dijit.byId("emailAddress").attr("required", req);
    dijit.byId("cardNumber1").attr("required", req);
    dijit.byId("startMonth").attr("required", req);
    dijit.byId("startYear").attr("required", req);
    dijit.byId("endMonth").attr("required", req);
    dijit.byId("endYear").attr("required", req);
    dijit.byId("cardSecurity").attr("required", req);
}

function printInvoice(url){
    var wInvoice = window.showModalDialog(
                                            url,
                                            0,
                                            "dialogwidth: 1000; dialogheight: 800; resizable: yes"
                                         );    
}

function what_is_this(url,title,h){
    Shadowbox.open({
            overlayColor: "#FFF",
            player:     "iframe",
	        content:    url,
            title:      title,
            height:     h,
            width:      550
    });
}

function get(obj) {
	return document.getElementById(obj);
}
