var CV={
  ajaxRequest:function(url, successHandler,ajaxFailureHandler){
		var failHandler;
		failHandler=ajaxFailureHandler!=undefined?ajaxFailureHandler:function(){Tapestry.error("Communication with the server failed.");};
		return new Ajax.Request(url, { onSuccess: successHandler, onFailure:failHandler});
	},
	notice:function(message,el){
		var old=$('742abd9a26894de2b24cb2fdae831738');
		if(old!=undefined)
			Element.remove(old);
		Insertion.Before($(el),"<h2 id='742abd9a26894de2b24cb2fdae831738' class='cvnotice' style='color:red'>"+message+"</h2>");
	},
	removeNotice:function(message,el){
		Element.remove($(el).select(".cvnotice")[0]);
	},
	show:function(el){
		return new Effect.Appear(el);
	},
	update:function(el){
		return new Effect.Highlight(el);
		//return new Effect.Fade(el);
	},
	slidedown : function (el){
    return new Effect.SlideDown(el);
	},
	slideup : function(el){
    return new Effect.SlideUp(el);
	},
	moveto:function(el){
		new Effect.ScrollTo(el,{duration:0.7});
	},
	prepareAjaxForm:function(el,successHandler,ajaxFailureHandler){
		var failHandler;
		failHandler=ajaxFailureHandler!=undefined?ajaxFailureHandler:function(){Tapestry.error("Communication with the server failed.");};
		el=$(el);
		if (el.tagName == "FORM"){
	        Tapestry.getFormEventManager(el).preventSubmission = true;
	        el.observe(Tapestry.FORM_PROCESS_SUBMIT_EVENT, function(){
        	
	        	if(!$("loading"))
	        	{
		        	var icon=new Element("img");
		        	icon.writeAttribute("src","/stuff/share/images/t/loading.gif");
		        	icon.writeAttribute("id","loading");
		        	el.appendChild(icon);
	        	}
	        	else $("loading").show();
	        		
	        	if(el.getAttribute("confirmation")!=undefined)
	        	{
	        		if(confirm(el.getAttribute("confirmation")))
	        		{
	        			el.request({onSuccess : successHandler, onFailure: failHandler});
	        		}
	        		else
	        		{
	        			$("loading").hide();
	        		}
	        	}
	        	else
	            el.request({onSuccess : successHandler, onFailure: failHandler});
	        });
	        return;
	    }
	},
	processScript:function(reply){
		if (reply.script != undefined){
			eval(reply.script);
		}
	},
	//when the main section changed,update the toolbar
	updateToolbar:function(url){ 
		CV.replaceSection(url,"cv_toolbar",function(){});
	},
	toggle:function(element,link,noeffect){
		 element = $(element);
		 if(!element.down()){
		 	return;
		 }
   		 if(Element.visible(element)){
   		 	if(noeffect==undefined){
   		 		new Effect.SlideUp(element,{duration:0.3});
   		 	}else{
   		 		element.hide();
   		 	}
   		 	if(link!=undefined){
   		 		Element.toggleClassName($(link),'minimize');
   		 		Element.toggleClassName($(link),'maxmize');
   		 	}
   		 }else{
   		 	if(noeffect==undefined){
   		 		new Effect.SlideDown(element,{duration:0.3});
   		 	}else{
   		 		element.show();
   		 	}
   		 	if(link!=undefined){
   		 		Element.toggleClassName($(link),'minimize');
   		 		Element.toggleClassName($(link),'maxmize');
   		 	}
   		 }
   		 //Element[Element.visible(element) ? 'hide' : 'show'](element);
   	 	 return element;
	},
	// update the whole section(el). url: the same as appendSection()
	//callback: the function called in successhandler
	updateSection:function(url,el,callback){ 
		var successHandler = function(transport){
			var reply = transport.responseJSON;
			$(el).update(reply.content);
			CV.update($(el));
			CV.processScript(reply);
			if(callback) callback.call();
		};
		
		var statusBar=new Element("div");
		statusBar.setStyle("margin:auto;padding:5px;text-align:center;vertical-align:middle;width:150px;");
		
    	if(!$("waiting"))
    	{
        	var icon=new Element("img");
        	icon.writeAttribute("src","/stuff/share/images/waiting.gif");
        	icon.setStyle("margin:auto;padding:5px");
        	icon.writeAttribute("id","waiting");
        	statusBar.update(icon);
    	}
    	else 
		{
			$("waiting").show();
			statusBar.update($("waiting"));
		}
    	
    	var message=new Element("div");
    	message.appendChild(document.createTextNode("Please wait for a moment..."));
    	
    	statusBar.appendChild(message);
    	$(el).update(statusBar);
		CV.ajaxRequest(url,successHandler);
	},
	replaceSection:function(url,el,callback){ 
		var successHandler = function(transport){
			var reply = transport.responseJSON;
			$(el).replace(reply.content);
			CV.update($(el));
			CV.processScript(reply);
			if(callback) callback.call();
		};
		CV.ajaxRequest(url,successHandler);
	},
	//append an component at the bottom of el (in el). url: where to find the component
	//callback: the function called in successhandler
	appendComponent:function(url,el,callback){ 
		var successHandler = function(transport){
			var reply = transport.responseJSON;
			Insertion.Bottom($(el),reply.content);
			CV.show($(el));
			CV.processScript(reply);
			if(callback) callback.call();
		};
		CV.ajaxRequest(url,successHandler);
	},
	//to store the new order of the main section order,
	//url : where to post the order info
	//containerId: Id of the element that contains the items
	//callback: the function called in successhandler
	updateSectionOrder:function(url,containerId,callback){
		var ser=Sortable.serialize(containerId,{});
		ser=(ser==''?'empty':ser);
		(new Ajax.Request(url,{
			onSuccess:function(transport,json){
				if(transport.responseText.indexOf("success/")>-1){
					if(callback!=undefined)
						callback.call();
				}else{
					Tapestry.error("update section position failed.")
				}
			},
			parameters:"ser="+encodeURIComponent(ser)+"&time="+(new Date().getTime())
		}));
	},
	//to init the section's dragdrop functions
	//url: where to store the order info,when the update event fired
	//containerId: Id of the element that contains the items
	initDragDrop:function(containerId,updateUrl){
		Sortable.create($(containerId),{handle:'handle',
			constraint:false,tag:'div',
			onUpdate:function(){
				CV.updateSectionOrder(updateUrl,containerId);
			}
		});
	},
	//confirmCallBack,has one argument: itemId,selected
	popup:function(el,confirmCallBack,cancelCallBack){
		$('popup_model').show();
		
	},
	cancelForm:function(containerId){
		$(containerId).update("");
	}
};
CV.Section={
	//option.url,option.container
	editItem:function(option){
		CV.updateSection(option.url,option.formzone,function(){
			CV.moveto(option.sectionform);
		})
	},
	//.. option.updateUrl,option.updateElement
	removeItem:function(option){
			if(confirm(option.message)){
 				CV.ajaxRequest(option.root+'/cd/cv/componentpool.education:delete/'+option.id,function(transport){
	 				if(transport.responseText.indexOf('success/')!=-1){
	 					CV.replaceSection(option.root+'/cd/cv/componentpool:getcomponent/'+option.section,'cvcontentlist_'+option.section,function(){
	 						CV.initDragDrop('cvcontentcontainer',option.root+'/cd/cv/edit:updateMainSectionOrder');
	 					});
	 				}else{
	 					alert('Error Occured!');
	 				}
	 			});
 			}
	},
	//.. option.updateUrl,option.updateElement
	changeItemsOrder:function(option){
		CV.ajaxRequest(option.url,function(transport,json){
			CV.updateSection(option.updateUrl,option.updateElement);
		});
	}
};

function onLoadEvent(fnc){
	if ( typeof window.addEventListener != "undefined" )
	{
		window.addEventListener("load", fnc, false);
	}
	else if ( typeof window.attachEvent != "undefined" ) 
	{
		window.attachEvent("onload", fnc);
	}
	else
	{
		if (window.onload != null)
		{
			var oldOnload = window.onload;
			window.onload = function ( e ) 
			{
				oldOnload( e );
				window[fnc]();
			};
		}
		else
		{
			window.onload = fnc;
		}
	}
}

var Bar=function(){
	this.resources=typeof(arguments[0].items)=='undefined'?[]:arguments[0].items;
	this.current_index=0;
	this.items=new Array();
	this.show=function(){
		var list=new Element("ul");
			list.setAttribute("id","imgList");
			list.setStyle("position: absolute; top: 0px; background: #ffffff;margin-left:-40px;-margin-left:0px;#margin-left:0px");
			
		var $this=this;
		for(var i=0;i<this.resources.length;i++)
		{
			var item=new Element("li");
				item.setAttribute("id","step"+i);
			if(this.current_index==i) item.writeAttribute("class","on");

			var bar=new BarItem({src:this.resources[i].src,onclick:this.resources[i].click,className:"",parent:$this,index:i,item:item,
				cmd:function(el){
					el.writeAttribute("class","on");
					$this.scrollTo(el);
				}
			});
			
			this.items.push(bar);
			
			item.appendChild(bar.getImageElement());
			list.appendChild(item);
		}
		
		$('process_bar').update(list);
		
/*		var ie=false,ie6=false,ie6_=false;
		
		if(window.navigator.appVersion.indexOf('MSIE')!=-1)
		{
			ie=true;
		}
		
		if(ie)
		{
			if(window.navigator.appVersion.indexOf('6.0')==-1)
			{
				ie6_=true;
				fixedPosition($('process_bar'),0,0);
			}
			else
			{
				ie6=true;
			}
		}
		else
		{
			fixedPosition($('process_bar'),0,0);
		}
*/		
		$('process_bar').show();
	};
	
	this.refresh=function(){
		for(var i=0;i<this.resources.length;i++)
		{
			$("step"+i).writeAttribute("class","");;
		}
	};
	
	this.scrollTo=function(el){
		var pos=el.cumulativeOffset();
		var availbleHeight=$('process_bar').scrollHeight-$('process_bar').offsetHeight;
		
		if(el.offsetTop > 234)
		$('process_bar').scrollTop+=el.offsetHeight;
		else
		$('process_bar').scrollTop-=el.offsetHeight;
	};
	
	this.click=function()
	{
		this.items[this.current_index].click();
	};

	this.next=function()
	{
		if(this.current_index<this.items.length-1)
		{
			this.current_index++;
		}
		else
		{
			this.current_index=0;
		}

		this.click();
	};
	
	this.close=function()
	{
		$('process_bar').hide();
	}
}

var BarItem=function(){
	this.src=arguments[0].src;
	this.className=arguments[0].className;
	this.parent=arguments[0].parent;
	this.cmd=arguments[0].cmd;
	this.item=arguments[0].item;
	this.index=arguments[0].index;
	this.onclick=arguments[0].onclick;
	
	this.click=function(){
		this.notify();
		this.cmd(this.item);
		this.onclick();
	};
	
	this.notify=function(){
		this.parent.current_index=this.index;
		this.parent.refresh();
	};
	
	this.getImageElement=function(){
		var $this=this;
		var table=new Element("table");
			table.setAttribute("cellspacing","0");
		var tbody=new Element("tbody");
		var tr=new Element("tr");
		var td=new Element("td");
		
		var element=new Element("img");
		element.setAttribute("src",this.src);
		element.observe("click",function(){
			$this.click();
		});
	
		td.appendChild(element);
		tr.appendChild(td);
		tbody.appendChild(tr);
		table.appendChild(tbody);

		return table;
	}
}

/*
作者：淡新举
功能：使元素fixed定位
*/
var fixedPosition = function(element ,top ,left){
	element.style.display = "block";
	
	var ie=false,ie6_=false;
	
	if(window.navigator.appVersion.indexOf('MSIE')!=-1)
	{
		ie=true;
	}
	
	if (ie)
	{
		element.style.position = "absolute";
		fixedPosition.setGlobal();
	}
	else
	{
		element.style.position = "fixed";
	}
	
	element.style.top = top +"px";
	element.style.left = left +"px";
};

/*添加css规则*/
fixedPosition.addCSSRule = function(key ,value){
   var css = document.styleSheets[document.styleSheets.length-1];
	css.cssRules ? 
		 (css.insertRule(key +"{"+ value +"}", css.cssRules.length)) :
		 (css.addRule(key ,value));

};

/*标志特定公共规则是否存在*/
fixedPosition.inited = false;

/*设置特定公共规则*/
fixedPosition.setGlobal = function(){
	if (! fixedPosition.inited)
	{
		document.body.style.height = "100%";
		document.body.style.overflow = "auto";
		fixedPosition.addCSSRule("*html" ,"overflow-x:auto;overflow-y:hidden;");
		fixedPosition.inited = true;
	}
};

var CSSController=function()
{
	function getStyle(selectorName) {
		var i=0;
		while (i<document.styleSheets.length) 
		{
			var rules;
			if (document.styleSheets[i].cssRules) {
				rules = document.styleSheets[i].cssRules;
			} else {
				rules = document.styleSheets[i].rules;
			}
			
			i++;
			
			var j=0;
			while (j<rules.length) {
				if (rules[j].selectorText == selectorName) {
					return rules[j].style;
				}
				
				j++;
			}
		}
		
		return false;
	}
}

var Cookies = {};
/**//**
 * 设置Cookies
 */
Cookies.set = function(name, value){
     var argv = arguments;
     var argc = arguments.length;
     var expires = (argc > 2) ? argv[2] : null;
     var path = (argc > 3) ? argv[3] : '/';
     var domain = (argc > 4) ? argv[4] : null;
     var secure = (argc > 5) ? argv[5] : false;
     document.cookie = name + "=" + escape (value) +
       ((expires == null) ? "" : ("; expires=" + expires)) +
       ((path == null) ? "" : ("; path=" + path)) +
       ((domain == null) ? "" : ("; domain=" + domain)) +
       ((secure == true) ? "; secure" : "");
};
/**//**
 * 读取Cookies
 */
Cookies.get = function(name){
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    var j = 0;
    while(i < clen){
        j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return Cookies.getCookieVal(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if(i == 0)
            break;
    }
    return null;
};
/**//**
 * 清除Cookies
 */
Cookies.clear = function(name) {
  if(Cookies.get(name)){
    var expdate = new Date(); 
    expdate.setTime(expdate.getTime() - (86400 * 1000 * 1)); 
    Cookies.set(name, "", expdate); 
  }
};

Cookies.getCookieVal = function(offset){
   var endstr = document.cookie.indexOf(";", offset);
   if(endstr == -1){
       endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
};