$(function(){
	if ($.History) $.History.init("#container");
});

function initPage(jParent){
	
	//validate form
	$("form.required-validate", jParent).each(function(){
		$(this).validate({focusInvalid:false, focusCleanup:true, errorElement:"span", ignore:".ignore"});
	});
	 
	//auto bind tabs
	$(".j-tab-auto-hover", jParent).tabs({eventType:"hover"});
	$(".j-tab-auto-click", jParent).tabs({eventType:"click"});
	
	//style css
	$('table.list tbody tr:odd', jParent).addClass('trbg');
	$('table.list tbody tr', jParent).hover(function(){
		$(this).addClass('hover');
	}, function(){
		$(this).removeClass('hover');
	});
	
	$('fieldset :not(.wrap) label', jParent).filter(":not(label.nowrap)").each(function(){
		var formField = $('input[type="text"], input[type="password"], textarea', $(this).parent());
		if (formField.size() == 1){
			if (!formField.attr("id")) formField.attr("id", formField.attr("name") + "_" +Math.round(Math.random()*10000));
			if (!$(this).attr("for")) $(this).attr("for", formField.attr("id"));
		}
	});
	$(".formContent>div", jParent).addClass("formUnit");

	$("div.button", jParent).hover(function(){
		$(this).addClass("buttonHover");
	},function(){
		$(this).removeClass("buttonHover");
	});
	$("div.buttonActive", jParent).hover(function(){
		$(this).addClass("buttonActiveHover");
	},function(){
		$(this).removeClass("buttonActiveHover");
	});
	
	$('input[type="text"], input[type="password"], textarea', jParent).focus(function(){
		$(this).addClass('focus');
	}).blur(function(){
		$(this).removeClass('focus');
	});

	$('input[type="text"].j-date',jParent).each(function(){
		var op = {showOn: 'button', buttonImage: '/styles/www/themes/default/images/calendar.gif', buttonImageOnly: true, dateFormat:'dd/mm/yy', changeYear:true, changeMonth: true, yearRange: '-10:+10'};
		if ($(this).attr("yearRange")) op.yearRange = $(this).attr("yearRange");
		$(this).datepicker(op);
	});
	
	$("select.required, input.required, textarea.required", jParent).each(function(){
		var jLabel = $(this).parent().find(">label");
		jLabel.append('<span class="required">*</span>');
	});
	
	// ajax link
	$("a[target=ajax]", jParent).each(function(){
		$(this).click(function(){
			var rel = $(this).attr("rel") || "container";
			if (rel == 'container')
				$("#"+rel).loadHistory($(this).attr("href"));
			else $("#"+rel).loadUrl($(this).attr("href"));
			return false;
		});
	});
	//dialog
	$("a[target=dialog]", jParent).each(function(){
		$(this).click(function(){
			var title = $(this).attr("title") || $(this).text();
			var params = {url:$(this).attr("href"),title:title};
			var w = $(this).attr("width");
			var h = $(this).attr("height");
			if (w) params.width = w;
			if (h) params.height = h;
			$.openDialog('#dialogBox',params);
			return false;
		});
	});
	
	Accordion.init($("#addendumBox"), {});
	$("#assessmentsBox").foldBox();
	$("ul.accordion").accordion();
	
	$("table.copyDim", jParent).copyDim();
}
(function($){
	$.fn.extend({
		copyDim: function(options){
			var op = $.extend({$cptr:"tbody>.j-cptr", $cpFrom:"tfoot [name=cpFrom]", $cpTo:"tfoot [name=cpTo]", $cpButton:"tfoot .button"}, options);
			
			return this.each(function(){
				var $this = $(this);
				var $cptr = $this.find(op.$cptr);
				var $cpFrom = $this.find(op.$cpFrom);
				var $cpTo = $this.find(op.$cpTo);
				var icpstart = $this.attr("cpstart") ? parseInt($this.attr("cpstart")) : 0;

				$cptr.each(function(i){
					$(this).click(function(){
						if (i < $cptr.size()-1){
							$cpFrom.val(i+icpstart);
							$cpTo.val(i+1+icpstart);
						}
					});
				});
				
				$this.find(op.$cpButton).click(function(){
					try{
						var iFrom = parseInt($cpFrom.val()-icpstart);
						var iTo = parseInt($cpTo.val()-icpstart);
						
						if (iFrom >= 0 && iFrom < $cptr.size() && iTo >=0 && iTo < $cptr.size() && iFrom != iTo){
							$cptr.eq(iFrom).find("[type=text]").each(function(index){
								var $toInput = $cptr.eq(iTo).find("[type=text]").eq(index);
								$toInput.val($(this).val());
							});
						}
					} catch (e){}
				});
			});
		}
	});
})(jQuery);

var Accordion = {
	_box: null,
	_op: {stLi:">li",stHeader:".accordionHeader",stContent:".accordionContent"},
	_menus: null,
	init: function(box, options){
		var $this = this;
		this._box = box;
		this._op = $.extend(this._op, options);
		this._menus = this._box.find(this._op.stLi);
		this._menus.find($this._op.stHeader).each(function(i){
			$(this).click(function(){
				$this.openPanel(i);
				return false;
			});
		});
	},
	_show: function(contentBox){
		var jHeader = $(contentBox).find(this._op.stHeader);
		if (jHeader.hasClass("collapsable")){
			this._hide();
		} else {
			$(contentBox).find(this._op.stContent).slideDown();
			jHeader.addClass("collapsable");
		}
	},
	_hide: function(contentBox){
		$(contentBox).find(this._op.stContent).slideUp();
		$(contentBox).find(this._op.stHeader).removeClass("collapsable");
	},
	openPanel: function(index){
		if (index < 0 || index > this._menus.size()) return;
		var $this = this;
		this._menus.each(function(i){
			if (index == i) {
				$this._show(this);
			} else {
				$this._hide(this);
			}
		});
	}
};

(function($){
	$.fn.extend({
		accordion: function(options) {
			var op = $.extend({stLi:">li",stHeader:".header",stContent:".content"},options);
			
			return this.each(function(){
				var $this = $(this);
				var $menus = $this.find(op.stLi);
				$menus.find(op.stHeader).click(function(){
					var $menu = $(this).parent();
					if ($menu.hasClass("selected")) {
						$menus.removeClass("selected");
					} else {
						$menus.removeClass("selected");
						$menu.addClass("selected");
					}
				});
			});
		}
	});

})(jQuery);

(function($){
	$.fn.extend({
		foldBox: function(options){
			var op = $.extend({listSt:">ul"}, options);
			return this.each(function(){
				var jList = $(this).find(op.listSt);
				if ($(this).find("iframe").size()<1){
					var iframeFrag = '<iframe src="about:blank" style="position:absolute;z-index:-1;top:19px;left:5px;display:none" frameborder="0"></iframe>';
					$(this).prepend(iframeFrag);
				}
				$(this).hover(function(){
						jList.show();
						$(this).find("iframe").show().height(jList.outerHeight(true)).width(jList.outerWidth(true));
					},function(){
						jList.hide();
						$(this).find("iframe").hide();
					});
			});
		}
	});
})(jQuery);

(function($){
	$.extend({
		openDialog: function(boxId, options){
			var op = $.extend({url: null, data:{}, title:"dialog", width:480, height:250, unit:"px"}, options);
			var jPopBox = $(boxId);
			var jContentBox = $(".j-content", jPopBox);
			
			var iWidth = op.width;
			var iHeight = op.height;
			if (op.unit == "%"){
				iWidth = screen.width * (op.width < 100 ? op.width : 50) / 100;
				iHeight = screen.height * (op.height < 100 ? op.height : 50) / 100;
			}
			$(jPopBox).width(iWidth+"px");
			jContentBox.height(iHeight+"px");
			
			$(".dialogHeader_c>h1", jPopBox).html(op.title);
			
			jPopBox.show().scrollCenter({scroll:false}).draggable({ handle: '.dialogHeader_c', containment: $("html")})
			$("#dialogBg").show();
			
			if (op.url) jContentBox.loadUrl(op.url,op.data,function(){
				jContentBox.find("[layoutH]").layoutH();
			});
			
			$(".close, .menuDone", jPopBox).click(function(){
				$.closeDialog(boxId)
			});

		},
		closeDialog: function(boxId){
			var jPopBox = $(boxId);
			jPopBox.hide();
			$("#dialogBg").hide();
			$(".j-content", jPopBox).html("");
		}
	});
})(jQuery);

function ajaxDoneEval(json) {
	try{
		return eval('(' + json + ')');
	} catch (e){
		return {};
	}
}
/**
 * Quidos jQuery plugins
 * 
 * @param {Object} $
 */  
(function($){
	$.fn.extend({

		loadUrl: function(url,data,callback){
			var aData = data || {};
			aData["timestamp"] = new Date().getTime();
//			this.load(url,aData,function(){
//				initPage(this);
//				if (jQuery.isFunction(callback)) callback();
//			});
			var $this = $(this);
			$.get(url, aData, function(v){
				var json = ajaxDoneEval(v);
				if (json.statusCode==301){
					alertMsg.error(Msg.get('session.timeout'), {okCall:function(){
						window.location = "/render.do?method=login";
					}});
				} else {
					$this.html(v).initPage($this);
					if (jQuery.isFunction(callback)) callback();
				}
			});
		},
		loadHistory: function(url){
			var $this = $(this);
			function loadUrl(url){
				$this.loadUrl(url);
			}
			loadUrl(url);
			if ($.History) {
				$.History.addHistory(url.replace("?","|"), loadUrl, url);
			}
		},
		initPage: function(jParent){
			initPage(jParent);
		},
		//options: url, width(>200), height(>200), unit(px|%)
		dialog: function(boxId, options){
			return this.each(function(){
				$(this).click(function(){
					$.openDialog(boxId, options);
				});
			});
		},
		// options: menuSelector, container
		navMenu: function (options){
			var op = $.extend({menuSelector:">ul > li", container:"#container", styleClass:"selected"}, options);
			
			if ($.History) $.History.init(op.container);
			
			function initMenus(menuBox){
				var jMenus = $(op.menuSelector, menuBox);
				if (!jMenus || jMenus.size() < 1) return;
				jMenus.eq(0).addClass(op.styleClass);
				jMenus.each(function(){
					initMenus(this);
                    var jMenu = $(this);                  
                    var switchMenu = function(url){
                        jMenus.removeClass(op.styleClass);
                        jMenu.addClass(op.styleClass);
                        $(op.container).loadUrl(url);
                    }                    
                    $(this).find("> a").click(function(){
						var url = this.href.replace(/^[a-zA-z]+:\/\/[^\/]*\//, '').replace(/#.*$/,'');
						if (!url || url.length < 1) return false;
						if ($.History) {
							$.History.addHistory(url, switchMenu, "/"+url);
						}
						switchMenu("/"+url);
						return false;
                    });
				});
			}
			return this.each(function(){
				initMenus(this);
			});
		},
		// options: eventType
		tabs: function (options){
			var aParam = $.extend({eventType:"click", stHead:"div.tabsHeaderContent > ul > li", stContent:"div.tabsContent > div"}, options);
			var iCurentIndex = 0;
			return this.each(function(){
				var jObj = $(this);
				var jTabs = jObj.find(aParam.stHead);
				var jGroups = jObj.find(aParam.stContent);
				var switchTab = function(iTabIndex){
					var jTab = jTabs.eq(iTabIndex);
					iCurentIndex = iTabIndex;
					jTabs.removeClass("selected");
					jTab.addClass("selected");
					jGroups.hide().each(function(iGroupIndex){
						if (iCurentIndex == iGroupIndex) $(this).show();
					});
					
				};
				jTabs.each(function(iTabIndex){
					if (aParam.eventType == "hover") $(this).hover(function(event){switchTab(iTabIndex)});
					else $(this).click(function(event){switchTab(iTabIndex)});
										
					$("a", this).each(function(){
						if ($(this).hasClass("j-url")){
							$(this).click(function(event){
								var jGroup = jGroups.eq(iTabIndex);
								if (this.href && !jGroup.html()) jGroup.loadUrl(this.href);
								if (aParam.eventType == "click") switchTab(iTabIndex);
								return false;
							});
						}
					});
				});

				if (jGroups.filter(":visible").size()>1) switchTab(iCurentIndex);
			});
		},
		layoutH: function(content){
			var jBox = content || $("#dialogBox .j-content");
			var iTabsContentH = jBox.height();
			return this.each(function(){
				var iLayoutH = $(this).attr("layoutH") || 0;
				try {
					iLayoutH = parseInt(iLayoutH);
				} catch (e) {
					iLayoutH = 0
				}
				$(this).height(iTabsContentH - iLayoutH > 50 ? iTabsContentH - iLayoutH : 50);
			});
		}
	});
})(jQuery);

