/**
===========================================================
    /script/core.js 
    Author:    zhuweiwei
    Email:    wzhu.email@gmail.com
    First    2008-12-13
    Modify    
    Last    

    Copyright © 2006-2008 
    http://www.cncmm.com 
    China. All Rights Reserved. 

===========================================================
*/
/*<![CDATA[*/
var CFG = null;
CFG = new Object();
CFG.wwwroot = "http://www.cncmm.com/";
CFG.author  = "wzhu";

CFG.url = top.location.href.toString();
if( CFG.url.indexOf("cncmm.com") == -1 ){
    /*top.location.href = CFG.wwwroot;*/
}else{
    var ar = CFG.url.split("/");
    CFG.domain = ar[2];
    CFG.coreurl = "http://" + CFG.domain + "/core/";
}

function $(id) {
    return document.getElementById(id);
};

function trim( str ){
    return str.replace( /^\s*|\s*$/g, "" );
};

String.prototype.trim = function() {
    return this.replace(/^\s*|\s*$/g, "");
};

function getTimeStamp(){
    return new Date().getTime();
};


function clearLinkBox(){
    /* Must run at the page onloaded */
    var objAs = document.getElementsByTagName("A");
    for( var i=0; i<objAs.length; i++ ){
        objAs[i].onfocus = function(){ this.blur() };
    }
};

function changeLang(lang){
    var oc = new COOKIE;
    oc.delCookie('lang');
    oc.setCookie('lang',lang);
    document.location.reload(true);
}

function fadeColor(id,red,green,blue){
    red = ( red >= 255 ) ? ( 255 ) : ( red + 3 );
    green = ( green >= 255 ) ? ( 255 ) : ( green + 3 );
    blue = ( blue >= 255 ) ? ( 255 ) : ( blue + 3 );

    $(id).style.backgroundColor = "RGB(" + red + ", " + green + ", " + blue + ")";

    var strfun =  "fadeColor(\""+ id + "\"," + red + "," + green + "," + blue + ");";
    if( red != 255 || green != 255 || blue != 255 ){
        window.setTimeout( strfun, 50 );
    }else{
        return ;
    }
};

function isin_csvString(csvString, value){
    if( csvString != "" ){
        var arr = csvString.toString().split(',');
        var l = arr.length;
        for(var i=0; i<l; i++){
            if(arr[i] == value){
                return true;
            }
        }
    }
    return false;
};

function getValueByTagName( xmldoc, tagName ){
    try{
        var items = xmldoc.getElementsByTagName( tagName );
        return (items.item(0).firstChild.data);
    } catch( E ){
        alert( E.number+":"+E.description );
        return "";
    }

    /*
    items.item(0).firstChild.data;
    items.item(0).firstChild.text;
    items.item(0).firstChild.nodeValue;
    items.item(0).childNodes.item(0).nodeValue;
    items[0].firstChild.nodeValue;
    */
};

function showRemote(id,ip){
    var o = new XHR();
    o.doParseResponseText=function(txt){
        $(id).innerHTML = "您的IP地址是: [" +ip+ "] 来自: " + txt;
    };
    o.setRequestUrl(CFG.coreurl);
    o.addParameter( "et", "loadipaddr" );
    o.addParameter( "type", "text" );
    o.addParameter( "ip", ip);
    o.Execute();
};

function showRemoteAddr(id){
    var o = new XHR();
    o.doParseResponseText=function(ip){
        showRemote(id, trim(ip) );
    };
    o.setRequestUrl(CFG.coreurl);
    o.addParameter( "et", "getremoteip" );
    o.addParameter( "type", "text" );
    o.Execute();
};

function getSelectText(){
    if (window.getSelection){
        return window.getSelection();
    }else if (document.getSelection){
        return document.getSelection();
    }else if (document.selection){
        return document.selection.createRange().text;
    }
    return null;
};

function addParameterToUrl(url,parameter,value){
    if(url.toString().indexOf("?") == -1){
        return url+"?"+parameter+"="+encodeURIComponent(value);
    }else{
        return url+"&"+parameter+"="+encodeURIComponent(value);
    }
};

function loadJSFile(path, reload){ 
    var scripts = document.getElementsByTagName("script"); 
    if (reload) {
        for (var i=0;i<scripts.length;i++){
            if (scripts[i].getAttribute("src").toLowerCase() == path.toLowerCase())
                return; 
        }
    }
    var sobj = document.createElement('script'); 
    sobj.setAttribute( "type", "text/javascript" );
    sobj.setAttribute( "src", path );
    var headobj = document.getElementsByTagName('head')[0]; 
    headobj.appendChild(sobj); 
};

function loadCSSFile(path, reload){ 
    var csses = document.getElementsByTagName("link"); 
    if (reload) {
        for (var i=0;i<csses.length;i++){
            if (csses[i].getAttribute("rel").toLowerCase() == "stylesheet" &&
                csses[i].getAttribute("href").toLowerCase() == path.toLowerCase() )
                return; 
        }
    }
    var sobj = document.createElement('link'); 
    sobj.setAttribute( "type", "text/css" );
    sobj.setAttribute( "rel", "stylesheet" );
    sobj.setAttribute( "href", path );
    var headobj = document.getElementsByTagName('head')[0]; 
    headobj.appendChild(sobj); 
};

function DHTML()
{
    /* this._m_id = null; */
    this._m_Version    = "2007/08/10";
    
    this.getObjectById = function( id ){
        try{
            return $( id );
        }catch(e){
            return null;
        }
    };

    this.getValueById = function ( id ){
        try{
            return $( id ).value;
        }catch(e){
            return null;
        }
    };

    this.setValueById = function( id, value ) {
        $( id ).value = value;
    };

    this.getTextById = function( id ){
        if ( navigator.appName.indexOf("Internet Explorer") != -1 ) {
            return $( id ).innerText;
        } else {
            return $( id ).textContent;        
        }
    };

    this.setTextById = function( id, text ) {
        if ( navigator.appName.indexOf("Internet Explorer") != -1 ) {
            $( id ).innerText = text;
        } else {
            $( id ).textContent = text;        
        }    
    };

    this.getHtmlById = function( id ) {
        try{
            return $( id ).innerHTML;
        }catch(e){
            return null;
        }
    };

    this.setHtmlById = function( id, html ) {
        $( id ).innerHTML = html;
    };

    this.setAttributeById = function( id, attr, value ){
        $( id ).setAttribute( attr, value );
    };
    
    this.getAttributeById = function( id, attr ){
        try{
            return $( id ).getAttribute( attr );
        }catch(e){
            return null;
        }
    };
    
    this.hiddenById = function( id ) {
        $( id ).style.display = "none";
    };
    
    this.displayById = function( id ) {
        $( id ).style.display = "block";
    };
    
    this.getFormDataByID = function( fm ){
        var element;
        var type;
        var formData = "";
        var myform = document.forms[ fm ];
    
        if( typeof form.name == "undefined" || myform.name== "" ) {
            myform = $( fm );
        }
    
        for ( var i = 0; i < myform.elements.length; i++ ) {
            element = myform.elements[i];
            type = element.type.toLowerCase();
            if ( type == "hidden" || type == "text" || type == "password" || type == "textarea" ){          
                formData += element.name + "=" + element.value + "&";
            }
            /*
                select-one
                select-multiple
            */
            else if ( type.indexOf("select") != -1 ) {
                for (var j = 0; j < element.options.length; j++ ) {
                    if (element.options[j].selected == true) {
                        formData +=  element.name + "=" + element.options[j].value + "&";
                    }
                }
            }else if ( type == "checkbox" ) {
                if(element.checked) {
                    formData += element.name + "=" + element.value + "&";
                }
            }else if ( type == "radio" ) {
                if (element.checked == true) {
                    formData += element.name + "=" + element.value + "&";
                }
            }
        }
        return( formData.substring(0, formData.length - 1) );
    };
};


function COOKIE()
{
    this._m_Path = "";
    this._m_Expires = "";
    this._m_Domain = "";/*CFG.domain;*/
    
    this.setPath = function(path) {    this._m_Path = path;    };
    this.setDomain = function(domain){ this._m_Domain = domain; };
    
    this.setExpire = function(time) {
        var time = parseInt(time, 10);
        var today = new Date();
        var expires = new Date();
        expires.setTime(today.getTime() + 1000 * time);
        this._m_Expires = expires;
    };
    
    /*
    Set-Cookie: ID=BC0CFA724B97C8EB9F869BC82CD49760; expires=Fri, 17-Aug-37 07:14:11 GMT; path=/; domain=.cncmm.com
    */
    this.setCookie = function(name, value) {
        
        var cookieString = name + "=" + encodeURIComponent(value);

        if(this._m_Path != ""){
            cookieString += "; path=" +  this._m_Path;
        }
        if(this._m_Domain != ""){
            cookieString += "; domain=" + this._m_Domain;
        }
        if(this._m_Expires != ""){
            cookieString += "; expires=" + this._m_Expires.toGMTString();
        }

        document.cookie = cookieString;
    };
/*
    this.addCookie = function(name, value) {
        
        var cookieString = name + "=" + encodeURIComponent(value);

        if(this._m_Path != ""){
            cookieString += "; path=" +  this._m_Path;
        }
        if(this._m_Domain != ""){
            cookieString += "; domain=" + this._m_Domain;
        }
        if(this._m_Expires != ""){
            cookieString += "; expires=" + this._m_Expires.toGMTString();
        }

        document.cookie += cookieString;
    };
*/    
    this.delCookie = function(name){
        if ( this.getCookie( name ) ){
            var cookieString =  name + "=";
            if(this._m_Path != ""){
                cookieString += "; path=" +  this._m_Path;
            }
            if(this._m_Domain != ""){
                cookieString += "; domain=" + this._m_Domain;
            }
            cookieString += "; expires=Thu, 01-Jan-1970 00:00:01 GMT";

            document.cookie = cookieString;
        }
        
    };    
        
    this.getCookie = function(name) {
        /*
        construct RE to search for target name/value pair
        var re=new RegExp(name+"=[^;]+", "i"); 
        if (document.cookie.match(re)){
            return document.cookie.match(re)[0].split("=")[1];
        }
        return "";
        */

        var search = name + "=";
        if(document.cookie.length > 0) {
            var offset = document.cookie.indexOf(search);
            if(offset != -1) {
                offset += search.length;
                var end = document.cookie.indexOf(";", offset);
                if(end == -1){
                    end = document.cookie.length;
                }
                return decodeURIComponent(document.cookie.substring(offset, end));
            }
        }
        return "";
    };
};



function List()
{
    this._m_OL = null;

    this.setObjectById = function(id){
        this._m_OL = $(id);
    };

    this.addOption = function( txt, val ){
        if( txt instanceof Array && 
            val instanceof Array && 
            txt.length == val.length )
        {            
            for( var i = 0; i < txt.length; i++){
                var o = document.createElement("option");
                var t = document.createTextNode(txt[i]);
                o.setAttribute("value", val[i]);
                o.appendChild(t);
                this._m_OL.appendChild(o);
            }
        }else if( txt.trim() != "" && val.trim() != ""){
            var o = document.createElement("option");
            var oc = document.createTextNode(txt);
            o.setAttribute("value", val);
            o.appendChild(oc);
            this._m_OL.appendChild(o);
        }
    };
    

    this.removeOption= function(){
        var l = this._m_OL.length;
        if(-1 == l){
            return;
        }
        for(var i=l-1; i >= 0 ; i--){
            var o = this._m_OL.options[i];
            if( o && o.selected == true){
                this._m_OL.removeChild(o);
            }
        }
    };

    this.removeAllOption= function(){
        while ( this._m_OL.hasChildNodes() ){
            this._m_OL.removeChild( this._m_OL.firstChild );
        }
    };

    this.changeOption= function(txt, val){
        var l = this._m_OL.length;
        if(-1 == l || txt.trim() == "" || val.trim() == ""){
            return;
        }
        for(var i=0; i < l; i++){
            var o = this._m_OL.options[ i ];
            if( o && o.selected == true ){
                o.setAttribute("value", val );
                o.firstChild.data = txt;
            }
        }
    };

    this.getOptionValue = function(){
        var l = this._m_OL.length;
        if(-1 == l){
            return false;
        }
        var val = new Array();
        for(var i=0; i < l; i++){
            var o = this._m_OL.options[ i ];
            if( o && o.selected == true){
                val.push(o.getAttribute("value"));
            }
        }
        return val;
    };

    this.getOptionText = function(){
        var l = this._m_OL.length;
        if(-1 == l){
            return false;
        }
        var txt = new Array();
        for(var i=0; i < l; i++){
            var o = this._m_OL.options[ i ];
            if( o && o.selected == true){
                txt.push(o.firstChild.data);
            }
        }
        return txt;
    };

    this.selectAll = function(){
        var l = this._m_OL.length;
        for(var i=0; i < l; i++){
            this._m_OL.options[i].selected = true;
        }
    };

    this.sort = function(){
        var l = this._m_OL.length;
        for (var i=0; i < l-1; i++){
            for( var j = i+1; j < l; j++ ){
                var oi = this._m_OL.options[ i ];
                var oj = this._m_OL.options[ j ];
                if( oi.firstChild.data.toString() > oj.firstChild.data.toString() ){
                    var tt = oi.firstChild.data;
                    var tv = oi.getAttribute("value");
                    oi.setAttribute( "value", oj.getAttribute("value") );
                    oi.firstChild.data = oj.firstChild.data;
                    oj.setAttribute( "value", tv );
                    oj.firstChild.data = tt;
                    /*
                    var o = oi;
                    oi = oj;
                    oj = o;
                    */
                }
            }
        }
    };        
};



function XHR()
{
    this._m_Version    = "2007/08/10";
    this._m_XmlHttp    = false;    /*  xmlHttpRequest Object  */
    this._m_IsXml      = false;    /*  responseXML Or responseText  */
    this._m_Method     = "GET";
    this._m_IsAsync    = true;
    this._m_IsCache    = true;
    this._m_Charset    = "UTF-8";
    this._m_Aborted    = false;
    this._m_Delay      = 10000;    /*    10s    */
    this._m_TimeOutID  = null;  
    this._m_MaxLength  = 2048;    /* GET QueryString MaxLength*/

    this._m_AlertLevel   = "E";    /*  Alert Switch  */
    this._m_QueryString  = "";
    this._m_RequestUrl   = "?";
    this._m_MimeValue    = "text/html";
    this._m_CopyRight    = "\n\nCopyright © 2006-2008 "+CFG.author+" "+CFG.wwwroot+". All Rights Reserved.";
    this._m_StatusText   = "未初始化";
    this._m_IsOk         = false;
/*    this._m_XmlValidate    = false;*/


    this.setAbort     = function(){ this._m_Aborted = true; };
    this.setSync      = function(){ this._m_IsAsync = false; };
    this.setAsync     = function(){ this._m_IsAsync = true; };
    this.setCacheOn   = function(){ this._m_IsCache = true; };
    this.setCacheOff  = function(){ this._m_IsCache = false; };
    this.setGetMethod = function(){ this._m_Method = "GET"; };
    this.setWarnOn    = function(){ this._m_AlertLevel = "W"; };
    this.setDebugOn   = function(){ this._m_AlertLevel = "D"; };
    this.setErrorOn   = function(){ this._m_AlertLevel = "E"; };
    this.toString     = function(){ return this._m_Version; };

    this.setTimeOut     = function(second){ this._m_Delay = 1000 * second };
    this.setCharset     = function(charset){ this._m_Charset = charset; };
    this.setRequestUrl  = function(url){ this._m_RequestUrl = url; };
    this.setQueryString = function(str){ this._m_QueryString = str; };

    this.setXmlMime = function(){
        this._m_IsXml = true;
        this._m_MimeValue = "text/xml";
    };

    this.setHtmlMime = function(){
        this._m_IsXml = false;
        this._m_MimeValue = "text/html";
    };

    this.setPostMethod = function(){
        this._m_Method = "POST";
        this._m_MimeValue = "application/x-www-form-urlencoded";
    };

    this.debugMSG = function(content){
        if(this._m_AlertLevel == "D"){
            alert(content + this._m_CopyRight);
        }
    };

    this.warnMSG = function(content){
        if(this._m_AlertLevel != "E"){
            alert(content + this._m_CopyRight);
        }
    };

    this.errorMSG = function(content){
        alert(content + this._m_CopyRight);
    };


    this.initX = function(){
        this.setXmlMime();
        this.setCharset("UTF-8");
        this._m_QueryString = "";
    };

    this.initT = function(){
        this.setHtmlMime();
        this.setCharset("UTF-8");
        this._m_QueryString = "";
    };

    this.createXmlHttpRequest = function(){
        /* Microsoft Internet Explorer */
        /*@cc_on @*/
        /*@if(@_jscript_version >= 5)
        if(window.ActiveXObject && !window.XMLHttpRequest){
            var MSXMLS = ["Msxml2.XMLHTTP.5.0",
                        "Msxml2.XMLHTTP.4.0",
                        "Msxml2.XMLHTTP.3.0",
                        "Msxml2.XMLHTTP",
                        "Microsoft.XMLHTTP"];
                        
            for(var i = 0; i < MSXMLS.length; i++){
                try {
                    this.debugMSG(MSXMLS[i]);
                    this._m_XmlHttp = new ActiveXObject(MSXMLS[i]);
                    return;
                }catch(E){
                    this.warnMSG(E.number+":"+E.description);
                    continue;
                }
            }
            return;
        }        
        @end @*/
        
        /* Mozilla FireFox */
        if(window.XMLHttpRequest){
            try{
                this._m_XmlHttp = new XMLHttpRequest();
                return;
            }catch(E){
                this.warnMSG(E.number+":"+E.description);
            }
        }
    };

    this.addTimeStamp = function(){
        this._m_QueryString += "timestamp=" + new Date().getTime()+"&";
    };

    this.addParameter = function(name, value){
        this._m_QueryString += name + "=" + encodeURIComponent(value)+"&";
        if( this._m_QueryString.length > this._m_MaxLength && 
            this._m_Method.toUpperCase()=="GET" )
        {
            this.setPostMethod();
            this.warnMSG( "Request Method Change: GET => POST" );
        }
    };

    this.doRequestUsingPost = function(){
        if(!this._m_IsCache){
            this.addTimeStamp();
        }
        this.debugMSG(this._m_RequestUrl);    
        this.debugMSG(this._m_QueryString);    

        this._m_XmlHttp.open(this._m_Method, this._m_RequestUrl, this._m_IsAsync);
        this.setCommonHeader();
        /*  Post /a.php HTTP/1.1  */
        this._m_XmlHttp.setRequestHeader("Method", "POST " + this._m_RequestUrl + " HTTP/1.1");
        this._m_XmlHttp.setRequestHeader("Content-Length",this._m_QueryString.length); 
        this._m_XmlHttp.send(this._m_QueryString);
    };

    this.doRequestUsingGet = function(){
        var queryString;
        if(!this._m_IsCache){
            this.addTimeStamp();
        }        
        if(this._m_RequestUrl.indexOf("?")> 0){
            queryString = this._m_RequestUrl + "&" + this._m_QueryString;
        } else {
            queryString = this._m_RequestUrl + "?" + this._m_QueryString;
        }

        this.debugMSG(queryString);
        this._m_XmlHttp.open(this._m_Method, queryString, this._m_IsAsync);
        this.setCommonHeader();
        this._m_XmlHttp.send(null);
    };

    this.setCommonHeader = function(){
        if(this._m_XmlHttp.overrideMimeType && this._m_IsXml){
            this._m_XmlHttp.overrideMimeType("text/xml");
        }
        
        this._m_XmlHttp.setRequestHeader("Content-Type", this._m_MimeValue + "; charset=" + this._m_Charset);
        
        if(!this._m_IsCache){
            this._m_XmlHttp.setRequestHeader("Cache-Control", "no-cache"); 
            this._m_XmlHttp.setRequestHeader("If-Modified-Since", "0");
        }    
    };

    this.getResponseHeader = function(key){
        if( this._m_IsOk ){
            return this._m_XmlHttp.getResponseHeader( key );
        }
        return null;
    };

    this.getAllResponseHeaders = function(){
        if( this._m_IsOk ){
            return this._m_XmlHttp.getAllResponseHeaders();
        }
        return null;
    };

    this.Execute = function(){
        var self = this;
        this.createXmlHttpRequest();
        if(this._m_XmlHttp){
            this.doAjaxRequestStart();
            this._m_TimeOutID = window.setTimeout(function(){ self._m_Aborted = true ; }, self._m_Delay);
            this._m_XmlHttp.onreadystatechange = function(){
				self.handleResponse();
            };

            (this._m_Method.toUpperCase()=="POST")? this.doRequestUsingPost(): this.doRequestUsingGet();

        } else {
            this.noXHR();
            return false;
        }
    };

	this.handleResponse=function(){
        this.debugMSG(this._m_XmlHttp.readyState);
        switch(this._m_XmlHttp.readyState){
        case 0:    
            /*self._m_StatusText = "未初始化";*/
        case 1:
            /*self._m_StatusText = "加载中";*/
        case 2:
            /*self._m_StatusText = "连接完成";*/
        case 3:
            /*self._m_StatusText = "交换数据";*/
            break;
        case 4 :
            this._m_StatusText = this._m_XmlHttp.statusText;
            this._m_IsOk = true;
            window.clearTimeout(this._m_TimeOutID);
            if(this._m_Aborted){
                this._m_XmlHttp.abort();
                this.warnMSG("Ajax Request Time Out");
                this.doAjaxRequestOver();
                return false;
            }
                    
			if(this._m_XmlHttp.status == 200){
                if(this._m_AlertLevel == "D"){
                    this.debugMSG(this._m_XmlHttp.getAllResponseHeaders()+ "\n" + this._m_XmlHttp.responseText);
                }
				try{
					if(this._m_IsXml){
						this.doParseResponseXml(this._m_XmlHttp.responseXML);
					}else{
						this.doParseResponseText(this._m_XmlHttp.responseText);
					}
				}catch(E){
					this.errorMSG(E.number+":"+E.description);
				}finally{
					this.doAjaxRequestOver();
					return false;
				}
			}else{
				this._m_StatusText = this._m_XmlHttp.statusText;
				this.debugMSG(this._m_StatusText);
				this.doAjaxRequestOver();
				return false;
			}
			break;/*case 4*/
		default:
			if(this._m_Aborted){
				window.clearTimeout(this._m_TimeOutID);
				this._m_XmlHttp.abort();
				this.debugMSG("Ajax Request Time Out");
				this.doAjaxRequestOver();
				return false;
			} 
			break;/*default*/
		}
	};

    this.noXHR = function(){
        /*  createXmlHttpRequest Error!  */
        this.debugMSG("Your Brower not support Ajax\n"+this._m_CopyRight);
    };

    this.doAjaxRequestStart = function(){
        this.debugMSG("Start Request");
        try{
            $("fade").innerHTML = "数据加载中，请稍候…";
            $("fade").style.display = "block";
        }catch(E){}
    };

    this.doAjaxRequestOver = function(){
        try{
            $("fade").style.display = "none";
            this.debugMSG("Over Response");
        }catch(E){}
    };

    /*  Must be reloaded  */
    this.doParseResponseXml = function(xmlDoc){
    };

    /*  Must be reloaded  */
    this.doParseResponseText = function(textDoc){
    };
};
/*]]>*/
