(function($) {
$.SPA = {

IDS:	{
	header: "#header",
	nav: "#nav",
	menu: "#menu",
	aside: "#aside",
	body: "#body",
	tabpages: "#tabpages",
	footer: "#footer"
},

EventType: {
	PageUnload:"PageUnload",	
	PageResize:"PageResize"
},

StatusCode: {
	OK:200, 
	Error:300, 
	Timeout:301
},

_msg:{
	error: "Sorry, the application has encounter an error.",
	serverError: "Sorry, the server error.",
	sessionTimout: "session timeout, please login again.",
	statusCode_503: "HTTP 503 error.",
	exceedMaxOpenPages: "Exceeding maximum open pages:{0}"
}, 

msg:function(key){
	return this._msg[key];
},

_debug:false,

debug:function(msg){
	if (this._debug) {
		if (typeof(console) != "undefined")
			console.log(msg);
		else
			alert(msg);
	}
},

evalJSON:function(data) {
	try{
		if ($.type(data) == 'string')
			return eval('(' + data + ')');
		else return data;
	} catch (e){
		return {};
	}
},

ajaxError:function(xhr, ajaxOptions, thrownError){
	if (alertMsg) {
		$.SPA.alertMsg("<div>Http status: " + xhr.status + " " + xhr.statusText + "</div>" 
			+ "<div>ajaxOptions: "+ajaxOptions + "</div>"
			+ "<div>thrownError: "+thrownError + "</div>"
			+ "<div>"+xhr.responseText+"</div>");
	} else {
		$.SPA.alertMsg("Http status: " + xhr.status + " " + xhr.statusText + "\najaxOptions: " + ajaxOptions + "\nthrownError:"+thrownError + "\n" +xhr.responseText);
	}
},

ajaxDone:function(json){
	if (json.statusCode === undefined && json.message === undefined) { 
		$.SPA.alertMsg(json);
	} 
	if(json.statusCode == $.SPA.StatusCode.Error) {
		$.SPA.alertMsg(json.message || $.SPA.msg("serverError"));
	} else if (json.statusCode == $.SPA.StatusCode.Timeout) {
		$.SPA.alertMsg(json.message || $.SPA.msg("sessionTimout"));
	} else {
		if(json.message) $.SPA.alertMsg(json.message);
	}
},

alertMsg: function(msg, callbacks) {
	alert(msg);
	if (callbacks && callbacks.onOK) callbacks.onOK();
},

wrap: function (elem){
	var $elem = $(elem || document);

	$("a[target=tabpages]", $elem).each(function(){
		$(this).click(function(event){
			var $this = $(this);
			var title = $this.attr("title") || $this.text();
			var icon = $this.data("icon") || "";
			var className = $this.data("class") || "";
			var tabid = $this.data("tabid") || "_blank";
			var refresh = (String($this.data("refresh")) == "true");
			var external = (String($this.data("external")) == "true");
			var closable = (String($this.data("closable")) != "false");
			var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unit-box:first"));
			
			$.SPA.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.data("warn") || $.SPA.msg("error"));
				return false;
			}
			
			$(".tabpages").tabpages("openTab",{
				tabid:tabid, 
				url:url,
				title:title, 
				icon:icon, 
				closable: closable,
				refresh:refresh, 
				external:external,
				className:className
			});

			event.preventDefault();
		});
	});

},

layout: function () {
	var h = $(window).height() - $("#header").outerHeight(true) - $("#footer").outerHeight(true) - 5;
	$("#aside").height(h);
	
	var w = $(window).width();
	if ($("#splitbar").size() == 0) {
	   w = w - 10;
	   $("#body").css({left:5});
	} else {
	   w = w - $("#splitbar").position().left - $("#splitbar").outerWidth(true) - 5;
	}
	$("#body, #tabpages").css({width: w, height: h});
	
	$(window).trigger($.SPA.EventType.PageResize);
},

init: function(options) {
	var op = $.extend({
			appid:"SPA",
			debug:false, 
			showContextMenu: true,
			maxOpenPages:15,
			onInit: $.noop
		}, options);
	this._debug = op.debug;
	this.appid = op.appid;
	
	$(".msg").each(function(){
	  $.SPA._msg[$(this).attr("title")] = $(this).text();
	});
	
	var ajaxbg = $("#background,#progressbar").hide();
	$(document).ajaxStart(function(){
		ajaxbg.show();
	}).ajaxStop(function(){
		ajaxbg.hide();
	});

	if ($.fn.menubar) {
		var defaultMenuSelected = function($a) {
			$.get($a.attr("href"), {}, function(html){
				$.SPA.wrap($(".sidebar-container").empty().append(html));
			});
		};
			
		$(".nav-menu").menubar({
			 onSelected: op.onMenuSelected || defaultMenuSelected
		});
	}

	if($.fn.sidebar) {
		$("#aside.sidebar").sidebar({minW:150, maxW:450, 
			onResized: function() {
				$.SPA.layout();
			}
		});
	}

	if($.fn.tabpages) {
		$(".tabpages").tabpages({
			showContextMenu: op.showContextMenu,
			contextMenu: {
				reloadTab: $.SPA.msg("reloadTab"),
				closeCurrentTab: $.SPA.msg("closeCurrentTab"),
				closeOtherTabs: $.SPA.msg("closeOtherTabs"),
				closeAllTabs: $.SPA.msg("closeAllTabs")
			},
			maxOpenPages: op.maxOpenPages,
			onExceedingMaxOpenPages: function() {
				$.SPA.alertMsg($.SPA.msg("exceedMaxOpenPages").format(op.maxOpenPages));
			}
		});
	}

	$.SPA.layout();
	$.SPA.wrap();

	$(window).resize(function(){
		$.SPA.layout();
	});

	if ($.History) $.History.init("#body");

	if ($.isFunction(op.onInit)) op.onInit();
	
}

};
})(jQuery);