//	International Fare Tool
//	UX FET: Scott Elfstrom
//	2009.12.17

jQuery(document).ready(function() {    
    if(jQuery("#fareSearchForm #slider").length > 0){	//	Make sure the slider placeholder is there before trying to use it
		//Initialize the slider
		jQuery("#fareSearchForm #slider").slider({
			range: "min",
			value: 200,
			min: parseInt(jQuery("#minValueHidden").val()),	//	Minimum value
			max: parseInt(jQuery("#maxValueHidden").val()),	//	Maximum value
			slide: function(event, ui) {
				//	Set the maximum value display and form fields
				//$("#fareSearchMaximum").text('$' + ui.value);
				jQuery("#fareSearchMaximum").text(jQuery("#currencyHidden").val() + ui.value);
				jQuery("#fareSearchMaximumField").val(ui.value);
			}
		});
		
		//	Set initial value
		var initValue = jQuery("#slider").slider("option","max");	
		
		//	Set form field to initial value, then hide it
		jQuery("#fareSearchMaximumField").val(initValue).hide();
		
		//	Add HTML for value range display
		jQuery("#aa-sliderBox").append('<p class="aa-fareRange"><span id="fareSearchMinimum"></span>&nbsp;to&nbsp;<span id="fareSearchMaximum"></span></p>');
		
		//	Set initial range display values
		//$("#fareSearchMinimum").text('$' + $("#slider").slider("option","min"));
		jQuery("#fareSearchMinimum").text(jQuery("#currencyHidden").val() + jQuery("#slider").slider("option","min"));
		
		//$("#fareSearchMaximum").text('$' + initValue);
		jQuery("#fareSearchMaximum").text(jQuery("#currencyHidden").val()  + initValue);
		
		//	Set initial slider position
		jQuery("#slider").slider("value", initValue);
		
		//	For Testing: return #fareSearchMaximum field value on form submit
		jQuery("#fareSearchForm").submit(function(e){e.preventDefault();alert(jQuery('#fareSearchMaximumField').val())});
    }
    
    
	//	Turn the table rows into links, based on the href attribute of the fare links
	tableToLinks("#fareList");
	//tableToLinks("#moreDestinations");
	tableToLinksAndHideMainSale("#moreDestinations");
	
	//	For UK list
	jQuery("#aa-fare-tool-extend-uk1 ul.clickable ul")
		.css("cursor","pointer")
		.hover(
			function(){
				jQuery(this).toggleClass("hover");
			},
			function(){
				jQuery(this).toggleClass("hover");
			}
		)
		.click(function(){
		  //get the url from href attribute and launch the url
		  window.location=jQuery(this).find("a").attr("href"); return false;
		});
		
		if (jQuery.browser.msie) {
		  selectSizeHack(jQuery);
	    }
});

//	Hack to enable <select> elements of proper width in IE
function selectSizeHack (jQuery) {
	jQuery("#aa-destination")
		.mouseover(function(){
			jQuery(this).data('cssData', {origWidth:jQuery(this).width(), origZ:jQuery(this).css('z-index')})
				.css('width','auto')
				.attr('multiple','multiple')
				.attr('size','6')
				.css('position','absolute')
				.css('z-index','999');
				if(jQuery(this).width() <= jQuery(this).data('cssData').origWidth) {
				jQuery(this).css('width','100%');
			}
	        })
	        .mouseout(function(){
				jQuery(this)
					.css("width", '100%')
					.css('z-index', jQuery(this).data('cssData').origZ)
					.removeAttr('multiple')
					.removeAttr('size');
			})
			.change(function(){
				jQuery(this)
					.css("width", '100%')
					.css('z-index', jQuery(this).data('cssData').origZ)
					.removeAttr('multiple')
					.removeAttr('size');
			});
}

//	Turns rows of the targeted table into links (Progressive Enhancement)
function tableToLinks(table){
	//	Collect the rows of the table
	var t = jQuery(table).find("tbody tr");
	
	//	Loop through the table rows
	jQuery.each(t,function(i,item){
		//	Get the fare link
		link = jQuery(item).find("td.aa-fare a");
		//	Make the link look like text
		link.addClass("mask");
		if(jQuery(table).hasClass("clickable")){
			//	Get the href attribute of the link
			url = jQuery(link).attr('href');

			//	Turn the table row into a link
			jQuery(item)
				//	Make the cursor behave like a link
				.css("cursor","pointer")

				//	Add hover state of <tr> since IE doesn't support :hover on non-links
				.hover(
					function(){
						jQuery(this).toggleClass("hover");
					},
					function(){
						jQuery(this).toggleClass("hover");
					}
				)

				//	Add a click event to open the link
				.bind("click",url,function(e){
					window.location = e.data;
				});
		}
			
		//	FOR TESTING ONLY. DO NOT INCLUDE IN FINAL BUILD - populate link with random values in the given range
		//if($("#fareSearchForm #slider").length > 0)
			//link.text("$"+randomFare($("#slider").slider("option","min"),$("#slider").slider("option","max")));
	});
}


//	Hides the record whose sale id is same as the main page sale id.
function tableToLinksAndHideMainSale(table){
	//	Collect the rows of the table
	var t = jQuery(table).find("tbody tr");
	
	// Getting the main sale id.
	var mainSaleId = ''+jQuery("#saleId").val();  
	
	// Removing the record related to the main sale id from the cross promote jsp.
    jQuery('#'+mainSaleId+'').remove(); 
    jQuery(table).find("tbody tr:even").addClass("alt");  
    
    //	Loop through the table rows
	jQuery.each(t,function(i,item){
		//	Get the fare link
		link = jQuery(item).find("td.aa-fare a");
		//	Make the link look like text
		link.addClass("mask");
		if(jQuery(table).hasClass("clickable")){
			//	Get the href attribute of the link
			url = jQuery(link).attr('href');

			//	Turn the table row into a link
			jQuery(item)
				//	Make the cursor behave like a link
				.css("cursor","pointer")

				//	Add hover state of <tr> since IE doesn't support :hover on non-links
				.hover(
					function(){
						jQuery(this).toggleClass("hover");
					},
					function(){
						jQuery(this).toggleClass("hover");
					}
				)

				//	Add a click event to open the link
				.bind("click",url,function(e){
					window.location = e.data;
				});
		}
	});
}

//	FOR TESTING ONLY. DO NOT INCLUDE IN FINAL BUILD.
function randomFare(min,max)
{
  var randVal = min+(Math.random()*(max-min));
  return Math.round(randVal);
}
		
//	Testing live filtering of fare list
function hideFares(table, currentValue){
	var t = jQuery(table).find("tbody tr");
	
	jQuery.each(t,function(i,item){
		fare = jQuery(item).find("td.aa-fare a").text();
		fare = fare.replace("$","");
		console.log(fare + "/" + currentValue);
		if(fare > currentValue){
			jQuery(item).hide();
		} else {
			jQuery(item).show();
		}
	});
}


function pagination(paginationURL)
{
   showTabsLoadingIframe();
	// for URL Date is Appended, As in IE the URL is chached, If we need to call the URL every time then the URL should be Unique.
	//alert("URL:" + paginationURL);
	//$("#tabsLoading").show();	
	//document.getElementById("tabsLoading2").style.display='';
	if(document.getElementById("aa-destination")!=null)
	{
		var selectedCity = document.getElementById("aa-destination").value;
		//alert(selectedCity);
		if(selectedCity!="0")
		{
		 	paginationURL = paginationURL + "&cityCode="+selectedCity;
		}
	}
	if(jQuery("#fareSearchMaximumField").val() != null)
	{
		var maxVal = jQuery("#fareSearchMaximumField").val();
		paginationURL = paginationURL + "&maxPriceSelected="+maxVal;
	}
	 jQuery.ajax({
		url : paginationURL+"&dispatch=pagination&date="+new Date().getTime(),		
		dataType: "html",
		success: updateMarkets,
		error: updateMarketsError		
	}); 
}

function paginationForUK(paginationURL)
{
   showTabsLoadingIframe();
	// for URL Date is Appended, As in IE the URL is chached, If we need to call the URL every time then the URL should be Unique.
	//alert("URL:" + paginationURL);
	//$("#tabsLoading").show();	
	//document.getElementById("tabsLoading2").style.display='';
	if(document.getElementById("aa-destination-uk")!=null)
	{
		var selectedCity = document.getElementById("aa-destination-uk").value;
		//alert(selectedCity);
		if(selectedCity!="0")
		{
		 	paginationURL = paginationURL + "&cityCode="+selectedCity;
		}
	}
	if(jQuery("#fareSearchMaximumField").val() != null)
	{
		var maxVal = jQuery("#fareSearchMaximumField").val();
		paginationURL = paginationURL + "&maxPriceSelected="+maxVal;
	}
	 jQuery.ajax({
		url : paginationURL+"&dispatch=pagination&date="+new Date().getTime(),		
		dataType: "html",
		success: updateMarkets,
		error: updateMarketsError		
	}); 
}

function cityCodeSearch(onChangeUrl)
{
    showTabsLoadingIframe();
	// for URL Date is Appended, As in IE the URL is chached, If we need to call the URL every time then the URL should be Unique.
	//alert("URL:" + paginationURL);
	//$("#tabsLoading").show();	
	//document.getElementById("tabsLoading2").style.display='';
	if(document.getElementById("aa-destination")!=null)
	{
		var selectedCity = document.getElementById("aa-destination").value;
		//alert(selectedCity);
		if(selectedCity!="0")
		{
		 	onChangeUrl = onChangeUrl + "&cityCode="+selectedCity;
		}
	}
	 jQuery.ajax({
		url : onChangeUrl+"&dispatch=cityCodeSearch&date="+new Date().getTime(),		
		dataType: "html",
		success: updateMarketsOnCityChange,
		error: updateMarketsError		
	}); 
}

function cityCodeSearchForUK(onChangeUrl)
{
    showTabsLoadingIframe();
	// for URL Date is Appended, As in IE the URL is chached, If we need to call the URL every time then the URL should be Unique.
	//alert("URL:" + paginationURL);
	//$("#tabsLoading").show();	
	//document.getElementById("tabsLoading2").style.display='';
	if(document.getElementById("aa-destination-uk")!=null)
	{
		var selectedCity = document.getElementById("aa-destination-uk").value;
		//alert(selectedCity);
		if(selectedCity!="0")
		{
		 	onChangeUrl = onChangeUrl + "&cityCode="+selectedCity;
		}
	}
	 jQuery.ajax({
		url : onChangeUrl+"&dispatch=cityCodeSearch&date="+new Date().getTime(),		
		dataType: "html",
		success: updateMarketsOnCityChange,
		error: updateMarketsError		
	}); 
}

function updateMarketsOnCityChange(htmlResponse){

    updateDivWithResponse(htmlResponse);
    //$("#marketsList").html(htmlResponse);
    
	//alert("max value:" + ($("#maxValueHidden").val()));
	//alert("min value:" + ($("#minValueHidden").val()));
	//alert("!max value:" + eval(!($("#maxValueHidden").val())));
	//alert("!min value:" + eval(!($("#minValueHidden").val())));
	
   //	if( (!($("#maxValueHidden").val()) || !($("#minValueHidden").val()))
   		//|| parseInt($("#maxValueHidden").val()) === parseInt($("#minValueHidden").val()) ){
   		//alert("hiding the slider");
   	   // $("#slider").slider("disable");
   	   // $(".aa-fareRange").hide();
   	   //  $("#aa-fareSearchForm-Button").hide();
   	//}else
   	 if(jQuery("#maxValueHidden").val() && jQuery("#fareSearchMaximum")
   			&& jQuery("#minValueHidden").val() && jQuery("#fareSearchMinimum") ){	
   		//alert("Updating the slider");
   	//	$("#slider").slider("enable");    	
   	//	$(".aa-fareRange").show();	 	
   	//	$("#aa-fareSearchForm-Button").show();	
 	 	jQuery("#slider").slider("option","max",parseInt(jQuery("#maxValueHidden").val()));
 		jQuery("#slider").slider("option","min",parseInt(jQuery("#minValueHidden").val()));
		//$("#fareSearchMaximum").text('$' + parseInt($("#maxValueHidden").val()));
		//$("#fareSearchMinimum").text('$' + parseInt($("#minValueHidden").val()));
		jQuery("#fareSearchMaximum").text(jQuery("#currencyHidden").val()  + parseInt(jQuery("#maxValueHidden").val()));
		jQuery("#fareSearchMinimum").text(jQuery("#currencyHidden").val()  + parseInt(jQuery("#minValueHidden").val()));
		jQuery("#fareSearchMaximumField").val(parseInt(jQuery("#maxValueHidden").val()));
		jQuery("#slider").slider("value", parseInt(jQuery("#maxValueHidden").val()));
	}   
    nd();
}

function updateDivWithResponse(htmlResponse){
  //$("#marketsList").html(htmlResponse);
  document.getElementById("marketsList").innerHTML = htmlResponse;
  
  	//	Make sure the table list placeholder is there before trying to use it
	if(jQuery("#fareList").length > 0){
      tableToLinks("#fareList");
    }
}

function onSubmit(onSearchUrl)
{
    showTabsLoadingIframe();
	// for URL Date is Appended, As in IE the URL is chached, If we need to call the URL every time then the URL should be Unique.
	//alert("URL:" + onSearchUrl);
	//$("#tabsLoading").show();	
	//document.getElementById("tabsLoading2").style.display='';
	if(document.getElementById("aa-destination")!=null)
	{
		var selectedCity = document.getElementById("aa-destination").value;
		//alert(selectedCity);
		if(selectedCity!="0")
		{
		 	onSearchUrl = onSearchUrl + "&cityCode="+selectedCity;
		}
	}
	if(jQuery("#fareSearchMaximumField").val() != null)
	{
		var maxVal = document.getElementById("fareSearchMaximumField").value;
		onSearchUrl = onSearchUrl + "&maxPriceSelected="+maxVal;
	}
	if(jQuery("#slider").slider( "option", "max" ) != null){
		var origMax = jQuery("#slider").slider( "option", "max" );
		onSearchUrl = onSearchUrl + "&origMax="+origMax;
	}
	 jQuery.ajax({
		url : onSearchUrl+"&dispatch=onSearch&date="+new Date().getTime(),		
		dataType: "html",
		success: updateMarkets,
		error: updateMarketsError		
	}); 
}

function updateMarkets( htmlResponse){
    updateDivWithResponse(htmlResponse);
    //$("#marketsList").html(htmlResponse);
	//$("#tabsLoading").hide();
	//document.getElementById("tabsLoading2").style.display='none';
	//alert("htmlText:" + htmlResponse);
    //$("#marketsList").html(htmlResponse);
    nd();
}

function updateMarketsError(response){
	//$("#tabsLoading").hide();
	//document.getElementById("tabsLoading2").style.display='none';
	nd();
	alert('FareTool Ajax Error : '+ response);	
	alert('response.status:' + response.status);
	alert('response.text:' + response.responseText);
}

function showTabsLoadingIframe() {
	 if(document.getElementById("locale")!=null)
	 {
	    var locale = document.getElementById("locale").value;
	    if(locale==='en_US' || locale==='en_GB')
	    {
		  overlib(OLiframeContent('/common/loading.jsp','535','221','loading',0,'auto'),FGCLASS,'tabsLoading',BGCLASS,'tabsLoading',BORDER,0,NOCLOSE,-STICKY,REF,'calID',REFC,'UR',REFP,'UR',REFX,-110,REFY,187);
		}
		else{
		  overlib(OLiframeContent('/common/loading_es.jsp','535','221','loading',0,'auto'),FGCLASS,'tabsLoading',BGCLASS,'tabsLoading',BORDER,0,NOCLOSE,-STICKY,REF,'calID',REFC,'UR',REFP,'UR',REFX,-110,REFY,187);
		}
	  }
	  else{
	    overlib(OLiframeContent('/common/loading.jsp','535','221','loading',0,'auto'),FGCLASS,'tabsLoading',BGCLASS,'tabsLoading',BORDER,0,NOCLOSE,-STICKY,REF,'calID',REFC,'UR',REFP,'UR',REFX,-110,REFY,187);
	  }
}

function UK_popUp(getUrl,getWidth,getHeight,getScrollVal) {
    var scrollVal;    
    var theUrl = getUrl;
    var theWidth = getWidth; 
    var theHeight = getHeight;
    var tempVal = getScrollVal.toLowerCase();

    if (tempVal == "y") {
        scrollVal = "yes";
    }
    else if (tempVal == "n") {
        scrollVal = "no";
    }  
    win = window.open(theUrl,"myWin","width="+theWidth+",height="+theHeight+",resizable=0,menubar=1,scrollbars="+scrollVal+",left=100,top=20");
}



function calendarEvent( calendarEventURL,depOrReturn,eventName,dateParam ){
    showTabsLoadingIframe();
	var ajaxURL = calendarEventURL + "&dispatch="+ eventName + "&depOrReturn=" + depOrReturn + "&dateParam=" + dateParam;
	ajaxURL += "&date="+  new Date().getTime();
	//alert("ajaxURL:"+ ajaxURL);
	 jQuery.ajax({
		url : ajaxURL, 		
		dataType: "html",
		success: updateCalendarView,
		error: updateMarketsError		
	}); 
}

function onTripChangeEvent( calendarEventURL, eventName, tripType ){
    //alert("Hi : " + tripType);
    showTabsLoadingIframe();
	var ajaxURL = calendarEventURL + "&dispatch="+ eventName + "&tripType=" + tripType;
	ajaxURL += "&date="+  new Date().getTime();
	//alert("ajaxURL:"+ ajaxURL);
	 jQuery.ajax({
		url : ajaxURL, 		
		dataType: "html",
		success: updateCalendarView,
		error: updateMarketsError		
	}); 
}

function updateCalendarView( htmlResponse){
	//alert("htmlText:" + htmlResponse);
    jQuery("#whenDoYouWantToGo").html(htmlResponse); 
    nd();
}

