$(function(){$.ajaxSetup({contentType: "application/x-www-form-urlencoded; charset=utf-8"  });});

var windowTitle = '';

function setWindowTitle(title) {
	windowTitle = title;
}

function initTargets(container){
	document.title = windowTitle;
	if (!container) container=null;
	initTargetAnchors(container);
	initTargetForms(container);
	initFormSubmitters(container);
	replaceChecks(container);
	replaceRadios(container);
}

function initFormSubmitters(container) {
   /* register anchors with class=formSubmitter to submit the form */
   $("form a.formSubmitter",$(container)).click(function(e) {
      $(e.target).parents(':first(form)').submit();
   });
}

function initTargetForms(container){
	$("form[target^='#']",$(container)).submit(function(e){
		var $this=$(this), url;
		var target=	$this.attr('target'), 
				isHistory=$this.hasClass("history"),
				isEmpty=$this.hasClass("empty"),
				method=$this.attr('method'),
				action=$this.attr('action');
		/* post the form if its method is 'post' and request is not meant for history */
		var isPost= $this.hasClass('usePost') && !isHistory && ('POST'==method || 'post'==method);
		if (isPost) url=buildTargetUrl(target,action);
		else url=buildTargetUrl(target,action,$this.serialize());
		if (!url) return false;
		/* pre-process - if callTargetPreload exists and returns false the link is not followed */
		if (!$.preload.execute(this, target, url)) return false;	
		if(window.recordAnalytics) recordAnalytics(url);
		/* if action is added to browser's history change state and let the event handler submit the action */
		if (isHistory) $.bbq.pushState({p:url,t:target,ts:(new Date()).getTime(),e:isEmpty});
		/* post the form */
		else if (isPost) {
			var formData = {};
			$(':input',$this).each(function () {
				var $field=$(this), $name=$field.attr('name'), $val=$field.val();
				if ($val && $field.hasClass("escapeText")) $val=escapeURI($val);

        if ($field.attr("type")!="checkbox") formData[$name]=$val;
        else if ($field.attr("checked")) formData[$name]=$val;
			});
			postContent(target,url,formData,isEmpty,$this.hasClass("scrollTop"));
		}
		/* or use get to request content */
		else loadContent(target,url,isEmpty,$this.hasClass("scrollTop"));
		return false;
	});
}

function initTargetAnchors(container){
	$("a[target^='#']",$(container)).click(function(e){
		var $this=$(this);
		var target=$this.attr('target');
		var url=buildTargetUrl(target,$this.attr('href'));
		if (!url) return false;
		/* pre-process - if callTargetPreload exists and returns false the link is not followed */
		if (!$.preload.execute(this, target, url)) return false;
		if(window.recordAnalytics) recordAnalytics(url);
		/* if url is added to browser's history change state and let the event handler submit the request */
		if ($this.hasClass("history")) $.bbq.pushState({p:url,t:target,ts:(new Date()).getTime(),e:($this.hasClass("empty"))});
		/* else load url */
		else loadContent(target,url,$this.hasClass("empty"),$this.hasClass("scrollTop"));
		return false;
	});
}

function loadContent(target,url,empty,scrollTop,backgroundLoad) {
	processRequest(target,url,"ts="+(new Date()).getTime(),empty,scrollTop,backgroundLoad)
}

function postContent(target,url,data,empty,scrollTop,backgroundLoad) {
	processRequest(target,url,data,empty,scrollTop,backgroundLoad)
}

function processRequest(target,url,data,empty,scrollTop,backgroundLoad) {
	if (!target || !url);
	if (!backgroundLoad) {
		closeDialog();
	}
	$(target).load(url,data,function(){
		initTargets(target);
		callTargetPostload(target);
	});

	if (empty) {
		if (target=='#container') $('#page').empty();
		else $(target).empty();
	}
	if (scrollTop) $('html, body').animate({scrollTop:0}, 0);
}

function callTargetPostload(target){
	if (!$(target)) return;
	/* used by overlays */
	var fx = $(target).data("postload"); 
	if ($.isFunction(fx)) fx.call();
	$(target).removeData("postload");
	/* other registered postload functions */
	$.postload.execute();
}

/* static extension of jQuery to allow registration and execution of preload functions */
(function($) {
	$.preload = {
		registeredFunctions: [],
		register: function(fx) {
			$.preload.registeredFunctions.push(fx);
		},
		execute: function(originElement, target, url) {
			var allow=true, prf = $.preload.registeredFunctions;
			if (!prf || prf.length == 0) return allow;
			if (!originElement) originElement = window;
			$.each(prf, function(idx) {
				var fx = prf[idx];
				if ($.isFunction(fx)) allow = allow && fx.call(originElement, target, url);
			});
			return allow;
		}
	};
})(jQuery);

/* static extension of jQuery to allow registration and execution of postload functions */
(function($) {
	$.postload = {
		registeredFunctions: [],
		register: function(fx) {
			$.postload.registeredFunctions.push(fx);
		},
		execute: function() {
			var prf = $.postload.registeredFunctions; 
			$.each(prf, function() {
				var fx = prf.shift();
				if ($.isFunction(fx)) fx.call();
			});
		}
	};
})(jQuery);

function buildTargetUrl(target,url,queryString){
	if (!target || !url) return;
	target=target.replace(/#/g,"$");
	if (queryString) url=$.param.querystring(url,queryString);
	if (url.indexOf(";jsessionid")>0) {
		return url.replace(";jsessionid", target+";jsessionid");
	} else if (url.indexOf("?")>0) {
		return url.replace("?", target+"?");
	} else {
		return url + target;
	}
}

function initHistory() { 
	$.bbq.pollDelay = 50;
	/* 	Bind a callback that executes when document.location.hash changes. */
	$(window).bind( "hashchange", function(e) { 
		var url = $.bbq.getState( "p" );
		var target = $.bbq.getState( "t" ); 

		if (!url && !target) return;
		/* content load from history always forces a scroll to top */
		loadContent(target, url, ($.bbq.getState( "e",true)),true);
 	}); 

	/*	Since the event is only triggered when the hash changes, we need 
		to trigger the event now, to handle the hash the page may have loaded with. */
	$(window).trigger( "hashchange" ); 
};

/*Function to move the screen to an specific position of it.*/
function scrollToPosition(position, velocity) {
	if (!velocity) velocity = "slow";
	if (!position) position = 0;
	if (position) {
		$('html, body').animate({scrollTop:position}, velocity);
	}
	return false;
}

