/**
 * HomeAway namespace
 */

var $j = jQuery.noConflict();

jQuery.noConflict();
(function($) { 

function escapedId(myid) { 
	return myid.replace(/(:|\.)/g,'\\$1');
}

ha = {page: {}, user: {}, ui: {},
strings: {},
	settings: {},
    
    util: {
    	isInt: function(c){ return((c>="0")&&(c<="9")) },
    	initToggles: function(){
			$(".expand .content").addClass("hidden");
			$(".expand .show").removeClass("hidden");
			$(".expand .action").bind("click", function(){
				var el = $(this).parent("div.container").children("div.content");
				if(el.hasClass("hidden")){
					el.removeClass("hidden");
					$(this).addClass("open");
				}
				else{
					el.addClass("hidden");
					$(this).removeClass("open");
				}
			});
		},
		initPopupUrls: function(){
			$(".popup-url").bind("click", function(){
				window.open(this.href);
				return false;
			});
		},	
		initSearchSwap: function(){
			if($("#searchKeywords").val() == ""){ 
				$("#searchKeywords").addClass("default");
				$("#searchKeywords").val($("#searchKeywords").attr("rel"));
			}
			else if($("#searchKeywords").val() != $("#searchKeywords").attr("rel")){
				$("#searchKeywords").val($("#searchKeywords").attr("rel"));
			}
			$("#searchKeywords").focus(function(){
				var val = $(this).val();
				$(this).removeClass("default");	
				if($(this).attr("rel") == $(this).val()){
					$(this).val("");
				}
			});
			$("#searchKeywords").blur(function(){
				var val = $(this).val();
				$(this).removeClass("default");
				if($(this).val() == ""){
					$(this).addClass("default");
					$(this).val($(this).attr("rel"));
				}
			});
			$("#startDateInput, #endDateInput").each(function(){
				if ($(this).val() == "" || $(this).val().indexOf("/") == -1){
					$(this).val($(this).attr("rel"));
					$(this).addClass("default");
				}
			});

			if($("#searchKeywordsWidget").val() == ""){ 
					$("#searchKeywordsWidget").addClass("default");
					$("#searchKeywordsWidget").val($("#searchKeywordsWidget").attr("rel"));
				}
				else if($("#searchKeywordsWidget").val() != $("#searchKeywordsWidget").attr("rel")){
					$("#searchKeywordsWidget").val($("#searchKeywordsWidget").attr("rel"));
					$("#searchKeywordsWidget").attr("rel");
				}
				$("#searchKeywordsWidget").focus(function(){
					var val = $("#searchKeywordsWidget").val();
					$("#searchKeywordsWidget").removeClass("default");	
					if($("#searchKeywordsWidget").attr("rel") == $("#searchKeywordsWidget").val()){
						$("#searchKeywordsWidget").val("");
					}
				});
				$("#searchKeywordsWidget").blur(function(){
					var val = $("#searchKeywordsWidget").val();
					$("#searchKeywordsWidget").removeClass("default");
					if($("#searchKeywordsWidget").val() == ""){
						$("#searchKeywordsWidget").addClass("default");
						$("#searchKeywordsWidget").val($("#searchKeywordsWidget").attr("rel"));
					}
				});
				
		},
		
		    initSubmit: function(){
				$('.searchKeywords').keyup(function(e){
		        		e = e || window.event;
		        		var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
		        		if (keyCode == 13) {
		        			ha.util.submit(e);
		        		}
		       	 });
				// this function attaches the submit function to the submit button of search froms
				$('form[id=keywordSearchForm],form[id=widget-search-form]').each(function(){
					$(this).submit(function(){ return false; });
		
					$('.search-submit-button', $(this)).click(function(e){
						ha.util.submit(e);
					});
				});
		    },
		
		    submit: function(e){
				// this function checks the search form keyword value against the defualt value to make sure the default value isnt passed when the user hasnt entered a keyword
		
				var formObj = $(e.target).parents('form'); //gets the parent form of the submit button clicked
				var keywords = $("input[name=keywords]", formObj).val();    //gets the value of the forms keyword input	
				var defaultMessage = $("input[rel]", formObj).attr("rel");	 //gets the default value of the keyword input
		
				var arrival = $("input[name=startDateInput]", formObj).val();
				var departure = $("input[name=endDateInput]", formObj).val();
		
				if ($.trim(keywords) != "" && keywords != defaultMessage) {
					keywords = "/keywords:" + encodeURIComponent(keywords);
				} else {
					keywords = "";
				}
		
				var url = brand.siteDomain + '/search';
				      url += keywords;
				      url += ha.util.dateParam($("input[name=startDateInput]", formObj) ,'arrival');
				      url += ha.util.dateParam($("input[name=endDateInput]", formObj), 'departure');
		
				window.location = url;
		    },
		
		    // return a formatted url param for a given search date string
		    dateParam: function(o,s){
				if ((typeof $(o).val() == "undefined") || (ha.util.delim($(o).val()) == "")){
		    			return "";
		    		} else if ($(o).val() != ha.strings.dateInputHelpText) {
		    			if (ha.strings.dateInputHelpText == 'mm/dd/yyyy') {
		    				var parts = $(o).val().split("/")
		    				return '/' + s + ':' + parts[2] + '-' + parts[0] + '-' + parts[1];
		    			}
		    			return '/' + s + ':' + $(o).val().split("/").reverse().join("-");
		    		}
		    		return "";
		    },
		    
		    // set the date string delimiters
		    delim: function(s){
				if (s.indexOf("/") == -1) {
					if(s.indexOf("-") > -1) s = s.replace(/-/g, "/");
					else if(s.indexOf(".") > -1) s = s.replace(/\./g, "/");
					else s = "";
				}
				return s;
		    }
		}
    
    
};

// new datepicker
ha.util.datepicker = {

	init: function(){
		$("form").each(function(){
			var $form = $(this);
		 	if ($(".datepicker-start", $form).length > 0 && $(".datepicker-end", $form).length > 0){
		 		$(".datepicker").each(function(){
		 			$(this).data("previous_value", $(this).val());
		 		});
				$('.datepicker-start', $form).datepicker({ 
					showAnim:"",
					minDate: 0,
					beforeShow: function() {
						setTimeout(function() {
								$('#ui-datepicker-div').css({zIndex:1500000});
						}, 10);
					},
					
					onSelect: function(){
						// if end start is cleared, clear end date too
						if(!$(this).val()){
							$(".datepicker-end", $form).val("");
						}
						ha.util.datepicker.updateDates($(this));

					},
					onClose:function(){
						// if the value changed, show the end date
						if($(this).val() && $(this).attr("rel") != $(this).val() && $(this).data("previous_value") != $(this).val()){
							var end = $('.datepicker-end', $form);
							setTimeout("$(\"#" + end.attr("id") + "\").focus()", 1);
						}
						$(this).data("previous_value", $(this).val());
					}
				});
				$('.datepicker-end', $form).datepicker({
				
					showAnim: "",
					minDate: +1,
					beforeShow: function() {
						setTimeout(function() {
							$('#ui-datepicker-div').css({zIndex:1500000});
						}, 10);
					},
					onSelect: function(){
						// if end date is cleared, clear start date too
						if(!$(this).val()){
							$(".datepicker-start", $form).val("").data("previous_value", "");
						}
						ha.util.datepicker.updateDates($(this));
					},
					onClose:function(){
						if(!$(".datepicker-start", $form).val() && $(this).val()){
							var start = $('.datepicker-start', $form);
							setTimeout("$(\"#" + start.attr("id") + "\").focus()", 1);
						}
						if ($("body.search-page").length > 0){
							ha.page.search.update(search.baseUrl);
						}
					}
				});
				$('.datepicker-end', $form).click(function(dateText, inst) { 
					var sv = $('.datepicker-start', $form).val();
					if (sv == '' || sv == $('.datepicker-start', $form).attr("rel")){
						$('.datepicker-end', $form).trigger('blur');
						$('.datepicker-start', $form).trigger('focus');
					}
				});
			} else if ($(".datepicker-start", $form).length > 0) {
				$('.datepicker-start', $form).datepicker({
					maxDate: -1, 
					showAnim: "",
					onClose:function(){
						if($(this).parents('#reviewForm').length > 0){
							$('#nameOnContract').focus();							
						}
					}
				});
				$(".datepicker", $form).change(function(){ ha.util.datepicker.updateStartDate(); });
			}
		});
	 	$('#ui-datepicker-div.ui-helper-clearfix').hide();
		
	},
	
	which: function(el){
		return $(el).attr("class").indexOf("datepicker-start") > -1 
			? "start" : $(el).attr("class").indexOf("datepicker-end") > -1 
				? "end" : null;
	},
	
	other: function(el, which){
		return $(el).parents("form").find("." + which);
	},
		
	updateDates: function(el) {
		$('#ui-datepicker-div.ui-helper-clearfix').show();
		
		var which = ha.util.datepicker.which(el);
		
		if(which == null){
			alert("no start or end date was found");
			return;
		}
		
		var start, end;

		if(which == "start"){
			start = el;
			end = ha.util.datepicker.other(el, "datepicker-end");
		}
		else{
			start = ha.util.datepicker.other(el, "datepicker-start");
			end = el;
		}
		
		if(start == null || end == null){
			alert("datepicker could not execute");
			return;
		}

		var startDate = start.datepicker("getDate");
		var startTime = startDate != null ? startDate.getTime() : 0;
		var endDate = end.datepicker("getDate");
		var endTime = endDate != null ? endDate.getTime() : 0;
		
		if (which == "start" && startTime > endTime){
			var endDate = startDate;
			endDate.setDate(startDate.getDate() + 1);
			if(endTime <= startTime){
				end.datepicker('setDate', endDate);
			}
			end.datepicker('option', 'minDate', endDate);
		} else if (startDate != null) {
			var minDate = startDate;
			minDate.setDate(startDate.getDate() + 1);
			end.datepicker('option', 'minDate', minDate);
		}
		
		$('.datepicker').each(function(){
			if ($(this).val() && $(this).val() == $(this).attr("rel")){alert('hi Im defualt');
				$(this).addClass("default");
			}
			else{
				$(this).removeClass("default"); 
			}
		});
		
	},
	
	updateStartDate: function() {
		$('#ui-datepicker-div.ui-helper-clearfix').css('display','block');
		if(typeof($("#startDateInput").attr("rel")) != 'undefined'){
			if ($("#startDateInput").val() != $("#startDateInput").attr("rel")){
				$("#startDateInput").removeClass("default"); 
			}
		}
	}
};



/*
 * FAVORITES
 * 
 */
ha.page.favorites = {
	init: function() {
		ha.page.search.initListingHover("");
		ha.ui.favorites.init();
		ha.ui.favorites.sidebarInit();
		
		// get search refinements URL from cookie and add url to search tabs
		var searchURL = ha.json.cookie.parse(ha.json.qpJsonCookie(), "searchURL");
		if (searchURL != null){
			var url = searchURL;
			
			if( url.indexOf('?view=') != -1 ){
				url = url.substr(0, url.indexOf('?view='))
			}
			if (url.search('search') != -1) {
				$('#list-view-button').attr('href',url);
				$('#grid-view-button').attr('href',(url+'?view=g'));
				$('#map-view-button').attr('href',(url+'?view=m'));
			}
		}
		ha.page.search.initEvents();
		
		$('.listing-main .content-container').click(function(e){
			var url = $(this).find('.listing-url').attr('href');
			if (typeof(url) != 'undefined'){
				window.location = url;
			}
		});

	    var label = getParameter("label");
	    $('.'+label).parents('.favorite-label').addClass("active");

		
	},
	createItem: function($favorite, labelName, successCallback){
		var favoriteId = $favorite.parents(".favorite-container").attr("ref");
		var splitFavoriteId = favoriteId.split("-");
		
		ha.api.traveler.createLabelAndFavorite(favoriteId, splitFavoriteId[0], splitFavoriteId[1], splitFavoriteId[2], labelName, successCallback);	
	},
	createLabel: function(e, $label) {
		/* For the sidebar's create label */
		var labelName = ($label.find(".display-note").html());
		
		$label.find('.display-view, .edit-view').hide();
		$label.find('.edit-note').val("");
		$label.find('.display-note').html("");
		$label.parent().find('.loading-item').show();
		
		var success = function(data) {
			$label.parent().find('.loading-item').hide();
			$label.find('.add-view').show();
			var label = eval("("+data+")");
			ha.page.favorites.addLabelUI(label.name, label.id, 0);
		}
		ha.api.traveler.labels.createLabel(labelName, success, "");
		
	},
	updateNote: function(e, $note){
		var favoriteId = $note.parents(".favorite-container").attr("ref");
		var splitFavoriteId = favoriteId.split("-");
		var note = ($note.parents(".favorite-container").find(".fn-note .display-note").html());
		var success = function(data) { ha.api.traveler.favorites.editFavorite(favoriteId, note); };
		ha.api.traveler.favorites.createFavorite(favoriteId, splitFavoriteId[0], splitFavoriteId[1], splitFavoriteId[2], success);
	},
	addFavoriteLabel: function(e, $favorite, labelId) {
		var favoriteId = $favorite.parents(".favorite-container").attr("ref");
		var splitFavoriteId = favoriteId.split("-");
		var success = function(data) { ha.api.traveler.favorites.labels.addLabel(favoriteId, labelId); };
		ha.api.traveler.favorites.createFavorite(favoriteId, splitFavoriteId[0], splitFavoriteId[1], splitFavoriteId[2], success);
		
	},
	removeFavoriteLabel: function(e, $favorite, labelIds) {
    	var favoriteId = $favorite.parents(".favorite-container").attr("ref");
    	ha.api.traveler.favorites.labels.removeLabel(favoriteId, labelIds);
    },
	refresh: function() {
		var userCookie = $.cookie("ha-usr-prst");
		if (userCookie != null) {			
			ha.api.traveler.getTraveler(function(json) {
							
				var jsonResult = eval("("+json+")");
				
				var name = '';
				//both names set
				if ((jsonResult.first_name != undefined) && (jsonResult.last_name != undefined)) {
					name = jsonResult.first_name + " " + jsonResult.last_name.charAt(0) + ".";
				}
				//first name set, no last name
				else if (jsonResult.first_name != undefined) {
					name = jsonResult.first_name;
				}
				//last name only
				else {
					name = jsonResult.last_name.charAt(0) + ".";
				}
				
				$('#user-links-dropdown').html("<span class='user-links-name'>" + name + "</span><span class='user-links-button-dropdown'></span>");
				
				// Remove all checkmarks
				$('.has-check').removeClass("has-check");
				$('.item-list').remove();
				
				// Set a bunch of variabels
				var json_favorites = jsonResult.favorites;
				var json_inquired = jsonResult.inquiredProperties;
				var json_visited = jsonResult.visitedProperties;
				var json_labels = jsonResult.labels;
				var json_labelIds = [];
				var json_labelNames = []; 
				for(var jLabel=0; jLabel < json_labels.length; jLabel++ ) {
					json_labelIds.push(json_labels[jLabel].id);
					json_labelNames.push(json_labels[jLabel].name);
				}
				$.fn.checklist.newLabels(json_labelIds,json_labelNames);
				
				// Set the list of labels (in case back button misses a new label)
				
				//Check for default label
				if(json_labels.length == 0){
					var globalDefaultItem = ha.strings.favorites.checklist.defaultItem;
					var userCookie = $.cookie("ha-usr-prst");
		    			
	            	ha.api.traveler.labels.createLabel(globalDefaultItem, function(data) {
	            		var defaultResult = eval("("+data+")");
						$.fn.checklist.addItem(defaultResult);
	    			});
		            	
		    	}
				
				// Iterate through Favorites
				var favoriteCount = 0;
				var noteCount = 0;
				if(json_favorites) {
					for(var favoriteIndex=0; favoriteIndex < json_favorites.length; favoriteIndex++ ) {
						var escaped_favorite_id = escapedId('fav-'+json_favorites[favoriteIndex].systemId+"-"+json_favorites[favoriteIndex].propertyId+"-"+json_favorites[favoriteIndex].unitId);
						var current_favorite = $(escaped_favorite_id);
						var data_favorites="";
						if(json_favorites[favoriteIndex].labels.length != 0) {
							
							var incrementFavoriteCount = false;
							for(var label=0; label< json_favorites[favoriteIndex].labels.length; label++) {
								// check if favorite id is in labels
								if($.inArray(json_favorites[favoriteIndex].labels[label], json_labelIds) != -1){
									data_favorites = data_favorites+""+json_favorites[favoriteIndex].labels[label]+"|";
									incrementFavoriteCount = true;
								} else {
									// remove favorites with favorite ids that are not in labels
									ha.api.traveler.favorites.labels.removeLabel(json_favorites[favoriteIndex].id, json_favorites[favoriteIndex].labels[label]);
								}
							}
							if(incrementFavoriteCount){
								current_favorite.addClass("has-check");
								++favoriteCount;
							}
							data_favorites = data_favorites.substring(0, data_favorites.length-1)
							current_favorite.attr("data-favorites", data_favorites);
						}
						
						if(json_favorites[favoriteIndex].note && json_favorites[favoriteIndex].note != "") {
							++noteCount;
							current_favorite.parents('.favorite-container').find('.display-view').show();
							current_favorite.parents('.favorite-container').find('.add-view').hide();
							current_favorite.parents('.favorite-container').find('.display-note').html(json_favorites[favoriteIndex].note);
							current_favorite.parents('.favorite-container').find('.edit-note').html(json_favorites[favoriteIndex].note);
						} else if(json_favorites[favoriteIndex].note == "") {
							current_favorite.parents('.favorite-container').find('.display-note').html("");
							current_favorite.parents('.favorite-container').find('.edit-note').val("");
							current_favorite.parents('.favorite-container').find('.add-view').show();
							current_favorite.parents('.favorite-container').find('.display-view').hide();
						}
					}
				}
				
				// Iterate through Visited
				if(json_visited) {
					for(var i=0; i < json_visited.length; i++ ) {
						var current_visited = $(escapedId('inq-viewed-'+json_visited[i].systemId+"-"+json_visited[i].propertyId+"-"+json_visited[i].unitId));
						current_visited.html(translation_visited);
						current_visited.show();
					}
				}
				
				// Iterate through Inquired
				if(json_inquired) {
					for(var i=0; i < json_inquired.length; i++ ) {
						var current_inquired = $(escapedId('inq-viewed-'+json_inquired[i].systemId+"-"+json_inquired[i].propertyId+"-"+json_inquired[i].unitId));
						current_inquired.html(translation_inquired);
						current_inquired.show();
					}
				}
				traveler_labels = {"labels": jsonResult.labels};
				
				ha.page.favorites.updateCount(favoriteCount, noteCount, jsonResult);
			});
		} else {
			ha.page.favorites.updateCount(0, 0, 0, 0);
		}
		
	},
    refreshCount: function() {
		var userCookie = $.cookie("ha-usr-prst");
		if (userCookie != null) {			
			ha.api.traveler.getTraveler(function(json) {
				
				var jsonResult = eval("("+json+")");
				
				// Set a bunch of variabels
				var json_favorites = jsonResult.favorites;
				var json_inquired = jsonResult.inquiredProperties;
				var json_visited = jsonResult.visitedProperties;
				var json_labels = jsonResult.labels;
				var json_labelIds = [];
				var json_labelNames = []; 
				for(var jLabel=0; jLabel < json_labels.length; jLabel++ ) {
					json_labelIds.push(json_labels[jLabel].id);
					json_labelNames.push(json_labels[jLabel].name);
				}
				
				// Iterate through Favorites
				var favoriteCount = 0;
				var noteCount = 0;
				if(json_favorites) {
					for(var favoriteIndex=0; favoriteIndex < json_favorites.length; favoriteIndex++ ) {
						// favorite count
						if(json_favorites[favoriteIndex].labels.length != 0) {
							var incrementFavoriteCount = false;
							for(var label=0; label< json_favorites[favoriteIndex].labels.length; label++) {
								// check if favorite label is in traveler labels
								if($.inArray(json_favorites[favoriteIndex].labels[label], json_labelIds) != -1){
									incrementFavoriteCount = true;
								}
							}
							if(incrementFavoriteCount){
								++favoriteCount;
							}
						}
						// note count count
						if(json_favorites[favoriteIndex].note && json_favorites[favoriteIndex].note != "") {
							++noteCount;
						}
					}
				}
				
				ha.page.favorites.updateCount(favoriteCount, noteCount, jsonResult);
			});
		}
    },// end refreshCount
    updateCount: function(favoriteCount, noteCount, jsonResult) {
    	
    	// update (inquired, viewed, noted) counts
		var inquiredCount = 0;
		var visitedCount = 0;
		if(jsonResult.inquiredProperties) {	
			inquiredCount = jsonResult.inquiredProperties.length;
		}
		if(jsonResult.visitedProperties) {
			visitedCount = jsonResult.visitedProperties.length;
		}
		
    	// update (inquired, viewed, noted) counts
		$('.inq-count').text(" ("+inquiredCount+")");
		$('.viewed-count').text(" ("+visitedCount+")");
		$('.noted-count').text(" ("+noteCount+")");
		$('.noted-count').text(" ("+noteCount+")");
		$('.favorite-count').text(favoriteCount);
		
		// update label counts
		var json_labels = jsonResult.labels;
		for(var i=0; json_labels && i < json_labels.length; ++i ) {
			$('.label-count-'+json_labels[i].id).text(" ("+json_labels[i].count+")")
		}
		
		// Refresh the Favorite and dropdown counts
		$('.favorite-count').text(" ("+favoriteCount+")");
		$('.favs-count').text(" ("+favoriteCount+")");
		
    },
    addLabelUI: function(labelName, labelId, quantity, isDefault){
    	if($('body').hasClass("favorites")) {					
			var $newLabel = "";
			$newLabel =$('<div class="favorite-label"><div class="display-block"><a class="favorite-item" href="/favorites?label='+labelId+'"><span class="name">'+labelName+'</span><span class="count label-count-'+labelId+'"> ('+quantity+')</span></a><div class="remove-label button-base xsm pdp-light '+((isDefault) ? "first" : "" )+'" ref="'+labelId+'">x</div></div></div>');

			$newLabel.find('.remove-label').click(function(){
				$newLabel.html('<div class="loading-item remove-label-'+labelId+'">&nbsp;</div>');
				ha.api.traveler.labels.deleteLabel(labelId);
			});
			
			$('.sidebar-section.favorite-labels').append($newLabel);
		}
    }
    
    
};

/*
 * Traveler-Favorites
 * API functions
 */

ha.api = {};
ha.api.traveler = {
		getTraveler: function(callback){
			return $.ajax({
				type: "GET",
				url: "/api/traveler",
				data: {
				},
				dataType: JSON,
				cache: false,
				success: function(data){
					callback(data);
				}
			})
		},
		createLabelAndFavorite: function(spu, systemId, propertyId, unitId, labelName, successCallback, failCallback) {
			ha.api.traveler.labels.createLabel(labelName, function(data) {
				var label = eval("("+data+")");				
				ha.page.favorites.addLabelUI(label.name, label.id, 1);
				ha.api.traveler.favorites.createFavorite(spu, systemId, propertyId, unitId, function(data) {
					var favorite = eval("("+data+")");
					ha.api.traveler.favorites.labels.addLabelAndRefresh(favorite.id, label.id, successCallback, failCallback);
					
					$.fn.checklist.addItem(label);
					
				}, failCallback);
			}, failCallback);
		},
		favorites: {
				createFavorite: function(id, systemId, propertyId, unitId, success, failCallback) {
					$.ajax({
						type: "POST",
						url: "/api/traveler/favorites",
						data: {
							"favorite":
							{
								"id": id,
								"systemId": systemId,
								"propertyId": propertyId,
								"unitId": unitId
							}
						},
						dataType: JSON,
						success: success,
						error: failCallback
					});
				},
				editFavorite: function(favoriteId, note){
					$.ajax({
						type: "PUT",
						url: "/api/traveler/favorites/"+favoriteId,
						data: {"favorite": {"note": note}},
						dataType: JSON,
						success: function(data){
							ha.page.favorites.refreshCount();
						}
					});
				},
				deleteFavorite: function(favoriteId){
					$.ajax({
						type: "DELETE",
						url: "/api/traveler/favorites/"+favoriteId,
						data: {},
						dataType: JSON,
						success: function(data){
							
						}
					});
				},
				labels: {
						addLabel: function(favoriteId, labelId) {
							$.ajax({
								type: "POST",
								url: "/api/traveler/favorites/"+encodeURIComponent(favoriteId)+"/labels",
								data: {
									label: labelId
								},
								dataType: JSON,
								success: function(data) {

									var userCookie = $.cookie("ha-usr-prst");
									if (userCookie != null) {
										var jsonResult = eval("("+data+")");
										

										if(s != undefined) {
											s.linkTrackVars="events";
											s.linkTrackEvents="event66";
											s.events="event66";
											s.tl(this,'o','favorites');
										}
									}
									ha.page.favorites.refreshCount();
								}// end success
								
							});
							
						},
						addLabelAndRefresh: function(favoriteId, labelId, successCallback, failCallback) {
							$.ajax({
								type: "POST",
								url: "/api/traveler/favorites/"+encodeURIComponent(favoriteId)+"/labels",
								data: {
									label: labelId
								},
								dataType: JSON,
								success: successCallback,
								error: failCallback
							});
							
						},
						removeLabel: function(favoriteId, labelId) {
							$.ajax({
								type: "DELETE",
								// excape uri component
								url: "/api/traveler/favorites/"+favoriteId+"/labels/"+labelId,
								data: {},
								dataType: JSON,
								success: function(data){
									var jsonResult= eval("("+data+")");
									if($('body').hasClass("favorites") && (!$('#main').hasClass("unique-list"))) {										
										if($('#fav-'+favoriteId).attr("data-favorites") == "" && !($('#fav-'+favoriteId).parents('.favorites-container').hasClass("has-note"))){
//											$('#fav-'+favoriteId).parents('.favorite-container').fadeOut('slow');
											
											var $favorite_container = $('#fav-'+favoriteId).parents('.favorite-container');
											var $checkbox = $favorite_container.find('.item-list');
											
											if( !($checkbox.is(":visible"))) {
												$favorite_container.fadeOut('slow', function(){
												});
											} else {
												var intervalId = setInterval(function(){
													if(!($favorite_container.find('.item-list').is(":visible"))) {
						
														if($favorite_container.find('.fn-checklist').attr("data-favorites") == "" && $favorite_container.find(".fn-note .display-note").html()== "") {
						
															$favorite_container.fadeOut('slow', function(){									
															});
														}
														clearInterval(intervalId);
													}
													else {
													}
												},  2000);
											}
											
										}
									}
									ha.page.favorites.refreshCount();

								}
							});
						}
				}
		},
		labels: {
				createLabel: function(labelName, success, failCallback) {
					$.ajax({
						type: "POST",
						url: "/api/traveler/labels",
						data: {
							"label": {"name": labelName}
						},
						dataType: JSON,
						success: success,
						failure: failCallback
					});
				},
				editLabel: function(labelId, labelName) {
					$.ajax({
						type: "PUT",
						url: "/api/traveler/labels/"+labelId,
						data: {
							"labelName": labelName
						},
						dataType: JSON,
						success: function(data){
							var jsonResult = eval("("+data+")");

							if(jsonResult.state == "PASS") {
								$('.favorite-labels-message').html(oldLabel+" is now: "+newLabel);
								$link.find('.name').html(newLabel);
								$link.find('.count').html("("+jsonResult.newLabelSize+")");
								$link.attr("href", "/favorites?label="+newLabel);

								$displayBlock.show();
								$renameBlock.hide();
							}
							else {
								$('.favorite-labels-message').html("Duplicate labels are not allowed");
								$renameBlock.find('.cancel').click();
							}

						}
					});
				},
				deleteLabel: function(labelId){
					$.ajax({
						type: "DELETE",
						url: "/api/traveler/labels/"+labelId,
						data: {},
						dataType: JSON,
						success: function(data){
							var jsonResult =  eval("("+data+")");
							$('.remove-label-'+labelId).parents('.favorite-label').fadeOut("slow");
							ha.page.favorites.refresh();
						}
					});
				}
		},
		registerSuccess: function(){
			if(s != undefined) {
				s.linkTrackVars="events";
				s.linkTrackEvents="event39";
				s.events="event39";
				s.tl(this,'o','register');
			}
		
		},
		addInquiry: function(systemId, propertyId, unitId, success, failCallback) {
			$.ajax({
				type: "POST",
				url: "/api/traveler/inquiries",
				data: {
					"inquiry":
					{
						"systemId": systemId,
						"propertyId": propertyId,
						"unitId": unitId
					}
				},
				dataType: JSON,
				success: success,
				error: failCallback
			});
		}
};

ha.page.pie = {
	attach: function() {
			if (window.PIE) {
				function getStyleProperty(element, styleProperty){
				  var prop="";
				  if(element.currentStyle)
				  {
				    prop=element.currentStyle[styleProperty];
				  }
				  else if(window.getComputedStyle)
				  {
				    prop=document.defaultView.getComputedStyle(element,null).getPropertyValue(styleProperty);
				  }
				  return prop;
				};
				
				$(function(){
				  	// attach PIE on elements with CSS3
				    $("body *").each(function() {
				     if(getStyleProperty(this,'border-radius')||getStyleProperty(this,'box-shadow')||getStyleProperty(this,'-pie-background'))
				     {
				       PIE.attach(this);
				     }
				    }); 
				});
				
		        $('.pie-htc').each(function() {
		            PIE.detach(this);
		        });
		        
		        $('.no-pie').each(function() {
		            PIE.detach(this);
		        });
			        
				$('.pie-htc').css('behavior', piepath);
				
				$('.gtmenu-wrap, .gtmenu-arrow-wrap').css('behavior', piepath);
					/* */
				
	    }
	},
	detach: function() {
		if (window.PIE) {
		
				function getStyleProperty(element, styleProperty){
				  var prop="";
				  if(element.currentStyle)
				  {
				    prop=element.currentStyle[styleProperty];
				  }
				  else if(window.getComputedStyle)
				  {
				    prop=document.defaultView.getComputedStyle(element,null).getPropertyValue(styleProperty);
				  }
				  return prop;
				};
				
				$(function(){
				  	// attach PIE on elements with CSS3
				    $("body *").each(function() {
				     if(getStyleProperty(this,'border-radius')||getStyleProperty(this,'box-shadow')||getStyleProperty(this,'-pie-background'))
				     {
				       PIE.detach(this);
				     }
				    }); 
				});
		} 
	}
};

// end new datepicker

$(document).ready(function(){
	ha.util.initToggles();
	ha.util.initSearchSwap();
	ha.util.initSubmit();
});


})(jQuery);
