/* 
	HomeAway Real Estate base.js
	
	Namespaces Defined:	
		hare.site.properties: properties content includes listings & map data
		hare.site.overview: includes map & area data
		hare.site.mapManager: includes all map loading, display and interaction methods
	
*/

// jQuery ajax setup
$.ajaxSetup({cache: false});

jQuery.browser.msie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object";

//namespace declaration
var hare = {
	site: {}	
};
hare.site.properties  = {};
hare.site.mapManager  = {};
hare.site.search  = {};

// required for modal form submissions 
jQuery.extend({
	  httpData: function( xhr, type, s ) {        
	        var ct = xhr.getResponseHeader("content-type"),
	                xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
	                script = type == "script" || !type && ct && ct.indexOf("script") >= 0,
	                json = type == "json" || !type && ct && ct.indexOf("json") >= 0,
	                data = xml ? xhr.responseXML : xhr.responseText;
	                
	                if ( xml && data.documentElement.tagName == "parsererror" )
	                    throw "parsererror";
	                
	                // Allow a pre-filtering function to sanitize the response
	                // s != null is checked to keep backwards compatibility
	                if( s && s.dataFilter )
	                    data = s.dataFilter( data, type );
	                
	                // If the type is "script", eval it in global context
	                if ( script ) 
	                    jQuery.globalEval( data );

	                // Get the JavaScript object, if JSON is used.
	                if ( json )
	                    data = eval("(" + data + ")");

	                return data;
	    }
});

// character counter plugin
(function($){  
    $.fn.extend({   
        countChars: function() {  
            return this.each(function() {  
            	
            	var recalc = function(e) {
            		var $target = $(e.target);
            		var available = maxChars - $target.val().length;
            		$target.next('p').text(available+' characters left.');
            	}
            	
            	var input = $(this);
				var maxChars = input.attr('maxlength');
				if (typeof(maxChars) == "undefined") return;
				input.css({'padding-bottom': '0px','margin-bottom': '0px'});
				var available = maxChars - input.val().length;
				input.after('<p style="margin-top: 0px; padding-top: 0px">'+available+' characters left.</p>');	
				input.keyup(recalc);
            });  
        }  
    });  
})(jQuery);  


jQuery.parseQuery = function(qs,options) {
	var q = (typeof qs === 'string'?qs:window.location.search), o = {'f':function(v){return unescape(v).replace(/\+/g,' ');}}, options = (typeof qs === 'object' && typeof options === 'undefined')?qs:options, o = jQuery.extend({}, o, options), params = {};
	jQuery.each(q.match(/^\??(.*)$/)[1].split('&'),function(i,p){
		p = p.split('=');
		p[1] = o.f(p[1]);
		params[p[0]] = params[p[0]]?((params[p[0]] instanceof Array)?(params[p[0]].push(p[1]),params[p[0]]):[params[p[0]],p[1]]):p[1];
	});
	return params;
}

// Event registry
function EventRegistry() {
	
	this._groups = new Array();
	
	this.bindEvent = function(group, selector, type, handler, data) {
		if (typeof (data) != "undefined") {
			$(selector).bind(type, data, handler);
		} else {
			$(selector).bind(type, handler);
		}
		
		if (typeof (this._groups[group]) == "undefined") {
			this._groups[group] = new Array();
		}
		var event = {"selector": selector, "type": type, "handler": handler, "data" : data };
		this._groups[group].push(event);
	};
	
	this.rebindEvents = function(group) {
		var groupArray = this._groups[group];
		if (typeof(groupArray) == "undefined") return;
		for (i = 0; i<groupArray.length; i++) {
			var event = groupArray[i];
			$(event.selector).unbind(event.type); // prevents dupes
			if (typeof (event.data) == "undefined") {
				$(event.selector).bind(event.type, event.handler);
			} else {
				$(event.selector).bind(event.type, event.data, event.handler);
			}
		}
	};
	
};

//Browser Window Size and Position
//copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
//you may copy these functions but please keep the copyright notice as well
function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;} function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;} function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;} function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;} function posRight() {return posLeft()+pageWidth();} function posBottom() {return posTop()+pageHeight();}

hare.site.modal = {
	configuredModals : new Array(),

	configureModal: function(clickSelector, divSelector, url, callback) {
		var modal = {
				clickSelector: clickSelector,
				divSelector: divSelector,
				url: url,
				callback: callback
		};
		hare.site.modal.configuredModals[divSelector] = modal;
		if (clickSelector != null) {
			$(clickSelector).click(function(e) {
				e.preventDefault();
				hare.site.modal.renderModal(divSelector);
			});
		}
	},
	
	centerModal: function(divSelector) {
		var width = $(divSelector).children(':first').width();
		$('.simplemodal-data').css('width', width);
		$.modal.impl.setPosition();
		$('#simplemodal-container').css('position', 'absolute');
		if ($.browser.msie) {
			$('.simplemodal-data').css('top', '0px');
			$(window).scroll(function () {
				var top = window.screenTop-100;
				$('#simplemodal-container').css('top', top+'px');
			});
	 	}
	},
	
	renderModal: function(divSelector) {
		$('div.loader').hide();
		var modal = hare.site.modal.configuredModals[divSelector];	
		var y = 50 + posTop();
		$(modal.divSelector).modal({
			onShow: function(dialog) {
				if (modal.url != null) {
					$.get(modal.url, function(data) {
						$(modal.divSelector).html(data);
						if (modal.callback != null) {
							modal.callback();
						}
						hare.site.modal.centerModal(divSelector);
					});
				} else if (modal.callback != null) {
					modal.callback();
					hare.site.modal.centerModal(divSelector);
				} else {
					hare.site.modal.centerModal(divSelector);
				}
			},
			onClose: function(dialog) {
				dialog.overlay.hide();
				$.modal.close();
				$(window).unbind('scroll');
			},
			position: [y],
			close: false,
			closeClass: 'close-dialog'
		});
	},
	
	getModalContent: function(modalDivId, arg, callback) {
	    var data = $("#"+modalDivId+" form").serialize() + arg;
	    var action = $("#"+modalDivId+" form").attr('action');
	    $('div.loader').show();
	    $.ajax({
	          type:"POST",
	          url: action,
	          data: data,
	          success: function(responseText){
	    			$('#loader').hide();
	    			try {
	    				var response = $.evalJSON(responseText);
	    			} catch (error) {}
	    			
	    			if (typeof (response) == "object") {
	    				$.modal.close();
	        			$("#user-nav").html(response.user);
	    				hare.site.setupUserProfileNav();
	    			} else {
	    				responseText = $.trim(responseText);
	    				if ($(responseText).filter('#'+modalDivId).length == 1) {
	    					$('#'+modalDivId).html($(responseText).filter('#'+modalDivId).html());
	    				} else {
	    					$('#'+modalDivId).html(responseText);
	    				}
	    			}	    			
					hare.site.eventRegistry.rebindEvents('modal');
					if (callback != null && callback != "undefined") {
						callback();
					}
    	  }
	    });
	},
	initConfirm: function() {}
}

//AJAX initialization of User header
hare.site.user = {
 	initUser: function(pageId) {
		var data;
		var action = "/user/" + pageId;
		$.ajax({
			type:"POST",
			url: action,
			data: data,
			success: function(responseText){
				try {
					var response = $.evalJSON(responseText);
					if (typeof (response) == "object") {
						$("#user-nav").replaceWith(response.user);
						hare.site.setupUserProfileNav();
					}
				} catch (error) {}
				
		  	}
	    });
	} 		
}

// AJAX support for Feedback actions
hare.site.feedback = {

	feedback: function(eventId, divId, inputId, emailId) {
		var input = $("#" + inputId);
		var value = input.val();
		var email = $('#' + emailId).val();
		var data = {ft: value, fe: email};
		var action = "/f/" + eventId;
		$.ajax({
			type:"POST",
			url: action,
			data: data,
		    dataType: "script",
			success: function(responseText){
			var response = eval(responseText);
				if(response.result){
					$("#" + inputId + "-success").fadeOut(500);
					$("#" + inputId + "-error").fadeOut(500);
			    	$("#" + inputId).removeClass("feedback-error");
			    	$("#" + inputId + "-success").html(response.message);
			    	$("#" + inputId + "-success").fadeIn(500).animate({opacity: 1.0}, 3000).fadeOut(500);
			    	$("#" + inputId).val('');
			    	$("#" + emailId).val('');
			    }else{
			    	$("#" + inputId + "-success").fadeOut(500);
			    	$("#" + inputId + "-error").hide();
			    	$("#" + inputId + "-error").html(response.message);
			    	$("#" + inputId + "-error").fadeIn(500);
			    	$("#" + inputId).addClass("feedback-error");
			    	$("#" + inputId).focus();
			    }				
		  	}
	    });	
	},
	
	configure : function(inputSelector, defaultValue) {
		if ($(inputSelector).val().length == 0) {
			$(inputSelector).val(defaultValue);
		}
		$(inputSelector).focus(function(){
			if ($(inputSelector).val() == defaultValue)
		    $(inputSelector).val('');
		    $(inputSelector).css("color", "#000");
		});
		$(inputSelector).blur(function(e){
		    $(inputSelector).css("color", "");
		});
	}
}

// AJAX validation for email and screen name availability
hare.site.register = {
	checkInput: function(e,data){
		var inputValue = $(e.target).val();
		if(inputValue != null && $.trim(inputValue) != ""){
			$.ajax({
			    type: "POST",
			    url: "/person-validation",
			    data: data + $(e.target).val(),
			    dataType: "script",
			    success:function(responseText){
    		        var errorElInsert = $(e.target).parent().prev();
					var response = eval(responseText);
					if(response.result){
						// check to see if we are in a table like /register
						// else we are in the /seller form
						if($(e.target).parent().is('td')) {
							if($(e.target).prev(".error")){
		    		        	$(e.target).prev(".error").remove();
		    		        }
		    		        var error = '<p class="error">'+response.error+'</p>';
		    		        $(error).insertBefore($(e.target)).hide().fadeIn(500);
		    		    	$(e.target).addClass("error");
						} else {
							if($(e.target).parent().prev().prev(".error")){
		    		        	$(e.target).parent().prev().prev(".error").remove();
		    		        }
		    		        var error = '<p class="error">'+response.error+'</p>';
		    		        $(error).insertBefore(errorElInsert).hide().fadeIn(500);
		    		    	$(e.target).addClass("error");
						}
	    		    } else {
						// check to see if we are in a table like /register
						// else we are in the /seller form
						if($(e.target).parent().is('td')) {
		    		    	$(e.target).prev(".error").fadeOut(500);
		    		    	$(e.target).prev(".error").remove();
						} else {
		    		    	$(e.target).parent().prev().prev(".error").fadeOut(500);
		    		    	$(e.target).parent().prev().prev(".error").remove();
						}
	    		    	$(e.target).removeClass("error");
	    		    }
			    }
			});
		}
	}
}



hare.site.setupUserProfileNav = function() {
	var bgc = $('div.welcome-div').css('background-color');
	var c = $('div.welcome-div').css('color');
	$('div.welcome-div, div.welcome-div-hover, div.user-profile-nav').hover(
		function() {
			$('div.welcome-div').css({'background-color':'#EBEDF3', 'color':'#0F6DB6'});
			$('div.welcome-div').addClass('welcome-div-hover');
			$('div.user-profile-nav').show();
		},
		function() {
			$('div.welcome-div').removeClass('welcome-div-hover');
			$('div.welcome-div').css({'background-color':bgc, 'color':c});
			$('div.user-profile-nav').hide();
		}
	);
	var bgc2 = $('div.user-profile-nav div:first').css('background-color');
	var c2 = $('div.user-profile-nav div:first').css('color');
	$('div.user-profile-nav div').hover(
	    function() {
	    	bgc2 = $(this).css('background-color');
	    	c2 = $(this).css('color');
	    	$(this).css({'background-color':c2,'color':bgc2});
	    	$(this).children('a').css({'background-color':c2,'color':bgc2});
	    },
	    function () {
	    	$(this).css({'background-color':bgc2,'color':c2});
	    	$(this).children('a').css({'background-color':bgc2,'color':c2});	    	
	    }
    );
}

hare.site.setupSellAHomeNav = function() {
	var offset = $('#sell-a-home').position();
	$('.sell-home-nav').css({top: offset.top+30, left: offset.left});
	
	$('#sell-a-home').mouseover(function() {
		showHoverMenu('.sell-home-nav', '#' + $(this).attr('id'));
	});
}

var hideMenuTimeout; //<--global var

/*
*	Pass the element (el) to show and the target (targetEl) that triggers event
*/
function showHoverMenu(el, targetEl) {

	var elem = el;
	
	$(elem).show();
	
	//hide menu when user clicks outside of it
	$('body').click(function(){hideHoverMenu(elem)});
	$(elem).click(function(e){e.stopPropagation();});
	
	//cancel the mouseout timeout if they happen to have rolled over a link within the menu
	$(elem).find('*').andSelf().hover(
		function(){
			if (hideMenuTimeout)
    			clearTimeout(hideMenuTimeout);
		},
		function(){
			if (hideMenuTimeout)
    			clearTimeout(hideMenuTimeout);
			
			hideMenuTimeout = setTimeout(function(){
				hideHoverMenu(elem);
			}, 1000)
		}
	);
	// handle the mouseout of the target element that triggers the event
	$(targetEl).hover(
		function(){
			if (hideMenuTimeout)
    			clearTimeout(hideMenuTimeout);
		},
		function(){
			if (hideMenuTimeout)
    			clearTimeout(hideMenuTimeout);
			
			hideMenuTimeout = setTimeout(function(){
				hideHoverMenu(elem);
			}, 1000)
		}
	);
}

function hideHoverMenu(el) {
	$(el).hide();
}

function confirm(title, msg, callback) {	
	hare.site.modal.renderModal('#confirm');
	$("#confirm").find('h1.jqmConfirmMsgTitle').html(title);
	$("#confirm").find('p.jqmConfirmMsg').html(msg);
    $('#confirm a.submit').click(function() {
    	$.modal.close();
        $('#confirm a.submit').unbind('click');
        
        if (typeof(callback) != "undefined" && $.isFunction(callback)) {
            callback();
        }
    });
    $('#confirm a.close-dialog').click(function() {
    	$.modal.close();
    });    
}

$(document).ready(function(){	

	try { //apply gradients, shadows, and accordians to styled boxes
		$.fn.roundbox.defaults.themepath = '/resources/2769/img/roundbox/';
		$('.rbgradient, .rborangegradient, .rbaccordian, .rbshadow').roundbox();
	} catch(e){}
	
	// init event registry
	hare.site.eventRegistry = new EventRegistry();
	
	//retain this for backwards compatibility with old style collapsers
	$(".action:not(.boxheader)").click(function(){
	    var el = $(this).parent("div.inner").children("div.collapsable");
	    //el.slideToggle("fast");
	    el.toggle();
	    $(this).toggleClass("open");
	});
	
	$.modal.defaults.closeClass = 'close-dialog';
		
    hare.site.modal.configureModal(null, '#modal-loading-results', null, null);
    
	hare.site.modal.configureModal(null, '#confirm', null, hare.site.modal.initConfirm);
	
});