// JavaScript Document
var hotels = new Array();
var curCurrency = "EUR";
var currenthotels = null;
var start = 0 ;
var last = 0;
var hotelNameFilter = '';
var hotelsortField = 'price';
var hotelresultsPerPage = 15;
var hotelpages = 0;
var isMapMode = false;
var hotelcurPage = 0;
var rating = new Dictionary(); //
var facilities = new Dictionary(); //
var suppliers = new Dictionary(); //
var type = new Dictionary(); //
var hotelfiltered ;//= filterSimilarHotels(hotelfiltered);
var hotelfilteredNoDupplicates;

if(!maxPriceYet)
  var maxPriceYet = 0;
if(!minPriceYet)
  var minPriceYet = 1000000;
if(!maxpr)
  var maxpr = 0;
if(!minpr)
  var minpr = 1000000;
if(!CurrencyCode)
  var CurrencyCode = curCurrency;
var updateFilters = true;
var filterMinPrice = 0;
var filterMaxPrice = 100000;
var ratingFilter = new Array();
var facilitiesFilter = new Array();
var suppliersFilter = new Array();
var typeFilter = new Array();
var detailedHotelId = "-1";

var done;
var searching;
var noImageStr = "No Image Available";
var defaultImage = "gz_files.php?uri=images/cached/defaulthotel.jpg";
var supplierLogoPath; supplierLogoPath = "getimage.php?type=2&u=http://www.travelfusion.com/images/logos/";
var hotelimagespath; hotelimagespath = "getimage.php?type=3&u=";
var isMapInitialized = false;
var map  = false;
var similarHotelsCount =0;
var isSingleMode; isSingleMode = false;
total = 0;
totalCalculated = false;
var tmphotels = [];

function setCookie(c_name,value,expiredays)
{
  $.cookie(c_name, value, {path: '/~travel/', expires: 10 })
  $.cookie(c_name, value, {expires: 10 })
}
/* function setCookie(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
  document.cookie=c_name+ "=" +escape(value)+";path=/~travel/"+
  ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
} */
isDebug=false;
function debug(str)
{
   if(isDebug)alert(str);
}
//alert(exchangeRates);

function getStarsHTML(stars)
{  
	starsHtml = "";
  stars=Math.round(stars);
	for(s = 0; s < stars ; s++)
	{
		starsHtml += '<img src="gz_files.php?uri=images/star.jpg" alt="" />';
	}
	for(s=s; s < 5; s++)
	{
		starsHtml += '<img src="gz_files.php?uri=images/star-1.jpg" alt="" />';
	}
  return starsHtml;
}
function getPriceRangeHTML()
{
	/* if(hotels.length < 1)
		return; */
	minPrice = parseFloat(minPriceYet);
	maxPrice = parseFloat(maxPriceYet);  
	//minPrice = currencyConvert(minPrice);
	//maxPrice = currencyConvert(maxPrice);
	//minPrice = roundToNearest(currencyConvertEx(minPrice,CurrencyCode),1);
	//maxPrice = roundToNearest(currencyConvertEx(maxPrice,CurrencyCode),1);
  //alert(minPrice + " ; " + maxPrice);
  
	var maxFilters = 4;
	var endRange = maxPrice ;
	//var startRange = minPrice + (Math.random() + 10);
	//var avg = (endRange-startRange) / maxFilters;
	var avg = endRange / maxFilters;
  var startRange = avg;
  
	var lastR = 0;
  html = '<ul><li><input name="radioPrice" type="radio" onclick="priceRangeChanged(this.value)" value="All" checked="checked" /> ' + Language['Results_Flights_STRING_AllPrices'] + '</li>' ;
  if (minPrice > 0 || maxPrice < 100000)
  {
    for(var i = 0; i < maxFilters ; i++)
    {
      startRange = roundToNearest(startRange,10);
      //var priceStr = formatPriceEx(startRange, false);
      stRange = roundToNearest(currencyConvertEx(lastR,CurrencyCode),1);
      endRange = roundToNearest(currencyConvertEx(startRange,CurrencyCode),1);
      var priceStr = formatPriceEx(endRange, false);
      if(lastR == minpr && startRange == maxpr)
        html += '<li><input name="radioPrice" type="radio" value="'+lastR + '-' +  startRange +'" onclick="priceRangeChanged(this.value)" checked="checked"  /> ' +   formatPriceEx(stRange,false) + ' - ' +  priceStr + ' ' + curCurrency + '</li>';
      else
        html += '<li><input name="radioPrice" type="radio" value="'+lastR + '-' +  startRange +'" onclick="priceRangeChanged(this.value)"  /> ' +   formatPriceEx(stRange,false) + ' - ' +  priceStr + ' ' + curCurrency + '</li>';
      lastR = startRange;
      
      startRange = startRange + avg;
    }
    startRange = roundToNearest(lastR,50);
    stRange = roundToNearest(currencyConvertEx(startRange,CurrencyCode),1);
    //endRange = roundToNearest(currencyConvertEx(startRange,CurrencyCode),1);
    
    if(startRange == minpr && 100000 == maxpr)
      html +='<li><input name="radioPrice" type="radio" value="Above-' + startRange + '" onclick="priceRangeChanged(this.value)" checked="checked"  /> ' + Language['Results_Flights_STRING_PricesAbove'] + ' ' + stRange + ' ' + curCurrency + '</li>' ;
    else
      html +='<li><input name="radioPrice" type="radio" value="Above-' + startRange + '" onclick="priceRangeChanged(this.value)"  /> ' + Language['Results_Flights_STRING_PricesAbove'] + ' ' + stRange + ' ' + curCurrency + '</li>' ;
  }
  
	html += "</ul>";
	//$("#priceRanges").html(html);
  return html;
}
function setPriceRangeHTML()
{
  $('#priceRanges').html(getPriceRangeHTML());
}
function priceRangeChanged(val)
{
	if(val == "All")
	{
		filterMinPrice = 0;
		filterMaxPrice = 100000;
	}
	else
	{
		vA = val.split("-");
		valMin = vA[0];
		valMax = vA[1];
    
		if(valMin == "Above")
		{
			filterMinPrice = valMax;
			filterMaxPrice = 100000;
		}else
		{
			filterMinPrice = valMin;
			filterMaxPrice = valMax;
		}
    //alert(pageURL);
	}
  setPriceRange();
	//sethotels();
}
function setPriceRange()
{
  //qryStr=(qryStrPR=='')?'':'&'+qryStrPR;
  if(filterMinPrice==0 && filterMaxPrice==100000)
    location.href=pageURL+'?'+qryStrPR;
  else
    location.href=pageURL+'?minpr='+filterMinPrice+'&maxpr='+filterMaxPrice+((qryStrPR=='')?'':'&'+qryStrPR);
}
function setHNameFilter(hname)
{
  if(hname=='')
    location.href=pageURL+'?'+qryStrHName;
  else
    location.href=pageURL+'?hName='+hname+((qryStrHName=='')?'':'&'+qryStrHName);
}
function filterHotelName(){
  fStr=document.getElementById('txtHotelName').value;
  if (fStr!='')
  {
    hotelNameFilter=fStr;
    setHNameFilter(fStr);
  }
  //return false;
}
function resetHName(){
  hotelNameFilter='';
  document.getElementById('txtHotelName').value='';
  setHNameFilter('');
}
function filterFacility(name,value,checked){
	//alert(name);alert(value);alert(checked);
  filterhotelsClicked(name,value,!checked);//alert(name);
  filter = eval(name);//alert(filter);
  filterStr = eval(filter);//alert(filterStr);
  if(filterStr!='')
    location.href=pageURL+'?facilities='+filterStr+((qryStrFac=='')?'':'&'+qryStrFac);
  else
    location.href=pageURL+((qryStrFac=='')?'':'?'+qryStrFac);
}
function setRatingFilter()
{
  for(i=0; i<=5; i++) {
    addLookup(rating, i, i);
  }
  //setPriceRangeHTML();
  $('#ratingFilter').html(getFilterHTMLRatings("ratingFilter",rating));
}
function setFacilityFilter()
{
  for(i=0; i<=5; i++) {
    addLookup(facilities, i, i);
    //filterhotelsClicked("facilitiesFilter",i,false);
  }
}//setFacilityFilter();
function getFilterHTMLRatings(name,list)
{
  //alert(ratingEx);
  if(ratingEx!='')
    ratEx=ratingEx.split(",");
  else
    ratEx= Array();
	wHtml = "<ul>";
	var pairs = list.Pairs();
	pairs.sort(sortStars);
  for (var i = 0; i < pairs.length; i++)
  {
    var pair = pairs[i];
    stars = parseInt(pair.value);
    starsHtml = getStarsHTML(stars);
    if(in_array(stars,ratEx)){
      chkState='';
      filterhotelsClicked(name,stars,false);
    }else{
      chkState='checked="checked"';
      filterhotelsClicked(name,stars,true);
    }
    wHtml += '<li><input name="'+ name +'" type="checkbox" value="' + stars + '"  onclick="setFilter(this.name,this.value, this.checked)" '+chkState+' /> ' + starsHtml + ' </li>';    
  }
  //wHtml += '<li><input name="'+ name +'" type="button" value="Go"  onclick="setFilter(this.name)" /></li>';    
	wHtml += "</ul>";
	return wHtml;
}
function filterhotelsClicked(name,value,checked)
{
  value=parseInt(value);
  filter = eval(name);
  if (checked==true) {
	  // remove from filter
	  var i = filter.indexOf(value);
	  if (i>=0)
	  filter.splice(i, 1);
  }else  {
	  // add to filter
	  filter.condAdd(value);
  }
}
function setFilter(name,value,checked)
{
  filterhotelsClicked(name,value,checked);
  filter = eval(name);
  ratStr = eval(filter);//alert(ratStr);
  if(ratStr!='')
    location.href=pageURL+'?pg=0'+'&ratingEx='+ratStr+((qryStrRat=='')?'':'&'+qryStrRat);
  else
    location.href=pageURL+'?pg=0'+((qryStrRat=='')?'':'&'+qryStrRat);
}
function addLookup(list, code, text)
{
  var res = list[code];
  if (res == null)
  {
      // not in list - add text (or code, if text is empty)
      list[code] = (text == null || text == '' ? code : text);
      updateFilters = true;
  }
  else if (res == code)
  {
      // already in list, equal to code and text is assigned - set text (it must be better)
      list[code] = text;
      updateFilters = true;
  }
}
function setCurrency(curr)
{
  curCurrency = curr.toUpperCase();
  //alert(curCurrency);
  setCookie("Currency",curCurrency);
  location.replace(location.href);
  //setHotels();
}

function showHotels(curr)
{
  
	//$.blockUI();
  curCurrency = curr.toUpperCase();
  setHotelCurrency();
  setPriceRangeHTML();
  
  //alert(hotels.length);
  setRatingFilter();
  showMap();
  //$.unblockUI();
}

function setHotelCurrency()
{ //alert(searchPg);
  for(i=0; i<hotels.length; i++) {
    arr= [];  amt=0;
    //alert(hotels[i].Price);
    if(searchPg==1){
      curency=rateListCurr;
      //alert(hotelRateList.length);
      /* if (hotelRateList.length == 0) {
        amt=hotels[i].Price;
        curency=hotels[i].CurrencyCode;
        amt = roundToNearest(currencyConvertEx(amt,curency),1);//alert(amt);
      }else{ */
        if(hotelRateList[hotels[i].HotelID]){
          lstHTML = 'Book on: ';
          rates=hotelRateList[hotels[i].HotelID]['Rates'];
          amt=rates[0]['ConvertedPrice'];
          //amt=Math.round(rates[0]['ConvertedPrice']/noOfDays);
          for(j=0; j<rates.length; j++) {
            //foreach(rates as rate){
            provAmt=number_format(rates[j]['ConvertedPrice']);
            prov=rates[j]['ProviderName'];
            //prov=rates[j]['ProviderName'].split('.');
            //prov=prov[0];
            //lstHTML += '<a href="hotel/'+hotels[i].HotelFileName+'.htm" target="_blank">' + prov +':&nbsp;'+curency+'&nbsp;'+ provAmt + '</a>&nbsp; ';
            lstHTML += '<a href="book.php?key='+rates[j]['Key']+'&provider='+prov+'" target="_blank">' + prov +':&nbsp;'+curency+'&nbsp;'+ provAmt + '</a>&nbsp; ';
            if(j==2)break;
          }
          //$('#allPrice_'+i).html('<a href="hotel/'+hotels[i].HotelFileName+'.htm">all prices &gt;&gt;</a>');
          //$('#allPrice_'+i).html('<a href="'+hotels[i].NavURL+'">all prices &gt;&gt;</a>');
          $('#allPrice_'+i).show();
        }else{
          amt='Not Available';
          lstHTML='';
        }
        $('#priceList_'+i).html(lstHTML);
      //}
    }else{
      amt=hotels[i].Price;
      curency=hotels[i].CurrencyCode;
      amt = roundToNearest(currencyConvertEx(amt,curency),1) ;
    }
    if (amt=='Not Available')
    {
      prcHTML='<div class="price">Not Available</div>';
    }else
    if(amt!='' && amt>0){
      //Price = roundToNearest(currencyConvertEx(amt,curency),2) + ' ' + curCurrency ;
      //Price = curCurrency + ' ' + Math.round(currencyConvertEx(amt,curency));
      Price = curCurrency + ' ' + number_format(amt);
      prcHTML='<div class="price"><strong>Prices from</strong></div><div class="price-txt">'+Price+'</div>';
    }else{
      prcHTML='<div class="price">&nbsp;</div>';
    }
    //alert(Price);
    $('#price_'+i).html(prcHTML);
  }
}
function chekPrices()
{
  document.getElementById('txtHotelCheckInDate').focus();
}
function sortStars(a,b)
{
	if(isNaN(a.value))
		a.value = 0;
	if(isNaN(b.value))
		b.value = 0;
	return a.value - b.value;
}
function in_array(needle, haystack, argStrict) { 
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    } 
    return false;
}
function initialize() {
	if (!isMapInitialized)
	{
    try {
      GBrowserIsCompatible();
      map = new GMap2(document.getElementById("map_canvas"));
      map.setCenter(new GLatLng( 37.4419, -122.1419), 13);
      $("#map_canvas").hide();
      $("#map_canvas").show();
      isMapInitialized = true;
      //alert("hello");
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
      //map.addControl(new GScaleControl());
      map.enableContinuousZoom();
      //map.enableScrollWheelZoom();
    }catch(err){
    }
  }
}
function showDetailedOverlay(hotel)
{
	map.clearOverlays();
	addMarker(hotel,true	);
	if(hotel.GeoCoordinates != null)
	{
		map.panTo(new GLatLng(hotel.GeoCoordinates.Latitude, hotel.GeoCoordinates.Longitude));
	}
}
function addClickevent(marker)
{
	GEvent.addListener(marker, "click", function() {
  	marker.openInfoWindowHtml(marker.html,{maxWidth:350});});
	return marker;
}
function addMarker(hotel,isDetailed)
{
	if(hotel.GeoCoordinates != null)
	{
		var latlng = new GLatLng(hotel.GeoCoordinates.Latitude, hotel.GeoCoordinates.Longitude);
		var marker;
		if(isDetailed)
		{
			var blueIcon = new GIcon(G_DEFAULT_ICON);
			markerDetailed = { icon:blueIcon };
			marker = new GMarker(latlng, markerDetailed);
		}
		else
		  marker = new GMarker(latlng, markerOptions);
		if (latlng != null && marker != null)
		{
			stars = hotel.Stars;
			/* if(stars == "UNK")
			{
				stars = 0;
			} */
			starsHtml = getStarsHTML(stars);
			//Price = roundToNearest(currencyConvert(hotel.Option[0].Price),1) ;
			Price = roundToNearest(currencyConvertEx(hotel.Price,hotel.CurrencyCode),1) ;
			Address = "";
			if(hotel.Address)
				Address = hotel.Address;
			hotelImage  = defaultImage;//"/images/cached/DefaultImage.jpg";
			if(hotel.Images && hotel.Images.length > 0)
				hotelImage = hotelimagespath + hotel.Images[0];
			hotelName = hotel.Name;
			
			if(marker != null && marker != "undefined")
			{
				cLink = "";
				lnk = hotel.Name;
				if(!isDetailed)
				{
					//lnk = '<a href="javascript:openHotel(' + hotel.HotelID + ')" style="color:#B30202; text-decoration:underline" >' + hotel.Name + '</a>';
					lnk = '<a href="hotel/'+hotel.HotelFileName+'.htm" style="color:#B30202; text-decoration:underline" >' + hotel.Name + '</a>';
				}
				else
				{
					cLink =  '<a href="javascript:closeHotel(' + hotel.HotelID + ')" style="color:#B30202; font-size:10px; text-decoration:underline" >Back to search results</a>';
					cLink = "<div style='padding-top:10px'>" + cLink + "</div>";
				}
				//Price = roundToNearest(currencyConvert(hotel.Option[0].Price),1) + ' ' + Currency;
				PriceStr = Price + ' ' + curCurrency ;
				
				marker.html = "<div>\
				  <div class='infoWindow'><img src='" + hotelImage + "' class='Hotel' />\
					<div>" + starsHtml + "</div>\
					<div class='Name'>" + lnk + "</div>\
					<div class='Address' style='padding-top:10px'>" + Address +"</div>\
					<div style='padding-top:10px'>Prices Starting From: \
					<span style='color:#B30202; font-weight:bold'>" + PriceStr + "</span></div>\
					" + cLink + "<div style='clear:both'></div>\
				  </div>";
				map.addOverlay(marker);
				addClickevent(marker);
			}
		}
	}
}
function resetMapMarkkers()
{
	if(!hotels || hotels.length < 1)
		return;
	if(!isMapInitialized)
		initialize();
  if(isMapInitialized){
	  map.clearOverlays();
	  // Create our "tiny" marker icon
    var blueIcon = new GIcon(G_DEFAULT_ICON);

    blueIcon.image = 'images/blank.png';
    blueIcon.shadow = 'images/shadow50.png';
    blueIcon.iconSize = new GSize(12,21);
    blueIcon.shadowSize = new GSize(22,20);
    var markers = new Array();
    
    // Set up our GMarkerOptions object
    markerOptions = { icon:blueIcon };
    setCenter = false;
    setPan = false;
    //for (var i = start; i < last; i++)
    for (var i = 0; i < hotels.length; i++)
    {
      hotel = hotels[i];
      if(hotel && hotel.GeoCoordinates != null && hotel.GeoCoordinates.Latitude>0)
      {
        addMarker(hotel,false);
        if(!setPan){
          setPan = true;
          map.panTo(new GLatLng(hotel.GeoCoordinates.Latitude, hotel.GeoCoordinates.Longitude));
        }
      }
    }
    /* if(hotels && hotels.length > 0)
    {
      hotel = hotels[start];
      if(hotel && hotel.GeoCoordinates != null)
      {
        map.panTo(new GLatLng(hotel.GeoCoordinates.Latitude, hotel.GeoCoordinates.Longitude));
      }
    } */
  }
}

function showMap()
{
  if(!isMapMode && hotels && hotels.length > 0)
  {
    isMapMode = true;
    var panelMaps = $('#maps');
    panelMaps.show();
  }
  resetMapMarkkers();
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, prec = decimals;
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
 
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
    if (s.indexOf(dec) === -1 && prec > 1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}
function updateFilterText()
{
    var panel = $('#filterText');
    setInnerHtml(panel, getFilterText());
}

function getFilterText()
{
    var text = '<span style="font-weight: bold">' + hotelResCount + '</span> of ' + 
        '<span style="font-weight: bold">' + hotelAllCount + '</span> options match your criteria' + '.';
    return text;
}