var PA = new Object();

PA.Config = {
	ATTRIBUTE_PREFIX: "cms",
	DEFAULT_TYPE: "content",
	
	TYPE_CONTENT: "content",
	TYPE_CHANNEL: "channel",
	TYPE_IMAGE: "image",
	TYPE_PARAM: "param",
	TYPE_FRIEND_LINK: "friend_link"
};

//PA.Document = "";
PA.ContextPath = "";
PA.ConsolePath = "";
PA.analysis = function(contextPath,consolePath,paDoc){
	if(!paDoc || !paDoc.doc){
		return;
	}
	//PA.Document = doc;
	PA.ContextPath = contextPath;
	PA.ConsolePath = consolePath;
	var body = paDoc.doc.getElementsByTagName("body")[0];
	if(!body){
		return;
	}
	var paFlag = PA.getAttribute(body,"paFlag");
	if(paFlag){
		return;
	}
	PA.addListener(body,"contextmenu",function(){return false;});

	var elements = paDoc.doc.all ? paDoc.doc.all : paDoc.doc.getElementsByTagName("body")[0].getElementsByTagName("*");
	var element;
	for(var i=0; i<elements.length; i++){
		try{
		element=elements[i];
		PA.prepare(element,paDoc);
		}catch(e){}
	}
	PA.setAttribute(body,"paFlag","true");
}



var PageAnalysis = function(doc,contextPath,consolePath){

	this.doc = doc;
	this.contextPath = contextPath;
	this.consolePath = consolePath;


}

PA.getAttribute = function(e,name,defaultValue){
	var result = e.getAttribute(PA.Config.ATTRIBUTE_PREFIX + ":" + name);
	if(!result && defaultValue != undefined){
		result = defaultValue;
	}
	return result;
}

PA.setAttribute = function(e,name,value){
	e.setAttribute(PA.Config.ATTRIBUTE_PREFIX + ":" + name,value);
}

PA.prepare = function(e,paDoc){
	e.target = "_self";
	var id=PA.getAttribute(e,"id");
	var type=PA.getAttribute(e,"type");
	if(!id && !type) return;

	var oldBGColor = e.style.backgroundColor;
	var oldBGImg = e.style.backgroundImage;
	var oldCursor = e.style.cursor;
	PA.addListener(e,"mouseover",function(){
		var menu = PA.getContextMenu(paDoc);
		menu.style.display="none";
		e.style.backgroundColor = "#ff0000";
		e.style.backgroundImage = "";
		e.style.cursor = "hand";
		e.title = "使用鼠标右键编辑";
		e.setAttribute("oldBGImg",oldBGImg);
		PA.stopEvent(PA.getEvent(paDoc.doc.parentWindow));
	});
	PA.addListener(e,"mouseout",function(){
		e.style.backgroundColor = oldBGColor;
		e.style.backgroundImage = oldBGImg;
		e.style.cursor = oldCursor;

	});
	PA.addListener(e,"contextmenu",function(){
		var menuConfig = PA.getMenuConfig(e,paDoc);
		PA.showMenu(e,menuConfig,paDoc);
		PA.stopEvent(PA.getEvent(paDoc.doc.parentWindow));
	});
	/*
	PA.addListener(e,"click",function(){
		alert("clicked");
	});
	*/
}

PA.getMenuConfig = function(e,paDoc){
	var type = PA.getAttribute(e,"type",PA.Config.DEFAULT_TYPE);
	type = type.toLowerCase();
	if(type == PA.Config.TYPE_CONTENT || type == PA.Config.TYPE_CHANNEL){
		var id = PA.getAttribute(e,"id","");
		var params=id.split(",");
		if(type == PA.Config.TYPE_CHANNEL || !params.length || params.length<=1 || params[1] == "0"){
			return {
				items:[
				{name:"编辑栏目名称和属性",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontChannel.jsp?id="+id,dialogProps:"dialogHeight:450px;dialogWidth:600px;"},
				{name:"本栏目下新增内容",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontContent.jsp?id="+id+"&new=true",dialogProps:"dialogHeight:600px;dialogWidth:800px;"},
				{name:"本栏目不显示(离线)",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontChannel.jsp?off=true&id="+id,dialogProps:"dialogHeight:1px;dialogWidth:1px;dialogLeft:2000px;dialogTop:2000px;",confirm:"确认需要离线此栏目吗？"}
				//{name:"新增栏目",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontChannel.jsp?id="+id+"&new=true",dialogProps:"dialogHeight:400px;dialogWidth:600px;"}
				]
			};
		}
		var paramStr = "EC_CMS_DETAIL.cn_sid="+params[0]+"&sid="+params[1];
		//&EC_CMS_DETAIL.cn_sid=376&vid=1770&sid=1770
		return {
			items:[
			{name:"编辑内容名称和属性",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontContent.jsp?_menu=_ec_content_mng&id="+id,dialogProps:"dialogHeight:600px;dialogWidth:800px;"},
			{name:"本内容不显示(离线)",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontContent.jsp?off=true&id="+id,dialogProps:"dialogHeight:1px;dialogWidth:1px;dialogLeft:2000px;dialogTop:2000px;",confirm:"确认需要离线此内容吗？"}]
		};
	}else if(type == PA.Config.TYPE_IMAGE){
		var imgSrc = PA.getImageSrc(e);
		return {
			items:[
			{name:"替换图片",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/frontTemplateImage.jsp?_menu=_ec_template_resource&image="+imgSrc,dialogProps:"dialogHeight:550px;dialogWidth:800px;",openType:"modelessDialog"},
			{name:"下载图片",url:PA.ContextPath+PA.ConsolePath+"/c?_menu=_ec_template_resource&_view=ECV_FRONT_RESOURCE_UPLOAD&_action=EC_FRONT_RESOURCE_UPLOAD.downloadTplRes&epod.token=NULL&image="+imgSrc,dialogProps:"dialogHeight:600px;dialogWidth:800px;",openType:"self"}]
		};
	}else if(type = PA.Config.TYPE_PARAM){
		return {
			items:[
			{name:"参数设置",url:PA.ContextPath+PA.ConsolePath+"/ecms/page/sysParam.jsp?_menu=_ec_system_param",dialogProps:"dialogHeight:500px;dialogWidth:800px;",openType:"modelessDialog"}
			]
		};
	}else if(type == PA.Config.TYPE_FRIEND_LINK){
		return {
			items:[
			{name:"javaeye",url:"http://www.javaeye.com",dialogProps:"dialogHeight:400px;dialogWidth:600px;"},
			{name:"csdn",url:"http://www.csdn.net",dialogProps:"dialogHeight:400px;dialogWidth:600px;"}]
		};
	}
	return type;
}

PA.getContextMenu = function(paDoc){
	var menuStyle = paDoc.doc.getElementById("cmsPAMenuStyle");
	if(!menuStyle){
		menuStyle = paDoc.doc.createElement("link");
		menuStyle.id = "cmsPAMenuStyle";
		menuStyle.href = PA.ContextPath + PA.ConsolePath + "/ecms/page/lib/pageAnalysis.css";
		menuStyle.rel = "Stylesheet";
		menuStyle.type = "text/css";
		paDoc.doc.getElementsByTagName("head")[0].appendChild(menuStyle);

	}

	var analysisJS = paDoc.doc.getElementById("cmsPAJS");
	if(!analysisJS){	
		analysisJS = paDoc.doc.createElement("script");
		analysisJS.id = "cmsPAJS";
		analysisJS.src = PA.ContextPath + PA.ConsolePath + "/ecms/page/lib/pageAction.js";
		analysisJS.language = "javascript";
		paDoc.doc.getElementsByTagName("head")[0].appendChild(analysisJS);
	}

	var menu = paDoc.doc.getElementById("cmsPAMenu");
	if(!menu){
		menu = paDoc.doc.createElement("div");
		menu.id = "cmsPAMenu";
		paDoc.doc.getElementsByTagName("body")[0].appendChild(menu);
	}

	return menu;
}

PA.showMenu = function(e,menuConfig,paDoc){
	if(!menuConfig) return;
	var menu = PA.getContextMenu(paDoc);
	var menuBody="";
	var item;
	var itemBody;
	for(var i=0; i<menuConfig.items.length; i++){
		item = menuConfig.items[i]; 
		//alert("PA.menuAction('"+item.url+"','"+item.dialogProps+"','"+item.confirm+"')");
		//itemBody = "<li onclick=\"window.showModalDialog('"+item.url+"',window,'"+item.dialogProps+"')\">" + item.name + "</li>";
		itemBody = "<tr><th><img src=\""+PA.ContextPath + PA.ConsolePath + "/ecms/page/images/cion0"+(i+1)+".gif\" width=\"36\" height=\"32\" /></th>"
				//+"<td onmouseover=\"this.className='current';\" onmouseout=\"this.className='';\" onclick=\"window.showModalDialog('"+item.url+"',window,'"+item.dialogProps+"')\">" 
				+"<td onmouseover=\"this.className='current';\" onmouseout=\"this.className='';\" onclick=\"paMenuAction('"+item.url+"','"+item.dialogProps+"','"+item.confirm+"','"+item.openType+"')\">" 
				+ item.name + "</td></tr>";
		menuBody +=itemBody;
	}
	//menuBody = '<ul>'+menuBody+'</ul>';
	menuBody = '<div><p><table width="100%" cellspacing="0" cellpadding="0">'+menuBody+'</table></p></div>';
	//alert(menuBody);
	menu.innerHTML = menuBody;
	menu.style.position = "absolute";
	PA.setPositionByMouse(menu,paDoc);
	menu.style.display = "";

	
	PA.addListener(paDoc.doc,"click",function(){
		menu.style.display = "none";
	});

	//paDoc.doc.parentWindow.currentEditElement = e;
	//currentEditElement = e;
	PA.setCurrentElement(e,paDoc.doc);
}

PA.setCurrentElement = function(e,doc){
	var curE = doc.getElementById("_cmsCurrentElement");

	if(!curE){	
		curE = doc.createElement("div");
		curE.id = "_cmsCurrentElement";
		curE.style.display="none";
		doc.getElementsByTagName("body")[0].appendChild(curE);
	}
	var eId = e.id;
	if(!eId){
		eId = "_cmsCurrent";
		e.id = eId;
	}
	curE.setAttribute("currentId", eId);
}

PA.getCurrentElement = function(doc){

	var curE = doc.getElementById("_cmsCurrentElement");

	if(!curE){	
		return null;
	}
	var curId = curE.getAttribute("currentId");
	return doc.getElementById(curId);
}

PA.showDialog = function(url,obj,props){
	obj.showModalDialog(getContextPath() + url,obj,props);
}
 
PA.setPositionByMouse = function(element,paDoc){
	var scrollLeft=paDoc.doc.documentElement.scrollLeft|| paDoc.doc.body.scrollLeft;
	var scrollTop=paDoc.doc.documentElement.scrollTop|| paDoc.doc.body.scrollTop;
	//是否w3c标准
	var screenW=paDoc.doc.compatMode== "CSS1Compat " ? paDoc.doc.documentElement.clientWidth : paDoc.doc.body.clientWidth;
	var screenH=paDoc.doc.compatMode== "CSS1Compat " ? paDoc.doc.documentElement.clientHeight : paDoc.doc.body.clientHeight;

	var event = PA.getEvent(paDoc.doc.parentWindow);
	var eventX = event.pageX || (event.clientX + scrollLeft - paDoc.doc.body.clientLeft);
	var eventY = event.pageY || (event.clientY + scrollTop - paDoc.doc.body.clientTop);

	var rightedge=scrollLeft-eventX;
	var bottomedge=scrollTop-eventY;
	//alert("eventX:" +eventX+",eventY:" +eventY+",screenX:" +scrollLeft+",screenY:"+scrollTop+",rightedge:"+rightedge+",bottomedge:"+bottomedge+",screenW:"+screenW+",screenH:"+screenH);
	if(eventX+element.offsetWidth > screenW+scrollLeft){
		element.style.left=eventX-element.offsetWidth + 'px';
	}else{
		element.style.left=eventX + 'px';
	}
	if(eventY+element.offsetHeight > screenH+scrollTop){
		element.style.top=screenH+scrollTop-element.offsetHeight + 'px';
	}else{
		element.style.top=eventY + 'px';
	}
}

PA.getImageSrc = function(element,paDoc){
	var src;
	if(element.tagName.toLowerCase()=='img' 
		|| (element.tagName.toLowerCase()=='input' && element.type.toLowerCase()=='image')){
		src = element.src;
	}else{
		src = PA.getCurrentStyle(element,'backgroundImage','background-image');
		if(src==null || src=="" || src=="none"){
			src = element.getAttribute("oldBGImg");
		}
		if(src!=null && src.toLowerCase().substr(0,4)=="url("){
			src = src.substring(4,src.indexOf(")"));
		}
	}
	var re = new RegExp("^(http[s]{0,1}://([^/]*))/.*","ig");
	re.exec(src);
	var locationPref=RegExp.$1;
	if(src.toLowerCase().indexOf("http")==0){
		if(src.indexOf(locationPref)!=-1){
			src=src.substring(locationPref.length+PA.ContextPath.length);
		}else{
			src="-1";
		}
	}else{
		var template = _templatePath.substring(PA.ContextPath.length);
		src = template  + src;
	}
	return src;
}

PA.setImageSrc = function(element,value,paDoc){
	if(element.tagName.toLowerCase()=='img' 
		|| (element.tagName.toLowerCase()=='input' && element.type.toLowerCase()=='image')){
		element.src=value;
	}else{
		eval("element.style.backgroundImage='url("+value+")'");
	}
	//alert(element.getAttribute("oldBGImg"));
	element.setAttribute("oldBGImg","url("+value+"?nocache="+Math.random()+")");
}

PA.getCurrentStyle = function(obj, cssproperty, csspropertyNS){ 
    if(obj.style[cssproperty]){  
        return obj.style[cssproperty];   
    }   
    if (obj.currentStyle) {// IE5+  
        return obj.currentStyle[cssproperty];   
    }else if (document.defaultView.getComputedStyle(obj, null)) {// FF/Mozilla   
        var currentStyle = document.defaultView.getComputedStyle(obj, null);   
        var value = currentStyle.getPropertyValue(csspropertyNS);   
        if(!value){//try this method   
            value = currentStyle[cssproperty];   
        }   
        return value;   
    }else if (window.getComputedStyle) {// NS6+  
        var currentStyle = window.getComputedStyle(obj, "");   
        return currentStyle.getPropertyValue(csspropertyNS);   
    }   
} 

PA.addListener = function(e,eventName,func){
	if(!e) return;
	if(e.attachEvent){
		e.attachEvent("on"+eventName,func);
	}else if(e.addEventListener){
		e.addEventListener(eventName,func,false);
	}else{
		e["on"+eventName]=func;
	}
}

PA.removeListener = function(e, evname, func) {
	if (e.detachEvent) { // IE
		e.detachEvent("on" + evname, func);
	} else if (e.removeEventListener) { // Gecko / W3C
		e.removeEventListener(evname, func, true);
	} else {
		e["on" + evname] = null;
	}
};

PA.getEvent = function(win){
	if(!win){
		win = window;
	}
	try{
		if(win.event){
			return win.event;
		}else{
			var o = arguments.callee.caller; 
			var e; 
			while(o != null){ 
				e = o.arguments[0];
				if(e && (e.constructor == Event || e.constructor == MouseEvent)) {return e;} 
					o = o.caller; 
				} 
			return null;
		}
	}catch(e){return null;}
}

PA.stopEvent = function(ev){
	if(document.all){
		ev.cancelBubble=true;
		ev.returnValue=false;
	}else{
		ev.preventDefault();
		ev.stopPropagation();
	}
	return false;
}

PA.getEventElement = function(){
	var event = PA.getEvent();
	if(event != null){
		var e = event.target || event.srcElement;
		return e;
	}
	return null;
}
