//Search: Search Type Functions
function showanimation(){
    document.getElementById('pagewidth').style.visibility='hidden';
    var h1 = document.getElementsByTagName("h1"); 
    for (var i = 0; i < h1.length; i++) { 
        h1[i].style.display = 'none'; 
    }
    document.getElementById('searching').style.display='block';
}

function showTeaserAnimation(){
    scroll(0,0);
    var pg_width = window.parent.document.getElementById('pagewidth');
    
    if (pg_width!=null)
    {
        pg_width.style.visibility='hidden';
    }
    
    var h1 = document.getElementsByTagName("h1"); 
    if(h1!=null)
    {
        for (var i = 0; i < h1.length; i++) { 
            h1[i].style.display = 'none'; 
        }
    }
    var parent_animation = window.parent.document.getElementById('searching');
    
    if(parent_animation!=null)
    {
        parent_animation.style.display='block';
    }
}

function confirmation(asMsg,asURL){
	if(confirm(asMsg)){
		document.location = asURL;
	}
}

function DisableReturn(aoForm,abDisabled){
    DisableReturn(aoForm, abDisabled, null);
}

function DisableReturn(aoForm,abDisabled,asSourceControlID){
    if (asSourceControlID == null)
    {
        document.getElementById("idddReturn_MonthYear").disabled = abDisabled;
        document.getElementById("idddReturn_Day").disabled = abDisabled;
        if(document.getElementById("idddReturn_Time")!=null)
        {  
            document.getElementById("idddReturn_Time").disabled = abDisabled;
        }
	}
	else
	{
        var lsSourceControlID = asSourceControlID.replace('$', '_');
	    document.getElementById(lsSourceControlID + "idddReturn_MonthYear").disabled = abDisabled; 
        document.getElementById(lsSourceControlID + "idddReturn_Day").disabled = abDisabled; 
        if(document.getElementById(lsSourceControlID + "idddReturn_Time")!=null)
        {
            document.getElementById(lsSourceControlID + "idddReturn_Time").disabled = abDisabled;
        }
	}
	if(document.getElementById("iImgidddReturn")!=null){
	document.getElementById("iImgidddReturn").disabled = abDisabled; }
}

//Search: Airport Related Functions
function cityItem(aiIndex,asCode,asDesc,aaDestinations){ //City Item Object
	this.cityIndex = aiIndex;
	this.cityCode = asCode;
	this.cityDesc = asDesc;
	this.cityDest = aaDestinations;
}
function changeDestinations(aeSelect){ //Used for the original FlightSearch page before being moved to a usercontrol
	var leFrom = aeSelect.iddlFrom;
	var leTo = aeSelect.iddlTo;
	changeDestinations(leFrom, leTo);
}
function changeDestinations(addlFrom,addlTo){ //Used for the original FlightSearch page after being moved to a usercontrol
	createDestinations(searchDestinationArrayByCode(addlFrom.value).cityIndex,addlTo);
}

function createDestinations(aiIndex,aeSelect){ //Create Destination drop down options
	var laDestinations;
	var laCityItem;
	laDestinations = aDestinations[aiIndex].cityDest;
	if(laDestinations.length > 0){
		aeSelect.length = 1; //Delete the existing options from the drop 'to' down.
		for(j=0;j<laDestinations.length;j++){
			laCityItem = searchDestinationArrayByCode(laDestinations[j]);
			if(typeof(laCityItem)!="undefined"){
			aeSelect.options[j] = new Option(laCityItem.cityDesc,laCityItem.cityCode);}
		}
	}
}

function searchDestinationArrayByCode(asCode){ //Search the Destination Array by Code.
	for(i=0;i<aDestinations.length;i++){
		if(aDestinations[i].cityCode == asCode){
			return new cityItem(i,aDestinations[i].cityCode,aDestinations[i].cityDesc);
		}
	}
}

//Search: Fare Type Functions
function faretype(obj){
	document.getElementById('CE').style.display = (obj.value=='CE')?'inline':'none';
    document.getElementById('FE').style.display = (obj.value=='FE')?'inline':'none';
	document.getElementById('B').style.display = (obj.value=='B')?'inline':'none';
}

//
/*
* ------------------------------------------------------------------
* Calendar Customisation Code
* ------------------------------------------------------------------
*/
var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;
var WEEKDAYS = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");

function MonthDays(yr,mth){ //Last Date in Month
	var mthE; 
  	mthE = new Date(yr,mth,1-1);
	return mthE.getDate();
}
function createDays(YrMth, Dy){ //Create Days
	var today = new Date();
	var tomorrow;
	var i = 0;
	var k,aYM,DiM,Mth;
	tomorrow = new Date(today.getFullYear(),today.getMonth(),today.getDate()+1) 
	lastday = new Date(today.getFullYear(),today.getMonth(),today.getDate()+365-1) 
	YM = YrMth.options[YrMth.selectedIndex].value
	aYM = YM.split("-");
  	DiM = MonthDays(aYM[1],aYM[0])
	Dy.length = 0;
	Mth = new Date(aYM[1],aYM[0]-1,1)
	startDay = (tomorrow.getTime() > Mth.getTime())?tomorrow.getDate():1;
	for(k = startDay;k < DiM + 1;k++){
		Mth = new Date(aYM[1],aYM[0]-1,k)
		if(Mth <= lastday)
		{
			Dy.options[i] = new Option(WEEKDAYS[Mth.getDay()]+' '+k,String('0'+k).substring(String('0'+k).length,String('0'+k).length-2));
			i++;
		}
	}
}
function createDaysOffset(YrMth, Dy, offset){ //Create Days
	var today = new Date();
	var tomorrow;
	var i = 0;
	var k,aYM,DiM,Mth;
	tomorrow = new Date(today.getFullYear(),today.getMonth(),today.getDate()+offset) 
	lastday = new Date(tomorrow.getFullYear(),tomorrow.getMonth(),tomorrow.getDate()+365-2) 
	YM = YrMth.options[YrMth.selectedIndex].value
	aYM = YM.split("-");
  	DiM = MonthDays(aYM[1],aYM[0])
	Dy.length = 0;
	Mth = new Date(aYM[1],aYM[0]-1,1)
	startDay = (tomorrow.getTime() > Mth.getTime())?tomorrow.getDate():1;
	for(k = startDay;k < DiM + 1;k++){
		Mth = new Date(aYM[1],aYM[0]-1,k)
		if(Mth <= lastday)
		{
			Dy.options[i] = new Option(WEEKDAYS[Mth.getDay()]+' '+k,String('0'+k).substring(String('0'+k).length,String('0'+k).length-2));
			i++;
		}
	}
}

function setReturnDate(fromYM,fromD,toYM,toD){ //Set Return Date
	if(fromYM.selectedIndex > toYM.selectedIndex){
		toYM.selectedIndex = fromYM.selectedIndex; //Set the month
		createDaysOffset(toYM, toD,2); //Create days of month
		toD.selectedIndex = fromD.selectedIndex; //Set the day
	}else{
		if(fromD.selectedIndex > toD.selectedIndex){
			toD.selectedIndex = fromD.selectedIndex; //Set the day
		}
	}
	//FA:SCAN01042009 - Set Return Date when previous month selected
	if(fromYM.selectedIndex < toYM.selectedIndex){
		toYM.selectedIndex = fromYM.selectedIndex; //Set the month
		createDaysOffset(toYM, toD,1); //Create days of month
		toD.selectedIndex = fromD.selectedIndex; //Set the day
	}	
	if(fromD.selectedIndex < toD.selectedIndex){
			toD.selectedIndex = fromD.selectedIndex; //Set the day
		}
	
}

function setReturnDatePlusOne(fromYM,fromD,toYM,toD){ //Set Return Date
	if(fromYM.selectedIndex > toYM.selectedIndex){
		toYM.selectedIndex = fromYM.selectedIndex; //Set the month
		createDaysOffset(toYM, toD,2); //Create days of month
		toD.selectedIndex = fromD.selectedIndex +1; //Set the day
	}
	if(fromYM.selectedIndex == toYM.selectedIndex)
	{
		if(fromD.selectedIndex >= toD.selectedIndex){
	        if(fromD.selectedIndex == (fromD.length-1)) {
	            toYM.selectedIndex = fromYM.selectedIndex + 1; //Set the month
		        createDaysOffset(toYM, toD,2); //Create days of month
		        toD.selectedIndex = 0;
	        } 
	        else 
	        {
	            var len_diff = toD.length - fromD.length;       // added this to handle diff length of days in 2 dropdowns
                toD.selectedIndex = fromD.selectedIndex +1+len_diff; //Set the day
	        }
		}
	}
}

function setDropDownDate(dDate,YrMth,Dy){
	aDate = dDate.split("-");
	for(i=0;i<YrMth.length;i++){
		if(YrMth.options[i].value==aDate[0]+'-'+aDate[1]){
			YrMth.selectedIndex=i;
		}
	}
	createDays(YrMth, Dy);
	for(i=0;i<Dy.length;i++){
		if(Dy.options[i].value==aDate[2]){
			Dy.selectedIndex=i;
		}
	}
	//Set the return date if not the to date element
	//if(YrMth.id.indexOf('to_date')!=0 && YrMth.form.to_date_monthyear){ 
	//	setReturnDate(YrMth.form.from_date_monthyear,YrMth.form.from_date_day,YrMth.form.to_date_monthyear,YrMth.form.to_date_day);
	//}
}

function setCalendarField(id){
 	document.getElementById(id + '_Date').value = document.getElementById(id+'_MonthYear').value+'-'+document.getElementById(id+'_Day').value;	
}
// This function gets called when the end-user clicks on a date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  var elYrMth = document.getElementById(cal.sel.id.replace('_Date','_MonthYear'));
  var elDy = document.getElementById(cal.sel.id.replace('_Date','_Day'));
  setDropDownDate(date,elYrMth,elDy);
    
//ND:SCAN23042009 - Set Return Date/Check-out Date when when Depart/Check-in date is selected in calendar 
if(elYrMth.id.indexOf("Depart") != -1 && elDy.id.indexOf("Depart") != -1)
{
    var elYrMthOut =  document.getElementById(elYrMth.id.replace('Depart','Return'));
    var elDyOut = document.getElementById(elDy.id.replace('Depart','Return'));
    setReturnDate(elYrMth,elDy,elYrMthOut, elDyOut);
}
else if(elYrMth.id.indexOf("CheckIn") != -1 && elDy.id.indexOf("CheckIn") != -1)
{
    var elYrMthOut =  document.getElementById(elYrMth.id.replace('CheckIn','CheckOut'));
    var elDyOut = document.getElementById(elDy.id.replace('CheckIn','CheckOut'));
    setReturnDatePlusOne(elYrMth,elDy,elYrMthOut, elDyOut);
}

if(cal.dateClicked){
  	cal.callCloseHandler();
  }
}
function closeHandler(cal) {
  cal.hide();                        // hide the calendar
  _dynarch_popupCalendar = null;
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, format) {
  var today = new Date();
  var el = document.getElementById(id + '_Date');
  setCalendarField(id);
  if(_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  }else{
    var cal = new Calendar(1, null, selected, closeHandler);
    cal.showsTime = false;
    cal.showsOtherMonths = true;
    cal.weekNumbers=false;
    cal.setDisabledHandler(isDisabled);
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(today.getFullYear(), today.getFullYear()+1);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use
  _dynarch_popupCalendar.showAtElement(el, "Br");        // show the calendar
  return false;
}

function isDisabled(date) {
  var today = new Date();
  return !((date.getTime() - today.getTime()) / DAY > 0 && (date.getTime() - today.getTime()) / DAY < 354)
}


/* Fare Rules */
function togglefarerule(aoLink,aoRule)
{
    if(aoRule.style.display == 'none')
    {
        aoRule.style.display = 'block';
        aoLink.innerHTML = 'Hide fare conditions';
    }else
    {
         aoRule.style.display = 'none';
        aoLink.innerHTML = 'Show fare conditions';
    }
}

function togglefareruleimages(aoRule,asIUrl,asType)
{
    //alert(document.getElementById('imgToggleFare' + asType).src);
    if(aoRule.style.display == 'none')
    {
        aoRule.style.display = 'block';
        document.getElementById('imgToggleFare' + asType).src = asIUrl + 'buttons/button_minus.gif';
        document.getElementById('imgToggleFare' + asType).alt = "Hide fare conditions";
    }
    else
    {
        aoRule.style.display = 'none';
        document.getElementById('imgToggleFare' + asType).src = asIUrl + 'buttons/button_plus.gif';
        document.getElementById('imgToggleFare' + asType).alt = "Show fare conditions"
    }
    return true;
    //alert(document.getElementById('imgToggleFare' + asType).src);
}


/*
* ------------------------------------------------------------------
Points Calculator
* ------------------------------------------------------------------
*/
var req;

function Initialize()
{
    //updated - better coding - to avoid exception happening
    if (window.XMLHttpRequest) 
    { 
        req = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    { 
     try 
        {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } 
     catch (e) 
        {
        try 
            {
               req = new ActiveXObject("Microsoft.XMLHTTP");
            } 
        catch (e) 
            {
                req = null;
            }
        }
    }                          
}

function Div(a, b) { return Math.floor(a/b) }

function SendQuery(aoPoints, asUrl, aiTotalPoints, asQuoteId, aiRounding, asQueryType)
{

	if (aoPoints.value == '') { aoPoints.value = 0; }
	var ldPoints = aoPoints.value.replace(/[^0-9]+/gi,"");

	if (ldPoints == '') { ldPoints = 0; }
	aoPoints.value = ldPoints;


	if (asQuoteId == '') 
	{
	    asQuoteId = document.getElementById("ihdnQuoteId").value;
	}
	
	if (document.getElementById("points-calculator-error1").value != '')
	{
	 	var loErrorLoc1 = document.getElementById("points-calculator-error1");
		var loErrorLoc2 = document.getElementById("points-calculator-error2");
		 	
		loErrorLoc1.innerHTML = "";
		loErrorLoc2.innerHTML = "";
	}

	// set this here so that the points format is consistent
	document.getElementById("itxbCalculatorPoints").value = addCommas(aoPoints.value);

    //Commented for VA requirement - ND
    /*
	var url = asUrl + "flight/calculatorrequest.aspx?points="+points+"&maxpoints="+aiTotalPoints+"&quote_id=" + asQuoteId+"&accommodation=true";
	if(req!=null)	{
		req.onreadystatechange = ProcessAccommodation;
		req.open("GET", url, true);
		req.send(null);
	}
	*/
	
	/* Using POST Request for VA Requirement */
	var url = asUrl + "flight/calculatorrequest.aspx";
	var params = "points="+points+"&maxpoints="+aiTotalPoints+"&quote_id=" + asQuoteId+"&accommodation=true";
	
	if(req!=null)	{
		req.onreadystatechange = Process;
		req.open("POST", url, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", params.length);
        req.setRequestHeader("Connection", "close");
        req.send(params);
	}

	
}

function Process()
{
	if (req.readyState == 4)
	{ 	// only if "OK"
		if (req.status == 200)
		{
			if(req.responseText!="")
			{
				var lsPay = getXMLResponse('pay');
				var lsError = getXMLResponse('error');
				var lsPoints = getXMLResponse('points');

				if(lsError.length > 0)
				{
				    var loErrorLoc1 = document.getElementById("points-calculator-error1");
				 	var loErrorLoc2 = document.getElementById("points-calculator-error2");

					loErrorLoc1.innerHTML = lsError;
					loErrorLoc2.innerHTML = lsError;
			    }
				document.getElementById("itxbCalculatorPay").value = lsPay; //req.responseText;
				document.getElementById("itxbCalculatorPoints").value = lsPoints;
			}
		}
		else
		{
		    var loErrorLoc1 = document.getElementById("points-calculator-error1");
		 	var loErrorLoc2 = document.getElementById("points-calculator-error2");

			loErrorLoc1.innerHTML = "";
			loErrorLoc2.innerHTML = "";

			lsError = "There was a problem retrieving data:<br />"+req.statusText;

		    loErrorLoc1.innerHTML = lsError;
			loErrorLoc2.innerHTML = lsError;
		}
	}
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function SendQuery(aoPoints,asUrl,aiTotalPoints,asQuoteId,aiRounding)
    {
	var mod10;
 	var points = aoPoints.value.replace(/[^0-9]+/gi,"");
 	var lsErrorText = "";
 	var loErrorLoc1 = document.getElementById("points-calculator-error1");
 	var loErrorLoc2 = document.getElementById("points-calculator-error2");
 	loErrorLoc1.innerHTML = "";
	loErrorLoc2.innerHTML = "";
	aoPoints.value = points;	
	mod10 = points % aiRounding;
	
	if ((mod10) > 0 )	{
			points = (mod10 > 5)?Number(points) + (aiRounding-mod10):points = Number(points) - mod10;
			aoPoints.value = points;	
			lsErrorText = "Points entered must be in multiples of " + aiRounding + ". This has been changed for you.";
			loErrorLoc1.innerHTML = lsErrorText;
			loErrorLoc2.innerHTML = lsErrorText;
	}
	if (points==''){
			lsErrorText = "Please enter a points amount.";
			loErrorLoc1.innerHTML = lsErrorText;
			loErrorLoc2.innerHTML = lsErrorText;			
			return false;
	}
	
	
	
	

	Initialize();
	/* Commented ND
	var url = asUrl + "flight/calculatorrequest.aspx?points="+points+"&maxpoints="+aiTotalPoints+"&quote_id=" + asQuoteId;
	//window.prompt("the url",url);
	if(req!=null)	{
		req.onreadystatechange = Process;
		req.open("GET", url, true);
		req.send(null);
	}
	*/
	/* Using POST Request for VA Requirement */
	var url = asUrl + "flight/calculatorrequest.aspx";
	var params = "points="+points+"&maxpoints="+aiTotalPoints+"&quote_id=" + asQuoteId;
	
	if(req!=null)	{
		req.onreadystatechange = Process;
		req.open("POST", url, true);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", params.length);
        req.setRequestHeader("Connection", "close");
        req.send(params);
	}
	
}
function Process(){
    var loErrorLoc1 = document.getElementById("points-calculator-error1");
 	var loErrorLoc2 = document.getElementById("points-calculator-error2");
	if (req.readyState == 4){ // only if "OK"
		if (req.status == 200){
			if(req.responseText!=""){
				var lsPay = getXMLResponse('pay')
				var lsError = getXMLResponse('error')
				if(lsError.length > 0){
				    loErrorLoc1.innerHTML = lsError;
				    loErrorLoc2.innerHTML = lsError;
			    }
				document.getElementById("itxbCalculatorPay").value = lsPay; //req.responseText;
				//alert(lsPay);
			}
		}else{
		    lsError = "There was a problem retrieving data:<br />"+req.statusText;
		    loErrorLoc1.innerHTML = lsError;
			loErrorLoc2.innerHTML = lsError;
		}
	}
}

function getXMLResponse(vLabel){
	var vLabelLen = vLabel.length
	var ResponseData = req.responseText
	var Len = ResponseData.length
	var i = 0
	var cEnd
	while(i<Len){
		var j = i + vLabelLen
		if(ResponseData.substring(i,j)==vLabel){
			cEnd = ResponseData.indexOf(";",j)
			if(cEnd==-1){
				cEnd = ResponseData.length
			}
			return unescape(ResponseData.substring(j+1,cEnd));
		}
		i++
	}
	return "";
}

function changeThumbnail(stringURL,caption)
{
    document.getElementById('imgHotelImage').src = stringURL;
    document.getElementById('ilblCaption').innerHTML = caption;
}

function changeRoomThumbnail(stringURL)
{
    document.getElementById('imgRoom').src = stringURL;
    //document.getElementById('ilblRoomCaption').innerHTML = caption;
}

function tooltip(target_items, name, x, y){
    $(target_items).each(
        function(i){
            var lsTitle = $(this).attr('title');
	            $("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
	        var my_tooltip = $("#"+name+i);
	        $(this).removeAttr("title").mouseover(
	            function(){
			        my_tooltip.css({opacity:1, display:"none"}).fadeIn(400);
	            }
	        ).mousemove(
	            function(kmouse){
			        my_tooltip.css({left:kmouse.pageX+x, top:kmouse.pageY+y});
	            }
	        ).mouseout(
	            function(){
			        my_tooltip.fadeOut(400);
	            }
	        );
        }
    );
}

function clearForms()
{
  var i;
  if (document.forms != null)
  {
      for (i = 0; (i < document.forms.length); i++) {
        document.forms[i].reset();
      }
  }
}
