var ACCOM_CALENDAR_URL = "/templates/tc/pieces/ajax/accomCalender.jsp";
var galleryImage = 1;
var isPageLoaded = false;
var isAltFlightsShown=false;
var isCalendarShown = true;

function onloadEvent(funcToLoad) {

  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = funcToLoad;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      funcToLoad();
    }
  }
}

function getDimensions() 
{
	var w = 0;
	var h = 0;
//IE
	if(!window.innerWidth)
	{
//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return [h, w];
}

onloadEvent(function() {
	isPageLoaded = true;
})

function checkPageLoaded() {
	return isPageLoaded;
}


function changeImage(imageId){
	if(slideShowEnabled == 1) disableSlideShow();
	if(document.getElementById('mainImage') && document.getElementById('img'+imageId)){
		document.getElementById('mainImage').src = document.getElementById('img'+imageId).src;
		imgNumber = imageId;
	}
}
var lastClickedValue =1;
function changeGalleryPagination(value,maxPages,index){
	if(document.getElementById('galPag'+value)){
		document.getElementById('galPag'+value).style.display = 'block';
	}
	if(value != galleryImage ){
	if(document.getElementById('galPag'+galleryImage)) {
		document.getElementById('galPag'+galleryImage).style.display = 'none';
			var href = document.getElementById('galpos'+value).getAttribute("href");
			    this.document.getElementById('galpos'+value).setAttribute('href_bak', href);
				this.document.getElementById('galpos'+value).style.color="gray";
				this.document.getElementById('galpos'+value).removeAttribute('href'); 
	}

		for(var k=0;k<maxPages;k++){
		if(k==index ){
		var href_bak= document.getElementById('galpos'+lastClickedValue).getAttribute("href_bak");
		if(href_bak == null){
		href_bak = document.getElementById('galpos'+lastClickedValue).getAttribute("href");
		}
		this.document.getElementById('galpos'+lastClickedValue).setAttribute('href', href_bak);
		this.document.getElementById('galpos'+lastClickedValue).style.color="#2EB135";
		}
	}


	}
	
	
	galleryImage = value;
	lastClickedValue = value;
}

function changerDisplay(id){
	if(document.getElementById(id)){
		if(document.getElementById(id).style.position == 'absolute'){
			document.getElementById(id).style.position = 'static';
			document.getElementById(id).style.left = '0px';
		} else if(document.getElementById(id).style.position == 'static'){
			document.getElementById(id).style.position = 'absolute';
			document.getElementById(id).style.left = '-500000px';
		}
	}
	
}
function playSlideShow(){
	if(slideShowEnabled == 1){
		if(document.getElementById('img'+slideShowImage)){
			if(document.getElementById('mainImage') && document.getElementById('img'+slideShowImage)){
				document.getElementById('mainImage').src = document.getElementById('img'+slideShowImage).src;
				imgNumber = slideShowImage;
				if(slideShowImage < maxNumber){
					++slideShowImage;
				} else {
					slideShowImage = 1;
				}
			}
			t=setTimeout("playSlideShow()",4000);
		}
	}
}

function enableSlideShow(){
	slideShowEnabled = 1;
	if(document.getElementById('playSlide')) document.getElementById('playSlide').style.display = 'none';
	if(document.getElementById('stopSlide')) document.getElementById('stopSlide').style.display = 'inline';
}

function disableSlideShow(){
	slideShowEnabled = 0;
	clearTimeout(t);
	if(document.getElementById('playSlide')) document.getElementById('playSlide').style.display = 'inline';
	if(document.getElementById('stopSlide')) document.getElementById('stopSlide').style.display = 'none';
}

function getSiMigrationId(){
	var c_name = "SIVISITOR";
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
	    		c_start=c_start + c_name.length+1;
	    		c_end=document.cookie.indexOf(";",c_start);
	   		if (c_end==-1) c_end=document.cookie.length;
	   		return unescape(document.cookie.substring(c_start,c_end));
	    	}
	  }
	return "";
}

function doCost(altPackageId, avgPrice, totalPrice, departureDate){
	if (altPackageId) {
		AjaxSearchResultTools.setSelectedPackage(altPackageId, function(data){
      setPrice(avgPrice,totalPrice,altPackageId,departureDate);
		});
		priceUpdated();
	} else {
		document.packageCost.submit();
	}
}
//function to put current time into form input
function setTimerValue(){
	var curDate = new Date();
	jQuery('#timerValue').val(curDate.getTime());
}
function getAllAlternativeFlights(path, id){

	document.getElementById("alternateFlightOptions").innerHTML = "<img src='/images/siteElements/loading.gif' alt='Loading' />";
	document.packageCost.selectHolidayIndex.value = document.getElementsByName("altflightoption")[0].value;
	document.getElementById('holidayIndex').value = document.getElementsByName("altflightoption")[0].value;
	//document.packageCost.bookNowHolidayIndex.value =  document.getElementsByName("altflightoption")[0].value;

	if (id == undefined) {
		id = document.getElementsByName("altflightoption")[0].value;
	}
	if(path && id){
		AjaxSearchResultTools.getAlternateFlightContent(path, id, function(data) {
			document.getElementById("alternateFlightOptions").innerHTML = data;	
			if(jQuery(data).find(".accommainflight").size() == 0){
				jQuery("#altFlightsSpan").css("display", "none");
			} else {
				jQuery("#altFlightsSpan").css("display", "block");
			};
			
		});
	}

}

function toggleAltFlights()
{
	if(!isAltFlightsShown){	
		document.getElementById("altFlightsSpan").innerHTML="Hide alternative flights";
		jQuery("#alternateFlightOptions").css("display", "block");
		altflightTracking('content/altflight/show');
		isAltFlightsShown=true;
	}else{
		jQuery("#alternateFlightOptions").css("display", "none");
		document.getElementById("altFlightsSpan").innerHTML="Show alternative flights";
		altflightTracking('content/altflight/hide');
		isAltFlightsShown=false;
	}
	
}

function changePackagePrice(totalPrice, avgPrice, currency,radFlag, packageId){

	window.location.href="#dummyAnchrForLink";
	if(avgPrice){
		document.getElementById("pricepp").innerHTML = currency +""+ roundNumber(avgPrice,0);// + "<span class='pp'>pp</span>";
	}
	if(totalPrice){
		if(document.getElementById("totalPriceText") !=null){
			//document.getElementById("totalPriceText").innerHTML="Total Price:";
			document.getElementById("totalPriceText").style.display = 'inline';
		}
		document.getElementById("totalprice").innerHTML = currency +""+ roundNumber(totalPrice,0);	
	}
	var oldHtml= document.getElementById("flightfirst").innerHTML;
	document.getElementById("flightfirst").innerHTML = "";
	
   

	var selected = 0;
	var isfound =false;
	var altid= packageId;
	if(document.accommodationForm.altflightoption != undefined){

	
		for (i=0;i<document.accommodationForm.altflightoption.length;i++){
			if (document.accommodationForm.altflightoption[i].checked==true){
				id = document.accommodationForm.altflightoption[i].value;
				document.getElementById(id+"_accomflightprice").innerHTML ="";
				document.getElementById("flightfirst").innerHTML = document.getElementById(id+"_altFlight").innerHTML;
				document.accommodationForm.altflightoption[0].checked = true;
				document.getElementById("altflightoption").checked=true;
				document.getElementById("alternateFlightOptions").style.display = 'none';
				document.getElementById("altFlightsSpan").innerHTML="Search alternative flights";
				isAltFlightsShown=false;
				if(id){
					//alert("i am here" +id);
					document.packageCost.selectHolidayIndex.value = id;
					document.getElementById('holidayIndex').value = id;
					//document.packageCost.bookNowHolidayIndex.value = id;
					AjaxSearchResultTools.setSelectedPackage(id, function(data) {
						//alert("hi");
					});
					
				}

				isfound = true;
			}
		}
		
		
	}

	if(!isfound){        
		document.getElementById("flightfirst").innerHTML = oldHtml;
		if(radFlag!='1')
		{      
     	for (i=0;i<document.accommodationForm.altflightoption.length;i++){
		if(document.accommodationForm.altflightoption[i] != undefined){
			if(document.accommodationForm.altflightoption[i].value==altid ){
		      document.accommodationForm.altflightoption[i].checked = true;
			  }
			else
			{	
			document.accommodationForm.altflightoption[i].checked = false;
            }
		 }
	   }
		
	  }
	}
	priceUpdated();
}

function setPrice(averagePrice,totalPrice, packageId, departureDate){
	currency = (totalPrice + "").substring(0,1);
	document.getElementById('pricepp').innerHTML = averagePrice;
	if(document.getElementById("totalPriceText") !=null){
		//document.getElementById("totalPriceText").innerHTML="Total Price:";
		document.getElementById("totalPriceText").style.display = 'inline';
	}
	document.getElementById('totalprice').innerHTML = totalPrice;
	document.getElementById('departureDate').value = departureDate;
	jQuery("#departureDateStatic").html(departureDate);
	if(packageId){
		document.packageCost.selectHolidayIndex.value = packageId;
		jQuery("#holidayIndex").attr('value', packageId);
	}
	if(packageId){
		AjaxSearchResultTools.getMainFlightContent("/templates/tc/pieces/accomFlightDetails.jsp", packageId,'', function(data) {
			var text = jQuery.trim(data).replace(new RegExp("\n",'g'),'').replace(new RegExp("\r",'g'),'').replace(new RegExp("\t",'g'),'');
			document.getElementById('flightfirst').innerHTML = '';
			jQuery("#flightfirst").html(text);
		});
	}
}

function showAccomCalendarWait(){
	var loadingDisplay = "<div class='dealsLoading'><img src='/images/siteElements/loading.gif' alt='Loading' /></div>";
	jQuery('#dealLoadIndicator').html(loadingDisplay).show();
	jQuery('#accombooknowDiv').hide();
	jQuery('#extraContent').hide();
	jQuery('#accomCalendarNoAvail').hide();
	jQuery('#calendarShowHideLinks').hide();
	/*if(document.getElementById('accomCalendarNoAvail')){
		document.getElementById('accomCalendarNoAvail').style.display='none';
	}*/
}


function tcFindAccomodationDeals(curencyCode, resultId, month, flagged, evalFunc) {
	showAccomCalendarWait();
	var url = ACCOM_CALENDAR_URL+"?flagged="+ flagged +"&result=" + resultId + "&month=" + month;
	AjaxSearchResultTools.getAccommodationDeals(month, url, function(data) {
		jQuery('#dealLoadIndicator').hide();
		jQuery('#calendarShowHideLinks').show();
		dwr.util.setValue("extraContent", data, {
			escapeHtml : false
		});
		jQuery('#accombooknowDiv').show();
		if(isCalendarShown) {
			jQuery('#extraContent').show();
		}
		// The following code allow execute the javascript in AJAX response calendar body.
		var ajaxScriptArray = document.getElementById('extraContent').getElementsByTagName('script');
		for(iCycle=0; iCycle<ajaxScriptArray.length; iCycle++) {
			eval(ajaxScriptArray[iCycle].text);
		}
		
		if (data.indexOf("@@@NO_SEARCH_RESULT@@@") < 0) {
			AjaxSearchResultTools.getPackagePrice(resultId, month, function(data) {
				if (data) {
					var priceArray = data.split("@");
					if(document.getElementById("priceppText") !=null){
						document.getElementById("priceppText").innerHTML="pp";
					}
					document.getElementById('pricepp').innerHTML = "&"+curencyCode + priceArray[0];//+"<span class='pp'>pp</span>";
					if(document.getElementById("totalPriceText") !=null){
						//document.getElementById("totalPriceText").innerHTML="Total Price:";
						document.getElementById("totalPriceText").style.display = 'inline';
					}
					document.getElementById('totalprice').innerHTML ="&"+curencyCode + priceArray[1];
					document.packageCost.selectHolidayIndex.value = priceArray[2];
					document.getElementById('holidayIndex').value = priceArray[2];
		
					AjaxSearchResultTools.getMainFlightContent("/templates/tc/pieces/accomFlightDetails.jsp", priceArray[2], month, function(data) {
						document.getElementById("flightfirst").innerHTML = data;	
					});
				}
			});
			changeDisplayPrice();
			var calendarBlock = document.getElementById('calendarDealSize');
			if (calendarBlock != null) {
				calendarDealSize = calendarBlock.value;
				selectedDate = document.getElementById('selectedDate').value;
				calviewTracking(calendarDealSize,selectedDate);
			}
		} else {
			handleNoMatrixPrice();
		}
		
		if(evalFunc) {
			evalFunc(function(evalData) {
				eval(evalData);
			});
		}
	});

}

function getAccomDivContainerID(flagged, resultId){
	var unID = 'extraContent_' + resultId;
	if(flagged == 'true'){
		unID = 'extraContent';
	}
	return unID;
}
function setActiveTab(tabID) {
	var currTabElem;
	var i=0;
	for (i=0;i<=42;i++)
	{
		var styleClass="";
		currTabElem = document.getElementById('calendar_'+i);

		if(currTabElem!=null){
			if(navigator.appName=='Microsoft Internet Explorer') {
				styleClass=currTabElem.className;
			} else {
				styleClass= currTabElem.getAttribute("class");
			}

			var effectiveClass = "calenderday";
			if(styleClass=="calenderday chosenandcheapest" || styleClass=="calenderday cheapest") {
				effectiveClass += " cheapest";
			}
			currTabElem.setAttribute("class", effectiveClass);
			currTabElem.setAttribute("className", effectiveClass);
		}
	}

	currTabElem = document.getElementById('calendar_'+tabID);
	if(navigator.appName=='Microsoft Internet Explorer') {
		styleClass=currTabElem.className;
	} else{
		styleClass= currTabElem.getAttribute("class");
	}
	if(styleClass=="calenderday cheapest") {
		currTabElem.setAttribute("class", "calenderday chosenandcheapest");
		currTabElem.setAttribute("className", "calenderday chosenandcheapest");
	} else {
		currTabElem.setAttribute("class", "calenderday chosen");
		currTabElem.setAttribute("className", "calenderday chosen");
	}
	var el = document.getElementById("activeCalendarCell");
	if (el != null) {
		if (el.value != tabID) {
			priceUpdated();
//			hideAltFlights();
			el.value = tabID;
		}
	}
	return;
}

function priceUpdated(){
	document.getElementById("priceupdate").style.display = "";
	setTimeout("document.getElementById('priceupdate').style.display = 'none'",2000)
}

function OnChange(dropdown)
{
	var myindex  = dropdown.selectedIndex
	var selectedDepartureGroupId = dropdown.options[myindex].value;
	var selectedPackageId = document.packageCost.selectHolidayIndex.value;
	var url = ACCOM_CALENDAR_URL;
}

/**
 * return the string before first '@'symbol
 */
function extractBeanElement(pBeanElem) {
	var index = pBeanElem.indexOf("@");
	var roomType = pBeanElem.split("_");
	if(roomType[1] != null){
		document.getElementById('accomroom_'+roomType[0]).value=roomType[1];
	}
	if(index>=0){
		var pBeanElemArray = pBeanElem.split("@");
		pBeanElem = pBeanElemArray[0];
	}
	return pBeanElem;
}

function getMatrixDeals(pBeanElem, pKeyword, pChangedParametersString, url){
	//alert(pBeanElem+":::::::::::::::"+pKeyword+":::::::::::::::"+pChangedParametersString+":::::::::::::::"+url);
	showAccomCalendarWait();
	if(pKeyword.match('addRoom') || pKeyword.match('removeRoom')){
	 pChangedParametersString=pKeyword;
	}
	else if(pKeyword.match('boardbasis')){
	 pChangedParametersString= pKeyword+"="+pBeanElem;
	}
	else if(pKeyword.match('duration')){
	 pChangedParametersString= pKeyword+"="+pBeanElem;
	}
	else if(pKeyword.match('departure')){
	 pChangedParametersString= pKeyword+"="+pBeanElem;
	}
	else if(pKeyword.match('datechange')){
	 pChangedParametersString= pKeyword+"="+pBeanElem;
	}
	else if(pKeyword.match('roomType')){
	 pChangedParametersString= pKeyword+"="+pBeanElem;
	}else if(pKeyword.match('childAges')){
		pChangedParametersString= pKeyword+"="+pBeanElem;
	}
	
	
	if(typeof pChangedParametersString == undefined) {
		pChangedParametersString = '';
	}
	
	AjaxSearchResultTools.getMatrixDealsForAccom(pChangedParametersString, ACCOM_CALENDAR_URL, function(data) {
		dwr.util.setValue("extraContent", data, {
			escapeHtml : false
		},setSelRoom);
		jQuery('#dealLoadIndicator').hide();
		jQuery('#calendarShowHideLinks').show();
		if(isCalendarShown) {
		
			jQuery('#extraContent').show();
		}
		
		if (data.indexOf('@@@NO_SEARCH_RESULT@@@') < 0) {
			changeDisplayPrice();
			var calendarDealSize = document.getElementById('calendarDealSize').value;
			var selectedDate = document.getElementById('selectedDate').value;
			//setRoomDetails();
			calviewTracking(calendarDealSize,selectedDate);
			//update the prices in a dropdown
			setselectedRoomOnPageLoad('');
			fillAccomMonth(dates);
		} else {
			handleNoMatrixPrice();
			fillAccomMonth(dates);
		}
	});
}
function setSelRoom(){
	setRoomDetails();
}
function handleNoMatrixPrice() {
	document.getElementById('accombooknowDiv').style.display='none';
	document.getElementById('accomflightsDiv').style.display='none';
	document.getElementById('accomCalendarNoAvail').style.display='block';
}

function populateRoomType(accommItemForRoomType,pKeyword,roomCount){
	if(pKeyword == 'addRoom'){
	var roomCounter= document.getElementById('roomCountValue').value;
	document.getElementById('roomCountValue').value= roomCounter;
	}
	//var idOfRoomAdded = document.getElementById('newAccomroom_2');
	//AjaxSearchResultTools.getMapForAddedRooms(accommItemForRoomType, pKeyword,roomCounter,addRoomMap);
}
function addRoomMap(data) {
	var newRoomCount = document.getElementById('roomCountValue').value;
	dwr.util.removeAllOptions('newAccomroom_'+newRoomCount);
	dwr.util.addOptions('newAccomroom_'+newRoomCount, data);
}

var changedParametersString = '';

function validatePaxCount(adultsCount,childrenCount,pBeanElem,dynamicRoomCount,roomCount){
	//alert(adultsCount+":::::::::::::::"+childrenCount+":::::::::::::::"+pBeanElem+":::::::::::::::"+dynamicRoomCount+":::::::::::::::"+roomCount);
	var totalRoom=roomCount;
	var passengerPerRoomArray='';
	if(dynamicRoomCount.match("adult")){
	   if(document.getElementById("roomDetails_1").style.display =="" || document.getElementById("roomDetails_1").style.display =='block'){
			passengerPerRoomArray+="adults_1="+document.getElementById("accomadult_1").value;
		}
		if(document.getElementById("roomDetails_2").style.display =="" || document.getElementById("roomDetails_2").style.display =='block'){
			passengerPerRoomArray+="&";
			passengerPerRoomArray+="adults_2="+document.getElementById("accomadult_2").value;
		}
		if(document.getElementById("roomDetails_3").style.display =="" || document.getElementById("roomDetails_3").style.display =='block'){
			passengerPerRoomArray+="&";
			passengerPerRoomArray+="adults_3="+document.getElementById("accomadult_3").value;
		}
	}
	if(dynamicRoomCount.match("children")){
		if(document.getElementById("roomDetails_1").style.display =="" || document.getElementById("roomDetails_1").style.display=='block'){
			passengerPerRoomArray+="children_1="+document.getElementById("accomchild_1").value;
			var totalRoom1ChildCount = document.getElementById("accomchild_1").value;
			var childAge ='';
			var childIndex=0;
			for(i=0;i<totalRoom1ChildCount;i++){
				childIndex +=i;
				childAge+="childAges_"+i+"="+document.getElementById("childAge_1_"+(i+1)+"_sel").value;
				if(i!= totalRoom1ChildCount-1){
					childAge+=":";
				}
			}
			passengerPerRoomArray +=";"+childAge;
			//alert("passengerPerRoomArray   "+passengerPerRoomArray);
		}
		//alert("displaytype2   "+ document.getElementById("roomDetails_2").style.display);
		if(document.getElementById("roomDetails_2").style.display =="" || document.getElementById("roomDetails_2").style.display=='block'){
			passengerPerRoomArray+="&";
			passengerPerRoomArray+="children_2="+document.getElementById("accomchild_2").value;
			var totalRoom2ChildCount = document.getElementById("accomchild_2").value;
			var childAge ='';
			var childIndex=6;
			//alert("totalRoom2ChildCount   "+ totalRoom2ChildCount);
			for(i=0;i<totalRoom2ChildCount;i++){
				childIndex +=i;
				childAge+="childAges_"+childIndex+"="+document.getElementById("childAge_2_"+(i+1)+"_sel").value;
				if(i!= totalRoom2ChildCount-1){
					childAge+=":";
				}
			}
			passengerPerRoomArray +=";"+childAge;
			//alert("passengerPerRoomArray   "+passengerPerRoomArray);
		}
		if(document.getElementById("roomDetails_3").style.display =="" || document.getElementById("roomDetails_3").style.display=='block'){
			passengerPerRoomArray+="&";
			passengerPerRoomArray+="children_3="+document.getElementById("accomchild_3").value;
			var totalRoom3ChildCount = document.getElementById("accomchild_3").value;
			var childAge ='';var childIndex=6;
			for(i=0;i<totalRoom3ChildCount;i++){
				childIndex +=i;
				childAge+="childAges_"+childIndex+"="+document.getElementById("childAge_3_"+(i+1)+"_sel").value;
				if(i!= totalRoom3ChildCount-1){
					childAge+=":";
				}
				//alert(childAge);
			}
			passengerPerRoomArray +=";"+childAge;
			//alert("passengerPerRoomArray   "+passengerPerRoomArray);
		}
		//alert("passengerPerRoomArray   "+passengerPerRoomArray);		
	}
	//alert("passengerPerRoomArray   "+passengerPerRoomArray);
	var value;
	if(document.getElementById('accomroom_'+roomCount) != null){
		value = document.getElementById('accomroom_'+roomCount).value;
	}else{
		value = document.getElementById('newAccomroom_'+roomCount).value;
	}
	paxDetails = value.split("@");
	
	if(document.getElementById('accomadult_'+roomCount) != null){
		adultsCount = document.getElementById('accomadult_'+roomCount).value;
	}else{
		adultsCount = document.getElementById('newAccomadult_'+roomCount).value;
	}
	if(document.getElementById('accomchild_'+roomCount) != null){
		childrenCount = document.getElementById('accomchild_'+roomCount).value;
	}else{
		childrenCount = document.getElementById('newAccomchild_'+roomCount).value;
	}
	var totalPaxCount = parseInt(adultsCount) + parseInt(childrenCount);
	var minPax = paxDetails[1];
	var maxPax = paxDetails[2];
	pBeanElem = extractBeanElement(pBeanElem);
	var error;
	if(minPax > totalPaxCount ){
		//alert("Increase the number of Passenger to support this room type");
		displayPaxErrorMesg(minPax, maxPax);
		document.getElementById('paxMixErrorSpan').style.display="block";
		error = "Error in pax mix";
		if(dynamicRoomCount.match('child')){
			updateChildAgeBlock(roomCount,pBeanElem);
		}		

		if(dynamicRoomCount.match('adult')){
			changedParametersString +=dynamicRoomCount+'='+adultsCount+'&';
		} else if (dynamicRoomCount.match('child')) {
			changedParametersString +=dynamicRoomCount+'='+childrenCount+'&';
		} else if (dynamicRoomCount.match('roomType')) {
		changedParametersString +=dynamicRoomCount+'='+pBeanElem+'&';
		}
		//changedParametersString +=dynamicRoomCount+'='+adultsCount+'&';
		
		return error;
	} else if(maxPax < totalPaxCount){
		//alert("Decrease the number of Passenger to support this room type");
		displayPaxErrorMesg(minPax, maxPax);
		document.getElementById('paxMixErrorSpan').style.display="block";
		error = "Error in pax mix";
		if(dynamicRoomCount.match('child')){
			updateChildAgeBlock(roomCount,pBeanElem);
		}		

		if(dynamicRoomCount.match('adult')){
			changedParametersString +=dynamicRoomCount+'='+adultsCount+'&';
		} else if (dynamicRoomCount.match('child')) {
			changedParametersString +=dynamicRoomCount+'='+childrenCount+'&';
		} else if (dynamicRoomCount.match('roomType')) {
		changedParametersString +=dynamicRoomCount+'='+pBeanElem+'&';
		}
		//changedParametersString +=dynamicRoomCount+'='+adultsCount+'&';
		
		return error;
	} else {
		document.getElementById('paxMixErrorSpan').style.display="none";
		if(dynamicRoomCount.match('child')){
			updateChildAgeBlock(roomCount,pBeanElem);
		} else if (dynamicRoomCount.match('roomType')) {
			updateChildAgeBlock(roomCount,document.getElementById('accomchild_'+roomCount).value);
		}
		//alert("passengerPerRoomArray   "+passengerPerRoomArray);
		getMatrixDeals(pBeanElem, dynamicRoomCount, passengerPerRoomArray, '');
		changedParametersString = '';
	}
}

function displayPaxErrorMesg(minPax, maxPax){

	document.getElementById("min").innerHTML = "'" + minPax + "'";
	document.getElementById("max").innerHTML = "'" + maxPax + "'";
}


function updateChildAgeBlock(roomCount,value){
	for(j=1;j<=6;j++){
		if(j<=value){	
			if(document.getElementById('childAge_'+roomCount+"_"+j) != null){
				document.getElementById('childAge_'+roomCount+"_"+j).style.display='block';
				document.getElementById('maxChildAgeMessage_'+roomCount).style.display='block';
			}else{
				document.getElementById('newChildAge_'+roomCount+"_"+j).style.display='block';
			}
		}else{
			if(document.getElementById('childAge_'+roomCount+"_"+j) != null){
				document.getElementById('childAge_'+roomCount+"_"+j).style.display='none';
			}else{
				document.getElementById('newChildAge_'+roomCount+"_"+j).style.display='none';
			}
		}
	}
}

function removeRooms(){
	var count = document.getElementById('roomCountValue').value;
	if(count>1) {
		if(document.getElementById('roomDetails_'+count) != null){
				document.getElementById('roomDetails_'+count).style.display='none';
				var childCount = document.getElementById('accomchild_'+count).value;
				for(i=1;i<=childCount;i++){
					document.getElementById('childAge_'+count+"_"+i).style.display='none'
					document.getElementById('childAge_'+count+"_"+i+"_sel").value =5;
				}				
				document.getElementById('accomchild_'+count).value=0;
				document.getElementById('accomadult_'+count).value=2;
			}else{
				document.getElementById('newRoomDetails_'+count).style.display='none';
				var childCount = document.getElementById('accomchild_'+count).value;
				for(i=1;i<=childCount;i++){
					document.getElementById('childAge_'+count+"_"+i).style.display='none'
					document.getElementById('childAge_'+count+"_"+i+"_sel").value =5;
				}
				document.getElementById('accomchild_'+count).value=0;
				document.getElementById('accomadult_'+count).value=2;
			}
		--count;
		if(count ==1){
				document.getElementById('removeRooms').style.display='none';
			}
		if(count ==2){
				document.getElementById('addRooms').style.display='block';
			}
	}
	document.getElementById('roomCountValue').value = count;
	
	var roomOptions1  = document.getElementById("accomroom_1").options;
	//alert( roomOptions1[0].value);
	//roomOptions1[0].selected=true;
	var roomOptions2  = document.getElementById("accomroom_2").options;
	//alert( roomOptions2[0].value);
	//roomOptions2[0].selected=true;
	var roomOptions3  = document.getElementById("accomroom_3").options;
	//alert( roomOptions3[0].value);
	//roomOptions3[0].selected=true;
	
	validateMinMaxPax(count);
}

/**
 * remove the Pax error messages when amount of people fit the room size
 * @param count - current room count
 */
function validateMinMaxPax(count) {
	if(jQuery('#paxMixErrorSpan').is(':visible')) {
		for(var roomCount=1;roomCount<=count; roomCount++) {
			if(document.getElementById('accomroom_'+roomCount) != null){
				var value = document.getElementById('accomroom_'+roomCount).value;
			} else {
				var value = document.getElementById('newAccomroom_'+roomCount).value;
			}
			paxDetails = value.split("@");
			if(document.getElementById('accomadult_'+roomCount) != null){
				var adultCount = document.getElementById('accomadult_'+roomCount).value;
			} else {
				var adultCount = document.getElementById('newAccomadult_'+roomCount).value;
			}
			if(document.getElementById('accomchild_'+roomCount) != null){
				var childtCount = document.getElementById('accomchild_'+roomCount).value;
			} else {
				var childtCount = document.getElementById('newAccomchild_'+roomCount).value;
			}
			var totalPaxCount = parseInt(adultCount) + parseInt(childtCount);
			var minPax = paxDetails[1];
			var maxPax = paxDetails[2];
			if((minPax > totalPaxCount) || (maxPax < totalPaxCount)){
				displayPaxErrorMesg(minPax, maxPax);
				document.getElementById('paxMixErrorSpan').style.display="block";
				return;
			}
		}
		document.getElementById('paxMixErrorSpan').style.display="none";
	}
}


function addRooms(){
	var count = document.getElementById('roomCountValue').value;
	//alert('roomCount:::::::::::::::' + count);
	var roomOptions1  = document.getElementById("accomroom_1").options;
	//alert( roomOptions1[0].value);
	//roomOptions1[0].selected=true;
	var roomOptions2  = document.getElementById("accomroom_2").options;
	//alert( roomOptions2[0].value);
	//roomOptions2[0].selected=true;
	var roomOptions3  = document.getElementById("accomroom_3").options;
	//alert( roomOptions3[0].value);
	//roomOptions3[0].selected=true;
	
	if(count <3)
		{
			++count;
			if(document.getElementById('roomDetails_'+count) != null){
				document.getElementById('roomDetails_'+count).style.display='block';
			}else{
				document.getElementById('newRoomDetails_'+count).style.display='block';
			}
			if(count ==2){
				document.getElementById('removeRooms').style.display='block';
			}
			if(count ==3){
				document.getElementById('addRooms').style.display='none';
			}
		}	
		document.getElementById('roomCountValue').value = count;
}

function changeDisplayPrice(){
	if(isAltFlightsShown){
		document.getElementById("alternateFlightOptions").style.display = 'none';
	 document.getElementById("altFlightsSpan").innerHTML="Search alternative flights";
	 isAltFlightsShown=false;

	}
	if(document.getElementById('calenderChossenPrice')){
		var selDealAvailable = true;
		var valArray = document.getElementById('calenderChossenPrice').value.split(",");
		var currency = valArray[1].substring(0, 1);
		var totalprice= roundNumber(valArray[1].substring(1),0);
		var packagePrice = currency+""+totalprice;
		setPrice(valArray[0],packagePrice, valArray[2], valArray[3])
		//document.getElementById('pricepp').innerHTML = document.getElementById('calenderChossenPrice').value+'<span class="pp">pp</span>';
		document.getElementById('accombooknowDiv').style.display='block';
		document.getElementById('accomflightsDiv').style.display='block';
	}
	else {
		document.getElementById('accombooknowDiv').style.display='none';
		document.getElementById('accomflightsDiv').style.display='none';
		if (!document.getElementById('dealPresent')) {
			document.getElementById('accomCalendarNoAvail').style.display='block';
		}
	}
	
	if(selDealAvailable != true){
		//execute this block only if sel deal not available.
		if(document.getElementById('dealPresent') != null){
			document.getElementById('accombooknowDiv').style.display='block';
			document.getElementById('accomflightsDiv').style.display='block';
		}
	}
}

function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
  var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
  return newnumber;
}

function ajaxTracking(trackingType, value, error){
	
	var selectedTrackingType = trackingType.split("_")[0];
	if(trackingType.split("_")[1] != null){
		var	selectedRoomCount = trackingType.split("_")[1];
	}else{
		var	selectedRoomCount = "";
	}

	if(selectedTrackingType == 'alternateFlights'){
		value = value + '_' +document.getElementById('trackDepartureTime_'+selectedRoomCount).innerHTML + '_'+document.getElementById('trackArrivalTime_'+selectedRoomCount).innerHTML;
	}

	if(selectedTrackingType == 'unit'){
		value=document.getElementById('roomCountValue').value;
	}
	if(selectedTrackingType == 'roomType'){
		value=value.split("@")[0];
	}
	if(selectedTrackingType == 'addRoom'){
		value=document.getElementById('roomCountValue').value;
		selectedRoomCount = document.getElementById('roomCountValue').value
		if(document.getElementById('accomroom_'+value) != null){
			code = document.getElementById('accomroom_'+value).value;
		}else{
			code = document.getElementById('newAccomroom_'+value).value;
		}
		code = code.split("@")[0];
		value = value+"_"+code;
	}
	if(selectedTrackingType == 'removeRoom'){
		value=document.getElementById('roomCountValue').value;
		selectedRoomCount = document.getElementById('roomCountValue').value
	}
	if(error) {
		AjaxSearchResultTools.siTagAccommodationWithError(selectedTrackingType, value, selectedRoomCount, error, updateAjaxTracking);
	} else {
		AjaxSearchResultTools.siTagAccommodation(selectedTrackingType, value, selectedRoomCount, updateAjaxTracking);
	}
}

function updateAjaxTracking(data) {
	eval(data);
}

function ajaxTrackingPayment(trackingType,value){
	AjaxSearchResultTools.siTagPassenger(trackingType,value,updatePaymentAjaxTracking);
	document.getElementById('pax_errors_mess').innerHTML = "";
	document.getElementById('searchErrorId').style.display = 'none';
}

function updatePaymentAjaxTracking(data) {
	eval(data);
	//document.getElementById('extraContent123').value = data;
}

function calviewTrackingCurrent(){
	var calendarDealSizeControl = document.getElementById('calendarDealSize');
	var selectedDateControl = document.getElementById('selectedDate');
	if(calendarDealSizeControl != null && selectedDateControl != null) {
		var calendarDealSize = calendarDealSizeControl.value;
		var selectedDate = selectedDateControl.value;
		calviewTracking(calendarDealSize,selectedDate);
	}
}

function calviewTrackingDate(selectedDate){
	var calendarDealSizeControl = document.getElementById('calendarDealSize');
	if(calendarDealSizeControl != null) {
		var calendarDealSize = calendarDealSizeControl.value;
		calviewTracking(calendarDealSize,selectedDate);
	}
}

function calviewTracking(numberOfDeals,selectedDate){
	sitracker.trackEvent("content/calendar/view/"+selectedDate+"/"+numberOfDeals);
}

function altflightTracking(value){
	sitracker.trackEvent(value);
}

function contentTracking(content,imageURL){
	var imageNameArray = imageURL.split("/");
	var imageName = imageNameArray[imageNameArray.length -1]
	sitracker.trackEvent(content+imageName);
}

function imageLoadingError(imageURL){
	var imageNameArray = imageURL.split("/");
	var imageName = imageNameArray[imageNameArray.length -1]
	sitracker.trackEvent("content/image/404error/"+imageName);
}

  function durationSorting(){
				
	var durationsArray = ["less than 7 nights", "7 nights", "8-13 nights", "14 nights", "More than 14 nights" ];
	var optionsArray = new Array();
	var durationSelObj = document.getElementById("inputnights");
	for(var i=0; i< durationSelObj.options.length;i++){
		optionsArray[i] = new Option(durationSelObj.options[i].text, durationSelObj.options[i].value);
		if(durationSelObj.options[i].selected)
			optionsArray[i].selected=true;
	}
	durationSelObj.options.length=0;
	for(var j=0;j<durationsArray.length;j++){
		for(var i=0;i<optionsArray.length;i++){
			if(durationsArray[j] == optionsArray[i].text){
				document.getElementById("inputnights").options[j]=optionsArray[i];	
				break;
			}
		}
	}
}

function showToolTips(ID){
	jQuery("#" + ID).show();
}

function hideToolTips(ID){
	jQuery("#" + ID).hide();
}
/*Search Results Page hover*/
function position(element) {
  if(element!=undefined){
  var p = {x: element.offsetLeft || 0, y: element.offsetTop || 0};
  while (element = element.offsetParent) {
    p.x += element.offsetLeft;
    p.y += element.offsetTop;
  }
    return p;
  }
  else{
    var p = {x: 5 || 0, y: 5 || 0};
    return p;

  }
}



function loading(id, tm) {
	var element = document.getElementById(id);
	var fp = position(element);
	var waitElem = jQuery('div.facetwaitprogress');
	var fpsearch = jQuery("div.fpsearch");

	waitElem.css("display", "block").css("top", fp.y - 45)
		.css("left", position(fpsearch[0]).x 
			+ parseInt(fpsearch.css('width'))
			+ parseInt(fpsearch.css('paddingLeft'))
			+ parseInt(fpsearch.css('paddingRight'))
			+ parseInt(fpsearch.css('borderLeftWidth'))
			+ parseInt(fpsearch.css('borderRightWidth')) 
			+ 10 
		);
	
	if (tm == 1) {
		var srpElem = jQuery('div#sectionsearchfat1');
		if (srpElem[0]) {
			var srp = position(srpElem[0]);
			jQuery('div.facetwaitOpacity').css("display", "block").css("top", srp.y).css("left", srp.x).css("height", srpElem.css("height"));
		}
	}
	if (typeof element.disabled != "undefined") {
		element.disabled = true;
	}
	jQuery('a', '.facetbody').removeAttr('href');
	jQuery('a', '.facetbody').attr('style', 'color:grey');
	jQuery('#clearcalendarlinkTCProducts').attr('style','display:none;');
	jQuery('a', '.fpartysize').css('textDecoration', 'underline');
	jQuery('a', '.fdepart').css('textDecoration', 'underline');
}

function disableTcFacetsNoResult()
{
	var wantedSet = jQuery('.tcsearch').children().not('#facetDBPaxCombination');
	wantedSet.find('a:not(.facetfilters > a)', '.fpartysize').removeAttr('href').removeAttr('onclick').attr('style', 'color:grey').css('textDecoration', 'underline').unbind('click');
	wantedSet.find('#bBookNow').removeAttr('href').removeAttr('onclick').attr('style', 'color:grey').css('textDecoration', 'underline').unbind('click');
	jQuery('#clearcalendarlinkTCProducts').attr('style','display:none;');
}

/*Function to display hidden values and update expanded values var*/

function showHiddenValuesFromFacet(divId, facetId){
	jQuery('.facetvaluehidden', '#' + divId).show();
	jQuery( '#' + divId + 'ShowLink').hide();
	jQuery( '#' + divId + 'HideLink').show();
	if(expandedFacets){
		expandedFacets += ":" + facetId;
	}
	else expandedFacets = facetId;

}

/*Function to disable hidden values and update expanded values var respectively
 taking some risk with using ":" in url*/

function hideHiddenValuesFromFacet(divId, facetId){
	jQuery('.facetvaluehidden', '#' + divId).hide();
	jQuery( '#' + divId + 'ShowLink').show();
	jQuery( '#' + divId + 'HideLink').hide();
	var facetsArray = expandedFacets.split(':');
	expandedFacets = '';
	for(var i=0;i < facetsArray.length;i++) {
		if(facetsArray[i] != facetId){
            if(expandedFacets){
               		 expandedFacets += ":" + facetsArray[i];
                  }
               	 else expandedFacets = facetsArray[i];
		}

	}
}


function initFacetIfExpanded(divId , facetId){
	var facetsArray = expandedFacets.split(':');
	for(var i=0;i < facetsArray.length;i++) {
		if(facetsArray[i] == facetId){
            jQuery('.facetvaluehidden', '#' + divId).show();
            jQuery( '#' + divId + 'ShowLink').hide();
            jQuery( '#' + divId + 'HideLink').show();
		}

	}
}
expandedFacets="";
function getFacetsToExpand(){
	if(expandedFacets){
		return expandedFacets;
	}
	else return '';
}

function addExpandParameter(id){
	id.href += '&expand=' + getFacetsToExpand();
}

currHotelPage = 1;

function displayHotelPage(pageNum)
{
	if (pageNum <= 0 || pageNum > lastHotelPage) {
		return;
	}
	document.getElementById("otherHotels_page" + currHotelPage).style.display = "none";
	document.getElementById("otherHotels_page" + pageNum).style.display = "";
	document.getElementById("hotelPageLinkTop_" + currHotelPage).innerHTML = "<a href=\"javascript:displayHotelPage(" + currHotelPage + ");\">" + currHotelPage + "</a>";
	document.getElementById("hotelPageLinkTop_" + pageNum).innerHTML = pageNum;
	document.getElementById("hotelPrevLinkTop").className = pageNum == 1 ? "pageprev_iconGray disabled" : "pageprev_icon";
	document.getElementById("hotelNextLinkTop").className = pageNum == lastHotelPage ? "pagenext_iconGray disabled" : "pagenext_icon";
	document.getElementById("hotelPageLinkBottom_" + currHotelPage).innerHTML = "<a href=\"javascript:displayHotelPage(" + currHotelPage + ");\">" + currHotelPage + "</a>";
	document.getElementById("hotelPageLinkBottom_" + pageNum).innerHTML = pageNum;
	document.getElementById("hotelPrevLinkBottom").className = pageNum == 1 ? "pageprev_iconGray disabled" : "pageprev_icon";
	document.getElementById("hotelNextLinkBottom").className = pageNum == lastHotelPage ? "pagenext_iconGray disabled" : "pagenext_icon";
	currHotelPage = pageNum;
}

// Help Page Query string
function getQueryString () {
 var strTheQuery = document.getElementById('theURL').value;
 var strURL1 = "thomascook.zendesk.com/search?query=";
 //var strURL2 = "&p_new_search=1&prod_lvl1=0";
 //alert(strURL1);
 //alert(strTheQuery);
 //alert(strURL2);
//window.location.href =  strURL1 + strTheQuery + strURL2;
window.location.href =  strURL1 + strTheQuery;
}


function setRoomDetails(){
	var accommItemForRoomType = document.getElementById("accommodationProdId").value;
	//alert('accommItemForRoomType::::;' +accommItemForRoomType);
	//alert('selectedRoom:::::::::::' + document.getElementById("accomroom_1").value);
	AjaxSearchResultTools.getRoomDataForSelectedPackage(accommItemForRoomType,function(data){
		setSelectedRoomCodes();
		var roomsInformation = data;
		if(selRoomCode != null && selRoomCode != ""){
		selRoomCode = selRoomCode.split("/")[0];
		} else {
			selRoomCode = "";
		}
		if(roomsInformation != null){
			for (var key in roomsInformation) {
				var keyArray = key.split("_");
				dwr.util.removeAllOptions('accomroom_'+keyArray[1]);
				dwr.util.addOptions('accomroom_'+keyArray[1], roomsInformation[key]);
				selectUpdatedRoom(selRoomCode,'accomroom_'+keyArray[1]);
			  //dwr.util.setValue('accomroom_'+keyArray[1], keyArray[0]);
			}
		}
		
		finalUpdateRoomType(selRoomCode);
	});
}

var selRoomCode;
function updateRoomData(data) {
	setSelectedRoomCodes();	
	var roomsInformation = data;
	if(selRoomCode != null && selRoomCode != ""){
		selRoomCode = selRoomCode.split("/")[0];
	} else {
		selRoomCode = "";
	}
	if(roomsInformation != null){
		for (var key in roomsInformation) {
		    var keyArray = key.split("_");
			dwr.util.removeAllOptions('accomroom_'+keyArray[1]);
			dwr.util.addOptions('accomroom_'+keyArray[1], roomsInformation[key]);
			selectUpdatedRoom(selRoomCode,'accomroom_'+keyArray[1]);
		  //dwr.util.setValue('accomroom_'+keyArray[1], keyArray[0]);
		}
	}
	
	finalUpdateRoomType(selRoomCode);
}

function selectUpdatedRoom(roomCode, roomsDropDown){
	var roomOptions  = document.getElementById(roomsDropDown).options;
	for(var i=0; i<roomOptions.length; i++){
		dropDownValue = roomOptions[i].value.split("@")[0]; 
		if(roomCode.toLowerCase() == dropDownValue.toLowerCase()){
			roomOptions[i].selected=true;
			break;
		}
	}
}

function finalUpdateRoomType(roomCode){
	var roomOptions  = document.getElementById("accomroom_1").options;
	for(var i=0; i<roomOptions.length; i++){
		dropDownValue = roomOptions[i].value.split("@")[0]; 
		if(roomCode.toLowerCase() == dropDownValue.toLowerCase()){
			roomOptions[i].selected=true;
			break;
		}
	}
}

function setSelectedRoomCodes(){
	AjaxSearchResultTools.setSelectedRoomCodes(function(data){
		var roomCodeData = data;
		if(roomCodeData != null){
			for (var key in roomCodeData) {
				if(roomCodeData[key].indexOf("/") >= 0){
					var code = roomCodeData[key].split("/")[0];
					document.getElementById("selectedRoomCode").value = code;
					selRoomCode = code;
					break;
				}
			}
		}
	});
}

function setRoomCodesInfo(data){
	var roomCodeData = data;
	if(roomCodeData != null){
		for (var key in roomCodeData) {
			if(roomCodeData[key].indexOf("/") >= 0){
				var code = roomCodeData[key].split("/")[0];
				document.getElementById("selectedRoomCode").value = code;
				selRoomCode = code;
				break;
			}
		}
	}
}

//update the boardbasis and dept airport options
function updateHolidayPanel(boardBasis, departureAirport, calendarIndex){
	//alert(calendarIndex);
	var deptOptions = document.getElementById("fdepfrom").options;
	if(deptOptions.length > 0){
		for(var i = 0; i < deptOptions.length; i++){
			dropDownDeptValue = deptOptions[i].value;
			if(departureAirport.toLowerCase().indexOf(dropDownDeptValue.toLowerCase()) >= 0
					|| dropDownDeptValue.toLowerCase().indexOf(departureAirport.toLowerCase()) >= 0){
				deptOptions[i].selected = true;
				var caption = jQuery(deptOptions[i]).text();
				jQuery("#departFromStatic").html(caption);
				break;
			}
		}
	}
	
	
	
	var boardOptions = document.getElementById("fboard").options;
	if(boardOptions.length > 0){
		for(var i = 0; i < boardOptions.length; i++){
			dropDownValue = boardOptions[i].value;
			if(boardBasis.toLowerCase()=== dropDownValue.toLowerCase()){
				boardOptions[i].selected=true;
				var caption = jQuery(boardOptions[i]).text();
				jQuery("#boardTypeStatic").html(caption);
				break;
			}
		}
	}
	
	//update the room based on the user Click
	//roomDetails_1,accomroom_1, roomDetails_2,accomroom_2, roomDetails_3,accomroom_3
	//set the selected room type for the room with display type = block or ""
	var room1displayType = document.getElementById("roomDetails_1").style.display;
	var room2displayType = document.getElementById("roomDetails_2").style.display;
	var room3displayType = document.getElementById("roomDetails_3").style.display;
	if(room1displayType=="" || room1displayType=='block'){
		var roomCode = document.getElementById("room_"+calendarIndex+"_1_code").value;
		var roomCodeArry = roomCode.split("/");
		var roomOptions  = document.getElementById("accomroom_1").options;
		for(var i=0; i< roomOptions.length;i++){
			//alert(roomOptions[i].value + ":::" + roomCodeArry[0]);
			if(roomOptions[i].value!="" && roomOptions[i].value.match(roomCodeArry[0])){
				roomOptions[i].selected=true;
				break;
			}
		}
	}
	if(room2displayType=="" || room2displayType=='block'){
		var roomCode = document.getElementById("room_"+calendarIndex+"_2_code").value;
		var roomCodeArry = roomCode.split("/");
		var roomOptions  = document.getElementById("accomroom_2").options;
		for(var i=0; i< roomOptions.length;i++){
			//alert(roomOptions[i].value + ":::" + roomCodeArry[0]);
			if(roomOptions[i].value!="" && roomOptions[i].value.match(roomCodeArry[0])){
				roomOptions[i].selected=true;
				break;
			}
		}
	}
	if(room3displayType=="" || room3displayType=='block'){
		var roomCode = document.getElementById("room_"+calendarIndex+"_3_code").value;
		var roomCodeArry = roomCode.split("/");
		var roomOptions  = document.getElementById("accomroom_3").options;
		for(var i=0; i< roomOptions.length;i++){
			//alert(roomOptions[i].value + ":::" + roomCodeArry[0]);
			if(roomOptions[i].value!="" && roomOptions[i].value.match(roomCodeArry[0])){
				roomOptions[i].selected=true;
				break;
			}
		}
	}
}

// update destination drop down on selection of departure
function updateDestinations(form){
	
	if(form.name=="flightsLocationSearchForm"){
	var depAirport1 = form.depAirport.value;
	AjaxSearchResultTools.getDestForSelectedDept(depAirport1,updateDestTCFlyData);
	}
	if(form.name=="flightsSearchForm"){
	var depAirport2 = form.depAirport2.value;
	AjaxSearchResultTools.getDestForSelectedDept(depAirport2,updateDestOtherAirData);
	}
}
function updateDestTCFlyData(data) {
	
	var destTCInfo = data;
	var sel = dwr.util.getValue(document.forms.flightsLocationSearchForm.arrAirport.id);

	dwr.util.removeAllOptions(document.forms.flightsLocationSearchForm.arrAirport.id);	
	dwr.util.addOptions(document.forms.flightsLocationSearchForm.arrAirport.id,destTCInfo,true);
	dwr.util.setValue(document.forms.flightsLocationSearchForm.arrAirport.id, sel)
}
function updateDestOtherAirData(data) {
	
	var destAirInfo = data;
	var sel = dwr.util.getValue(document.forms.flightsSearchForm.arrAirport2.id);

	dwr.util.removeAllOptions(document.forms.flightsSearchForm.arrAirport2.id);	
	dwr.util.addOptions(document.forms.flightsSearchForm.arrAirport2.id,destAirInfo,true);
	dwr.util.setValue(document.forms.flightsSearchForm.arrAirport2.id, sel)
}

// update departure drop down on selection of destination

function updateDepartures(form){
	
	if(form.name=="flightsLocationSearchForm"){
		
	var arrAirport1 = form.arrAirport.value;
	AjaxSearchResultTools.getDepartForSelectedDest(arrAirport1,updateDepartTCFlyData);
	}
	if(form.name=="flightsSearchForm"){
	
	var arrAirport2 = form.arrAirport2.value;
	AjaxSearchResultTools.getDepartForSelectedDest(arrAirport2,updateDepartOtherAirData);
	}
}
function updateDepartTCFlyData(data) {
	
	var departTCInfo = data;
	var sel = dwr.util.getValue(document.forms.flightsLocationSearchForm.depAirport.id);
	
	dwr.util.removeAllOptions(document.forms.flightsLocationSearchForm.depAirport.id);	
	dwr.util.addOptions(document.forms.flightsLocationSearchForm.depAirport.id,departTCInfo,true);
	dwr.util.setValue(document.forms.flightsLocationSearchForm.depAirport.id, sel)
}
function updateDepartOtherAirData(data) {
	
	var departAirInfo = data;
	var sel = dwr.util.getValue(document.forms.flightsSearchForm.depAirport2.id);

	dwr.util.removeAllOptions(document.forms.flightsSearchForm.depAirport2.id);	
	dwr.util.addOptions(document.forms.flightsSearchForm.depAirport2.id,departAirInfo,true);
	dwr.util.setValue(document.forms.flightsSearchForm.depAirport2.id, sel)
}


/* Show - Hide*/
function showHide(shID) {
   if (document.getElementById(shID)) {
      if (document.getElementById(shID+'-show').style.display != 'none') {
         document.getElementById(shID+'-show').style.display = 'none';
         document.getElementById(shID).style.display = 'block';
      }
      else {
         document.getElementById(shID+'-show').style.display = 'inline';
         document.getElementById(shID).style.display = 'none';
      }
   }
}


function  updateSelectedRoomDropDown() {
	 //alert(document.getElementById("selectedRoomCode").value)
}

/*
	set the selected room on the pageLoad
 */
function setselectedRoomOnPageLoad(roomType){
	var accommItemForRoomType = document.getElementById("accommodationProdId").value;
	//alert('accommItemForRoomType::::;' +accommItemForRoomType);
	//alert('selectedRoom:::::::::::' + document.getElementById("accomroom_1").value);
	var room1SelectedValue = document.getElementById("accomroom_1").value;
	var room2SelectedValue = document.getElementById("accomroom_2").value;
	var room3SelectedValue = document.getElementById("accomroom_3").value;
	//alert(room1SelectedValue +":::"+ room2SelectedValue+":::"+room3SelectedValue);
	AjaxSearchResultTools.getRoomDataForSelectedPackage(accommItemForRoomType, roomType, function(data){
		var roomsInformation = data;
		if(selRoomCode != null && selRoomCode != ""){
			selRoomCode = selRoomCode.split("/")[0];
		} else {
			selRoomCode = "";
		}

		if(roomsInformation != null){
		   for (var key in roomsInformation) {
                var keyArray = key.split("_");
                dwr.util.removeAllOptions('accomroom_'+keyArray[1]);
                var originalOptions = roomsInformation[key];
                var options = {};
                var index = 0;                
                var indexToInsertAt = 1;
                if(!originalOptions[""]) {
                    indexToInsertAt = 0;
                }                                
                for (var roomKey in originalOptions) {
                    if(index == indexToInsertAt) {
                        options['-1'] = 'Room options for your selected departure date';
                    }
                    options[roomKey] = originalOptions[roomKey];
                    index++;
                }
                dwr.util.addOptions('accomroom_'+keyArray[1], options);
		   }
		}
		jQuery("option[value='-1']").attr('disabled', 'disabled').css('padding-top', '3px').css('color', '#999999');
		improveSelects();

		//set the selected room type for the room with display type = block or ""
		var room1displayType = document.getElementById("roomDetails_1").style.display;
		var room2displayType = document.getElementById("roomDetails_2").style.display;
		var room3displayType = document.getElementById("roomDetails_3").style.display;
		if(room1displayType=="" || room1displayType=='block'){
			document.getElementById("accomroom_1").value = room1SelectedValue;
		}
		if(room1displayType=="" || room1displayType=='block'){
			document.getElementById("accomroom_2").value = room2SelectedValue;
		}
		if(room1displayType=="" || room1displayType=='block'){
			document.getElementById("accomroom_3").value = room3SelectedValue;
		}	
	});
		//this for cutting option on accommodation page under IE7/8 Windows XP
	jQuery("#accomroom_1_fake option").text(jQuery("#accomroom_1 option:selected").text());
	jQuery("#accomroom_2_fake option").text(jQuery("#accomroom_2 option:selected").text());
	jQuery("#accomroom_3_fake option").text(jQuery("#accomroom_3 option:selected").text());
}

function improveSelects() {
	 for (var i = 1 ; i <= 3; i++) {
	     var selected = false;
	     jQuery("#accomroom_" + i).find('option').each( function (i, elem) {
	         selected = selected || elem.selected;
	     });
	        if(!selected) {
	            var anyRoomOption = jQuery("#accomroom_" + i).find('option[value=""]');
	            if(anyRoomOption.length > 0) {
	                anyRoomOption.attr('selected', 'selected');
	            } else {
	                jQuery("#accomroom_" + i).find('option:first').attr('selected', 'selected');                
	            }
	        }
	 }
}

function showHideCalendar() {
var displayedText = jQuery("#extraContent").css('display');
	if(displayedText) {
		if (jQuery.trim(displayedText) == 'none') {
			showCalendarDiv();
			fillAccomMonth(dates);
		} else {
			hideCalendarDiv();
		}
	}
}

function showCalendarDiv(){
jQuery("#extraContent").slideDown('fast');
jQuery("#hideCalendarLink").show();
jQuery("#showCalendarLink").hide();
isCalendarShown = true;
}

function hideCalendarDiv() {
jQuery("#extraContent").slideUp('fast');
jQuery("#showCalendarLink").show();
jQuery("#hideCalendarLink").hide();
isCalendarShown = false;
}

/* Clickable area*/
jQuery(document).ready(function(){
	jQuery(".click").click(function(){
	if (jQuery(this).find("a").attr("target")=="_blank") {
	  window.open(jQuery(this).find("a").attr("href")); return false;
	  }
	  else { window.location=jQuery(this).find("a").attr("href"); return false;
	  }
	});
	jQuery(".click").css("cursor","pointer");
});

/* Tabs */
jQuery.fn.ihTabs = function(options){
	var options = jQuery.extend({
		activeClass: 'active',
		links: "> li ",
		linkHolder: 'ul.tabs',
		tabHolder: '.tab_content',
		onChange: null,
		duration: 300
	}, options);

	return this.each(function(i, wrapper){
		var time = 300; // in ms
		jQuery(options.linkHolder, wrapper).each(function(){
			jQuery(this).parent().addClass("with-js");
			var links = jQuery(options.links, this); //cache DOM elements
			var tabs = jQuery(options.tabHolder, wrapper);
			var active = links.index(links.filter('.'+options.activeClass)); // get active tab index
			if(active==-1) active = 0;
			links.removeClass(options.activeClass).eq(active).addClass(options.activeClass); // init state of links
			tabs.css({position:'absolute', top: '-9999px', left: '-9999px'}); //Hide all tab content
			jQuery(links.eq(active).find("a").attr("rel")).attr('style', '');

			links.unbind('click').click(function(){
				if(jQuery(this).hasClass(options.activeClass)){
				 //no events need 
				}else{
					links.removeClass(options.activeClass);
					var curentTab = jQuery(this).addClass(options.activeClass).find("a").attr("rel"); //Find the rel attribute value to identify the active tab + content
					tabs.css({opacity:0});
					jQuery(curentTab).attr('style','').hide().fadeIn(time); //Fade in the active ID content
					tabs.not(curentTab).css({position:'absolute', top: '-9999px', left: '-9999px'});
					var otherLinks = jQuery('body').find('a[rel="'+curentTab+'"]').not( jQuery(this).find('a') );
					otherLinks.parents(options.linkHolder).find(options.links).removeClass(options.activeClass);
					otherLinks.parent().addClass(options.activeClass);
					if(jQuery.isFunction(options.onChange)){options.onChange.apply(this);};
				};
				return false;
			});
		});
	});
}

function clickTab(id) {
	jQuery("."+id + " a").click();
}

jQuery(document).ready(function(){
	jQuery('body').ihTabs();
	jQuery('.tab_content').ihTabs({
		linkHolder: 'ul.subTabs',
		tabHolder: '.inner_tabs'
	});
	
	isCalendarShown = ('true' == jQuery("#showCalendarSwitch").val());
});

