var search_queue = {};
var searching_obj = null;
var photo_obj = null;
var photo_cache = new Array();
var photo_list = new Array();
var current_index = 0;
var rs_id = "";
var now = '';
var property_cache = {};

$(function()
{
  
	$('nav ul').hover(  
	   function() {  
		  $(this).addClass('hovered');     /* On hover add the class 'hovered' and apply the hovered styles */ 
	   }, function() {  
		  $(this).removeClass('hovered');  /* On mouseout remove the class 'hovered' and reset the styles   */ 
	   }  
	);  
  
  $("#avs_arrival").datepicker({
	  showOn: 'button',
	  buttonImage: '/cms-themes/Default/images/calendar.png',
	  buttonImageOnly: true,
	  dateFormat: 'mm/dd/yy',
	  minDate: new Date()
  });
	
	
  // quick search
  $("#quick_search .browse_for").click(browseRentals);   
	
  // change search
  if ($('.change_search').length > 0)
  {
	  $(".change_search").click(showAvailabilitySearchForProperty);
  }
		
  if ($('.show_promos').length > 0)
  {
	  $(".show_promos").click(showCurrentPromos);
  }
				
	
  // availability search	
  $('#avs_submit').click(function() {
      setupSearchResults();
  });	
	
  // create the searching overlow
  $("#searching").overlay({
	  // some mask tweaks suitable for facebox-looking dialogs
	  mask: {
		  color: '#000000',
		  loadSpeed: 200,
		  opacity: 0.75
	  },
	  closeOnClick: false
  });
  
  searching_obj = $("#searching").data("overlay");
  $('#searching').bgiframe();

  if ($('#photo_gallery_overlay').length > 0)
  {
	// create the photo gallery overlay
	$("#photo_gallery_overlay").overlay({
		mask: {
			color: '#000000',
			loadSpeed: 200,
			opacity: 0.75
		},
		left: 'center',
		top: 15,
        onBeforeLoad: function() {
          this.getOverlay().appendTo('body');
		}
	});
	
	photo_obj = $("#photo_gallery_overlay").data("overlay");
	$('#photo_gallery_overlay').bgiframe();
	
	
	$('#photos .thumbnail').click(setPhoto);
	$('.property_image').click(setPhoto);
	
	$('#photo_gallery_overlay .prev').click(prevPhoto);
	$('#photo_gallery_overlay .next').click(nextPhoto);
	//cachePhotos();
  }

  if ($('#inquire_date').length > 0)
  {
		$("#inquire_date").datepicker({
				showOn: 'button',
				buttonImage: '/images/calendar.png',
				buttonImageOnly: true,
				dateFormat: 'mm/dd/yy'
			});  
  }
  
  if ($('#top_inquire_date').length > 0)
  {
		$("#top_inquire_date").datepicker({
				dateFormat: 'mm/dd/yy'
			});  
  }
  
  if ($('#top_inquire_form').length > 0)
  {
	  $("#top_inquire_form").validationEngine()
  }    
  
  if ($('#inquire_form').length > 0)
  {
	  $("#inquire_form").validationEngine()
  }  
  
  $( "#auto_properties" ).autocomplete({
	  minLength: 3,
	  source: function(request, response) {
		  if ( request.term in property_cache ) {
			  response( property_cache[ request.term ] );
			  return;
		  }
		  
		  $.ajax({
			  url: "/property-search",
			  dataType: "json",
			  data: request,
			  success: function( data ) {
				  property_cache[ request.term ] = data;
				  response( data );
			  }
		  });
	  },
	  select: function(event, ui) {
		var url = ui.item.id;
		if (url !='' && url != undefined && url != null)
		{
		  window.location.href = url;
		}
	  }
  });
  
  
  loadBookingEngine();
});

function loadBookingEngine(params)
{
  // only do this if the booking engine element exists!
  if ($('#booking_engine').length > 0)
  {
	  setupBookingEngine();
  }
}

function setupBookingEngine()
{
	$("#ls_date").datepicker({
			showOn: 'button',
			buttonImage: '/images/calendar.png',
			buttonImageOnly: true,
			dateFormat: 'mm/dd/yy',
			beforeShowDay : function (date)
			{
				if (date < now)
					return [0];
					
				var day = date.getDate()
				var month = parseInt(date.getMonth()) + 1;
				if (month == arrival_month)
				{
					if (in_array(day, disabled_dates))
					{
						return [0];
					}
					else
					{
						return [1];
					}
				}
				else
				{
					return [0];
				}
			},
			onChangeMonthYear : function (year,month,inst)
			{
				var ran=Math.floor(Math.random()*1000000);
				$.ajax({
					  url: "/get_availability_calendar.php",
					  global: false,
					  type: "GET",
					  async: false,
					  data: ({arrival_month: month, arrival_year: year, rs_id: rs_id, r: ran}),
					  dataType: "text",
					  success: function(data){
						disabled_dates = data.split(',');
						arrival_month = month;
					  }
				   }
				);					
			}				
		});
	
  if ($('#book_now').length > 0)
  {
	  $("#book_now").validationEngine()
  }
  
  if ($('#show_taxes').length > 0)
  {
	  $("#show_taxes").click(function(){
		  $("#tax_details").slideToggle();
		  return false;
	  });
  }
  
  if ($('#card_type').length > 0)
  {
	  $("#card_type").click(function(){
		  $.validationEngine.loadValidation("#card_number");
	  });
  }
  
	if ($('#booking_policy').length > 0)
	{
		$("#booking_policy[rel]").overlay({mask: '#000'});
		$("#booking_overlay").bgiframe();
	}
	
	if ($('#use_travel_insurance').length > 0)
	{
		$("#use_travel_insurance").click(function(){
			$('#travel_insurance_check').val(($(this).attr('checked') ? 1 : 0));
			$('#travel_insurance').submit();
		});
	}	
	
}

function showAvailabilitySearchForProperty()
{
  if ($('#search_area').length > 0)
  {  
	$('#search_area').slideDown();
  }
}

function showCurrentPromos()
{
  if ($('#current_promos').length > 0)
  {  
	$('#current_promos').slideToggle();
  }
}

// cache the large photos for quicker loading
function cachePhotos()
{
 	var args_len = photo_list.length;
	for (i = 0;i<args_len; i++)
	{
	  var cacheImage = document.createElement('img');
	  cacheImage.src = photo_list[i].photo;
	  photo_cache[i] = cacheImage;
	} 
}

function nextPhoto()
{
	current_index++;
	if (current_index >= photo_list.length)
	{
		current_index = 0;
	}
	setPhoto(current_index);
}

function prevPhoto()
{
	current_index--;
	if (current_index < 0)
	{
		current_index = photo_list.length - 1;
	}
	setPhoto(current_index);	
}

function setPhoto(index)
{
	if (!photo_obj.isOpened())
	  photo_obj.load();
	  
	$('#large_image_src').fadeOut(200, function()
	{
		// figure out our index
		if (typeof index != 'number')
		{
			var temp = index.target.id.split('_');
			index = parseInt(temp[1]);
		}
		$("#large_image_src").attr("src", photo_cache[index].src);
		$('#photo_gallery_overlay .caption').html(photo_list[index].caption);
		
		var current_page = current_index + 1;
		
		$('#photo_gallery_overlay .gallery_status').html(current_page + '/' + photo_list.length);
		current_index = index;						
		$("#large_image_src").fadeIn(200);
	});
}


function setupSort()
{
   $('#avs_sort').change(function() {
   	  search_queue['getSearchResults()'] = 'sort';
	  setTimeout(processQueue, 1000);
   });    
}
 
function setupFilters()
{
  $("#search_filters .filter").unbind('click');
	$("#search_filters .filter").click(function(){
	  var key = $(this).attr('name') + $(this).val();
	  search_queue['getSearchResults()'] = key;
	  setTimeout(processQueue, 1000);
  });
}
function setupSearchResults()
{
  $('#browse_rentals').val(0)
  setupFilters();
  getSearchResults();
}

function processQueue()
{
  for (n in search_queue)
  {
	if (n != 'remove')
	{
	  eval(n);
	  delete search_queue[n];
	}
  }
}

function browseRentals(obj)
{
  setupFilters();
  $('#browse_rentals').val(1);
  
  // if we want exact parameters. More than likely through the /search-results page
  if (obj.resort != undefined)
  {
	  $('#quick_bedrooms').val(obj.rooms);
	  $('#keyword').val(obj.keyword);
	  $('p.group_property_type .filter').each(function() {
		  if ($(this).val() == obj.type)
		  {
			$(this).attr('checked', true);
		  }
	  });
	  $('p.group_location .filter').each(function() {
		  if (obj.resort != 'any' && $(this).attr('title').indexOf(obj.resort) > -1)
		  {
			$(this).attr('checked', true);
		  }
	  });
	getSearchResults();
	return false;
  }
 
  $('#quick_bedrooms').val($(this).attr('title'));
  
  $('.filter').attr('checked', false);
  
  if ($('#quick_bedrooms').val() == 'private')
  {
	$('#quick_bedrooms').val('')
	$('p.group_property_type .filter').each(function() {
	    if ($(this).val() == '1')
		{
		  $(this).attr('checked', true);
		}
	});
  }
  getSearchResults();
  return false;
} 

function getSearchResults()
{
	//$("#property_temp").val('');
	  
	if ($('#quick_facts_box').length > 0)
	{
	  $('#quick_facts_box').slideUp();
	}
	  
	var arrival = '';	  
	if ($('#browse_rentals').val() == '0')
	{
	  var arrival = $('#avs_arrival').val();
	  if (arrival == 'mm/dd/yyyy')
	  {
		//TODO make this look nicer, maybe handle it a different way
		alert("Please choose an arrival date");
		return false;
	  }
	}	
	$('#below_search').hide();
	$('#search_filters').slideDown('fast');
	
  
	  
	searching_obj.load();
	  
	var bedrooms = '';
	if ($('#browse_rentals').val() == '0')
	{
	  bedrooms = $('#avs_bedrooms').val();
	}
	else
	{
	  bedrooms = $('#quick_bedrooms').val();
	}	  
	  
	if (bedrooms == 'private')
	{
	  bedrooms = '';
	  $('p.group_property_type .filter').each(function() {
		  if ($(this).val() == '1')
		  {
			$(this).attr('checked', true);
		  }
	  });
	}
   	var property_type = [];
     $('.group_property_type :checked').each(function() {
       property_type.push($(this).val());
     });

   	var rating = [];
     $('.group_rating :checked').each(function() {
       rating.push($(this).val());
     });

   	var amenity = [];
     $('.group_amenities :checked').each(function() {
       amenity.push($(this).val());
     });
	 
     var locations = [];
     $('.group_location :checked').each(function() {
       locations.push(escape($(this).val()));
     });

	var nights = '';     
	if ($('#browse_rentals').val() == '0')
	  nights = $('#avs_nights').val();
	

	var resort = '';
	if ($('#browse_rentals').val() == '0')
	  resort = $('#avs_resort').val();
	  
	var sort = '0';
	if  ($('#avs_sort').length > 0)
	  sort = $('#avs_sort').val();
	 
    var ran=Math.floor(Math.random()*1000000);
	
	var browse = '';
	if ($('#browse_rentals').val() == '1')
	  browse = '&browse=1';	
	
	var keyword = '';
	if ($('#keyword').val() != '')
	  keyword = $('#keyword').val();
	  
	var container = $("#left_column");
	if ($('#property_right_column').length > 0)
	  container = $("#property_right_column");
	  
    container.load("/ajax-search-results?arrival="+arrival+browse+"&nights="+nights+"&rooms="+bedrooms+"&location="+locations+"&resort="+resort+"&amenity="+amenity+"&rating="+rating+"&property_type="+property_type+"&keyword="+keyword+"&sort="+sort+"&r="+ran, function(response, status, xhr){
	   container.html(unescape(response));
	   setTimeout("closeMe()",200);
    });
	
	return true;
}

 function closeMe()
 {
	searching_obj.close();
 }
 
 function doCheckCreditCard()
 {
	var card_num = $('#card_number').val();
	var card_type = $('#card_type').val();
	var val = checkCreditCard(card_num, card_type);
	return (val ? false : true);
 }
 
function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "305, 36, 38, 54,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305",
               checkdigit: true};
  cards [4] = {name: "AmEx", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,622,64,65",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "16", 
               prefixes: "35",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "12,13,14,15,16,18,19", 
               prefixes: "5018,5020,5038,6304,6759,6761",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913,4508,4844",
               checkdigit: true};
  cards [12] = {name: "LaserCard", 
               length: "16,17,18,19", 
               prefixes: "6304,6706,6771,6709",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}
 
 /*** utility functions ***/
 
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;
}
 
var popup;
function openWindow(url,myWidth,myHeight)
{
  if (popup != null && !popup.closed) { 
  	popup.close();
  }
  popup = window.open(url,"","toolbar=0,location=0,directories=0,status=no,scrollbars=yes,menubar=0,resizable=yes,screenX=10,screenY=10,left=10,top=10,width=" + myWidth + ",height=" + myHeight);
}