/**
 * HomeAway namespace
 */
 
//extend jQuery to identify msie6 instead of plain old msie
var b = navigator.userAgent.toLowerCase();
jQuery.browser = {
		safari: /webkit/.test(b),
		opera: /opera/.test(b),
		msie: /msie/.test(b) && !/opera/.test(b),
		msie6: /msie 6.0/.test(b) && !/opera/.test(b),
        mozilla: /mozilla/.test(b) && !/(compatible|webkit)/.test(b)		
}

var ha = {
	map: {},
	
    page: {},
    
    seo: {
    	/* business requirement to have markup up high but display down low */
    	showSeoText: function() {
    		// check if the elements exist before calling them - the no search results page and some decorates
    		// do not for instance
    		if ($j('#searchText') && $j('#searchTextPosition')) {
    			$j('#searchTextPosition').append($j('#searchText'));
    		}
    	}
    },
    
    settings: {},
    
    //site wide usage
    site: {},
    
    strings: {},
    
    ui: {},
    
    util: {
    	isInt: function(c){ return((c>="0")&&(c<="9")) },
    	initToggles: function(){
			$j(".expand .content").addClass("hidden");
			$j(".expand .show").removeClass("hidden");
			$j(".expand .action").bind("click", function(){
				var el = $j(this).parent("div.container").children("div.content");
				if(el.hasClass("hidden")){
					el.removeClass("hidden");
					$j(this).addClass("open");
				}
				else{
					el.addClass("hidden");
					$j(this).removeClass("open");
				}
			});
		},
		initPopupUrls: function(){
			$j(".popup-url").bind("click", function(){
				window.open(this.href);
				return false;
			});
		},	
		initSearchSwap: function(){
			if($j("#searchKeywords").val() == ""){ 
				$j("#searchKeywords").addClass("default");
				$j("#searchKeywords").val($j("#searchKeywords").attr("rel"));
			}
			else if($j("#searchKeywords").val() != $j("#searchKeywords").attr("rel")){
				$j("#searchKeywords").removeClass("default");
			}
			$j("#searchKeywords").focus(function(){
				var val = $j(this).val();
				$j(this).removeClass("default");	
				if($j(this).attr("rel") == $j(this).val()){
					$j(this).val("");
				}
			});
			$j("#searchKeywords").blur(function(){
				var val = $j(this).val();
				$j(this).removeClass("default");
				if($j(this).val() == ""){
					$j(this).addClass("default");
					$j(this).val($j(this).attr("rel"));
				}
			});
		}
    	
    }
    
};
 
/* 
 * Straightforward/simple Observer pattern implementation
 * Example useage:
 * var publisher = new Observer
 * publisher.subscribe(function(msg){
 *    alert(msg);
 * });
 * publisher.fire("Event fired!");
 */
function Observer() {
	this.fns = [];
}

Observer.prototype = {
	subscribe : function(fn) {
		this.fns.push(fn);
	},
	unsubscribe : function(fn) {
		this.fns = this.fns.filter(
			function(el) {
				if (el !== fn) {
					return el;
				}
			}
		);
	},
	fire : function(o, thisObj) {
		var scope = thisObj || window;
		this.fns.forEach(
			function(el) {
				el.call(scope, o);
			}
		);
	}
};
// Add some sugar to the Array prototype
Array.prototype.forEach = function(fn, thisObj) {
    var scope = thisObj || window;
    for ( var i=0, j=this.length; i < j; ++i ) {
        fn.call(scope, this[i], i, this);
    }
};
Array.prototype.filter = function(fn, thisObj) {
    var scope = thisObj || window;
    var a = [];
    for ( var i=0, j=this.length; i < j; ++i ) {
        if ( !fn.call(scope, this[i], i, this) ) {
            continue;
        }
        a.push(this[i]);
    }
    return a;
};

/*
 * GLOBAL
 * advancedSearchForm, homeSearchForm, keywordSearchForm, refineSearchForm (aka sidebar)
 * noResults, 404error, error, secondary pages, etc.
 */
var searchErrorObserver = new Observer;

ha.site.searchform = {
    init: function(){
        
        $j('#searchKeywords').keyup(function(e){
        	e = e || window.event;
        	var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
        	if (keyCode == 13) {
        		ha.site.searchform.submit(e);
        	}
        });
        
    	$j('form[name=searchForm],form[name=refineSearchForm]').each(function(){
    		$j(this).submit(function(e){
    			return false;
    		});
    		
    		$j('.search-submit-button', $j(this)).click(function(e){
    			ha.site.searchform.submit(e);
    		});
    	});
    	
    	$j("#price-range-fields .input").bind("focus", function(){
    		$j("#price-range-vaidation").addClass("hidden").css("display", "");
    	});
    	
    },
    
    isDigit: function(e){
    	var charCode = (e.which) ? e.which : window.event ? window.event.keyCode : 0;
   		if (charCode > 31 && (charCode < 48 || charCode > 57)){
   			return false;
   		}
   		return true;
    },
    
    submit: function(e){
    	var formObj = $j('form[name=searchForm],form[name=refineSearchForm]');
    	if (e){
    		formObj = $j(e.target).parents('form');
    	}
    	
    	// determine what sort of search has been performed
    	var searchType = formObj.attr("id");
    	if(searchType == "simple-search")
    		searchType = "simple";
    	else if(searchType == "keywordSearchForm")
    		searchType = "keyword";
    	else if(searchType == "adv-search-form")
    		searchType = "advanced";
    	else if(searchType == "refineSearchform")
    		searchType = "availability";
    	else
    		searchType = "notknown";
    		
		$j.cookie('searchType', searchType, {expires: 1, path: '/'});	
    	
    	if(ha.site.searchform.validate($j('#startDateInput',formObj).val(), $j('#endDateInput',formObj).val())){ 
    		// get keywords
        	var keywords = ($j("input[@name=keywords]", formObj).length > -1) ? $j("input[@name=keywords]", formObj).val() : "";
        	var defaultMessage = $j("input[@rel]", formObj).attr("rel");
        	
        	if ($j.trim(keywords) !="" && keywords!=defaultMessage) {
        		keywords = "/keywords:" + keywords;
        	}
        	else{
        		keywords = "";
        	}
        	
        	var refinements = "";
        	if ($j("#refinements",formObj).val() != null && $j.trim($j("#refinements",formObj).val()) != ''){
        		// get refineSearchForm refinements aka sidebar
        		refinements += $j("#refinements",formObj).val().replace("+", "*");
        	}
        	else{
        		// get advancedSearchForm refinements
        		var refinements = "";
        		$j('input, select',formObj).each(function(i,el){
        			if ((el.type == "select-one" && el.value != '') || (el.type == "checkbox" && el.checked)){
        				refinements += '/' + el.value;
        			}
        		});
        	}

			// validate price range        	
        	var priceFrom = $j("#priceFrom").val(); 
        	var priceTo = $j("#priceTo").val();
        	var prices = "";
        	
        	if(priceFrom !=null && priceTo != null && parseInt(priceFrom) > parseInt(priceTo)){
        		searchErrorObserver.fire();
        		$j("#price-range-vaidation").fadeIn("def");
	        	return false;
        	}
        	//Were prices provided?
        	if(priceFrom !=null && priceFrom > 0){
        		prices += "/minPrice/" + priceFrom;
        	}
            if (priceTo !=null && priceTo > 0) {
        		prices += "/maxPrice/" + priceTo;
        	}
			//If prices provided, add currency 
			if((priceFrom !=null && priceFrom > 0) 
			||
			  (priceTo !=null && priceTo > 0)) {
		        prices += "/currency/" + brand.baseCurrency;
    	    }
        	var url = '/search';
	    	if (refinements != ''){ url += '/refined'; }
       		url += keywords;
   			url += refinements;
   			url += ha.site.searchform.dateParam($j('#startDateInput', formObj),'arrival');
   			url += ha.site.searchform.dateParam($j('#endDateInput', formObj),'departure');
   			url += prices;
    		window.location = url;
    	}
    },
    
    validate: function(startDate, endDate){
    	var dateFormat = brand.dateInputHelpText;
    	var startMonth,startDay,startYear,endMonth,endDay,endYear,startDim,endDim;
    	var hasStartDate = (startDate!=undefined && startDate!="" && startDate!=dateFormat);
    	var hasEndDate = (endDate!=undefined && endDate!="" && endDate!=dateFormat);

    	var errorSearch = ha.strings.advancedSearchError;
    	var errorMissing = ha.strings.bothDatesRequiredMessage;
    	
    	if((hasStartDate && !hasEndDate) || (hasEndDate && !hasStartDate)){
    		alert(errorMissing);
    		return false;
    	} 
    	else if (hasStartDate && hasEndDate){
			startDate = ha.site.searchform.delim(startDate).split("/");
			endDate = ha.site.searchform.delim(endDate).split("/");
			
			if (startDate.length != 3 || endDate.length != 3){
				alert(errorSearch);		
				return false;
			} 
			else if (startDate.length == 3 && endDate.length == 3){
				var i,j;
				// validate if date objects are integers
				for (i = 0; i< 3; i++){
					for (j = 0; j<startDate[i].length; j++){
						if (!ha.util.isInt(startDate[i].charAt(j))){
							alert(errorSearch);	
							return false; break;
						}
					}
					for (j = 0; j<endDate[i].length; j++){
						if (!ha.util.isInt(endDate[i].charAt(j))){
							alert(errorSearch);	
							return false; break;
						}
					}
				}
				
				if (dateFormat == 'mm/dd/yyyy'){
					startMonth = startDate[0];
					startDay = startDate[1];
					endMonth = endDate[0];
					endDay = endDate[1];
				}
				else {
					startMonth = startDate[1];
					startDay = startDate[0];
					endMonth = endDate[1];
					endDay = endDate[0];
				}
			
				startYear = (startDate[2].length == 4) ? startDate[2] : parseInt('20'+startDate[2]);
				endYear = (endDate[2].length == 4) ? endDate[2] : parseInt('20'+endDate[2]);

				startDim = ha.site.searchform.dim(startMonth,startYear);
				endDim = ha.site.searchform.dim(endMonth,startYear);
				
				var start = new Date();
				var end = new Date();
				start.setFullYear(startYear, startMonth-1, startDay);
				end.setFullYear(endYear, endMonth-1, endDay);
				
				// validate date continuity, past dates, and
				// date day does not exceed number of days in the month
				var today = new Date(); 
				if(end<start || start<today || end<today || startDim < startDay || endDim < endDay){
					alert(errorSearch);
					return false;
				}
			}
    	}
    	return true;
    },
    
    // return a formatted url param for a given search date string
    dateParam: function(o,s){
    	if ((typeof $j(o).val() == "undefined") || (ha.site.searchform.delim($j(o).val()) == "")){
    		return "";
    	}
    	else if ($j(o).val() != brand.dateInputHelpText){
    		if (brand.dateInputHelpText == 'mm/dd/yyyy'){
    			var parts = $j(o).val().split("/")
    			return '/' + s + ':' + parts[2] + '-' + parts[0] + '-' + parts[1];
    		}
    		return '/' + s + ':' + $j(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;
    },
    
    // return the number of days in a given month
    dim: function(m,y){
    	var dim = new Array(12);
    	dim[0] = 31;
    	if((y % 4 == 0) && ((!(y % 100 == 0)) || (y % 400 == 0)))
    		dim[1] = 29;
    	else
    		dim[1] = 28;
    	dim[2] = 31;
    	dim[3] = 30;
    	dim[4] = 31;
    	dim[5] = 30;
    	dim[6] = 31;
    	dim[7] = 31;
    	dim[8] = 30;
    	dim[9] = 31;
    	dim[10] = 30;
    	dim[11] = 31;
    	return dim[m-1];
    }
};


/*
 * HOME PAGE
 */
var homeBannerUrl2 = function(s){ this.s=s;}
var homeBannerUrl3 = function(s){ this.s=s;}
ha.page.home = {
	init: function(){
		ha.util.initToggles();
		if (homeBannerUrl2.s || homeBannerUrl3.s) ha.page.home.initSwapImages();
	},
	initSwapImages: function(){
		var swapduration = 8000;
		var timeout;

		$j("#layer2 img").attr("src", homeBannerUrl2.s);
		$j("#layer3 img").attr("src", homeBannerUrl3.s);
		
		$j(window).load(function(){
		
			$j("#layer2 img, #layer3 img").show();
			// fix text dimming in Firefox
			// http://allinthehead.com/retro/328/when-bugs-collide-fixing-text-dimming-in-firefox-2
	
			function show() {
				$j('#layer1').fadeIn(1500)
				setTimeout(function(){
					$j('#layer2').css({display:'block'});
				}, 1501);
				timeout = setTimeout(hideOne, swapduration);
			}
			function hideOne(){
				$j('#layer1').fadeOut(1500);
				timeout = setTimeout(hideTwo, swapduration);
			}
			function hideTwo(){
				$j('#layer2').fadeOut(1500);
				timeout = setTimeout(show, swapduration);
			}
			
			timeout = setTimeout(hideOne, swapduration);

		}); 

	}
}

/*
 * SEARCH PAGE
 */
ha.page.search = {
	init: function(){
		/**
		* Let's make sure the new sort cookie destroyed
		* It should only be sent when the client performs
		* a new sort
		*/
		$j.cookie('newSort', null);
		
		$j("#sortingSelect").change(function(){
			ha.page.search.onSortChange();
		});
		
		if($j("#fullAdsFirst")) {
			$j("#fullAdsFirst").change(function(){
				ha.page.search.onFullAdsFirstChange();
			});
		}
		
		// set up Omniture events
		ha.page.search.setOmnitureEvents();
		
		ha.util.initToggles();
		
		ha.page.search.initCollapsableRegions();
		
		ha.page.search.initPriceToggle();
		
		ha.page.search.initSnippets(5, 30);

        $j('.listing-photo-carousel').carousel();
        $j('.listing-photo-carousel').each(function(n, carousel) {
            var target = $j(carousel).parent().find('.listing-photo img');
            $j(carousel).find('img').each(function(n, image) {
                var linker = $j(image).parent();
                $j(linker).click(function() {
                    this.blur();
                    target.attr('src', $j(linker).attr('href'));
                    return false;
                });
            });
        });

    },

	/**
	* This method is tied to the select box 'sortingSelect'.  When its state changes, 
	* this method will change the current page's URL to the destination in the sort select. 
	**/
	onSortChange: function(){
	    // find the select
		select = document.getElementById("sortingSelect");
		
		// grab the destination string
		destination = select[select.selectedIndex].value;
			
		// if it exists (i.e. is not the "Select One:" option
		if (destination) {
			//null expires deletes cookie at browser exists
			if ($j.cookie('orderByOffer') != null) {
				$j.cookie('orderByOffer', null, {path: '/'});
			}
			$j.cookie('orderBy', destination, {path: '/'});
			$j.cookie('searchType', "newsort", {expires: 1, path: '/'});
			// then go there
			ha.page.search.doSort();
		}
	},
	
	/**
	* This method is tied to the checkbox for showing properties with images first
	**/
	onFullAdsFirstChange: function() {
	    checkbox = document.getElementById("fullAdsFirst");	    
	    $j.cookie('fullAdsFirst', null, {path: '/'}); // This ensures that non-session cookies are deleted
		$j.cookie('fullAdsFirst', checkbox.checked, {path: '/'});
		ha.page.search.doSort();	    
	},

	/**
	 * Sets the page size via a cookie.
	 */
	doSetPageSize: function(pageSizeSelect){
		var newPageSize = Number(pageSizeSelect.options[pageSizeSelect.selectedIndex].text);
			
		$j.cookie('pageSize', newPageSize, {expires: 7, path: '/'});
		ha.page.search.doSort();
	},
	
	doSort: function(){
		$j.cookie('newSort', 1);
		window.location = window.location;
	},
	
	setOmnitureEvents: function(){
		$j("#sidebarContent ul.criteria ul.criteria li").bind("click", function(event){
			$j.cookie('searchType', "refinement:" + $j(this).attr("id"), {expires: 1, path: '/'});
		});
	},
	
	initPriceToggle: function(){
		var priceValues = ($j('#priceFrom.input').val() + $j('#priceTo.input').val());
		if (priceValues > 0) {
			$j("#price-range .action").addClass("open");
			$j("#price-range .content").removeClass("hidden");
			$j("#findByDateButton").insertAfter("#price-range-fields");
		}

		$j("#price-range .action").bind("click", function(){
			if($j(this).hasClass("open")){
				$j("#findByDateButton").insertAfter("#price-range-fields");
				$j("#priceFrom").focus();
			}
			else{
				$j("#findByDateButton").insertAfter("#findByDateForm");
	    		$j("#price-range-vaidation").addClass("hidden").css("display", "");
				$j("#price-range-fields input").val("");
			}
		});
	},
	
	initSnippets: function(yOff,xOff) {
        $j('.reviews-popup').each(function(n, popup) {
        	var popupid = '#'+popup.id;
        	var ratingdivid = popupid.replace('-snippet-','-read-')+" a.rating";
        	popup = $j(popupid);
        	var popupheight = popup.height();
    		var cssValues = {"top" : (yOff - popupheight) + "px",
    			"left" : xOff + "px"};
        	$j(ratingdivid).hover( function() { // over function
        		popup.css(cssValues).fadeIn(200);
        	},
        	function() { // out function
        		popup.fadeOut(100);
        	});
        });
	},
	
	initCollapsableRegions: function(){
		$j("body.consolidated-region ul.criteria li ul.region > li").each(function(){
			// only apply the event to regions which have child nodes to display
			if($j(this).find("ul.children").size() > 0){
				$j(this).addClass("parent");
				$j(this).click(function(event){
					var target = $j(event.target);
					if(target.attr("tagName") == "A"){
						return true;
					}
					if(target.hasClass("parent")){
						target.toggleClass("open");
					}
				});
			}
		});

	}
};

/*
 * LANDING PAGE
 */ 
ha.page.landing = {
	init: function(){
		if ($j("#mapLink").length > 0){
			$j("#mapLink").click(function(){
				ha.page.landing.showMap();
			});
		}else if ($j("#map").length > 0){
			$j("#map").css("display","block");
		}
		$j(".zero-features a.headerLink").click(function(){
			return false;
		});
		ha.page.landing.seoCoulmn();
	},
		
	showMap: function showMap(){
		if($j("#mapTxt").html() == ha.strings.viewMapMsg) {
			$j("#mapTxt").html(ha.strings.closeMapMsg);
				
			$j("#map").css({display:"block", backgroundColor:"#fff", borderColor:"#fff", textAlign:"center"});	
			$j("#mapDivHeader").css({display:"none"});
			$j("#mapDivFooter").css({display:"none"});
			$j("#regionMapImage").css({margin:"10px"});
		} else {
			$j("#map").css({display:"none"});
			$j("#mapTxt").html(ha.strings.viewMapMsg);
		}
	},
	
	seoCoulmn: function(){
		/* Show and Hide seo content on right column of landing page */

		$j(document).ready(function(){
			var h = $j("#searchText").height();
			if(h >= 300) {
				$j("#searchText").addClass("closed-seo");
				$j("#fade span").click(function(){
					$j('#searchText').removeClass("closed-seo");
				});
				$j("#hideSeo").click(function(){
					$j('#searchText').addClass("closed-seo");
				});
			}
			else{ 
				$j("#hideSeo").css("display","none");
			};
		});		
	}
};



/*
 * ADV SEARCH
 */
ha.page.advancedSearch = {
	init: function(){
		$j('#refinementsContent0, #refinementsContent1, #refinementsContent2').hide();
		if ($j("#keywords").val()){
			document.searchForm.keywords.focus();
		}
		
		searchErrorObserver.subscribe(function(){
			//scroll into view
	        $j('html,body').animate({scrollTop: $j("#price-range-fields").offset().top}, 500);
		});
		ha.util.initToggles();
		
	}
};

/*
 * PROPERTY DETAILS
 */
var jsEnabled = function(s){ this.s=s;}
var commentsLangTxt = function(s){ this.s=s;}
var ajaxInquirySubmitted = new Observer;
var jsonrpcClient = null;

ha.page.property = {
    init: function(){
		ha.page.property.initInquiry();
		ha.page.property.initNavBar();
		
		if (ha.settings.similarPropertiesOn){
			ha.util.initToggles();
		}
		
		if(window.ie6) { 
        	// get the image tag
        	image = $j('#regionMapImage');
        	if(image) {
        		imageSourceUrl = image.srcsure
        		image.src="";
        		image.src=imageSourceUrl;
        	}
        }
		
		ha.page.property.initVoteCount();
	},
	initReviewsJSONClient: function(ajaxUrl) {
		try {
			jsonrpcClient = new JSONRpcClient(ajaxUrl);
		} catch (e) {
			// alert(e + "\nmessage=" + e.message);
		}
	},
	// the ajaxurl changes based on deployment type, and we don't have that available here in css land
	reviewsCount: function(cssId, systemId, propertyId, unitId) {
		try {
			jsonrpcClient.review.getReviewCount(
				function(result, exception) {
					if($j('#review-read-'+cssId).length > 0){
						if (parseInt(result) > 0) {
							$j('#review-read-'+cssId).css("display","block");
							$j('#reviewcount-'+cssId).text(result);
						}
						else{
							$j('.rating','#review-write-'+cssId).css({paddingTop:"10px",paddingBottom:"10px"});
							$j('#review-write-'+cssId).css("display","block");
							$j('#review-link').css("display","none");
						}
						return;
					}
					$j('#reviewcount-'+cssId).text(result);
				}, systemId, propertyId, unitId);
		} catch (e) {
			// Let's just turn on the write review link if reviews is down
			$j('.rating','#review-write-'+cssId).css({paddingTop:"10px",paddingBottom:"10px"});
			$j('#review-write-'+cssId).css("display","block");
			$j('#review-link').css("display","none");
		}
	},
	
	notVoted: function(reviewId) {
		//check for the cookie for the review being passed in
		if (document.cookie.match("HATravelerReviewHelpful"+ reviewId )) {
			// cookies matched, return the message
			$j('#reviewMessage_' + reviewId).html($j("#alreadyVotedMessage").html());
			return false;
		}
		//set the cookie
		$j.cookie("HATravelerReviewHelpful" + reviewId, 0, {expires: 18250, path:'/'});
		return true;
	},
	
	updateVotes: function(reviewId, helpfulVote, totalVote, showThankYou) {
		if(showThankYou) {
			$j('#reviewMessage_' + reviewId).html($j("#thankYouMessage").html());
		}
		votesContent = $j('#helpfulVotesLabel').html() + ' <span class="helpfulVotes">' + helpfulVote + '</span>/<span class="totalVotes">' + totalVote +'</span>';
		$j('#reviewVote_' + reviewId).html(votesContent);
	},
	
	vote: function(reviewId, helpful) {
		callback = function(result, exception) {
			if (exception) {
				//alert(exception.message); uncomment to debug
				return;
			}
			ha.page.property.updateVotes(reviewId,result[0],result[1], true);
		}
	
		if (ha.page.property.notVoted(reviewId)) {
			if(jsonrpcClient != null){
				if (helpful) {
					jsonrpcClient.review.voteHelpful(callback, reviewId);
				} else {
					jsonrpcClient.review.voteUnhelpful(callback, reviewId);
				}
			}
		}
	},
	
	initVoteCount: function() {
		// collect all the reviewIds by parsing the ids of the .voteLeft divs
		reviewIds = []
		$j(".voteLeft").each(function(){
			reviewIds.push(parseInt(this.id.replace("reviewMessage_","")));
		});
		
		renderVoteCounts = function(voteResults, exception) {
			if(exception) {
				// alert(exception.message); uncomment to debug
				return;
			}
			for(reviewId in voteResults.map) {
				helpful = voteResults.map[""+reviewId][0];
				total = voteResults.map[""+reviewId][1];
				if (helpful>0) {
					ha.page.property.updateVotes(reviewId, helpful, total, false);
				}
			}
		}
		
		if(jsonrpcClient != null && reviewIds && reviewIds.length > 0){
			// we use the javaClass notation here to hint to JSONRPC that we want an ArrayList for the resultant java collection
			jsonrpcClient.review.findVoteCounts(renderVoteCounts, {"javaClass": "java.util.ArrayList", "list":reviewIds});
		}
	},
	
	initNavBar: function(){
		var anchors = new Array('photos','location','rates','amenities');
		for (var i=0; i< anchors.length; i++){
			if ($j('#'+anchors[i]+'-bar').length == 0 || $j('#'+anchors[i]+'-bar').css("display") == "none"){
				$j('.'+anchors[i]+'-link').css("display","none");
			}
		}
	},
	
	initInquiry: function(){
		ha.page.property.initInquiryComments();
		var submitViaAjax = false;
		if (jsEnabled.s && $j('#jsEnabled').length > 0) { 
			submitViaAjax = true;
			$j("input[@name=jsEnabled]").val("true");
		}
		
		if($j('#propertyInquiryForm').length > 0) {
			
			var now = new Date();
			now = now.getTimezoneOffset()/60;
			$j('#localGMTOffset').val(now);
				
			if(!submitViaAjax || submitViaAjax == 'false') {
				$j('#submitButton').click(function(e) { 
					ha.page.property.inquiryStatus(true);
					$j("#propertyInquiryForm").submit();
				});
			} else {
				var ajaxFormOptions = {
				    	success: ha.page.property.inquiryComplete,
				    	error: ha.page.property.inquiryFailure
					};
				
				$j('#submitButton').click(function(e){
					var comments = $j("#comments").val();
					if (comments.indexOf(ha.strings.propertyCommentsLangTitle) == 0) { $j("#comments").val(""); }
						
					ha.page.property.inquiryStatus(true);
				});
				
				$j('#propertyInquiryForm').ajaxForm(ajaxFormOptions);
			}
		}
	},
	
	initInquiryComments: function(){
		if ($j('#comments').length == 0) return;
		
		var hasDefaultTxt = ($j('#comments').val().indexOf(ha.strings.propertyCommentsLangTitle) == 0) ? true : false;
		var maxChars = $j('#comments').attr('maxlength');
		var allowedKeys = new Array(8,9,27,46,33,34,35,36,37,38,39,40,45);
		
		//onload: set the default text and style; then set the counter.
		if ($j("#comments").val() == "") {
			$j("#comments").val(commentsLangTxt.s);
			$j("#comments").css("color","#ccc");
			hasDefaultTxt = true;
		}
		else if (hasDefaultTxt){
			$j("#comments").css("color","#ccc");
		}
		
		//onfocus: clear default text and set font color
		var setAttribute = function(){
			if ($j(this).val().indexOf(ha.strings.propertyCommentsLangTitle) == 0){
				$j(this).val("");
				$j(this).css("color","#333");
			}
		}
		$j('#comments').focus(setAttribute);
		
		//onkeyup: monitor length and update counter
		var limiter = function(event){
			var charCount = $j(this).val().length;
			var lineCount = $j(this).val().split(/\r\n|\n|\r\|\f/).length;
			var totalCount = (charCount > 0) ? charCount + lineCount : 0;
			var remainder = ((maxChars - totalCount) > -1) ? maxChars - totalCount : 0;
			
			if(event.metaKey || event.ctrlKey || event.altKey) return true;
			
			if(jQuery.inArray(event.keyCode, allowedKeys) != -1){
				$j('#remainder').text(remainder);
				return true;
			}
			
			if(totalCount >= maxChars){
				$j(this).val($j(this).val().substr(0,maxChars-lineCount));
				$j('#remainder').text(remainder);
				return false;
			}
			$j('#remainder').text(remainder);
		}
		
		$j('#comments').keyup(limiter);
		if (hasDefaultTxt) {
			$j('#remainder').text(maxChars);
		}
		else{
			$j('#comments').change(limiter).change();
		}
	},
	
	inquiryStatus: function (show) {
    	if (show) {
    		if ($j('#submitButton').length > 0) {
    			$j('#submitButton').onclick = null;
    		}
    		
    		//IE6 only:
    		//render country code in a simple input while the inquiry status is overlaid
    		//otherwise the country code drop down pokes through the status overlay
    		//	
    		if($j.browser.msie6) {
            	var text=$j('#inquirerPhoneCountryCode :selected').text();
            	var parentNode = $j('#inquirerPhoneCountryCode').parent();
            	$j('#inquirerPhoneCountryCode').remove();
            	parentNode.append("<input type='text' value='"+text+"' />");
            }
            
    		$j('#inquiry-status').css("height", $j('#enquiry-form').attr("offsetHeight") - 40 + "px");
    		$j('#inquiry-status').css("visibility","visible");
    		return; // force a return because the debugger jumped down to line 194!!
    	} else {
    		$j('#inquiry-status').css("visibility","hidden");
    	}					
    },
    
	inquiryComplete: function(responseText, statusText){
    	$j("#inquiryReplacementDiv").html(responseText);

		datePickerController.create(); ha.util.datePickControl.linkDates('startDateInput','endDateInput'); 
    	
    	if (statusText == "success" && $j("#jsEnabled").length == 0){
    		if (jQuery.browser.mozilla && navigator.userAgent.toLowerCase().indexOf("mac") != -1) { 
    			$j("#propertyInquiry").css({position:"static"});
    		}
    		$j("#owner-contact-info").css("display","none");
			$j("#propertyInquiry .propertySubHead").css("display","none");
    		$j("#enquiry-form .form").css("width","100%");
    		
    		// Fire off the inquiry confirmation vbis tracking data
    		submitInqTracker();

			// load iframe ads
			$j("iframe[@rel]").each(function(){
				$j(this).attr("src", $j(this).attr("rel"));
			});
    	}
    	else {
    		ha.page.property.inquiryError();
    		//force a change to linkdates
    		$j("#startDateInput").change();
    		ha.page.property.initInquiry();
    		if (ha.settings.omnitureOn){
    			var errs="";
		    	$j(".form-error-inline", "#enquiry-form").each(function(i){
			    	if($j(".body p", this).text() != ""){
			    		errs+=$j(".body p", this).text() + " ";
			    	}
			    });
    		
    			ajaxInquirySubmitted.fire(errs);
    		}
    		
    	}
    	       
    	ha.page.property.inquiryStatus(false);
    },
    
    inquiryFailure: function() {
    	var newHtml = '<div style="text-align:center">';
    	newHtml += '<p class="formError">' + ha.strings.errorMessage + '</p>';
    	newHtml += '<p>&nbsp;</p>';
    	newHtml +='</div>';
    	$j("#inquiryReplacementDiv").html(newHtml);
    	
    	ha.page.property.inquiryStatus(false);
    },
    
    inquiryError: function(){
    	if(!document.getElementById("enquiry-form"))
    		return;
    	// if there is not an error message then suppress the error divs
    	// this occurs when triphomes returns errors that we are handling
    	// at times we want to display our error and suppress the triphome response
    	$j(".form-error-inline", "#enquiry-form").each(function(i){
	    	if($j(".body p", this).text() == ""){
	    		$j(this).css("display","none");
	    	}
	    });
    	// global close popups
    	$j("#enquiry-form").click(function(e){
    		var type = '';
    		
			if($j(e.target).hasClass("form-error-icon")){
				type = "icon";
			}
			
			$j(".form-error-msg", "#enquiry-form").each(function(i){
		    	if(!$j(this).hasClass("hidden")){
		    		$j(this).addClass("hidden");
		    	}
		    });
			
   			if(type == "icon"){
   				$j(e.target).next().removeClass("hidden");
   			}
    	});
    }, 

    getMonth: function(propertyId, systemId, unitId, offset) {
    	$j.ajax({
    		url: "/propertyAvailabilityNextPrevious.htm?propertyId=" + propertyId + "&uni_id=" + unitId + "&systemId=" + systemId + "&offset=" + offset,
    		type: "get", 
    		success: function(html){ $j("#availabilityCalendars").html(html);},
    		error: function(){alert(ha.strings.errorMessage);}
    	});
    },
    
    getCurrency: function(systemId, propertyId, unitId, currency){
    	$j.ajax({
    		url: "/propertyCurrencyChange.htm?systemId=" + systemId + "&propertyId=" + propertyId + "&uni_id=" + unitId + "&currency=" + currency,
    		type: "get",
    		success: function(html){$j("#rates").html(html);}, 
    		error: function(){alert(ha.strings.errorMessage);}
    	});
    }
};


/* Based off of:
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 */
var mbWidth = 498;
var mbHeight = 575;
var mbScroll = 'yes';

ha.ui.modalbox = {
	init: function(){
		$j('a.modalbox').click(function(){
			var t = this.title || this.name || null;
			if(t==null) t = "";
			var u = this.href;
			ha.ui.modalbox.show(t,u);
			this.blur();
			return false;
		});
	},

	show: function(title, url) {
		
		var sOverlay = ""; var sBody = "";
		var sLoad = '<div id="mb-load"><img src="/resources/7516/images/icon/modal-loader.gif" /></div>';
	
		try {
			
			if (typeof document.body.style.maxHeight == "undefined") {
				$j("body","html").css({height: "100%", width: "100%"});
				$j("html").css("overflow","hidden");
				if (document.getElementById("mb-hide") == null) {
					sOverlay += '<iframe id="mb-hide"></iframe>';
					sOverlay += '<div id="mb-overlay"></div>';
					sOverlay += '<div id="mb-window"></div>';
				}
			}
			else if(document.getElementById("mb-overlay") == null){
				sOverlay += '<div id="mb-overlay"></div>';
				sOverlay += '<div id="mb-window"></div>';
			}
		
			$j("body").append(sOverlay);
			$j("#mb-overlay").click(ha.ui.modalbox.remove);
	
			$j("body").append(sLoad);
			$j('#mb-load').show();

			var args = ha.ui.modalbox.getArgs(url);
			
			if (args.length > 0){
				for (var i=0; i<args.length; i++){
					if (i == 0) mbWidth = args[0];
					else if (i == 1) mbHeight = args[1];
					else if (i == 2) mbScroll = args[2];
				}
			}

			var sBody = '<iframe frameborder="0" hspace="0" src="'+ url +'" scrolling="'+ mbScroll +'" title="'+ title +'"id="mb-iframe" name="mb-iframe" style="width:'+ mbWidth +'px; height:'+ mbHeight +'px;" allowtransparency="true" onload="ha.ui.modalbox.showIframe()"> </iframe>';
			$j("#mb-window").append(sBody);

			ha.ui.modalbox.position();
		
			if(frames['mb-iframe'] === undefined){ // safari
				$j("#mb-load").remove();
				$j("#mb-window").css({display:"block"});
				$j(document).keyup(function(e){ 
					var key = e.keyCode; 
					if(key == 27){ ha.ui.modalbox.remove(); }
				});
			}

			var fr = document.getElementById("mb-iframe"); 
			if (document.all)
    			fr.document.body.focus(); 
			else 
				fr.contentDocument.body.focus();
		
		} catch(e) {
			//do nothing
		}
	},
	
	/* Args can be set by setting a mbArgss=value in the url
	 * If no args are set then an empty Array will be returned
	 * More than one arg can be set in the mbParams value but
	 * they must be seperated by a - delimiter.
	 */
	getArgs: function(url){
		var url = url.split('?');
		var mbArgsArray = new Array();
		
		if(url[1]){
			if (url[1].indexOf("mbArgs") > -1){
				var urlNVPairs = url[1].split('&');

				for(i=0; i<=(urlNVPairs.length); i++){
					if(urlNVPairs[i]){
						var urlNVPart = urlNVPairs[i].split('=');
						if (urlNVPart[0] == "mbArgs") {
							if (urlNVPart[1].indexOf("-") > -1) {
								mbArgsArray = urlNVPart[1].split("-");
							}
							else{
								mbArgsArray = new Array(urlNVPart[1]);
							}
							break;
						}
					}
				}
			}
		}
		
		return mbArgsArray;   
	},
	
	showIframe: function(){
		$j("#mb-load").remove();
		$j("#mb-window").css({display:"block"});
	},

	remove: function(){
		$j("#mb-overlay").unbind("click");
		$j("#mb-window").fadeOut("fast",function(){$j('#mb-window,#mb-overlay,#mb-hide').remove();});
		$j("#mb-load").remove();
		if (typeof document.body.style.maxHeight == "undefined") {
			$j("body","html").css({height: "auto", width: "auto"});
			$j("html").css("overflow","");
		}
		document.onkeydown = "";
		return false;
	},
	
	position: function(){
		$j("#mb-window").css({marginLeft: '-'+ parseInt((mbWidth / 2),10) +'px', width: mbWidth +'px'});
		if ( !(jQuery.browser.msie && typeof XMLHttpRequest == 'function')) {
			$j("#mb-window").css({marginTop: '-'+ parseInt((mbHeight / 2),10) +'px'});
		}
	}
	
};

/*
 *      jQuery extensions
 */

(function ($) {

/*
 *      maxlength
 */

$.fn.maxlength = function(settings) {

    if (typeof settings == 'number')
        settings = { maxlength: settings };
    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    checkKey = function(event) {
        var $field = $(this);
        var key = event.keyCode;
        var val = $field.val();

        if (val.length < settings.maxlength)
            return;

        if (event.metaKey || event.ctrlKey || event.altKey)
            return;

        switch (key) {
            case 8:     // delete
            case 9:     // tab
            case 27:    // escape
            case 33:    // pgup
            case 34:    // pgdn
            case 35:    // end
            case 36:    // home
            case 37:    // left
            case 38:    // up
            case 39:    // right
            case 40:    // down
            case 45:    // insert
            case 46:    // delete
                return;
            default:
                event.preventDefault();
        }
    };

    checkMaxLength = function(event) {
        var $field = $(this);
        var val = $field.val();

        if (val.length > settings.maxlength) {
            val = val.substring(0, settings.maxlength);
            $field.val(val);
        }

        $field.parent().find(settings.charsRemaining).html("" + (settings.maxlength - val.length));
    };

    return this.each(function() {
        var $field = $(this);
        $field.keydown(checkKey);
        $field.change(checkMaxLength);
        $field.keyup(checkMaxLength);
        $field.keyup();
        $field.parent().find(settings.charsTotal).html("" + settings.maxlength);
    });
};

$.fn.maxlength.defaults = {
    charsTotal      : '.chars-total',
    charsRemaining  : '.chars-remaining',
    maxlength       : 500
};

/*
 *      carousel
 */

$.fn.carousel = function(options) {

    var settings = {
        speed   : 500,
        left    : '.left',
        right   : '.right'
    };

    if (options) {
        $.extend(settings, options);
    }

    var Carousel = function() {
        var container;
        var carousel;
        var slider;
        var items;
        var index = 0;
        var max_index = 0;
        var minx = 0;

        var init = function(container) {
            container = container;
            carousel = $(container).find('.carousel');
            slider = $(carousel).find('ul');

            minx = parseInt($(slider).css("margin-left"));

            $(container).find(settings.right).click(function() {
                container.carousel.slide_left(4);
                this.blur();
                return false;
            });

            $(container).find(settings.left).click(function() {
                container.carousel.slide_right(4);
                this.blur();
                return false;
            });

            $(slider).find('img').one("load", function() {
                refresh();
            });

            refresh();
        };

        var refresh = function() {
            var listitems = $(slider).find('li');
            var total_width = 0;

            items = listitems.map(function(n, item) {
                var offset = total_width;
                var width = $(item).outerWidth() + parseInt($(item).css('margin-left')) + parseInt($(item).css('margin-right'));
                total_width += width;
                return offset;
            });
            slider.width(total_width);
            var max_offset = $(slider).width() - $(carousel).width();
            items.each(function(n, item) {
                if (item < max_offset) {
                    max_index = n + 1;
                    return;
                }
            });
        };

        var slide = function(offset) {
            $(slider).animate({marginLeft: minx-offset}, settings.speed);
        };

        var slide_left = function(n) {
            index += (n == undefined) ? 1 : n;
            if (index > max_index)
                index = max_index;
            slide(items[index]);
        };

        var slide_right = function(n) {
            index -= (n == undefined) ? 1 : n;
            if (index < 0)
                index = 0;
            slide(items[index]);
        };

        return {
            init: init,
            slide_left: slide_left,
            slide_right: slide_right
        };
    };

    return this.each(function() {
        $.extend(this, { carousel: Carousel() });
        this.carousel.init(this);
    });
};

})(jQuery);


$j(document).ready(function(){
	//global
	ha.site.searchform.init();
	
	// nit pop-up url's
	ha.util.initPopupUrls();
	
	// move the bookmark button into the correct location in the document
	// the Fewo bookmark button has a div parent element
	// the other products have an anchor parent element
	// so we target both flavours
	$j("li.addthis").append($j("#addthis-placeholder div,#addthis-placeholder a"));

	// load iframe ads
	$j("iframe[@rel]").each(function(){
		$j(this).attr("src", $j(this).attr("rel"));
	});
	
	//clear search type cookie
	$j.cookie('searchType', null, {path: '/'});	

	//home
	if ($j("body.homePage").length > 0){
		ha.page.home.init();
	}
	
	//search
	if ($j("body.search-page").length > 0){
		ha.seo.showSeoText();
		ha.page.search.init();
	}
	
	//landing
	if ($j("body.landing").length > 0){
		ha.seo.showSeoText();
		ha.page.landing.init();
	}
	
	//advanced search
	if ($j("body.adv-search").length > 0){
		ha.page.advancedSearch.init();
	}
	
	//property details
	if ($j("body.property").length > 0){
		ha.page.property.init();
		ha.ui.modalbox.init();

	}
});
