/*
   User defined functions.
   
   Relies on calendar.js to be included on the same page. (see use of fn calculateDuration())
*/

/*
 * Function to submit a date change. Expects the inDate to be of format dd/mm/yyyy. Will submit only the date that needs to change. 
 */
 
function submitDateChange(inDate, inDateFld, inIncrement, inComponentId)
{
   /* date is dd/mm/yyyy */
   var pen_dateArr = inDate.split('/');
   
   var pen_date = new Date();
	
   /* setUTCFullYear expects months in the range of 0 to 11 */
   pen_date.setUTCFullYear(pen_dateArr[2], (pen_dateArr[1] - 1), pen_dateArr[0]); 
	
   /* increment date */

   var newDate = parseInt(pen_date.getUTCDate()) + parseInt(inIncrement);

   pen_date.setUTCDate(newDate);
 	 
   /* need to submit date in format dd/mm/yyyy */
   var newMonth = (pen_date.getUTCMonth() + 1);
   
   newMonth = newMonth > 9 ? newMonth : '0' + newMonth;
       
   var submitDate = pen_date.getUTCDate() + "/" + newMonth + "/" + pen_date.getUTCFullYear();
  
   /* inComponentId, inReqFldId, inReqValue */ 
   cdpForm.updateComponentSingleReqWrapper(inComponentId, inDateFld, submitDate, 'processRequest');
}

/*
 * Function ensures the conditions are acknowledged before the user is allowed to submit.
 */ 
function validateBookingForm(inErrorDiv)
{
	var isMissingField = false;
    
	document.getElementById('contactErrorMsg').style.display = "none";
	document.getElementById('contactErrorMsg').innerHTML = "";
	document.getElementById('creditErrorMsg').style.display = "none";
	document.getElementById('creditErrorMsg').innerHTML = "";
    //document.getElementById(inErrorDiv).style.display = "none";	
	
    if(!fieldSpecifiedCorrectly('pgrContact', 'Contact Phone', 'contactErrorMsg'))
		isMissingField = true;

    if(!fieldSpecifiedCorrectly('pgrEmail', 'Email', 'contactErrorMsg')) 
		isMissingField = true;		
    
    if(!fieldSpecifiedCorrectly('pgrAddress1', 'First Street Address Line', 'contactErrorMsg')) 
		isMissingField = true;
	
	if(!fieldSpecifiedCorrectly('town', 'Town', 'contactErrorMsg')) 
		isMissingField = true;
	
	if(!fieldSpecifiedCorrectly('state', 'State', 'contactErrorMsg')) 
		isMissingField = true;
	
	if(!fieldSpecifiedCorrectly('postcode', 'Postcode', 'contactErrorMsg')) 
		isMissingField = true;
		
	if(!fieldSpecifiedCorrectly('cardName', 'Credit Card holder name', 'creditErrorMsg'))
		isMissingField = true;

    if(!fieldSpecifiedCorrectly('cardNumber', 'Credit Card number', 'creditErrorMsg')) 
		isMissingField = true;		
    
    if(!fieldSpecifiedCorrectly('expDateMonth', 'Credit Card expiry Month', 'creditErrorMsg')) 
		isMissingField = true;
    
    if(!fieldSpecifiedCorrectly('expDateYear', 'Credit Card expiry Year', 'creditErrorMsg')) 
		isMissingField = true;
    

	var country = document.getElementById("country");
	document.getElementById("pgrAddress3").value = country.options[country.selectedIndex].value;

    if (document.getElementById('accept1') && !document.getElementById('accept1').checked)
    {
		document.getElementById(inErrorDiv).style.display = 'none';
		document.getElementById(inErrorDiv).style.display = '';
		return;
    }
    
    if (document.getElementById('accept2') && !document.getElementById('accept2').checked)
    {
		document.getElementById(inErrorDiv).style.display = 'none';
		document.getElementById(inErrorDiv).style.display = '';
		return;
    }
    
    if (document.getElementById('accept3') && !document.getElementById('accept3').checked)
    {
	    document.getElementById(inErrorDiv).style.display = 'none';
	    document.getElementById(inErrorDiv).style.display = '';
	    return;
    }		

	if (isMissingField) return;	
	
	concatFields();
	
    cdpForm.completeBookingWrapper('finalizeBooking');
}

function fieldSpecifiedCorrectly(inId, inDescription, inErrorType){
	var field = document.getElementById(inId);

	if (field && field.value.length == 0)
	{
		document.getElementById(inErrorType).innerHTML += "Must enter the " + inDescription + ".<br/>";
		document.getElementById(inErrorType).style.display = "block";
		return(false);
	}
	
	if (field.value.indexOf(',') >= 0)
	{
		document.getElementById(inErrorType).innerHTML += "Cannot enter a comma (,) in the field " + inDescription + ". <br/>";
		document.getElementById(inErrorType).style.display = "block";
		return(false);
	}

	return(true);
}

function concatFields()
{	
	var fields = '';
;
	fields += document.getElementById('town').value + ',';
	fields += document.getElementById('state').value + ',';
	fields += document.getElementById('postcode').value;

	
	document.getElementById("pgrAddress2").value = fields;
	
	fields = '';
	fields += document.getElementById('expDateMonth').value + '/';
	fields += document.getElementById('expDateYear').value;
	
	document.getElementById("cardExp").value = fields;
} 

/*
 * Function ensures the conditions are acknowledged before the user is allowed to submit. Supports links
 */ 
function validateBooking(inErrorDiv)
{
    if (document.getElementById('accept1') && !document.getElementById('accept1').checked)
    {
		document.getElementById(inErrorDiv).style.display = 'none';
		document.getElementById(inErrorDiv).style.display = '';
    }
    
    if (document.getElementById('accept2') && !document.getElementById('accept2').checked)
    {
		document.getElementById(inErrorDiv).style.display = 'none';
		document.getElementById(inErrorDiv).style.display = '';
    }
    
    if (document.getElementById('accept3') && !document.getElementById('accept3').checked)
    {
	    document.getElementById(inErrorDiv).style.display = 'none';
	    document.getElementById(inErrorDiv).style.display = '';
    }
    
    cdpForm.completeBookingWrapper('finalizeBooking');
}

function closeWorkingDiv()
{
    document.getElementById('componentWorkingSection').innerHTML = "&nbsp;";
}

function verifyPromoCdp(arg_form, inStartDate, inEndDate, inDepFltSched, inRetFltSched)
{
	if (document.getElementById("depCityCdp") != null)
	{
		var depCity = document.getElementById("depCityCdp").value;
	    if (depCity == " ")
	    {
	    	alert("Enter a departure city");
	    	return(false);
	    }
	}
    
    if (!verifyCdpDates(inStartDate, inEndDate, inDepFltSched, inRetFltSched))
        return(false);
    
    if (!checkAdultInfant())
    	return(false);
    
    return(verifyCdp(arg_form));
}

function verifyCdpDates(inStartDate, inEndDate, inDepFltSched, inRetFltSched)
{
    var depDate = new Date(convertDate(document.getElementById("startDate").value)); 
    var retDateVal = document.getElementById("endDate").value
   
    if (!retDateVal || retDateVal.length == 0)
    {
        alert("Enter a returning date");
        return(false);
    }    
      
    var retDate = new Date(convertDate(retDateVal));
 
    if (!validateDuration(depDate, retDate))
    {
        alert("duration does not validate");
        return(false);
    }
        
    // Variables newDow, startDate, and stopDate in calendar.js
    negDow = inDepFltSched;    
    startDate = new Date(inStartDate);
    stopDate = new Date(inEndDate); 
    
    
    if (disallowDate(depDate))
    {
        alert("No departing flights available for the specified date");
        return(false);
    }    
    
    negDow = inRetFltSched;

        
    if (disallowDate(retDate))
    {
        alert("No returning flights available for the specified date");
        return(false);
    }   
    
    return(true);
}

function validateDuration(inDepDate, inRetDate)
{
    var duration = calculateDuration(inDepDate, inRetDate);
    
    if (duration < 1)
    {
        alert("Return date must be after the departing date");
        return(false);
    }
    
    document.getElementById("duration").value = duration;
    
    return(true);
}

function depCityChange()
{
    document.getElementById("startDate").value = "";
    document.getElementById("endDate").value = "";
    var depCity = document.getElementById("depCityCdp").value;
    
    var startDateFltSch = document.getElementById("startDateFltSch");
    var endDateFltSch = document.getElementById("endDateFltSch");

    startDateFltSch.innerHTML = dowValues(fltDepSched[depCity]);
    if (startDateFltSch.innerHTML.length == 0)
        startDateFltSch.style.display = "none";   
    else
        startDateFltSch.style.display = "";  
    
    endDateFltSch.innerHTML = dowValues(fltRetSched[depCity]);
    if (endDateFltSch.innerHTML.length == 0)
        endDateFltSch.style.display = "none"; 
    else
        endDateFltSch.style.display = "";    
    
}

/**
 * Expects Day of Week String in form of 1,2,3 .. 
 * @param {Object} inDowStr
 */
function dowValues(inDowStr)
{
    var weekArray = new Array("", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun");
    var fltStr = ""
        
    if (inDowStr == null)
        return(fltStr);
        
    var dowStrArr = inDowStr.split(",");
    
    if (dowStrArr.length == 0)
		return(fltStr);
		   
    for(var i = 0; i < dowStrArr.length; i++)
    {
		var dayOfWeekNum = dowStrArr[i];
		
		if (!dayOfWeekNum || dayOfWeekNum > 7 || dayOfWeekNum < 0)
			continue;
			
        fltStr = fltStr + weekArray[dayOfWeekNum];
        
        if (i != (dowStrArr.length - 1))
            fltStr = fltStr + ", ";
    }
  
  	if (fltStr.length == 0)
		return(fltStr);
		
    return("No Flights: " + fltStr);
}

function verifyCdp(arg_form)
{
    lclMsg = "";
    totalPassengers =parseInt (arg_form.child_1.value) +  parseInt (arg_form.adult_1.value);
    
    if (( totalPassengers < minTotPax) || ( totalPassengers > maxTotPax))
    {
       lclMsg += "- Selected a minimum of " + minTotPax + " and a maximum " + maxTotPax + " passengers (incl. children)\n";         
    }
    
    if(arg_form.child_1.value > 0)
    {
    	for(i = 1; i <= arg_form.child_1.value; i++)
    	{
    		if (document.getElementById("cdpRm1ChildAge" + i).value == 0)
    		{
    			lclMsg += "- Entered ages of all children";
    			break;
    		}
    	}
    }
    if (minDuration!=0 || maxDuration != 0)
    {
        
        selectedStay = parseInt (arg_form.duration.value); 
        
        if (selectedStay < minDuration )
        {
            lclMsg += "- The minimum number of nights allowed is " + minDuration +" \n";    
            
        }
        if (selectedStay > maxDuration)
        {
            lclMsg += "- The maximum number of nights allowed is " + maxDuration +" \n";        
        }
        
        //test if number is entered in number of nights.
        testVar = isNaN(selectedStay);
        if (testVar == true){
            lclMsg += "- Please enter a valid number for nights \n";    
        }
    }
    
    if(lclMsg!="")
    {
        lclMsg = "Please ensure you have...\n" + lclMsg;
        alert(lclMsg);
        return false;
    }

    var adult_count = arg_form.adult_1.value;
    var child_count = arg_form.child_1.value;
    var room_mixes = adult_count + "A";
    if (child_count > 0)
    {
        room_mixes += child_count + "C";
        for (i = 1; i <= child_count; i++)
            room_mixes += "-" + document.getElementById("cdpRm1ChildAge" + i).value;
    }          

    document.getElementById("room_mixes").value = room_mixes;   

    return true;
}

function displayCdpChildAgeBoxes(numChild)
{
    if (document.getElementById("bookingPanel")!=null){
        // children allowed for hotel and holiday booking
        var chdds = document.getElementById("bookingPanel").getElementsByTagName("dd");
        totNum = chdds.length;
    } else {
        //fixed number for site main search box hotel booking
        totNum = 4;
    }
    document.getElementById("ChildAgeRow").style.display = numChild > 0 ? "" : "none";
    for (i=1; i<=numChild; i++)
        document.getElementById("cdpRm1ChildAge" + i).style.display = "";
    for (; i<=totNum; i++)
        document.getElementById("cdpRm1ChildAge" + i).style.display = "none";
    
}

function goButtonValidate(inDurationField)
{
    var durationFld = document.getElementById(inDurationField);
    if (durationFld.value == null || durationFld.value.length == 0)
    {
        return(false);
    }
    return(true);
}

function checkAdultInfant()
{
	var i, child_age, number_infant = 0;
	var adults = document.getElementById("cdpRm1AdultCount").value;
	var children = document.getElementById("cdpRm1ChildCount").value;

	for(i = 1; i <= children; i++)
	{
		child_age = document.getElementById("cdpRm1ChildAge" + i).value;
		if (child_age == 0)
		{
			alert("Enter ages of all children");
			return(false);
		}
		else if (child_age == 1)
		{
			number_infant++;
		}
	}
	
	if (!hasFlights)
		return(true);
	
	if (adults < number_infant)
	{
		alert("Number of children under the age of 1 can not be greater than number of adults");
		return(false);
	}
	return(true);
}

