// JavaScript Document
function tendaInitialization(){
	//bindClickLink
	var links= $A(document.getElementsByTagName('a'));
	links.each(function(x){x.onclick=onClickLink.bindAsEventListener(x)});
	
	if($('dwindexattcat')){   //downlaods index no-refresh button
		var dwidxLinks= $A($('dwindexattcat').getElementsByTagName('li'));
		dwidxLinks.each(function(x){x.onmouseover=onMouseoverDwidxAttCat.bindAsEventListener(x)});
	}
	
	if($('pdinst')){
		var pdinstLis= $A($('pdinst').getElementsByTagName('a'));
		pdinstLis.each(function(x){x.onclick=onPdinstLiClick.bindAsEventListener(x)});
	}
	
	
	//CDATA transform for firefox,netscape etc.Gecko
	tendaData.cdataTransform();
	if($('showcatpic')){
		var catpic= $A($('showcatpic').getElementsByTagName('img'));
		catpic.each(function(x){x.onclick=onCatPicClick.bindAsEventListener(x)});
	}
	
	//Init the left menu sitebody's height   just for IE
	//reSizeLeft();
	if($('pdchildcats'))
		$('sitebody').style.background='#FFFFFF url(/'+tendaData.vDir+'templates/tendacms/skins/pdleftbg.gif) repeat-y left';
}


function submitForm(x){
 	while(x.nodeName.toLowerCase()!='form'){
 		x=x.parentNode;
	}
	arguments[1]? arguments[1](x):x.submit();
}

function trim(str) {
        return (str + '').replace(/\s+/g, ' ').replace(/(\s+)$/g, '').replace(/^\s+/g, '');
}

function checkSearchForm(x){
	var inputs = $A(x.getElementsByTagName('input'));
	var alertstr='';
	var arrStr = Array('请输入关键字..','请输入关键词..','');
	inputs.each(
		function(x){
			arrStr.each(function(y){alertstr+=y==(x.value=trim(x.value))?'请输入关键字..<br />':''});
		}
	);
	if (alertstr) 
		showMessage(alertstr);
	else
		x.submit();
}

function onCatPicClick(){
	onPdinstThumbClick(this.src.replace('thumb_',''));
}

function reSizeLeft(){
		//$('pdchildcats').style.height =($('sitebody').offsetHeight-6)+'px';
		//while($('sitebody').offsetHeight-$('pdchildcats').offsetHeight==6)
		//	$('pdchildcats').style.height=$('pdchildcats').offsetHeight-2;

}

function onPdinstLinkClick(){
	
	if (this.target)
		return true;
	var xmld,xsld;
	new Ajax.Request(this.href,{
		method:'get',
		onComplete: function (req){
			xmld = req.responseXML;
			new Ajax.Request('/'+tendaData.vDir+'xsl/downtemp.xsl',{
				method:'get',
				onComplete: function (req2){
					xsld= req2.responseXML;
					updatediv('pdcontent',xmld.selectSingleNode('document/content/contentbody'),xsld);
				}
			});
		}
	});	
	return false;
}

function onPdinstArtClick(){
	
	if (this.target)
		return true;
	var xmla,xsla;
	new Ajax.Request(this.href,{
		method:'get',
		onComplete: function (req){
			xmla = req.responseXML;
			new Ajax.Request('/'+tendaData.vDir+'xsl/articontentbody.xsl',{
				method:'get',
				onComplete: function (req2){
					xsla= req2.responseXML;
					var pdart=document.createElement('div');
					pdart.setAttribute('id','pdart');
					pdart.style.minHeight=(parseInt($('relatecontent').offsetHeight)+10)+'px';
					Try.these(
					function(){pdart.style.height='auto!important';$('pdcontent').style.overflowX='visible'},
					function(){var ua = navigator.userAgent;if(/msie 6/i.test(ua)) pdart.style.height=(parseInt($('relatecontent').offsetHeight)+10)+'px';});
					//add close button
					var closebutton=document.createElement('div');
					closebutton.setAttribute('id','closebutton');
					closebutton.setAttribute('onclick','closepdart()');
					closebutton.appendChild(document.createTextNode('×'));
					pdart.appendChild(closebutton);
					$('pdcontent').innerHTML='';
					$('pdcontent').appendChild(pdart);
					updatediv('pdart',xmla.selectSingleNode('//contentbody'),xsla,'add');
					if($('pagesplit')){
						var links = $A($('pagesplit').getElementsByTagName('a'));
						links.each(function(x){x.onclick=onPdinstArtClick.bindAsEventListener(x)});
					}
				}
			});
		}
	});	
	return false;
}

function closepdart(){
	var lis=$A($('pdinst').getElementsByTagName('li'));
	lis.each(function(x){if(x.className=='current') x.getElementsByTagName('a')[0].click()});
}
function onPdinstLiClick(){
	
	var pdinstLis= $A($('pdinst').getElementsByTagName('li'));
	pdinstLis.each(
		function(x){
			if(x.className=='current')
				x.className='';
		}
	);	
	var li=this.parentNode.parentNode;
	li.className='current';
	
	var	pdinstXml=new Array();
	var	pdinstXsl;
	var	currentOption;
	currentOption=li.id;
	new Ajax.Request(this.href,{
		method:'get',
		onComplete: function (req){
			pdinstXml[currentOption] = req.responseXML;
			new Ajax.Request('/'+tendaData.vDir+'xsl/pdop.xsl',{
				method:'get',
				onComplete: function (req2){
					pdinstXsl= req2.responseXML;
					updatediv('pdcontent',pdinstXml[currentOption],pdinstXsl);
					if($('pdopframe')){
						var links = $A($('pdopframe').getElementsByTagName('a'));
						links.each(function(x){x.onclick=onPdinstLinkClick.bindAsEventListener(x)});
					}
					else if($('pdlinklist')){
						var links = $A($('pdlinklist').getElementsByTagName('a'));
						links.each(function(x){x.onclick=onPdinstArtClick.bindAsEventListener(x)});
					}
				}
			});
		}
	});
	return false;
}

function onSelectClick(tendaselect){
	var ul = tendaselect.getElementsByTagName('ul')[0];
	ul.style.display=(ul.style.display=='')? 'none':'';
}

function onPdinstThumbClick(src){      //all images showed by a pop window will call this func.
	if(src==''||src=='/'+tendaData.vDir){
		showMessage('对不起，看起来好像没有这个图片<br />您可以留言提醒我们，我们将尽快修正.');
		return;
	}
	if(!document.images){
		showMessage('<div style="text-align:center"><img src='+src+' /></div>','图片展示');
		return;
	}
	var img = new Image(); 
	img.src = src;
	if (img.width>20){
		var width=img.width<440?440:img.width;
		showMessage('<div style="text-align:center"><img src='+src+' /></div>','图片展示','',width);
	}
	else{
		if(tendaData.tempstr!=src){
			showMessage('图片载入中，请稍候...<br />如果图片较大或者您的网速不佳，可能需要较长时间。');
			tendaData.tempstr=src;
		}
		setTimeout('onPdinstThumbClick(tendaData.tempstr)',300);
	}
}

function showMessage(msg){//showMessage(msg,title,button,width,height)
	var x,title,msgbody,button,closebt,width;
	 width=arguments[3]?arguments[3]+20:'460';
	closebt = '<div id="closebutton" onclick=\'$("messagebox").style.display="none"\'>×</div>';
	title='IP-COM 站点消息 - ';
	title+=arguments[1]?arguments[1]:'警告'; 
	(arguments[1]=='none')?title=closebt:title='<div id="msgtitle"><div>'+closebt+'<span>'+title+'</span></div></div>';
	switch (arguments[2]){
		case 2:button='<div id="buttonrow"><div id="button"><div>YES</div></div><div id="button"><div>NO</div></div></div>';break;
		case 0:button='';break;
		default :button='<div id="buttonrow"><div id="button"  onclick=\'$("messagebox").style.display="none"\'><div>OK</div></div></div>';
	}
	
	if($('messagebox')){
		x=$('messagebox');	
		x.innerHTML='';
		x.style.display='';
	}
	else{
		x=document.createElement('div');
		x.setAttribute('id','messagebox');
		$('footer').appendChild(x);
	}
	var left = document.documentElement.clientWidth/2-width/2;
	var top = document.documentElement.scrollTop+110;
	left=left<0? 0:left;
	x.style.left=left+'px';
	x.style.top=top+'px';
	msgbody=document.createElement('div');
	msgbody.setAttribute('id','msgbody');
	x.appendChild(msgbody);
	
	msgbody.style.width =width+'px';
//	msgbody.style.height = arguments[4]?arguments[4]:'180px';
	msgbody.innerHTML=title+'<div id="msgcontent">'+msg+'</div>'+button;
	if($('msgtitle'))
		new mbContent('messagebox','msgtitle');
	
}
//prototype bind a onclick
function updateBody(xml,xsl){
		alert('!!');
}
function onClickLink(){

	if(this.href && this.href!='')
		return true;		//this function is undering testing.
	else
		showMessage("Sorry,This link looks bad.");
	return false;
	//-----------Analyze the link whitch was clicked-------
	var href = this.href;
	var module = href.substr(0,20);
	if ( module.indexOf('/')>0)
		module = module.substr(0,module.indexOf('/'));
	else if (module.length<2)
		module='index';
	alert(module);
	//------------load xml and xsl -----------------------
	new Ajax.Request(href,{
			method:'get',
			onSuccess: function (req){
				xml = req.responseXML;
				xslpath ='/'+tendaData.vDir+'xsl/'+module+'.xsl';
				alert(xslpath);
				new Ajax.Request(xslpath,{
					method:'get',
					onSuccess: function (req){
						xsl = req.responseXML;
						updateBody(xml,xsl);
					}
				});
			}
		});
	return false;
}

function headsechchk(x){
	alert('');
	return false;	
}

function onMouseoverDwidxAttCat(){    //downloads index page no-refresh button
	var dwidxLi= $A($('dwindexattcat').getElementsByTagName('li'));
	dwidxLi.each(
		function(x){
			if(x.className=='current')
				x.className='';
		}
	);	
	this.className='current';
	
	/*var attLink =this.getElementsByTagName('a')[0].href;
	attLink = attLink.substring(attLink.indexOf('catid='),attLink.indexOf('&pdcatid'));
	dwidxLi= $A($('dwbrothercat').getElementsByTagName('a'));*/
	//dwidxLi.each(function(x){x.href=x.href.replace(/catid=[0-9]*/,attLink)});	
}

function checkKeywords(x){
	return x!=''&&x!='Please input the keyword...';
}

function dwsubmit(){
	if(!checkKeywords($('dwkeywords').value)){
		alert('Please input the keyword...');
		return;
	}
	$('dwsearchform').submit();	
}

function tendaWebData(){
	this.vDir = ''; 				//virtualDirectory
	this.needTransform = new Array();
	this.nTCount =0;
	this.temp=0;
	this.tempstr='';
	this.cdataTransform = function(){
		//return;
		var i ;
		for (i=0;i<this.nTCount;i++)
			if (x==this.needTransform[i])
				return;
		for (i=0;i<this.nTCount;i++){
			var x = document.getElementById(this.needTransform[i]);
			if(x.style.display=='none' && x.hasChildNodes()){
				if (x.firstChild.data)
				x.innerHTML = x.firstChild.data.replace(/&nbsp;/g,' ');
			}
			else{
				//x.innerHTML = temp.replace(/&nbsp;/g,' ');
			}
			x.style.display = '';
		}		
		this.needTransform = new Array();
		this.nTCount =0;
	}
  	this.addTransform = function (x){
		var i ;
		for (i=0;i<this.nTCount;i++)
			if (x==this.needTransform[i])
				return;
		this.needTransform[this.nTCount++] = x ;
	}
}

function tendaFocus (){
	this.interval_time=7; 		//图片停顿时间，单位为秒，为0则停止自动切换
	this.focus_width=266;
	this.focus_height=78;
	this.text_height=0;			//this.focus_height+this.text_height 相加之和最好是偶数,否则数字会出现模糊失真的问
	this.text_align="center" ;	//标题文字对齐方式(left、center、right)题
	this.pics="";
	this.links="";
	this.texts="";
	this.showed=false;
	this.show = function(){
		if (this.showed)
			return;
		var swf_height=this.focus_height+this.text_height; 
		document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+ this.focus_width +'" height="'+ swf_height +'">');
		document.write('<param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="/'+tendaData.vDir+'images/focus.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#F0F0F0">');
		document.write('<param name="menu" value="false"><param name=wmode value="opaque">');
		document.write('<param name="FlashVars" value="pics='+this.pics+'&links='+this.links+'&texts='+this.texts+'&borderwidth='+this.focus_width+'&borderheight='+this.focus_height+'&textheight='+this.text_height+'">');
		document.write('<embed src="/'+tendaData.vDir+'images/focus.swf" wmode="opaque" FlashVars="pics='+this.pics+'&links='+this.links+'&texts='+this.texts+'&borderwidth='+this.focus_width+'&borderheight='+this.focus_height+'&textheight='+this.text_height+'" menu="false" bgcolor="#F0F0F0" quality="high" width="'+this.focus_width +'" height="'+this.focus_height +'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
document.write('</object>');
		this.showed = true;
	}	
}

var tendaData = new tendaWebData();
function MM_jumpMenu(targ,selObj,restore){ 
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function updatediv(divname,xml,xsl){
	var action=arguments[3]?arguments[3]:'cover'; 
	if(typeof(XSLTProcessor)!='undefined'){
		var xsltProcessor = new XSLTProcessor();
		$(divname).style.display='none';
		tendaData.addTransform(divname);
		xsltProcessor.importStylesheet(xsl);
		if (action=='cover'){
			$(divname).innerHTML = '';
			$(divname).appendChild(xsltProcessor.transformToFragment(xml, document));
		}
		else
			$(divname).appendChild(xsltProcessor.transformToFragment(xml, document));
		tendaData.cdataTransform();
	}
	else if(Prototype.Browser.IE){
			if (action=='cover'){
				$(divname).innerHTML = xml.transformNode(xsl);
			}
			else
			$(divname).innerHTML = $(divname).innerHTML + xml.transformNode(xsl);
		$(divname).innerHTML.evalScripts();
	}
	else{
		$(divname).innerHTML = '施工中。。';	
	}
}
function preloadImages(){
  if(document.images){
    if(!document.imageArray) document.imageArray = new Array();
    var i,j = document.imageArray.length, args = preloadImages.arguments;
    for(i=0; i<args.length; i++){
      if (args[i].indexOf("#")!=0){
	  	document.imageArray[j] = new Image;
        document.imageArray[j++].src = args[i];
      }
    }
  }
}

/*-----------product function-------------*/
function showmenu(x){
	$(x).style.display = $(x).style.display =='none' ? '' : 'none';
}

//XmlDom support
function XmlDom() {
    //通过对象/属性检测法，判断是IE来是Mozilla
    if (window.ActiveXObject) {
        var arrSignatures = ["MSXML2.DOMDocument",
                             "Microsoft.XmlDom"];
                         
        for (var i=0; i < arrSignatures.length; i++) {
            try {
        
                var oXmlDom = new ActiveXObject(arrSignatures[i]);
            
                return oXmlDom;
        
            } catch (oError) {
                //ignore
            }
        }          

        throw new Error("MSXML is not installed on your system."); 
           
    //同上          
    } else if (document.implementation && document.implementation.createDocument) {
        
        var oXmlDom = document.implementation.createDocument("","",null);

        //创建Mozilla版本的parseError对象
        oXmlDom.parseError = {
            valueOf: function () { return this.errorCode; },
            toString: function () { return this.errorCode.toString() }
        };
        
        //初始化parseError对象
        oXmlDom.__initError__();
                
        
        oXmlDom.addEventListener("load", function () {
            this.__checkForErrors__();
            this.__changeReadyState__(4);
        }, false);

        return oXmlDom;        
        
    } else {
        throw new Error("Your browser doesn't support an XML DOM object.");
    }
}

//此处用到了该书中一个浏览器系统检测js文件，如果是Mozilla
if (document.implementation && document.implementation.createDocument) {

    Document.prototype.readyState = 0;
    Document.prototype.onreadystatechange = null;

    
    Document.prototype.__changeReadyState__ = function (iReadyState) {
        this.readyState = iReadyState;

        if (typeof this.onreadystatechange == "function") {
            this.onreadystatechange();
        }
    };
    //初始化parseError对象
    Document.prototype.__initError__ = function () {
        this.parseError.errorCode = 0;
        this.parseError.filepos = -1;
        this.parseError.line = -1;
        this.parseError.linepos = -1;
        this.parseError.reason = null;
        this.parseError.srcText = null;
        this.parseError.url = null;
    };
    
    Document.prototype.__checkForErrors__ = function () {

        if (this.documentElement.tagName == "parsererror") {

            var reError = />([\s\S]*?)Location:([\s\S]*?)Line Number (\d+), Column (\d+):<sourcetext>([\s\S]*?)(?:\-*\^)/;

            reError.test(this.xml);
            
            this.parseError.errorCode = -999999;
            this.parseError.reason = RegExp.$1;
            this.parseError.url = RegExp.$2;
            this.parseError.line = parseInt(RegExp.$3);
            this.parseError.linepos = parseInt(RegExp.$4);
            this.parseError.srcText = RegExp.$5;
        }
    };
    
     //定义Mozilla的loadXML方法   
    Document.prototype.loadXML = function (sXml) {
    
        this.__initError__();
    
        this.__changeReadyState__(1);
    
        var oParser = new DOMParser();
        var oXmlDom = oParser.parseFromString(sXml, "text/xml");
 
        while (this.firstChild) {
            this.removeChild(this.firstChild);
        }

        for (var i=0; i < oXmlDom.childNodes.length; i++) {
            var oNewNode = this.importNode(oXmlDom.childNodes[i], true);
            this.appendChild(oNewNode);
        }
        
        //载入后检查错误
        this.__checkForErrors__();
        
        //没有问题，设置readyState属性为4
        this.__changeReadyState__(4);

    };
    
    Document.prototype.__load__ = Document.prototype.load;

    Document.prototype.load = function (sURL) {
        this.__initError__();
        this.__changeReadyState__(1);
        this.__load__(sURL);
    };
    
    Node.prototype.__defineGetter__("xml", function () {
        var oSerializer = new XMLSerializer();
        return oSerializer.serializeToString(this, "text/xml");
    });
	
	
	if( document.implementation.hasFeature("XPath", "3.0") )
    {
       // prototying the XMLDocument
       XMLDocument.prototype.selectNodes = function(cXPathString, xNode)
       {
          if( !xNode ) { xNode = this; } 
          var oNSResolver = this.createNSResolver(this.documentElement)
          var aItems = this.evaluate(cXPathString, xNode, oNSResolver, 
                       XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
          var aResult = [];
          for( var i = 0; i < aItems.snapshotLength; i++)
          {
             aResult[i] =  aItems.snapshotItem(i);
          }
          return aResult;
       }

       // prototying the Element
       Element.prototype.selectNodes = function(cXPathString)
       {
          if(this.ownerDocument.selectNodes)
          {
             return this.ownerDocument.selectNodes(cXPathString, this);
          }
          else{throw "For XML Elements Only";}
       }
    }

    // check for XPath implementation
    if( document.implementation.hasFeature("XPath", "3.0") )
    {
       // prototying the XMLDocument
       XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)
       {
          if( !xNode ) { xNode = this; } 
          var xItems = this.selectNodes(cXPathString, xNode);
          if( xItems.length > 0 )
          {
             return xItems[0];
          }
          else
          {
             return null;
          }
       }
       
       // prototying the Element
       Element.prototype.selectSingleNode = function(cXPathString)
       {    
          if(this.ownerDocument.selectSingleNode)
          {
             return this.ownerDocument.selectSingleNode(cXPathString, this);
          }
          else{throw "For XML Elements Only";}
       }
    }
}

function createXml(str){
	var xdom = XmlDom();
	xdom.loadXML(str);
	return xdom;
}

var mbContent = Class.create({
	initialize: function(id,tlid){
		this.wd = $(id);
		this.Mousedown =0;
		this.wdStartPoint = {x:0,y:0};
		this.mouseStartPoint ={x:0,y:0};
		$(tlid).onmousedown = this.onMsDown.bindAsEventListener(this);
		document.documentElement.onmouseup = this.onMsUp.bindAsEventListener(this);
		document.documentElement.onmousemove = this.onMsMove.bindAsEventListener(this);
	},
	onMsDown: function(evt){
		this.Mousedown =1;
		this.mouseStartPoint = this.mouseCoords(evt);
		this.wdStartPoint = this.getDivPos();
	},
	getDivPos: function(){
		var posx= parseInt(this.wd.style.left.replace('px',''));
		var posy= parseInt(this.wd.style.top.replace('px',''));
		return {x:posx,y:posy};
	},
	onMsMove: function(evt){
		if(this.Mousedown){
			var p = this.mouseCoords(evt);
			this.wd.style.left = (this.wdStartPoint.x+p.x-this.mouseStartPoint.x)+'px';
			this.wd.style.top = (this.wdStartPoint.y+p.y-this.mouseStartPoint.y)+'px';
		}
	},
	onMsUp: function(evt){
		this.Mousedown =0;	
	},
	mouseCoords: function(ev){
		if(ev.pageX || ev.pageY){
		 return {x:ev.pageX, y:ev.pageY};
		}
		return {
		 x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
		 y:ev.clientY + document.body.scrollTop     - document.body.clientTop
		};
	}
});