/* Page
===========================================================================*/

YAHOO.util.Event.onDOMReady(function (ev) {
  var opaqueLink = YAHOO.util.Dom.get("opaque-link");
  
  YAHOO.util.Event.addListener(opaqueLink, 'mouseover', function() {
    YAHOO.util.Dom.setStyle('opaque_tooltip','display', 'block');
  });
  
  YAHOO.util.Event.addListener(opaqueLink, 'mouseout', function() {
    YAHOO.util.Dom.setStyle('opaque_tooltip','display', 'none');
  });
});

/* Misc
===========================================================================*/

function validateDates() {
  var ciDate = new Date($('#check_in').val());
  var coDate = new Date($('#check_out').val());
  if (ciDate == 'Invalid Date' || coDate == 'Invalid Date') {
    alert("Invalid dates were entered. Please verify your check-in and check-out dates.");
    return false;
  };

  if (ciDate >= coDate) {
    alert("Check-in date must be before check-out date.");
    return false;
  };

  if (coDate - ciDate >= 86400000 * 30) {
    alert("Check-out date must be less than 30 days from check-in date.");
    return false;
  };
  return true;
};

$(function(){
  // Populate Search links
  $(".populate-search").click(function(e) {
    e.preventDefault();
    
    var search_form = $("#search");
    
    // Property or Market?
    if ($(this).is("a")) {
      var link = $(this);
    } else {
      var link = $($(this).find("a")[0]);
    }
    
    // Change form[action] (Market vs Property)
    var href = link.attr("href");
    
    search_form.attr("action", href);
    
    if (href.indexOf("destination=") != -1) {
      $("#destination").val(href.split("destination=")[1].split("&")[0]);
    } else {
      $("#destination").val("");
    }
    
    if (href.indexOf("#") != -1) {
      $("#tab").val(href.split("#")[1]);
    } else {
      $("#tab").val("");
    }
    
    // Show Title (Market vs Property)
    var text = link.attr("title") || link.text();
    
    search_form.find(".promo-title-booking-form").text(text).css(
      { backgroundColor: "#ffcc00" }
    ).animate({ backgroundColor: "#E7F6C9" }, 1500, "linear");
    
    // Enable Search Button
     search_form.find(".submitbutton-grayedout").addClass("submitbutton").removeClass("submitbutton-grayedout");
    
    // Scroll up to form
    $.scrollTo(search_form, 250);
  }).find("a").click(function(e) {
    e.preventDefault();
  });
  
  
  // (1) - when user clicks a hotel -or- location, prepare div#dates-popup by passing over values
  $('a.dates-popup').click(function() {
    // hide div#dates-popup
    $('div#dates-popup').hide();
    
    // get name, type, permalink
    lh_name = $(this).parents("li").find("h4:first").text(); // hotel name
    lh_type = 'hotel';
    if(lh_name=='') {
      lh_name = $(this).text(); // location name (ex: los angeles, ca)
      lh_type = 'location';
    }
    lh_permalink = $(this).attr('href');
    
    // copy name, type, permalink    
    $('div#dates-popup h3').text(lh_name);
    $('div#dates-popup input#lh_type').val(lh_type);
    $('div#dates-popup a.go').attr('href', lh_permalink);
    
    // go to div#dates.popup and show
    $(this).attr('href', '#dates-popup');
    $('div#dates-popup').fadeIn();
  });
  
  
  
  
  // (2)
  // append 'check_in' and 'check_out' dates into a.go
  // validate
  // ex: http://www.getaroom.com/properties/orlando-courtyard-suites?check_in=05/23/2009&check_out=05/29/2009
  $('div#dates-popup a.go').click(function() {
    // get check_in, check_out and type
    check_in = $('#check_in').val();
    check_out = $('#check_out').val();
    lh_type = $('#lh_type').val();
    
    // validations
      // dates exist?
      // dates formatted correctly?
      // check_in before check_out?
      // diff between check_in and check_out less than 30 days?
      // copy from getaroom.com/javascripts/app_search.js ?
    
    // get the url
    href = $(this).attr('href');
    
    // apply url formatting based off of lh_type
    if(lh_type=="location"){href+='';}
    if(lh_type=="hotel"){href+='?';}
    
    // append dates to url
    href += '&check_in='+check_in+'&check_out='+check_out;
    
    // go to url
    location.href = href;
    
    // prevent link from going anywhere or acting normally
    return false;
  });
});  

$(document).ready(function() {
	// date fields
	 var zeroPad = function(num, digits) {
	   num = num.toString();

	   while (num.length < digits) {
	     num = "0" + num;
	   }

	   return num;
	 };

	 var stringFromDate = function(d) {
	   return zeroPad(d.getMonth() + 1, 2) + '/' + zeroPad(d.getDate(), 2) + '/' + d.getFullYear();
	 };

	 var setupDateField = function(state) {
	   var container = YAHOO.util.Dom.get("search-check" + state),
	       input     = YAHOO.util.Dom.get("check_" + state);
	       div       = document.createElement("div");

	   if (!container || !input) {
	     if (window.console) { console.log("Invalid date field state { container: " + container + ", input: " + input + " } (" + state + ")"); }
	     return null;
	   }

	   div.id        = "check" + state + "-cal";
	   div.className = "dual-calendar";
	   container.appendChild(div);

	   var cal = new YAHOO.widget.CalendarGroup(div.id, {
	     selected: input.value,
	     mindate: (state == "in") ? new Date() : YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 1)//,
	   });

	   YAHOO.util.Event.on(input,                                 "focus", cal.show, cal, true);
	   YAHOO.util.Event.on(container.getElementsByTagName("img"), "click", cal.show, cal, true);

	   YAHOO.util.Event.on(input, "change", function(e) {
	     if (this.value.match(/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/) == null) {
	       this.value = "";
	     }
	   });

	   cal.selectEvent.subscribe(function(type, args, obj) { 
	     var date = cal.toDate(args[0][0]);

	     if (date) {
	       input.value = stringFromDate(date);
	     }

	     cal.hide();
	   });

	   cal.beforeShowEvent.subscribe(function(type, args, obj) {
	     if (input.value) {
	       cal.deselectAll();
	       cal.cfg.setProperty("selected", input.value);

	       var date = cal.getSelectedDates()[0];

	       if (date) { cal.cfg.setProperty("pagedate", date); }

	       cal.render();
	     } else {
	       cal.deselectAll();
	       cal.cfg.setProperty("pagedate", new Date());
	       cal.render();
	     }
	   });

	   cal.render();

	   return cal;
	 };

	 var checkInCal  = setupDateField("in");
	 var checkOutCal = setupDateField("out");

	 if (checkInCal && checkOutCal) {
	   // Autoupdate check-out date when changing check-in date
	   checkInCal.selectEvent.subscribe(function(type, args, obj) {
	     var date = checkInCal.toDate(args[0][0]);

	     if (date) {
	       date = YAHOO.widget.DateMath.add(date, YAHOO.widget.DateMath.DAY, 2);

	       YAHOO.util.Dom.get("check_out").value = stringFromDate(date);
	     }
	   });

	   // If navigating via keyboard, avoid overlapping calendars
	   YAHOO.util.Event.on("check_out", "focus", checkInCal.hide,  checkInCal,  true);
	   YAHOO.util.Event.on("check_in",  "focus", checkOutCal.hide, checkOutCal, true);

	   // Close calendars when page clicked
	   YAHOO.util.Event.on(document.documentElement, "click", function(e) {
	     var target     = YAHOO.util.Event.getTarget(e),
	         checkInEl  = YAHOO.util.Dom.get("search-checkin"),
	         checkOutEl = YAHOO.util.Dom.get("search-checkout");

	     if (target != checkInEl && !YAHOO.util.Dom.isAncestor(checkInEl, target)) {
	       checkInCal.hide();
	     }

	     if (target != checkOutEl && !YAHOO.util.Dom.isAncestor(checkOutEl, target)) {
	       checkOutCal.hide();
	     }
	   });
	 }	

	function formatDate(date) {
	  var mo = date.getMonth() + 1;
	  var dy = date.getDate();
	  var yr = date.getFullYear();

	  if (mo < 10) {
	    mo = "0" + mo;
	  };
	  if (dy < 10) {
	    dy = "0" + dy;
	  };
	  return mo + "/" + dy + "/" + yr;
	};

// });

/*functions for displaying room/adult/children/ages form fields*/
// $(document).ready(function() {
	
	$("#rinfo").val("");
	var searchSet = "";
	$("#rooms").change(function() {
		
		var roomsSel = $(this).val();
		var numRooms = $("#rooms_search_list").children().size();

		for (var room=numRooms; room<roomsSel; room++) {	
		
			var roomIndex = room+1;
		
			($("#rooms_search_list")).append(insertNextRoom(room+1));
			($("#room_" + roomIndex + "_children")).bind("change", function(){
				
				var childrenId = $(this).parent().attr("id");
			 	var idnum = childrenId.substr(childrenId.length-1,childrenId.length);
			 	var additionalChildren = $("#"+childrenId).find(".child-ages").children().size();
				//append
				for (var childIndex = additionalChildren; childIndex < $(this).val(); childIndex++) {
					($("#"+childrenId).find(".child-ages").append(insertNextChild(idnum,childIndex+1)));
				}
				//remove
				for (var n=1; n<(additionalChildren+1); n++){
					if (n > $(this).val()) {
						$("#"+childrenId).find(".child-ages").children(':last-child').remove();
					}
				}
			});
		}		
		//see if we need to remove any
		for (var n=1; n<numRooms+1; n++){
			if (n > roomsSel) {
				$("#rooms_search_list").children(':last-child').remove();
			}
		}	
	});
	
	
	//bind the children dropdowns depending on number of rooms 
	var rooms = parseInt($("#rooms").val(), 10);
	
	for (var i = 1; i < rooms+1; i++) {		
			
		$("#room_" + i + "_children").bind("change", function(){
					
			var childrenVal = $(this).val();
			var childrenId = $(this).parent().attr("id");
			
			var idnum = childrenId.substr(childrenId.length - 1, childrenId.length);
			var additionalChildren = $("#" + childrenId).find(".child-ages").children().size();
			//append
			for (var childIndex = additionalChildren; childIndex < childrenVal; childIndex++) {
				($("#" + childrenId).find(".child-ages").append(insertNextChild(idnum, childIndex + 1)));
			}
			//remove
			for (var n = 1; n < (additionalChildren + 1); n++) {
				if (n > childrenVal) {
					$("#" + childrenId).find(".child-ages").children(':last-child').remove();
				}
			}
		});
	}
	
	//inserts for more rooms/children
	function insertNextRoom(room) {
		return '<li class=\"search-grouping\">\n	<div class=\"room-num\">Room '+room+'</div> <div class=\"search-adults\">\n	 	<label for=\"adults'+room+'\">Adults<\/label>		<select class=\"booking-select\" id=\"room_'+room+'_adults\"><option value=\"1\">1<\/option>\n<option value=\"2\" selected=\"selected\">2<\/option>\n<option value=\"3\">3<\/option>\n<option value=\"4\">4<\/option>\n<option value=\"5\">5<\/option>\n<option value=\"6\">6<\/option>\n<option value=\"7\">7<\/option>\n<option value=\"8\">8<\/option><\/select>		<span class=\"age-text\">(ages 18+)<\/span>\n	<\/div>\n	<div id=\"children_'+room+'\" class=\"search-children\">\n		<label for=\"room_'+room+'_children\">Children<\/label>		<select class=\"booking-select\" id=\"room_'+room+'_children\"><option value=\"0\">0<\/option>\n<option value=\"1\">1<\/option>\n<option value=\"2\">2<\/option>\n<option value=\"3\">3<\/option>\n<option value=\"4\">4<\/option>\n<option value=\"5\">5<\/option>\n<option value=\"6\">6<\/option>\n<option value=\"7\">7<\/option>\n<option value=\"8\">8<\/option><\/select> <span class=\"age-text\">(ages 0-17)<\/span>	\n<div class=\"child-ages\"></div><\/div>\n<\/li>';
	};
	
	function insertNextChild(room, child) {	
		return '<div class=\"child\">\n	<label for=\"room_'+room+'_age_'+child+'\" class=\"child-age\">Age of Child #'+child+'<\/label>\n	<select id=\"room_'+room+'_age_'+child+'\"><option value=\"\" selected=\"selected\">-<\/option>\n<option value=\"0\">&lt; 1<\/option>\n<option value=\"1\">1<\/option>\n<option value=\"2\">2<\/option>\n<option value=\"3\">3<\/option>\n<option value=\"4\">4<\/option>\n<option value=\"5\">5<\/option>\n<option value=\"6\">6<\/option>\n<option value=\"7\">7<\/option>\n<option value=\"8\">8<\/option>\n<option value=\"9\">9<\/option>\n<option value=\"10\">10<\/option>\n<option value=\"11\">11<\/option>\n<option value=\"12\">12<\/option>\n<option value=\"13\">13<\/option>\n<option value=\"14\">14<\/option>\n<option value=\"15\">15<\/option>\n<option value=\"16\">16<\/option>\n<option value=\"17\">17<\/option><\/select>\n<\/div>';
	};
	
	
	// $('#search').bind('submit', function() {
	//     return validateDates();
	//   });

	//bind search function to btn
	$('#search').bind('submit', function(e) {
		if ($(this).find(".submitbutton-grayedout").length) {
			e.preventDefault();
			alert("Please select a hotel or destination to continue.");
			return;
		}
		
		// return validateDates();
		//get and set the initial values
		var rooms = parseInt($("#rooms").val(), 10);
		var adultAge = 18;
		var ageAlert = false;
		var ageAlertMsg = "Please enter the age of every child";
		//searchSet = json object to send to search
		searchSet = "[";
		
		// get and add rooms/adults/children
		for(var x=0; x<rooms; x++){
			searchSet += "[";
			var adults = parseInt($("#room_"+(x+1)+"_adults").val(), 10);
			var children = parseInt($("#room_"+(x+1)+"_children").val(), 10);
			
			for(i=1; i<children+1; i++) {
				searchSet += parseInt($("#room_"+(x+1)+"_age_"+i).val(), 10) +",";
				//check for empty child ages
				if ( $("#room_"+(x+1)+"_age_"+i+" option[selected]").val() == "" ) {
					if (ageAlert == false) {
						alert(ageAlertMsg);
						ageAlert = true;
						return false;
					};
				};
			};
			
			for(i=0; i<adults; i++) {
				searchSet += adultAge+",";
			};
			
			searchSet += "],";
			//remove extra garbage
			searchSet = searchSet.replace(/,],$/,"],");	
		};
		
		searchSet += "]";
		//remove more garbage
		searchSet = searchSet.replace(/,]$/,"]");
		searchSet = searchSet.replace(/,]]$/,"]]");
		
		//strip off extra form names we don't need to pass
		$("#search").find("select").removeAttr("name");
		
		//populate rinfo
		$("#rinfo").val(searchSet);	
	});
});



// $(document).ready(function() {
	// search fields
	// $("input[id^='popular_city']").bind("click",function() {
	//   $('#destination').val(this.value);
	//   clear_dest=true;
	// });
	// $('#destination').bind('click', function(){
	//   $("input[id^='popular_city']").attr('checked','');
	//   if (clear_dest) {
	//     $('#destination').val("");
	//   }
	// });
// 	$('#destination').bind('blur', function(){
// 	  clear_dest=false;
// 	});
// 	$("#destination").attr("autocomplete", "off");
// 	$("#destination").autocomplete("www.getaroom.com/locations/list.js", { selectFirst: true, minChars: 2 });
// });