$(function(){
	endecaSearch.init();
});

var endecaSearch = {

	// Keep track of fetched quick views so we don't get them unecessarily
	fetchedQuickViews : Array,

    init : function() {
        
        // Collapse all 'more' links, and more link listeners
        endecaSearch.closeMenus();
        lis = document.getElementsByTagName('LI');
        for(var i = 0; i < lis.length; i++){
        	if(lis[i].className.match("more-link")){
                // Attach the listeners
                var moreLink = utils.findChildNode(lis[i]);
                moreLink.onclick = endecaSearch.openMenu;
        	}
        }        
		
		//Attaching jquery tabs for Advanced Search
		var advanceSearchTabs;
		if($('#search-forms').length > 0){
			advanceSearchTabs = $('#search-forms').tabs();
			//if comming to the page and searchType is other than inCity, then we need to select proper tab.
			//when first come to the page
			 $('input:radio[name=searchType]:checked').parents('li').find('a').click();
			 //when tab radio button is clicked
			 $('input:radio[name=searchType]').click(function(e){
				$(e.target).parents('li').find('a').click();
			 });
			 // when tab link is clicked
			  $('#search-forms ul#search-tabs a').click(function(e){
				$(e.target).parents('li').find(':radio').attr('checked', true);
			});
		}
		
        
        // Attach compare form validation on results page
        if(document.getElementById("comparison-form")) {
        	var compareForm = document.getElementById("comparison-form");
        	compareForm.onsubmit=endecaSearch.validateCompareForm;
        }
        
        // Attach Form validation for e-incentive Award form
        if($('form.eincentive-award-form').length > 0)
        {
        	$('form.eincentive-award-form').submit(endecaSearch.validate_eIncentive);
        }
        
        // Set up the availability toggle
        if(document.getElementById("availability-filter")) {
        	document.getElementById("availability-filter").onchange = endecaSearch.searchRefiner;
        }
        
        // Set up currency converter
        if(document.getElementById("currency")) {
        	document.getElementById("currency").value = document.getElementById("current-currency").value;
        	document.getElementById("currency").onchange = endecaSearch.searchRefiner;
        }
        
        // Set up the per page whatever
        if($('#recordsPerPage').length > 0)
        {
        	$('#recordsPerPage').change(endecaSearch.searchRefiner);
        }
        
        // Set up the guided nav
        if(document.getElementById("guided-nav")) {
	        if(document.getElementById("guided-nav")) {
	       		effects.initializeExpandableContent("ul","h4");
	       		effects.initializeExpandableContent("div","h2");
	       	}
	       	YAHOO.util.Event.on(document.getElementById("guided-nav-items"), "click", endecaSearch.guidedNavFilter);
	       	var navCheckBoxes = YAHOO.util.Dom.getElementsByClassName("guided-nav-control");
	       	for (var p=0; p<navCheckBoxes.length; p++) {
	        	if(YAHOO.util.Dom.hasClass(navCheckBoxes[p], "selected-refinement")) {
	        		navCheckBoxes[p].checked = true;
	        	}
	        	else {
	        		navCheckBoxes[p].checked = false;
	        	}
	        }
	        
	    }
	    
	    // Set up content on mult locations page
        if(document.getElementById("gs_edit-search-form")) {
       		effects.initializeExpandableContent("div","h2");
       	}
        
        // Set up the quickview
        if(document.getElementById("property-results")) {
	        var quickViewToggles = YAHOO.util.Dom.getElementsByClassName("open-quick-view");
	        for (var m=0; m<quickViewToggles.length; m++) {
	        	quickViewToggles[m].onclick = endecaSearch.toggleQuickView;
	        }
	        var quickViewToggles = YAHOO.util.Dom.getElementsByClassName("quick-view-hide");
	        for (var n=0; n<quickViewToggles.length; n++) {
	        	quickViewToggles[n].onclick = endecaSearch.toggleQuickView;
	        }
	        var quickViews = YAHOO.util.Dom.getElementsByClassName("quick-view");
	        for (var o=0; o<quickViews.length; o++) {
	        	var quickViewTabs = new YAHOO.widget.TabView(quickViews[o].id);
	        }	
        }
        
        if(document.getElementById("switch-to-redemption")) {
        	$('#switch-to-redemption').click(endecaSearch.switchToRedemption);
        }
        if(document.getElementById("switch-to-cash")) {
        	$('#switch-to-cash').click(endecaSearch.switchToCash);
        }
    	 
    	// Open hidden stuff if values are selected
    	if(document.getElementById("edit-search-form")) {
    		// Set up the edit search form on the search results page
    		effects.initializeExpandableContent("div","h3");
    		effects.initializeExpandableContent("form","h2");
    		
    		var rewardsSection = document.getElementById("hidden-rewards-container");
    		var rewardsTrigger = document.getElementById("hidden-rewards-trigger");
    		var specialRatesSection = document.getElementById("hidden-special-rates-container");
    		var specialRatesTrigger = document.getElementById("hidden-special-rates-trigger");
    		
    		if(document.getElementById("useRewardsPoints")) {
    			if(document.getElementById("useRewardsPoints").checked) {
    				rewardsSection.style.display ="block";
    				rewardsTrigger.onclick = effects.hideContent;
    				rewardsTrigger.className="expanded";
    			}
    		}
    		if(document.getElementById("marriottRewardsNumber")) {
	    		if(document.getElementById("marriottRewardsNumber").value != "") {
					rewardsSection.style.display ="block";
					rewardsTrigger.onclick = effects.hideContent;
					rewardsTrigger.className="expanded";
	    		}
	    	}
	    	if(document.getElementById("none")){
	    		if(!document.getElementById("none").checked) {
					specialRatesSection.style.display ="block";
					specialRatesTrigger.onclick = effects.hideContent;
					specialRatesTrigger.className="expanded";
	    		}
    		}	
    	}
		
		if(document.getElementById("compare-page-container")) {
			effects.matchHeight('hotel-info');
			effects.matchHeight('org');
			effects.matchHeight('rate-info');
			effects.alignBottom('rate-info');
			effects.matchHeight('compare-column');
		}
		
		//wrap long search titles for non-IE browsers
		if(document.getElementById("results-header"))
		{
			var resultsHeaderHeight = document.getElementById("results-header").offsetHeight;
			var resultsHeaderPosition = YAHOO.util.Dom.getStyle("results-header","position");
			if(resultsHeaderHeight > 32 && resultsHeaderPosition == "absolute")
			{
				document.getElementById("page-container").style.paddingTop = "52px";
				document.getElementById("page-container").style.background = "url(/Images/CSS_Backgrounds/cccccc_1x1.gif) 0 52px repeat-x";
			}
		}
	},

    openMenu : function() {
        endecaSearch.closeMenus();
        
        // Get to the li
        var listItem = utils.findParentNode(this);
        
        // Hide the more link
        listItem.style.display = "none";
        
        // Show all the lis in the list
        while(listItem.tagName == 'LI') {
            listItem = utils.findPreviousNode(listItem);
            if(!listItem) {
                return false;
            }
            listItem.style.display = "block";
        }
    },
    
    closeMenus : function() {
        // Get all the ULs
        uls = document.getElementsByTagName('UL');
        for(var i = 0; i < uls.length; i++){
            // Look for collapsable menues
        	if(uls[i].className.match("collapsable-menu")){
                var listItem = utils.findChildNode(uls[i]);
                var count = 1;
                var menuSize = 6;
                
                var listParent = utils.findParentNode(uls[i]);
                if(utils.findParentNode(uls[i]).id == "guided-nav"){
                    var menuSize = 3;}
                
                // Hide any item more than five
                while(listItem != null) {
                    if(count > menuSize) {
                        listItem.style.display = "none";
                    }
                    listItem = utils.findNextNode(listItem);
                    count++;
                }
            }
        }
        // Get all the LIs
        lis = document.getElementsByTagName('LI');
     
        for(var i = 0; i < lis.length; i++){
        	if(lis[i].className.match("more-link")){
                // Show the More >> links
                lis[i].style.display = "block";
        	}
        }
    },
        
    toggleQuickView : function() {
    	var quickViewMarsha = this.id.substring(18,this.id.length);
    	var quickViewToShow = "quick-view-" + quickViewMarsha;
    	var quickViewToggle = "quick-view-toggle-" + quickViewMarsha;
    	var propertyRecord = "property-record-" + quickViewMarsha;
    	var siteLocale = document.getElementById("site-locale").value;

    	if(this.className == "open-quick-view") {
    		// The user wants to open the quick view
    		
    		var attributes = {height: { to: 290 }};
    		
			YAHOO.util.Dom.addClass(document.getElementById(propertyRecord), "active-record");
    		this.className = "close-quick-view";
	
    		if(!endecaSearch.fetchedQuickViews[quickViewMarsha]) {
    		// If we haven't already, fetch the data from the backend
    		
    			// function sends image request to Omniture
    			// with data of first quick view opened only
    			if(document.getElementById("omniSiteTrackingOn") && document.getElementById("omniSiteTrackingOn").value == "true") {
	    			sendExpandQuickView("searchResults", quickViewMarsha.toUpperCase(), "");
	    		}
    			
    			// Set the vData cookie on the initial load
	    		var vData = "vData=expandQuickView=" + quickViewMarsha + "; path=/";
				document.cookie = vData;
				
    			YAHOO.util.Dom.addClass(quickViewToShow, "loading");
    		
	    		HotelQuickViewRemoteService.retrievePropertyDetail(quickViewMarsha, siteLocale, function(data) {
	    			if(data == {}){
	    				return true;
	    			}
	    			
	    			//Populating the dom with values
	    			$("#"+quickViewMarsha + "-address-line-1").html(data.address.addressLine1);
	    			$("#"+quickViewMarsha + "-address-line-2").html(data.address.addressLine2);
	    			$("#"+quickViewMarsha + "-address-city").html(data.address.city);
	    			$("#"+quickViewMarsha + "-address-state").html(data.address.stateCode);
	    			$("#"+quickViewMarsha + "-address-country").html(data.address.country);
	    			
	    			$("#"+quickViewMarsha + "-address-postal-code").html(data.address.postalCode);
	    			$("#"+quickViewMarsha + "-phone-number").html(data.address.phoneNumber);
	    			$("#"+quickViewMarsha + "-description").html(data.propertyPromoShortDesc);
	    			$("#"+quickViewMarsha + "-business-meetings").html(data.businessMeetingsVO.highlightsInfoList[0]);
	    			$("#"+quickViewMarsha + "-social-events-weddings").html(data.socialEventsVO.highlightsInfoList[0]);
	    			$("#"+quickViewMarsha + "-is-driving-direc-support").html(data.drivingDirectionsSupportedCountry);
	    			//Check for existence  of airport data, some hotels do not have any ex. DELER
	    			if(data.airportVOlist.length > 0) { 
	    				$("#"+quickViewMarsha + "-airport-name").html(data.airportVOlist[0].airportFullName);
	    				$("#"+quickViewMarsha + "-airport-code").html(data.airportVOlist[0].airportCode);
	    				$("#"+quickViewMarsha + "-airport-directions").html(data.airportVOlist[0].hotelDrivingDirections);
	    				$("#"+quickViewMarsha + "-airport-alternate").html(data.airportVOlist[0].airAlternateTransport);
	    				$("#"+quickViewMarsha + "-airport-bus").html(data.airportVOlist[0].busServiceDescription);
	    				$("#"+quickViewMarsha + "-airport-subway").html(data.airportVOlist[0].subwayServiceDescription);
	    				$("#"+quickViewMarsha + "-airport-taxi").html(data.airportVOlist[0].taxiServiceDescription);
	    			}
	    			
	    			
	    	    	
	    	    	if(!(data.airportVOlist.length > 1)) { document.getElementById(quickViewMarsha + "-more-airports").style.display = "none"; }
	    	    	
	    	    	// Put together the parkingInfo
	    	    	var parkingInfo = "";
	    	    	if(data.parkingVO.onsiteParkingDesc != null) {
	    	    		parkingInfo = parkingInfo + data.parkingVO.onsiteParkingDesc;
	    	    	}
	    	    	if(data.parkingVO.valetParkingDesc != null) {
	    	    		if(parkingInfo != "") {
	    	    			parkingInfo = parkingInfo + "; "; 
	    	    		}
	    	    		parkingInfo = parkingInfo + data.parkingVO.valetParkingDesc;
	    	    	}
	    	    	if(data.parkingVO.offsiteParkingDesc!= null) {
	    	    		if(parkingInfo != "") {
	    	    			parkingInfo = parkingInfo + "; ";
	    	    		}
	    	    		parkingInfo = parkingInfo + data.parkingVO.offsiteParkingDesc;
	    	    	}
	    	    	if(data.parkingVO.additionalParkingInfo != null) {
	    	    		if(parkingInfo != "") {
	    	    			parkingInfo = parkingInfo + "; ";
	    	    		}
	    	    		parkingInfo = parkingInfo + data.parkingVO.additionalParkingInfo;
	    	    	}
	    	    	if(parkingInfo == "") { 
	    	    		document.getElementById(quickViewMarsha+"-parking-container").style.display = "none";
	    	    	}
	    	    	else {
	    	    		$("#"+quickViewMarsha + "-parking-info").html(parkingInfo);
	    	    	}
	    	    	var drivingDirectionLink = document.getElementById(quickViewMarsha + "-driving-directions-link");
	    	    	if(drivingDirectionLink != null && !data.drivingDirectionsSupportedCountry) { 
	    	    		document.getElementById(quickViewMarsha + "-driving-directions-link").style.display = "none";
	    	    	}
	    	    	
	    	    	// Set the brand image
	    	    	var brandImg = document.getElementById(quickViewMarsha + "-brand-image");
	    	    	brandImg.src = brandImg.src.replace("NOBRAND", data.brandCode);
	    	    	
					if(data.photoVO != "") {
						//imgPath pulled from global namespace
						var imagePath = imgPath;
						var photoList = quickViewMarsha + "-carousel-list";
						var imageList = [];
						var urlList = [];
						var altList = [];
						for(var i = 0; i < data.photoVO.length; i++){
							imageList.push(imagePath + data.photoVO[i].thumbnailImageFile);
							urlList.push(data.photoVO[i].photoTourPopupPgURL);
							altList.push(data.photoVO[i].imageAltTag);	
						};
						var carouselObj = {
							imgPathList:imageList,
							urlList: urlList,
							altTextList: altList
						};
					
						var carouselId = quickViewMarsha + "-carousel";
						var previousButton = quickViewMarsha + '-prev-arrow';
						var nextButton = quickViewMarsha + '-next-arrow';
						var carousel = new Carousel(carouselId, {prevElement:previousButton, nextElement:nextButton}, carouselObj);
					};
	    	    	
					// unescape any HTML that came back in the highlights
	    	    	if(document.getElementById(quickViewMarsha + "-business-meetings")) { 
	    	    		document.getElementById(quickViewMarsha + "-business-meetings").innerHTML = document.getElementById(quickViewMarsha + "-business-meetings").innerText;
	    	    	}
	    	    	if(document.getElementById(quickViewMarsha + "-social-events-weddings")) {
	    	    		document.getElementById(quickViewMarsha + "-social-events-weddings").innerHTML = document.getElementById(quickViewMarsha + "-social-events-weddings").innerText;
	    	    	}
	    	    	
	    	    	// Put together the amenties lists    	    	
					amenitiesLists = YAHOO.util.Dom.getElementsByClassName(quickViewMarsha+'-amenities');
					for(i=0; i<data.featureList.length; i++) {
						for(j=0; j<amenitiesLists.length; j++) {
							if(YAHOO.util.Dom.hasClass(amenitiesLists[j], data.featureList[i].groupKey)) {
								var newAmenity = document.createElement("LI");
								if(data.featureList[i].available) {
									YAHOO.util.Dom.addClass(newAmenity, "available");
								}
								newAmenity.innerHTML = data.featureList[i].details[0];
								amenitiesLists[j].appendChild(newAmenity);
							}
						}
					}
					
					// Get rid of the loading class
					YAHOO.util.Dom.removeClass(quickViewToShow, "loading");
					
					// Blank out the vData cookie
	    			var vData = "vData=; path=/";
					document.cookie = vData;
				});
				
				endecaSearch.fetchedQuickViews[quickViewMarsha] = true;
			}
    	}
    	else {
    		// Close the quick view
    		var attributes = {height: { to: 0 }};
    		
    		if(this.className == "quick-view-hide") {
    			document.getElementById(quickViewToggle).className = "open-quick-view";
    		}
    		else {	
    			this.className = "open-quick-view";
    		}
    		
    		setTimeout(function setIt() {document.getElementById(propertyRecord).className = ""}, 200);
    	}
    	
    	var anim = new YAHOO.util.Anim(quickViewToShow, attributes, .1);
		anim.animate();

    	return false;
    },
    
    searchRefiner : function() {
    	var attribute = this.name;
    	var attributesValue = this.value;
    	if(attributesValue != "") {
    		window.location = "/search/refineSearch.mi?" + attribute + "=" + attributesValue;
    	}
    },
    
    guidedNavFilter : function(e) {
    	var guidedNavTarget = YAHOO.util.Event.getTarget(e);
	    if(guidedNavTarget.className.match("guided-nav-control")) {
	    	var guidedNavLinkId = "nav-link-" + guidedNavTarget.id.substring(10,guidedNavTarget.id.length);
	    	var guidedNavLink = document.getElementById(guidedNavLinkId);
	    	window.location = guidedNavLink.href;
	    } 
	    else if (guidedNavTarget.tagName == "A") {
	    	var guidedNavCheckboxId = "nav-check-" + guidedNavTarget.id.substring(9,guidedNavTarget.id.length);
	    	if(document.getElementById(guidedNavCheckboxId)) {
	    		var guidedNavCheckbox = document.getElementById(guidedNavCheckboxId);
	    		guidedNavCheckbox.checked = true;
	    	}
	    	return true;
	    }
    },

	validateCompareForm : function()
	{
		var checkboxGroup = this.elements["compareHotels"];
		var numberOfSelected = 0;
		var vsCompareHotels = new String();
		
		if(checkboxGroup.length != null) {
			var checkboxGroupSize = checkboxGroup.length;
			for ( counter = 0; counter < checkboxGroupSize; counter++ ) {
				if (checkboxGroup[counter].checked) {
					numberOfSelected ++;
					if (numberOfSelected > 1) {
					    vsCompareHotels += "_";
					}
					vsCompareHotels += checkboxGroup[counter].value.substring(0, 5);
				}
			}
		}
		else {
			var checkboxGroupSize = 1;
			for ( counter = 0; counter < checkboxGroupSize; counter++ ) {
				if (checkboxGroup.checked) {
					numberOfSelected ++;
					vsCompareHotels += checkboxGroup.value.substring(0, 5);
				}
			}
		}
		
		var groupSalesSearch = document.getElementById("group-sales-search").value;
		
		if (numberOfSelected == 0) {
			var minimumErrorMsg = document.getElementById("minimum-message").value;
			alert(minimumErrorMsg);
			return false;
		}	
		else if (groupSalesSearch == "true") { 
			if (numberOfSelected > 3) {
				var maximumErrorMsg = document.getElementById("group-sales-maximum-message").value;
				alert(maximumErrorMsg);
				return false;
			}
		}	
		else if (numberOfSelected > 4) {
			var maximumErrorMsg = document.getElementById("maximum-message").value;
			alert(maximumErrorMsg);
			return false;
		}	
		else {
		    this.vsCompareHotels.value = vsCompareHotels;
		    this.submit();
			return true;
		}
	},
	
		
	getDate : function(daySelectBox, monthAndYearSelectBox, extraDays) {
	// Returns a date object based on selected values in the form
	  var date = null;
	  if(daySelectBox.selectedIndex != 0 && monthAndYearSelectBox.selectedIndex != 0)
  {
    var dateArray = monthAndYearSelectBox.value.split( "/" );
	    var day = Math.min( daySelectBox.value, endecaSearch.daysInMonth(dateArray[0] - 1, dateArray[1]));
	    date = new Date( dateArray[1], dateArray[0] - 1, day + extraDays);
  }
  return date;
	},
	
	setDate : function(daySelectBox, monthAndYearSelectBox, dateField, date) {
	// Sets a date in the form
  var x = 0;
		while (x < daySelectBox.length) {
			if (daySelectBox.options[x].value == date.getDate()) {
      daySelectBox.selectedIndex = x;
      x = daySelectBox.length;
    }
			else {
      x++;
    }
  }
  x = 0;
  var monthYear = (date.getMonth() + 1) + "/" + date.getFullYear();
		while (x < monthAndYearSelectBox.length) {
		    if(monthAndYearSelectBox.options[x].value == monthYear) {
      monthAndYearSelectBox.selectedIndex = x;
      x = monthAndYearSelectBox.length;
    }
			else {
      x++;
    }
  }
  dateField.value = ( date.getMonth() + 1 ) + "/" + date.getDate() + "/" + date.getFullYear();
	},
	
	daysInMonth : function(month, year) {
		return 32 - new Date( year, month, 32 ).getDate();
	},
		
	buildMarriottBrandsVSParam : function(form) {
		var checkboxGroup =  form.elements["marriottBrands"];
		var checkboxGroupSize = checkboxGroup.length;
		var allCheckboxIndex = checkboxGroup.length - 1;
		var allCheckbox = checkboxGroup[allCheckboxIndex];
		
		var vsParam = new String();
		if ( allCheckbox.checked )
		{
			vsParam += "All";
		}
		else
		{
			var numberOfSelected = 0;
			for ( counter = 0; counter < checkboxGroupSize; counter++ )
			{
				if (checkboxGroup[counter].checked)
				{
					numberOfSelected ++;
					if (numberOfSelected > 1)
					{
					    vsParam += "_";
					}
					vsParam += checkboxGroup[counter].value;
				}
			}
		}
		
		return vsParam;
	},
	
	validate_eIncentive : function() {
		var objForm = this;
		var URI = "/search/submitSearch.mi?"
		var queryStringParams;
		var incentiveType_Number = $(objForm).find(":input[name=displayableIncentiveType_Number]").val();
	
			if ((incentiveType_Number != '' ) && (($(objForm).find(":input[name=fromDate]").val() == null || $(objForm).find(":input[name=fromDate]").val() == '') || ($(objForm).find(":input[name=toDate]").val() == null || $(objForm).find(":input[name=toDate]").val() == ''))) {
			alert('Please enter check-in and check-out dates when searching by award number or type');	
			return false;
		}
	
		var city = $(objForm).find(":input[name=destinationAddress.city]").val();
		var state = $(objForm).find(":input[name=destinationAddress.stateProvince]").val();
		var country = $(objForm).find(":input[name=destinationAddress.country]").val();
		var fromDate = $(objForm).find(":input[name=fromDate]").val();
		var toDate = $(objForm).find(":input[name=toDate]").val();
		var roomCount = $(objForm).find(":input[name=roomCount]").val();
		var numGuests = $(objForm).find(":input[name=guestCount]").val();
		var brand = $(objForm).find(":input[name=marriottBrands]").val();
		var marriottRewardsNumber = $(objForm).find(":input[name=marriottRewardsNumber]").val();
		
		queryStringParams="searchType=InCity&incentiveType_Number=" + incentiveType_Number + "&destinationAddress.city=" + city + 
					"&destinationAddress.stateProvince=" + state + "&destinationAddress.country=" + country + "&fromDate="
					+ fromDate + "&toDate=" + toDate+ "&roomCount=" + roomCount + "&guestCount=" + numGuests + "&marriottRewardsNumber="
					+ marriottRewardsNumber + "&marriottBrands=" + brand;
		URI = URI + queryStringParams;
		window.open(URI, "_self");		
		return(false);
	},
    
    switchToCash : 	function(e) {
    	e.preventDefault();
    	var formObj = $('#edit-search-form');
    	$(formObj).find('#useRewardsPoints').attr('checked', false).end().submit();
	},

	switchToRedemption : function(e) {
		e.preventDefault();
		var formObj = $('#edit-search-form');
		$(formObj).find(':input[name=corporateCode]').val("").end().find(':input[name=displayableIncentiveType_Number]').val('').end()
					.find('#none').attr('checked','true').end().find('#useRewardsPoints').attr('checked', true).end().submit();
	}	
	
}
