var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);

   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}
function utf16to8(str) {
    var out, i, len, c;

    out = "";
    len = str.length;
    for(i = 0; i < len; i++) {
 c = str.charCodeAt(i);
 if ((c >= 0x0001) && (c <= 0x007F)) {
     out += str.charAt(i);
 } else if (c > 0x07FF) {
     out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
     out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
     out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
 } else {
     out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
     out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
 }
    }
    return out;
}

function utf8to16(str) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = str.length;
    i = 0;
    while(i < len) {
 c = str.charCodeAt(i++);
 switch(c >> 4)
 { 
   case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
     // 0xxxxxxx
     out += str.charAt(i-1);
     break;
   case 12: case 13:
     // 110x xxxx   10xx xxxx
     char2 = str.charCodeAt(i++);
     out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
     break;
   case 14:
     // 1110 xxxx  10xx xxxx  10xx xxxx
     char2 = str.charCodeAt(i++);
     char3 = str.charCodeAt(i++);
     out += String.fromCharCode(((c & 0x0F) << 12) |
        ((char2 & 0x3F) << 6) |
        ((char3 & 0x3F) << 0));
     break;
 }
    }

    return out;
}
/*判断字符串中是否包含中文*/
function iszw(str)
{
	var a = /[\u4e00-\u9fa5]/; 
	return a.test(str);
}

var Browser = {
    ie   :!!(window.attachEvent && !window.opera),  //ie
    gecko:!!(navigator.userAgent.indexOf('Gecko')>-1 && navigator.userAgent.indexOf('KHTML') == -1) //firefox系列的
}
function ignoreEmptyNode(node){
    if(node && node.nodeType == 1){
        for(var i=0,len =node.childNodes.length;i<len;i++){
            var _d = node.childNodes[i];
            if(typeof(_d) == 'undefined') break;
            if(_d.nodeType ==3 && _d.nodeValue.strip()==''){					                
                node.removeChild(_d);
            }
        }
    }
    return node;
}	
if(window.HTMLElement) {
    HTMLElement.prototype.__defineSetter__("outerHTML",function(sHTML){
        var r=this.ownerDocument.createRange();
        r.setStartBefore(this);
        var df=r.createContextualFragment(sHTML);
        this.parentNode.replaceChild(df,this);
        return sHTML;
        });

    HTMLElement.prototype.__defineGetter__("outerHTML",function(){
    var attr;
        var attrs=this.attributes;
        var str="<"+this.tagName.toLowerCase();
        for(var i=0;i<attrs.length;i++){
            attr=attrs[i];
            if(attr.specified)
                str+=" "+attr.name+'="'+attr.value+'"';
            }
        if(!this.canHaveChildren)
            return str+">";
        return str+">"+this.innerHTML+"</"+this.tagName.toLowerCase()+">";
        });        
    HTMLElement.prototype.__defineGetter__("canHaveChildren",function(){
        switch(this.tagName.toLowerCase()){
            case "area":
            case "base":
            case "basefont":
            case "col":
            case "frame":
            case "hr":
            case "img":
            case "br":
            case "input":
            case "isindex":
            case "link":
            case "meta":
            case "param":
            return false;
        }
        return true;
     });
}


if( document.implementation.hasFeature("XPath", "3.0") ){
    if(typeof XMLDocument =='undefined')  XMLDocument = {};
    XMLDocument.prototype.loadXML = function(xmlString){
        var childNodes = this.childNodes;
        for (var i = childNodes.length - 1; i >= 0; i--)
            this.removeChild(childNodes[i]);

        var dp = new DOMParser();
        var newDOM = dp.parseFromString(xmlString, "text/xml");
        var newElt = this.importNode(newDOM.documentElement, true);
        this.appendChild(newElt);
   };     
   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;
   }
   if(typeof Element == 'undefined')  Element = {};  
   Element.prototype.selectNodes = function(cXPathString){
      if(this.ownerDocument.selectNodes){
         return this.ownerDocument.selectNodes(cXPathString, this);
      }
      else{throw "For XML Elements Only";}
   }
   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;
      }
   }
   Element.prototype.selectSingleNode = function(cXPathString){    
      if(this.ownerDocument.selectSingleNode){
         return this.ownerDocument.selectSingleNode(cXPathString, this);
      }
      else{throw "For XML Elements Only";}
   }
}

if(typeof HTMLElement!="undefined" && !HTMLElement.prototype.insertAdjacentElement){
    HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode){
        switch (where){
            case 'beforeBegin':
                this.parentNode.insertBefore(parsedNode,this)
                break;
            case 'afterBegin':
                this.insertBefore(parsedNode,this.firstChild);
                break;
            case 'beforeEnd':
                this.appendChild(parsedNode);
                break;
            case 'afterEnd':
                if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
                else this.parentNode.appendChild(parsedNode);
                break;
        }
    }
    HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr){
        var r = this.ownerDocument.createRange();
        r.setStartBefore(this);
        var parsedHTML = r.createContextualFragment(htmlStr);
        this.insertAdjacentElement(where,parsedHTML)
    }
    HTMLElement.prototype.insertAdjacentText = function (where,txtStr){
        var parsedText = document.createTextNode(txtStr)
        this.insertAdjacentElement(where,parsedText)
    }
	HTMLElement.prototype.__defineGetter__("children", 
     function () { 
         var returnValue = new Object(); 
         var number = 0; 
         for (var i=0; i<this.childNodes.length; i++) { 
             if (this.childNodes[i].nodeType == 1) { 
                 returnValue[number] = this.childNodes[i]; 
                 number++; 
             } 
         } 
         returnValue.length = number; 
         return returnValue; 
     } 
	);
	HTMLElement.prototype.__defineGetter__( "innerText", 
	    function(){
	     var anyString = "";
	     var childS = this.childNodes;
	     for(var i=0; i<childS.length; i++) {
	      if(childS[i].nodeType==1)
	       anyString += childS[i].tagName=="BR" ? '\n' : childS[i].innerText;
	      else if(childS[i].nodeType==3)
	       anyString += childS[i].nodeValue;
	     }
	     return anyString;
	     } 
	);
	HTMLElement.prototype.__defineSetter__( "innerText", 
    	function(sText){ 
    		this.textContent=sText; 
    	}
	);
}
function ie(){ return  Browser.ie;}
function firefox(){ return Browser.gecko;}
function $get(id){ return (typeof id =='object' )?id:document.getElementById(id);}

/*获取传入的同一级上一个节点 节点为任意类型*/
function getPreviousSibling(node){
    var _n = node.previousSibling;
    if(!_n) return null;
    while(_n && _n.nodeType != node.nodeType){
        _n = _n.previousSibling;
    }
    return _n;
}

function getNextSibling(node){
    var _n = node.nextSibling;
    if(!_n) return null;
    while(_n && _n.nodeType != node.nodeType){
        _n = _n.nextSibling;
    }
    return _n;
}
function getElementsByAttribute(parentElement,attributeName,attributeValue){
        var children = ($get(parentElement) || document.body).getElementsByTagName('*'),el = [];
        var pattern  = '/(^|\s*)'+attributeValue+'(\s*|$)/ig',att,child;        
        for(var i=0,len = children.length;i< len;i++){
            child = children[i];
            att = child.getAttribute(attributeName);            
            if(att && att.match(eval(pattern))){
                el.push(child);
            }   
        }
        return el;         
}
function getElementsByClassName(parentElement,className) {
   var children = ($get(parentElement) || document.body).getElementsByTagName('*');      
   var elements = [], child, pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");      
  for (var i = 0, length = children.length; i < length; i++) {
    child = children[i];
    var elementClassName = child.className;
    if(elementClassName.length == 0) continue;
    if(elementClassName == className || elementClassName.match(pattern))  elements.push(child);
  }
  return elements;
};
function getElementsByMyName(element,value){
        return getElementsByAttribute(element,'name',value);
}

Object.extend = function(destination, source,strick) {
  for (var property in source) {
    if(strick &&(typeof destination[property] == 'undefined'))  continue;
    destination[property] = source[property];
  }
  return destination;
}
var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}
function transToXml(string){
    if(typeof string != 'string') return;    
    var parser = new DOMParser();
    return parser.parseFromString(string,'text/xml');
}
function transToString(xml){
    if(!xml) return;
    var ser = new XMLSerializer();
    return ser.serializeTostring(xml,'text/xml');
}
Array.prototype.any = function(iterator){        
    for(var i=0;i< this.length;i++){
        if(typeof iterator == 'function'){
            if(iterator(this[i],i)) return true;
        }
    }
    return false;
}
Object.extend(String.prototype,{
    strip:function(){
         return this.replace(/^\s+/, '').replace(/\s+$/, '');
    },
    include:function(pattern){
        return this.indexOf(pattern) > -1;
    },
    equal:function(_string){
        return !!this.match(eval('/\\b'+_string+'\\b/ig'));
    },
    stripHTML:function(){
        return this.replace(/<\/?[^>]+>/gi,'')
    }
});
function cumulativeOffset(element){
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
}
function getPostion(element){
    var c = cumulativeOffset(element);
    var p = [c[0],c[1],c[0]+element.offsetWidth , c[1] + element.offsetHeight];
    return p;
}

Builder = {
    node:function(el){        
        var element =  document.createElement(el||'div');
        if(!element) return null;
        if(arguments[1]){
            if(this._isStringOrNumber(arguments[1]) ||this._isElement(arguments[1])) this._children(element,arguments[1]);            
            else if(typeof(arguments[1]) == 'object') for(attr in arguments[1])  element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
        }
        if(arguments[2]){            
            this._children(element,arguments[2]);
        }
        return element;
    },
    _children:function(element,children){               
        if(children instanceof Array){
            for(var i = 0 ;i< children.length;i++){                    
                this._buildChildren(element,children[i]);        
            }
        } else this._buildChildren(element,children);      
        return element;
    },
    _isStringOrNumber:function(string){
        return (typeof(string)=='string' || typeof(string)== 'number');
    },
    _isElement:function(el){
        return (typeof(el)=='object' && el.nodeType ==1);
    },
    _buildChildren: function(element,children){                                                
        if(this._isElement(children)) element.appendChild(children);
        else if(this._isStringOrNumber(children)) element.innerHTML = children;        
    }    
}

function setStyle(element,style){
    element = $get(element);    
    if(typeof(style)=='object' && element){
        var elementStyle = element.style;
        for(var property in style){
            elementStyle[(property == 'float' || property == 'cssFloat') ?(elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :property] = style[property];
        }
    }
    return element;
}
function hide(element){
    if(element instanceof Array){
        for(var i=0;i<element.length;i++) setStyle(element[i],{display:'none'});
    } else
    return setStyle(element,{display:'none'});
}
function show(element){
    return setStyle(element,{display:'block'});
}
function $w(string){    
     string = ( string = string.toString())?string.replace(/^\s+/, '').replace(/\s+$/, ''):'';
     return string?string.split(/\s+/):[];           
}  


function valid(v){return typeof(v)!='undefined'}
function isNull(v){return typeof(v)=='undefined' || v==null}
// 聚合两个对象(用于使类对象具有派生功能)
Object.prototype.extend = function(object) { 
	for (property in object) { 
		this[property] = object[property]; 
	} 
	return this; 
} 
// 支持数组Array
Object.prototype.clone = function(all){
	var cloneObj = new Object();
	if (valid(all) && all){
		for(prop in this){
			if(typeof(this[prop])=="object") cloneObj[prop] = this[prop].clone(all);
			else cloneObj[prop] = this[prop];
		}
	}else{for(prop in this){cloneObj[prop] = this[prop];}}
	return cloneObj;
}

function validProp(prop){return prop!='extend' && prop!='clone';}

// 使类函数具有直接调用的能力，正常情况类函数只有通过类的实例(对象)来调用，该方法可直接调用类函数，并指定object为函数作用的对象
// 作用：
// 1、让一个对象的函数，作用于另一个对象身上，即使另一个对象不含有该函数(可实现下面的bind功能)
// 2、可调用一个函数参数数量未知的函数，这样在函数未定义时就可调用(可实现重载函数的调用、类派生和接口类，如下面的带构造函数的类定义)

if (!Function.prototype.apply) { 
Function.prototype.apply = function(object, parameters){
  if (!object)   object = window; 
  if (!parameters) parameters = new Array(); 
  var params = new Array(); 
  for (var i = 0; i < parameters.length; i++) params[i] = 'parameters[' + i + ']'; 
  object.__apply__ = this; 
  var result = eval('object.__apply__(' + params.join(', ') + ')'); 
  object.__apply__ = null; 
  return result; 
}} 

Function.prototype.bind = function(object) { 
var __method = this;
return function() { 
  __method.apply(object, arguments); 
} 
}
function $A(arg){
        for(var i = 0 ,result = [],length = arg.length;i< length;){
            result.push(arg[i++]);
        }
        return result;
} 
Function.prototype.bindAsEventListener = function(object) {
      var __method = this, args = $A(arguments), object = args.shift();
      return function(event) {
        return __method.apply(object, [event || window.event].concat(args));
      }
}

// 版本兼容，使Array具有push方法
if (!Array.prototype.push) { 
Array.prototype.push = function() { 
    var startLength = this.length; 
    for (var i = 0; i < arguments.length; i++) 
    this[startLength + i] = arguments[i]; 
  return this.length; 
} 
} 
Array.prototype.insert = function(idx,e){this.splice(idx,0,e);}
Array.prototype.del = function(idx){return this.splice(idx,1);}
Array.prototype.remove = function(item){var i=0;while(i<this.length){if(this[i]==item) this.splice(i,1);else i++;}}
Array.prototype.removeArray = function(array, idx){var i=0;while(i<this.length){if(this[i][idx]==array[idx]) this.splice(i,1);else i++;}}

String.prototype.trim = function(){return this.replace(/^\s*|\s*$/g,"");}
String.prototype.removeTag = function(){return this.replace(/<([^<>]*)>|&nbsp;/gi,"");}

// 创建一个可继承的带构造函数的类, 所有成员都是虚函数。(base类必须由CLASS创建的。否则(即用函数表现的类)出错)
function CLASS(base)
{
	if(!valid(base)) base = null;
	var clsObj = function(){
		if (this.base==null){this.create.apply(this, arguments);return;}
		var creators = [clsObj];
		
		while(this.base){creators.push(this.base);this.base = this.base.base;}
		for(var i=creators.length-1; i>=0; i--) this.extend(creators[i].prototype);
		for(var i=creators.length-1; i>=0; i--) creators[i].prototype.create.apply(this, arguments);
	}
	clsObj.prototype.base = base;
	clsObj.prototype.create = function(){}
	// 用于调用虚函数的基类实现
	clsObj.prototype.callof = function(func)
	{
		func = func.replace(/::/g, '.prototype.');
		func = func.replace(/\(/g, '.apply(this,[');
		func = func.replace(/\)/g, '])');
		eval(func);
	}
	// 用于声明一个类，可用于定义成员变量，和函数接口
	clsObj.declare = function(){}
	// 用于实现一个类
	clsObj.implement = function(implementation){
		this.prototype.extend((new this.declare()).extend(implementation));
	}
	return clsObj;
}

// html 对象的获取
//-------------------------------------------------------------------------------
/*
  关于 getElementsByTagName('*') 和 all、 childNodes 和 children、 parentNode 和 parentElement、body 和 documentElement
  功能一样，但
  W3C的DOM模型中没有all对象，所以在Netscape 6.0 中放弃了对all的支持，因此必须用getElementsByTagName('*')来代替
  IE中坚持向前兼容，所以仍然支持，但getElementsByTagName('*')只有在ie 5.0以后支持
  同样W3C的DOM模型中也没有children、 parentElement对象，一些支持W3C的浏览器(firefox)，就不支持该对象，而支持parentNode、childNodes
*/

function getChildrenByName(obj, name) {
	var l = obj.children.length;
	var children = [];	
	for (var i=0; i<l; i++) {
		if (obj.children[i].name==name) children.push(obj.children[i]);
	}
	return children;
}
function getChildrenByTagName(obj, tagName) {
	var l = obj.children.length;
	var children = [];	
	for (var i=0; i<l; i++) {
		if (obj.children[i].tagName==tagName) children.push(obj.children[i]);
	}
	return children;
}
function getChildrenByClassName(obj, className) {
	var l = obj.children.length;
	var children = [];	
	for (var i=0; i<l; i++) {
		var child = obj.children[i];
		var classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				children.push(child);
				break;
			}
		}
	}
	return children;
}
function getElementsByName(obj, name) {

	var l = obj.getElementsByTagName('*').length;
	var elements = [];	
	for (var i=0; i<l; i++) {
		if (obj.children[i].name==name) elements.push(obj.getElementsByTagName('*')[i]);
	}
	return elements;
}
function getElementsByTagName(obj, tagName) {
	return obj.getElementsByTagName(tagName);
}
function getParentByName(obj, name) {
	var parent = obj.parentElement;
	while(parent)
	{
		if (parent.name == name) return parent;
		parent = parent.parentElement;
	}
	return null
}
function getParentByTagName(obj, tagName) {
	var parent = obj.parentElement;
	while(parent)
	{
		if (parent.tagName == tagName) return parent;
		parent = parent.parentElement;
	}
	return null
}
function getParentByClassName(obj, className) {
	while(obj)
	{
		if (valid(obj.className)){
			var classNames = obj.className.split(' ');
			for (var j = 0; j < classNames.length; j++){if (classNames[j] == className)return obj;}
		}
		obj = obj.parentElement;
	}
	return null
}
function getNextSiblingByName(obj, name) {
	var next = obj.nextSibling;
	while(next)
	{
		if (next.name == name) return next;
		next = next.nextSibling;
	}
	return null
}
function getNextSiblingByTagName(obj, tagName) {
	var next = obj.nextSibling;
	while(next)
	{
		if (next.tagName == tagName) return next;
		next = next.nextSibling;
	}
	return null
}
function getNextSiblingByClassName(obj, className) {
	var next = obj.nextSibling;
	while(next)
	{
		var classNames = next.className.split(' ');
		for (var j=0; j<classNames.length; j++){if(classNames[j]==className)return next;}
		next = next.nextSibling;
	}
	return null
}
function getPrevSiblingByName(obj, name) {
	var prev = obj.previousSibling;
	while(prev)
	{
		if (prev.name == name) return prev;
		prev = prev.previousSibling;
	}
	return null
}
function getPrevSiblingByTagName(obj, tagName) {
	var prev = obj.previousSibling;
	while(prev)
	{
		if (prev.tagName == tagName) return prev;
		prev = prev.previousSibling;
	}
	return null
}
function getPrevSiblingByClassName(obj, className) {
	var prev = obj.previousSibling;
	while(prev)
	{
		var classNames = prev.className.split(' ');
		for (var j = 0; j < classNames.length; j++){if (classNames[j] == className)return prev;}
		prev = prev.previousSibling;
	}
	return null
}

//document.getElementsByName //获取不了div对象
//document.getElementsByTagName
document.getElementsByClassName = function(className) { 
	var elements = []; 
	for (var i = 0; i < document.getElementsByTagName('*').length; i++) { 
	  var element = document.getElementsByTagName('*')[i]; 
	  var classNames = element.className.split(' '); 
	  for (var j = 0; j < classNames.length; j++) { 
		if (classNames[j] == className) { 
		elements.push(element); 
		break; 
		} 
	  } 
	} 
	return elements; 
} 

//-------------------------------------------------------------------------------

function getAbsPos(obj)
{
	var p = [0, 0];
	while (obj && obj.tagName != "BODY")
	{
		p[0] += obj.offsetLeft;
		p[1] += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return p;
}
function getAbsRect(obj)
{
	var r = [0, 0, 0, 0];
	var p = getAbsPos(obj);
	r[0]=p[0];
	r[1]=p[1];
	r[2]=p[0]+obj.offsetWidth;
	r[3]=p[1]+obj.offsetHeight;
	return r;
}
function isInRect(x, y, rect)
{
	return x>=rect[0] && x<=rect[2] && y>=rect[1] && y<=rect[3];
}

function RectInRect(rect1, rect2)
{
	return rect1[0]>rect2[0] && rect1[2] < rect2[2] && rect1[1]>rect2[1] && rect1[3]<rect2[3];
}

function getOffsetToParent(x, y, rect)
{
}

//-------------------------------------------------------------------------------
function toggle(handle){handle.style.display = (handle.style.display == 'none' ? '' : 'none'); return handle.style.display != 'none';}
function show(handle){handle.style.display = '';}
function isVisible(handle){return handle.style.display != 'none';}
function hasClassName(handle, className)
{ 
    var a = handle.className.split(' ');
    for (var i = 0; i < a.length; i++){
      if (a[i] == className) return true; 
    } 
    return false; 
}
function addClassName(handle, className)
{
    removeClassName(handle, className); 
	handle.className += ' ' + className; 
} 
function removeClassName(handle, className)
{
  var newClassName = ''; 
  var a = handle.className.split(' '); 
  for (var i = 0; i < a.length; i++) { 
    if (a[i] != className) { 
    if (i > 0) newClassName += ' '; 
    newClassName += a[i]; 
    }
  } 
  handle.className = newClassName; 
}

function getStyleSheet(title)
{
	var styles = document.styleSheets;
	for(var i=0; styles.length; i++){var s=styles.item(i); if (s.title == title) return s;}
	return null;
}

function getNodeValue(node)
{   
    node = ignoreEmptyNode(node);
 if(node && node.firstChild) return node.firstChild.nodeValue;
 else return "";
}

// cls 可以不写，pos 也可不写(默认为beforeEnd)
function $(tag, cls, to, pos)
{
	var obj = document.createElement(tag);
	if(!valid(cls)) return obj;
	if(typeof(cls)=='string')obj.className = cls;
	else{pos=valid(to)?to:null;to=cls;}
	if (!isNull(to)) to.insertAdjacentElement(isNull(pos)?'beforeEnd':pos, obj);
	return obj;
}
function $e(cls, to, pos){return $('DIV', cls, to, pos);}
// src 可以不写，pos 也可不写(默认为beforeEnd)
function $i(w, h, src, to, pos)
{
	var obj = document.createElement('IMG');
	obj.width = w;obj.height = h;
	if(!valid(src)) return obj;
	if(typeof(src)=='string')obj.src = src;
	else{pos=valid(to)?to:null;to=src;}
	if (!isNull(to)) to.insertAdjacentElement(isNull(pos)?'beforeEnd':pos, obj);
	return obj;
}
//-------------------------------------------------------------------------------

var Event = {
    KEY_BACKSPACE: 8, 
    KEY_TAB:     9, 
    KEY_RETURN:   13, 
    KEY_ESC:     27, 
    KEY_LEFT:   37, 
    KEY_UP:     38, 
    KEY_RIGHT:   39, 
    KEY_DOWN:   40, 
    KEY_Delete:   46,
    stopped : false,
    pstopped : false,

    isLeftClick: function() {
      return (((event.which) && (event.which == 1)) || 
            ((event.button) && (event.button == 1))); 
    }, 
    scrollX: function() { 
      return document.documentElement.scrollLeft || document.body.scrollLeft;
    }, 
    scrollY: function() { 
      return document.documentElement.scrollTop || document.body.scrollTop;
    },

    realX: function(event) { 
      return event.pageX || (event.clientX +(document.documentElement.scrollLeft || document.body.scrollLeft));
    }, 
    realY: function(event) { 
      return event.pageY || (event.clientY +(document.documentElement.scrollTop || document.body.scrollTop));
    },
    stopDefault: function() { event.returnValue = false;},
    stopParent: function() { this.pstopped = true}, 
    resumeParent: function() { var r=this.pstopped; this.pstopped = false; return r;}, 
    stop: function(set) { this.stopped = set;}, 
    isStopped: function(set) { return this.stopped;},
    //阻止向上冒泡
    stops:function(event){
        if (event.preventDefault) {
          event.preventDefault();
          event.stopPropagation();
        } else {
          event.returnValue = false;
          event.cancelBubble = true;
        }
    },
    observe:function(element, name, observer, useCapture){
            element = $get(element);
            useCapture = useCapture||false;
            if(name.toLowerCase() == 'keypress' && element.attachEvent) name = 'keydown';
            if(element.addEventListener) element.addEventListener(name,observer,useCapture);                
            else element.attachEvent('on' + name, observer);
    }
}

//-------------------------------------------------------------------------------

function tryExe ()
{ 
  var ret = null; 
  for (var i = 0; i < arguments.length; i++) { 
    var fun = arguments[i]; 
    try { ret = fun(); break; } catch (e) {} 
  } 
  return ret; 
} 

/** 
* 定义 Ajax 对象
*/ 
//------------------------------------------------------------

var Ajax = { 
  getHttp: function() { 
    return tryExe( 
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}, 
	  function() {return new ActiveXObject('Msxml2.XMLHTTP')}, 
	  function() {return new ActiveXObject('Msxml3.XMLHTTP')}
      ) || false; 
  },
  emEvents : ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']
} 

Ajax.CRequest = CLASS();
Ajax.CRequest.declare = function()
{
	this.http = null;
	this.domDoc = null;
    this.async = true; 
	this.header = {};
	this.event = {};

	// 对象函数
	this.create = function(){}	// 构造对象
	this.Get = function(){}
	this.Post = function(){}
	this.disconnect = function(){}
	this.onStateChange = function(){}
	this.responseIsSuccess = function(){}
	this.responseIsFailure = function(){}
	this.getData = function(){return this.http.responseBody;}
	this.getText = function(){try{return this.http.responseText;} catch(e){return "";}}
	this.getXML = function(){return this.http.responseXML;}
	this.getXMLData = function(tag){}
}
Ajax.CRequest.implement(
{
	// 构造对象
	create : function(async)
	{
		this.async = async;
		this.http = Ajax.getHttp(); 
	},
	post : function(url)
	{
		this.header.Content_type = 'application/x-www-form-urlencoded'; 
		if (this.http.overrideMimeType) this.header.Connection = 'close';
		this.domDoc = null;
		try {
			var i=url.indexOf('?');
			param = i<0?'':url.substring(i+1, url.length);
			url = url.substring(0,i);
			//alert(url+"........................");
			this.http.open('post', url, this.async); 
			var reg = /_/g;
			for (prop in this.header){
				if (validProp(prop)) this.http.setRequestHeader(prop.replace(reg, '-'), this.header[prop]);
			}
			if (this.async) { 
				this.http.onreadystatechange = this.onStateChange.bind(this); 
				//setTimeout(function(){this.onStateChange(1)}.bind(this), 10); 

			}
//			alert(param);
			param = encodeURI(param);
			this.http.send(param);
		} catch (e){} 
	},
	get : function(url)
	{
		this.domDoc = null;
		try {
			this.http.open('get', url, this.async); 

			for (prop in this.header){
				if (validProp(prop))  this.http.setRequestHeader(prop, this.header[prop]);
			}

			if (this.async) { 
				this.http.onreadystatechange = this.onStateChange.bind(this); 
				//setTimeout(function(){this.onStateChange(1)}.bind(this), 10); 
			}
			this.http.send();
		} catch (e){} 
	},

	disconnect : function()
	{
		if (this.http) this.http.abort();
	},
	
	onStateChange: function(readyState)
	{
		if (typeof(state)=='undefined'){
			readyState = this.http.readyState; 
			if (readyState == 1) return; 
		}
		var eventPrc = this.event['on' + Ajax.emEvents[readyState]];
		if (valid(eventPrc)) eventPrc(this);
		if (readyState == 4) this.http.onreadystatechange = function(){}; 
	}, 
	
	responseIsSuccess: function()
	{ 
		return (this.http.status == undefined || this.http.status == 0 || (this.http.status >= 200 && this.http.status < 300)); 
	}, 
	
	responseIsFailure: function()
	{ 
		return !this.responseIsSuccess(); 
	},
	
	/*getXMLData : function(tag)
	{
		if (this.domDoc==null) this.domDoc = this.getXML();
		if (this.domDoc==null) return '';
		var root = this.domDoc.documentElement;
		if (root==null) return '';
		var data = root.getElementsByTagName(tag).item(0);
		if (data) return data.firstChild.nodeValue;
		return '';
	}*/
	getXMLData : function(tag)
	{
		if (this.domDoc==null) this.domDoc = this.getXML();		
		if (this.domDoc==null) return'';
		var root = this.domDoc.documentElement;		
		if (root==null) return '';
		return getNodeValue(root.selectSingleNode(tag));
	}
});

/*------------------------------------------------------------ 
* 定义 ig_Image 操作对象*/

var ig_Image = {	
	ValidImage : function(imgName)
	{
			var g_ImgObj = new Image();
			g_ImgObj.src = imgName;
			if(g_ImgObj.width <= 0)
			{ 
				g_ImgObj = null;
				return false;
			} 
			else 
			{ 
				g_ImgObj = null;
				return true;	
			}
	},
	GetImgWidth : function(imgName)
	{
		var g_ImgObj = new Image();
		g_ImgObj.src = imgName;
		var pwidth = g_ImgObj.width;
		g_ImgObj = null;
		return pwidth;
	},
	GetImgHeight : function(imgName)
	{
		var g_ImgObj = new Image();
		g_ImgObj.src = imgName;
		var pheigth = g_ImgObj.height;
		g_ImgObj=null;
		return pheight;
	}
}
/** 
* 定义 cookie 操作对象
*/ 
//------------------------------------------------------------

var Cookies = {
	GetCookie : function(name, cookiename)
	{
		var s = "";
		if(isNull(cookiename))
		{
			if(typeof(g_isWeb)!= 'undefined' && 0==g_isWeb)
			{
				s = objIG.ReadCookie("http://zhongsou.com");
			}
			else
			{
				s = document.cookie;
			}
		}
		else
		{
			s = this.GetCookie(cookiename);
		}
		var start = s.indexOf(name + "=");
		if (start<0) return ""; else start += name.length+1;
		var end = isNull(cookiename) ? s.indexOf (";", start) : s.indexOf ("|", start);
		if (end < 0) end = s.length;
		return decodeURIComponent(s.substring(start, end));
	},
	GetCookies : function()
	{
		var s = "";
		if(!isNull(g_isWeb) && 0==g_isWeb)
		{
			s = objIG.ReadCookie("http://zhongsou.com");
		}
		else
		{
			s = document.cookie;
		}
		var cookies = [];
		pairs = s.split('; ');
		var pair = null;
		for (var i=0; i<pairs.length; i++)
		{
			pair = pairs[i].split('=');
			cookies.push(pair[0],pair[1]);
		}
		return cookies;
	},
	// expires 单位为秒
	SetCookie : function(name, value, expires, path, domain, secure)
	{
		if(!isNull(g_isWeb) && 0==g_isWeb)
		{
			var s = name+"="+encodeURIComponent (value)+";";
			objIG.WriteCookie(s, "http://zhongsou.com");
		}
		else
		{
			var expdate = new Date();expdate.setTime(expdate.getTime());
			if(valid(expires)) expdate.setTime(expdate.getTime() + ( expires * 1000 ));
			document.cookie = name + "=" + encodeURIComponent (value) + (valid(expires)?("; expires="+ expdate.toGMTString()):"")+(valid(path)?("; path=" + path):"")+(valid(domain)?("; domain=" + domain):"")+((valid(secure)&&secure) ? "; secure" : "");
		}
		
	},
	DelCookie : function(name, path, domain)
	{
		var exp = new Date();
		exp.setTime (exp.getTime() - 1);
		if(!isNull(g_isWeb) && 0==g_isWeb)
		{
			var s = name + "=; expires="+ exp.toGMTString()+(valid(domain)?("; domain=" + domain):"")+(valid(path)?("; path=" + path):"");
			objIG.WriteCookie(s, "http://zhongsou.com");
		}
		else
		{
			var val = this.GetCookie(name);
			if (val==null) return;
			document.cookie = name + "=; expires="+ exp.toGMTString()+(valid(domain)?("; domain=" + domain):"")+(valid(path)?("; path=" + path):"");
		}
	}
}

//**获得页面、窗口高度及宽度**//
function getPageSize(){

var xScroll, yScroll;

if (window.innerHeight && window.scrollMaxY) {
xScroll = document.body.scrollWidth;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}

var windowWidth, windowHeight;
if (self.innerHeight) { // all except Explorer
windowWidth = self.innerWidth;
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}

// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}

// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = windowWidth;
} else {
pageWidth = xScroll;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
return arrayPageSize;
}

//检验输入框是否为空,flag=="t"时检验字符串，flag=="i"是检验数字,title是输入框的名字，str是里面的字符串
function t_check(flag, title, str, max, min)
{
	if(flag=="p" || flag=="pl")
	{
		var s = str.replace(/(^\s*)|(\s*$)/g, "");
		s = s.toLowerCase();
		var re0 = (flag=="pl" ? (/.*/ig) : (/^(http|ftp|file):\/\/.*/ig));
		//var re1 = /(jpg|gif|png)$/ig;
		if(!isNull(s.match(re0)) || s.indexOf("http://pic2.zhongsou.com")!=-1)
		{
			return 1;
		}
		else
		{
			alert("对不起,请在 "+title+" 中输入jpg,gif或者png格式的图片链接!");
			return -1;
		}
	}
	var l = 0;
	var s = [];
	if(flag=="i")
	{
		if (isNaN(parseInt(str)))
		{
			alert("请输入数字");
			return -1;
		}
		l=parseInt(str);
		s[0]="大";
		s[1]="小";
		s[2]=" 以上的数字!";
		if(str.indexOf(".")>0)
		{
			alert("对不起, "+title+" 不能为小数!");
			return -1;
		}
	}
	else
	{
		l=str.length;
		s[0]="长";
		s[1]="短";
		s[2]=" 个字符(每个汉字是两个字符)";
	}

	if(0==l)
	{
		alert("请输入 "+title+" !");
		return -1;
	}
	if(!isNull(max) && -1!=max)
	{
		if(l>max)
		{
			alert("您输入的 "+title+" 超出了最"+s[0]+"限制:"+max+"!");
			return -1;
		}
	}
	if(!isNull(min) && -1!=min)
	{
		if(l<min)
		{
			alert("您输入的 "+title+" 过"+s[1]+",您至少要输入 "+min+s[2]);
			return -1;
		}
	}
	return 1;
}

//检验当前页中是否已经有了某类型的块（该类型不许重复添加），有则返回-1
function b_check(type)
{
	if(5!=type && 6!=type && 8!=type && 9!=type)
	{
		return 1;
	}
	else
	{
		var l = [];
		var oP = myig.gateway.pageobj[myig.gateway.curpage];
		l[0] = oP.module[0].length;
		l[1] = oP.module[1].length;
		l[2] = oP.module[2].length;
		var r = 0;
		for(var c=0; c<3; c++)
		{
			r = 0;
			while(r<l[c])
			{
				if(oP.module[c][r].Type == type)
				{
					var str = (5==type ? "歌曲列表" : (6==type ? "公告" : (8==type ? "相关块推荐" : (9==type ? "引用者列表" : "错误")))); 
					alert("对不起, "+str+" 块已经在当前页里,无法重复添加!");
					return -1;
				}
				r++;
			}
		}
		return 1;
	}
}

//隐藏下拉框之类的
function hideingObj(obj, str)
{
	var o = null;
	var oD = null;
	var f = 0;
	var mr = getAbsRect(obj);
	if(!isNull(str))
	{
		eval('hideObj'+str+' = null;hideObj'+str+' = [];');
		f = 1;
	}
	else
	{
		hideObj = null;
		hideObj = [];
	}
	h_index = 0;
	if(!isNull(oPage.showModule))
	{
		var cl = oPage.showModule.length;
		for(var c=0; c<cl; c++)
		{
			var rl = oPage.showModule[c].length;
			for(var rr=0; rr<rl; rr++)
			{
				oD = oPage.showModule[c][rr];
				var r = getAbsRect(oD);
				if(RectOnRect(r, mr) || RectOnRect(mr, r) || (c==0 && f==1))
				{
					o = oPage.showModule[c][rr].getElementsByTagName("select");
					var l = o.length;
					for(var i=0; i<l; i++)
					{
						o[i].style.display = "none";
						if(!isNull(str))
						{
							eval('hideObj'+str+'[h_index++] = o[i];');
						}
						else
						{
							hideObj[h_index++] = o[i];
						}
					}
				}
			}
		}
	}
}

//显示下拉框之类的
function showObj(str)
{
	if(!isNull(str))
	{
		var s = 'if(!isNull(hideObj'+str+')){var l = hideObj'+str+'.length;for(var i=0; i<l; i++){hideObj'+str+'[i].style.display = "";}hideObj'+str+' = null;}';
		eval(s);
	}
	else
	{
		if(!isNull(hideObj))
		{
			var l = hideObj.length;
			for(var i=0; i<l; i++)
			{
				hideObj[i].style.display = "";
			}
			hideObj = null;
		}
	}
	h_index = 0;
}

//判断两个矩形是否有重叠部分
function RectOnRect(r, mr)
{
	return (isInRect(r[0],r[1],mr) || isInRect(r[0],r[3],mr) || isInRect(r[2],r[1],mr) || isInRect(r[2],r[3],mr));
}

//读一个xml文件并返回CDATA中内容
function loadXmlData(rurl)
{
	var o = mycom.Load(rurl);
	if (o!=null){
		var tree = o.selectSingleNode('//tree');
		var node = tree.firstChild;				
		while(node.nodeType !='4'){
		    node = node.nextSibling;
		}
		var str = node.nodeValue;		
		return str;
	}
	return -1;
}

var _st = window.setInterval; 
window.setInterval = function(fRef, mDelay) 
{ 
	if(typeof fRef == 'function')
	{
		var argu = Array.prototype.slice.call(arguments,2); 
		var f = (function(){ fRef.apply(null, argu); }); 
		return _st(f, mDelay); 
	} 
	return _st(fRef,mDelay); 
}



function GetScaleLineInLine(L1,L2)
{
	var s = [null,null];
	if(L1[0] > L2[0] && L1[0]  < L2[1])
	{
		s[0] = 1;
	}
	if(L1[1] > L2[0] && L1[1]  < L2[1])
	{
		s[1] = 1;
	}
	
	if(s[0] == 1 && s[1] == 1)
	{
		s = null;
		return 100;
	}
	else
	{
		if(s[0] == 1)
		{
			s = null;
			return (L2[1] - L1[0])/(L2[1] - L2[0])*100;
		}
		if(s[1] == 1)
		{
			s = null;
			return (L1[1] - L2[0])/(L2[1] - L2[0])*100;
		}
	}

	return 0;
}

function logIn()
{
	if (typeof(g_hname) == "undefined")
	{
		var g_hname = null;
		if (!location)
		{
			g_hname = location.hostname;
		}
		else
		{
			g_hname = g_location.hostname;
		}
		if (g_hname.indexOf('.') != g_hname.lastIndexOf('.'))
		{
			g_hname = g_hname.substring(g_hname.indexOf('.')+1);
		}
	}
//登陆
if(!isNull(g_isWeb) && g_isWeb == 0)
{
	var rv = objIG.IGLogin(1);
	if(rv == 0)
	{
		window.open("http://uid."+g_hname+"/igportal/login.aspx","_self");
		//window.open("http://192.168.10.93/webtest/login.aspx","_self");
	}
	rv = null;
}
else
{
	window.open("http://uid."+g_hname+"/igportal/login.aspx?page=http://myig.zhongsou.com","_self");
}
}

function openSelfPage(url)
{
	Cookies.SetCookie("ig_tadd", g_pageData[g_curPage].Id, 24*30*60, "/", "zhongsou.com", false);
	window.open(url);
}

function logOut()
{
//删除cookie
if(!isNull(g_isWeb) && g_isWeb == 0)
{
	if(window.confirm("您退出的同时也将注销IG客户端和聊天工具，是否退出？"))
	{
		Cookies.DelCookie("un_web", "/", "zhongsou.com");
		objIG.IGLogin(0);
		location.reload();
	}
}
else
{
	Cookies.DelCookie("un_web", "/", "zhongsou.com");
	location.reload();
}
}
function pull(f){ var s = document.createElement('script'); s.type = 'text/javascript'; s.src = f; document.getElementsByTagName('head')[0].appendChild(s); } 

function LoadFlash(modid,str){
	/*3种格式 html url ubb*/
	//str = regExpFlashStr(str);
	var obj = document.getElementById("c"+modid);
	obj.parentNode.style.display = "inline";
	obj.innerHTML = getFlashCont(regExpFlashStr(str));
}

function regExpFlashStr(str){
	str=str.replace(/<script[^>]*>[\s\S]*<[\\]*\/script[^>]*>/ig,""); 
	str=str.replace(/\r\n/ig,""); 
	var ubbExp = /^\[.+\](.*)\[\/.+\]$/i;
	var urlExp = /^http/i;
	var htmlExp = /\.htm(l){0,1}/gi;
	
	if(htmlExp.test(str)){
		return false;
	}else if(str.search("<") != -1){ // html
		var tmp = /src=([^\s]+)/i.exec(str);//去掉g
		if(tmp == null)
		tmp = /data=([^\s]+)/i.exec(str);//去掉g
		var url = RegExp.$1;
		var args = /flashvars=([^\s]+)/gi.exec(str);
		if(args != null){
			var arg = RegExp.$1;
			url = url.replace(/\"|\'/gi,"");
			arg = arg.replace(/\"|\'/gi,"");
			url = url +"?"+arg;
		}
		if(/\/$/gi.test(url)){return false}
		if(/\/\./gi.test(url)){return false}
		str = url.replace(/\"|\'/gi,"");
	}else if(ubbExp.test(str)){ //ubb
		var url = str.replace(ubbExp,"$1");
		if(/\/$/gi.test(url)){return false}
		if(/\/\./gi.test(url)){return false}
		str = url.replace(/\"|\'/gi,"");
	}else if(urlExp.test(str)){ // url
		if(/\/$/gi.test(str)){return false}
		if(/\/\./gi.test(str)){return false}
	}else{
		return false;
	}
	return str;
}

function getFlashCont(url)
{
	var flashStr = "";
	if(ie())
	{
		flashStr = '<div><object height="95%" width="100%" type="application/x-shockwave-flash" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value=$url name="movie"/><param value="best" name="quality"/><param value="#fff" name="bgcolor"/><param value="transparent" name="wmode"/><param value="always" name="allowScriptAccess"/><embed height="95%" width="100%"  wmode="transparent" bgcolor="#fff" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="best" allowScriptAccess="always" src=$url/></object></div>';
	}
	else if(firefox())
	{
		flashStr = '<div><object><embed src=$url width="100%" height="95%" type="application/x-shockwave-flash" allowScriptAccess="always" wmode="Transparent"/></object></div>';
	}

	flashStr = flashStr.replace(/\$url/g,url);
	return flashStr;
}

/*
* 描述：跨浏览器的设置 innerHTML 方法
*       允许插入的 HTML 代码中包含 script 和 style
* 作者：kenxu <ken@ajaxwing.com>
* 日期：2006-03-23
* 参数：
*    obj: 合法的 DOM 树中的节点
*    htmlCode: 合法的 HTML 代码
* 经测试的浏览器：ie5+, firefox1.5+, opera8.5+
*/
  /*var setInnerHTML = function (el, htmlCode) {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('msie') >= 0 && ua.indexOf('opera') < 0) {
        htmlCode = '<div style="display:none">&nbsp;</div>' + htmlCode;
        htmlCode = htmlCode.replace(/<script([^>]*)>/gi,
                                    '<script$1 defer>');
        el.innerHTML = htmlCode;
        el.removeChild(el.firstChild);
    } else {
        var el_next = el.nextSibling;
        var el_parent = el.parentNode;
        el_parent.removeChild(el);
        el.innerHTML = htmlCode;
        if (el_next) {
            el_parent.insertBefore(el, el_next)
        } else {
            el_parent.appendChild(el);
        }
    }
}*/
var setInnerHTML = function (el, htmlCode)
{
	/*purge(el);
	el.innerHTML = "";
	el.innerHTML = htmlCode.replace(/<script[^>]*>((.|[\r\n])*?)<\\?\/script>/ig, "");
	var sHtml = htmlCode;
	evalScript(sHtml); 
	el = null;
	sHtml = null;
	htmlCode = null;*/
	setInnerHTML2(el, htmlCode);

}
var setInnerHTML2 = function (el, htmlCode)
{
	purge(el);
	el.innerHTML = "";
	el.innerHTML = htmlCode;
	var sHtml = htmlCode;
	evalScript(sHtml); 
	evalStyle(sHtml)
	el = null;
	sHtml = null;
	htmlCode = null;

}
function getScript(str) 
{ 
	var matchAll = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'img'); 
	var matchOne = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'im'); 

	var a = str.match(matchAll) || []; 
	var result = []; 
	for(var i = 0; i <a.length; i++)
	{ 
		result.push((a[i].match(matchOne) || ['', ''])[1]); 
		a[i] = null;
	} 
	a = null;
	matchAll = null;
	matchOne = null;
	str = null;
	return result; 
} 

function evalScript(str)
{ 
	var scripts = getScript(str); 
	for(var i = 0; i < scripts.length; i++)
	{ 
		eval(scripts[i]); 
		scripts[i] = null;
	} 
	scripts = null;
	str = null;
} 

function getStyleCon(str) 
{ 
	var matchAll = new RegExp('(?:<style.*?>)((\n|\r|.)*?)(?:<\/style>)', 'img'); 
	var matchOne = new RegExp('(?:<style.*?>)((\n|\r|.)*?)(?:<\/style>)', 'im'); 

	var a = str.match(matchAll) || []; 
	var result = []; 
	for(var i = 0; i <a.length; i++)
	{ 
		result.push((a[i].match(matchOne) || ['', ''])[1]); 
		a[i] = null;
	} 
	a = null;
	matchAll = null;
	matchOne = null;
	str = null;
	return result; 
} 

function evalStyle(str)
{ 
	var styles = getStyleCon(str); 
	for(var i = 0; i < styles.length; i++)
	{ 
		setCss("abcd",styles[i]);
		styles[i] = null;
	} 
	styles = null;
	str = null;
}

function setCss(id, content) {
       
    var cssId = 'css_' + id;
    var checkId = document.getElementById(cssId);
    if (!checkId) {
      var css = document.createElement("style");
      css.setAttribute('id', cssId);
      css.setAttribute('type','text/css');
      var head = document.getElementsByTagName('head').item(0);
      head.appendChild(css);
	  checkId = document.getElementById(cssId);
    } 

    if (checkId.styleSheet){ // IE
	  
      checkId.styleSheet.cssText += content;
    } else { // w3c
      checkId.appendChild(document.createTextNode(content));
    }
    
}

function bytes(str){
	var len = 0;
	for(var i = 0; i < str.length; i++){
		if(str.charCodeAt(i) > 127){
			len++;
		}
		len++;
	}
	return len;
}
function getbytesStr(str,strlen,flag){
	var len = 0;
	if (strlen == null)
	{
		strlen == 32;
	}
	for(var i = 0; i < str.length; i++)
	{
		if(str.charCodeAt(i) > 127)
		{
			len++;
		}
		len++;
		if (len > strlen)
		{
			str = str.substring(0,i);
			if (flag == 1)
			{
				str += "...";
			}
			return str;
		}
	}
	return str;
}            

var getHost = function(url) { 
     var host = "null";
     if(typeof url == "undefined" || null == url){
		 if(!isNull(location))
          url = location.href;
		 else
		 url = g_location.href;
		 }
     var regex = /.*\:\/\/([^\/]*).*/;
     var match = url.match(regex);
     if(typeof match != "undefined" && null != match)
         host = match[1];
     return host;
}
window._open = window.open;
window.open = function(sURL,sName,sFeatures,bReplace)
{
	var PopWindow = null;
	if(sName == undefined){sName="_blank"};  
	if(sFeatures == undefined){sFeatures=""};  
	if(bReplace == undefined){bReplace=false}; 
	PopWindow = window._open(sURL,sName,sFeatures,bReplace);
	
	if(!PopWindow)
	{
		var domain = getHost();
		alert("您当前使用的浏览器可能应用了禁止弹出窗口的设置，为了保证您正常使用个人门户，请设置允许来自【" + domain + "】该域名下的网页弹出!如果仍无法解决此问题，您的电脑可能安装了某种禁止窗口弹出的程序(如：浏览器插件、防火墙等)，请检查并修改设置后重试!");	
		domain = null;
	}
	else
	{
		PopWindow.focus();
	}
	
	return PopWindow;  
}
function purge(d) {
    var a = d.attributes;
    if (a) {
        var l = a.length;
        for ( var i = 0; i < l; i += 1) {
			if (!!!a[i])
			{
				continue;
			}
            var n = a[i].name;
            if (typeof d[n] == 'function') {
                d[n] = null;
            }
			n = null;
        }
    }
    a = d.childNodes;
    if (a) {
        l = a.length;
        for (i = 0; i < l; i += 1) {
            purge(d.childNodes[i]);
        }
}
a = null;
d = null;
}

function GetClassStyle(theClass,element)
{
	var lastvalue = "";
	try
	{
		var cssRules;
		if (document.all) {
		   cssRules = 'rules';
		}
		else if (document.getElementById) {
		   cssRules = 'cssRules';
		}
		var L1 = document.styleSheets.length;
		for (var S = 0; S < L1; S++){
		var sheetsObj = null;
		try
		{
			sheetsObj = document.styleSheets[S];
		}
		catch (e)
		{
			continue;
		}
		if(!sheetsObj) continue;
		var O1 = null;
		try
		{
			O1 = sheetsObj[cssRules];
		}
		catch (e)
		{
			continue;
		}
		if(!O1) continue;
		var L2 = O1.length;
		   for (var R = 0; R < L2; R++) {
			if (O1[R] && O1[R].selectorText && (O1[R].selectorText.toLowerCase() == theClass.toLowerCase())) {
			 var cv = O1[R].style[element]; 
			 if(cv != null && cv != "")
			 {
				  lastvalue = cv;
			 }
			}
		   }
		   O1 = null;
		}
	}
	catch (e)
	{
	}

	return lastvalue;
};
function countInputChars(obj,ids,counts){
	if(obj){ 
		var values = obj.value ;
		if(isMaxInputString(values,counts)){ 
		  obj.value=values.substring(0,counts) ;
		}  
		var i =counts-values.length;
		if(i<0){i=0};
		document.getElementById(ids).innerHTML=i;
	}
};
function isMaxInputString(value,count){
	if(value.length>count){
		return true ;
	}else{
		return false ;
	}
};
function isUrlComponent(url,canNull) {
	if(canNull && canNull==true && url.trim()=="")return true;
	return /(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/.test(url);
}
/**
 * 去掉url中http://协议头
 */
function trimURLProtocol(website){
	website=website.trim();
	var i=website.indexOf("://"); 
	if(i!=-1){
		website=website.substring(i+"://".length,website.length);
	}
	if(website.length>1 && website.charAt(website.length-1)=='/'){
		website=website.substring(0,website.length-1);
	}
	return website;
}
/**
 * 解析原始高级检索关键字，获得filetype和website,keyword
 * @return var obj={fileType:"",webSite:"",keyword:""};
 */
function parseAdvSearchKeyword(advKeyword){
	var obj={fileType:"",webSite:"",keyword:""};
	advKeyword=advKeyword.trim();
	var KEY_TYPE="filetype:";
	var regexpType=/\s*filetype:\S{3}\s*/g;
	var fileType=advKeyword.match(regexpType);
	if(fileType!=null){
		fileType=fileType.toString().trim();
		fileType=fileType.substring(KEY_TYPE.length,KEY_TYPE.length+3);
		obj.fileType=fileType;
		//document.getElementById("select_search_filetype").value=fileType;
		advKeyword=advKeyword.replace(regexpType,"");
	}/*else{
		document.getElementById("select_search_filetype").value="";	
	}*/
	var KEY_SITE="site:";
	var regexpSite=/\s*site:\S+\s*/g;
	var webSite=advKeyword.match(regexpSite);
	if(webSite!=null){
		webSite=webSite.toString().trim();
		webSite=webSite.substring(KEY_SITE.length,webSite.length).trim();
		//document.getElementById("input_search_website").value=webSite;
		obj.webSite=webSite;
		advKeyword=advKeyword.replace(regexpSite,"");
	}/*else{
		document.getElementById("input_search_website").value="";	
	}*/
	advKeyword=advKeyword.trim();
	obj.keyword=advKeyword;
	//document.getElementById("kword").value=advKeyword;
	return  obj;
}
/**
 * 获得高级检索关键字，支持 website 和 filetype ,keyword
 */
function buildAdvSearchKeyword(filetype,website,simpleKeyword,encodeSite){
	filetype=filetype.trim();
	website=website.trim();
	simpleKeyword=simpleKeyword.trim();
	var advParams="";
	//if(ttype == "31"){
	//var filetype=document.getElementById("select_search_filetype").value;
	//var website=document.getElementById("input_search_website").value.trim();
	website=trimURLProtocol(website);
	if(filetype!=""){
		advParams="filetype:"+filetype+" "; 
	}		
	if(website!=""){
		if(encodeSite && encodeSite==true){
			advParams+="site:"+encodeURI(website)+" ";				
		}else{
			advParams+="site:"+website+" ";
		}
		
	}
	advParams+=simpleKeyword;
	/*}else{
		advParams=simpleKeyword;	
	}
	*/	
	return advParams.trim();
}
/**
 * 网页高级检索（包括站点和文档类型），检索错误，返回错误描述。
 */
function getErrorOfAdvSearch(params){
	var msg="抱歉，没有找到";
	if(params.website.trim()!="") msg+=" 网站来源："+params.website+" ";
	if(params.filetype.trim()!="")msg+=" 网站格式：."+params.filetype+" ";
	if(params.Keyword.trim()!="") msg+=" 关键词："+params.Keyword+" ";
	return msg+="相关的结果。";
}
