var jsPath = "/sign/js";
var classPath = jsPath + "/classes";

/**
 * @author mars
 * 
 * this file depends on prototype.js
 */
function parseInt2(num){
	var i = parseInt(num);
	i = i?i:0;
	return i;
}
/**
 * get an event instance between browser difference
 * @param Event event
 * @return Object
 */
function $E(event){
	return event || window.event;
}

/**
 * json string to json object
 * @param String json
 */
function $J(json){
	return Try.these(function (){return eval("("+json+")");},
					 function (){return null;});
}


/**
 * make a piece of HTML string to a DOMElement
 * 
 * @param String domText
 * @return DOMElement
 */
function $D(domText){
	var tempDom = document.createElement("div");
	tempDom.innerHTML = domText;
	var returnValue = tempDom.childNodes[0];
	tempDom = null;
	return $(returnValue);
}



/**
 * let the object become the event's propagation object
 * @param Object obj
 * @param Function func_name
 */
function _(obj, func_name){
	return function(event){
		obj[func_name].call(obj, event);
	};
}

function msgSuccess(holder, msg){
	$(holder).innerHTML = '<span class="success">'+msg+'</span>';
}

function msgFail(holder, msg){
	$(holder).innerHTML = '<span class="fail">'+msg+'</span>';
}

function GetCookie(sName)
{
  // cookies are separated by semicolons
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    // a name/value pair (a crumb) is separated by an equal sign
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) 
      return unescape(aCrumb[1]);
  }

  // a cookie with the requested name does not exist
  return null;
}


Object.extend(String.prototype, {
	/**
	 * @author mars
	 * @method String.prototype.trim
	 * @return String
	 * @since 07-03-29
	 */
	trim: function(){
		return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
  	}
});



var ScriptLoader = new Object();

Object.extend(ScriptLoader,
	{
		/**
		 * include a js file to the document after it was loaded
		 * @method ScriptLoader.include
		 * @param Array scripts
		 */
		include: function(scripts){
			if(!(scripts instanceof Array)){
				var scripts = $A(arguments);
			}
			for(var i = 0; i<scripts.length; i++){
				var jsDom = document.createElement("script");
				jsDom.src = scripts[i];
				document.getElementsByTagName("HEAD")[0].appendChild(jsDom);
			}
		},
		/**
		 * preload a js file to the document when it is loading
		 * @method ScriptLoader.preload
		 * @param {Object} scripts
		 */
		preload: function(scripts){
			if(!(scripts instanceof Array)){
				var scripts = $A(arguments);
			}
			for(var i = 0; i<scripts.length; i++){
				document.write("<script type='text/javascript' src='"+scripts[i]+"'></script>")
			}
		}
	}
);

var ClassLoader = new Object();
Object.extend(ClassLoader,
	{
		/**
		 * @method ClassLoader.include
		 */
		include: function(){
			var classes = $A(arguments);
			for(var i = 0; i<classes.length; i++){
				this.__checkPackage(classes[i]);
				classes[i] = classPath + "/" + classes[i].replace(/\./g, "/") + ".js";
			}
			ScriptLoader.include(classes);
		},
		/**
		 * @method ClassLoader.preload
		 */
		preload:function(){
			var classes = $A(arguments);
			for(var i = 0; i<classes.length; i++){
				this.__checkPackage(classes[i]);
				classes[i] = classPath + "/" + classes[i].replace(/\./g, "/") + ".js";
			}
			ScriptLoader.preload(classes);
		},
		/**
		 * check if the package exists, while not, create it
		 *  
		 * @method ClassLoader.__checkPackage
		 * @param String className
		 * @return Array
		 */
		__checkPackage:function(className){
			var pos = className.indexOf('.');
			do{
				var packageName = className.substr(0, pos);
				var expression = 'window.' + packageName + '==undefined';
				if(eval(expression)){
					expression = 'window.'+packageName+'= new Object();';
					eval(expression);
				}
			}while((pos = className.indexOf('.', pos+1))!=-1);
		}
	}
);

var CSSLoader = new Object();
Object.extend(CSSLoader,
	{
		/**
		 * @method CSSLoader.include
		 */
		include: function(){
			var css = $A(arguments);
			for(var i = 0; i<css.length; i++){
				if(document.createStyleSheet){
					document.createStyleSheet(css[i]);
				}else{
					var cssDom = document.createElement("style");
					cssDom.innerHTML = "@import '"+css[i]+"';";
					document.getElementsByTagName("HEAD")[0].appendChild(cssDom);
				}
			}
		}
	}
);

function nodeRemoveAll(node){
	for(var i=node.childNodes.length-1; i>=0; i--){
		node.removeChild(node.childNodes[i]);
	}
	return node;
}

function nodeAppendAll(node, nodes){
	for(var i=0; i<nodes.length; i++){
		node.appendChild(nodes[i]);
	}
	return node;
}

function createEmptyDOM(){
	if (document.implementation.createDocument){ 
		myDocument =document.implementation.createDocument("","",null); 
	} else if (window.ActiveXObject){ 
		// Internet Explorer, create a new XML document using ActiveX 
		// and use loadXML as a DOM parser. 
		myDocument = new ActiveXObject("Microsoft.XMLDOM");
	}
	return myDocument;
}

function parseXML(xmlString){
	if (document.implementation.createDocument){ 
		// Mozilla, create a new DOMParser 
		var parser = new DOMParser(); 
		myDocument = parser.parseFromString(xmlString, "text/xml"); 
	} else if (window.ActiveXObject){ 
		// Internet Explorer, create a new XML document using ActiveX 
		// and use loadXML as a DOM parser. 
		myDocument = new ActiveXObject("Microsoft.XMLDOM");
		myDocument.async="false"; 
		myDocument.loadXML(xmlString); 
	}
	return myDocument;
}

if (!document.all){
    var  ex;
    XMLDocument.prototype.__proto__.__defineGetter__( "xml" ,  function (){
         try {
             return   new  XMLSerializer().serializeToString( this );
        } catch (ex){
             var  d  =  document.createElement( "div" );
            d.appendChild( this .cloneNode( true ));
             return  d.innerHTML;
        }
    });
    Element.prototype.__proto__.__defineGetter__( "xml" ,  function (){
         try {
             return   new  XMLSerializer().serializeToString( this );
        } catch (ex){
             var  d  =  document.createElement( "div" );
             d.appendChild( this .cloneNode( true ));
             return  d.innerHTML;
        }
    });
    XMLDocument.prototype.__proto__.__defineGetter__( "text" ,  function (){
         return   this .firstChild.textContent
    });
    Element.prototype.__proto__.__defineGetter__( "text" ,  function (){
         return   this .textContent
    });


    XMLDocument.prototype.selectSingleNode = Element.prototype.selectSingleNode = function (xpath){
         var  x = this .selectNodes(xpath)
         if ( ! x  ||  x.length < 1 ) return   null ;
         return  x[ 0 ];
    }
    XMLDocument.prototype.selectNodes = Element.prototype.selectNodes = function (xpath){
         var  xpe  =   new  XPathEvaluator();
         var  nsResolver  =  xpe.createNSResolver( this .ownerDocument  ==   null   ? 
             this .documentElement :  this .ownerDocument.documentElement);
         var  result  =  xpe.evaluate(xpath,  this , nsResolver,  0 ,  null );
         var  found  =  [];
         var  res;
         while  (res  =  result.iterateNext()){
		 	found.push(res);
		 }
         return  found;
    }
}

function GetActiveText(objHTML) {
	if(document.selection){
		var obj=$(objHTML);
		obj.currPos = document.selection.createRange().duplicate()
	}
}

function GetActiveText(event) {
	event = $E(event);
	var obj = Event.element(event);
	if(document.selection){
		obj.currPos = document.selection.createRange().duplicate();
	}
}

function InsertText(objHTML,strText,bolReplace) {
	if(strText==""){return("")}
	var obj=$(objHTML);
	
	if(document.selection){
		if (obj.currPos){
			if(bolReplace && (obj.value=="")){
				obj.currPos.text=strText
			}
			else{
				obj.currPos.text+=strText
			}
		}
		else{
			obj.value+=strText
		}
	}
	else{
		if(bolReplace){
			obj.value=obj.value.slice(0,obj.selectionStart) + strText + obj.value.slice(obj.selectionEnd,obj.value.length)
		}
		else{
			obj.value=obj.value.slice(0,obj.selectionStart) + strText + obj.value.slice(obj.selectionStart,obj.value.length)
		}
	}
	obj.focus();
}

function ReplaceText(objHTML,strPrevious,strNext) {
	var obj=$(objHTML);
	var strText;
	var doc = obj.ownerDocument;
	
	if(doc!=null && doc.selection && doc.selection.type == "Text"){
		if (obj.currPos){
			var range = doc.selection.createRange();
			range.text = strPrevious + range.text + strNext;
			return("");
		}
		else{
			strText=strPrevious + strNext;
			return(strText);
		}
	}
	else{
		if(obj.selectionStart || obj.selectionEnd){
			strText=strPrevious + obj.value.slice(obj.selectionStart,obj.selectionEnd) + strNext;
			return(strText);
		}
		else{
			strText=strPrevious + strNext;
			return(strText);
		}
	}
}

function createTag(tagName, tagPropertyJSON){
	var tag = document.createElement(tagName);
	return Object.extend(tag, tagPropertyJSON);
}

Object.extend(Element,{ 
	getPosition:function(element){
		element = $(element);
		
		if(element.offsetParent!=undefined && element.offsetParent!=null ){
			var parentPos = Element.getPosition(element.offsetParent);
			var left = element.offsetLeft;
			var top = element.offsetTop;
			
			//alert(element.tagName+":"+top);
			
			//alert(element.parentNode.tagName +":"+ element.parentNode.offsetTop);
			return {left: left + parentPos.left, top: top + parentPos.top};
		}else{
			return {left: element.offsetLeft, top: element.offsetTop};
		}
		
	}
});
/*
Object.extend(Element.prototype, {
	findAncestorTag: function(tagName){
		var ancestors = this.ancestors();
		for(var i=0; i<ancestors.length; i++){
			if(ancestors[i].tagName == tagName.toUpperCase()){
				return ancestors[i];
			}
		}
	}
});

*/

Object.extend(Element, {
	findAncestorTag: function(element,tagName){
		var ancestors = element.ancestors();
		for(var i=0; i<ancestors.length; i++){
			if(ancestors[i].tagName == tagName.toUpperCase()){
				return ancestors[i];
			}
		}
	}
});

Object.extend(Element, {
	getHTML: function(element){
		return element.xml || element.outerHTML;
	}
});

Object.extend(Element, {
	findAncestor: function(element,func){
		var ancestors = element.ancestors();
		return ancestors.find(func);
	}
});

Object.extend(Element, {
	isInViewPort: function(element){
		var pos = Element.getPosition(element);
		var dem = element.getDimensions();
		var top = document.documentElement.scrollTop;
		var bottom = top + document.documentElement.clientHeight;
		var left = document.documentElement.scrollLeft;
		var right = left + document.documentElement.clientWidth;
		
		return (pos.top > top) && (pos.top + dem.height < bottom) 
			&& (pos.left > left) && (pos.left + dem.width < right);
	}
});

Object.extend(Element, {
	disableSelection: function(element){
		element = $(element);
		if (typeof element.onselectstart!="undefined") //IE route
			element.onselectstart=function(){return false;};
		else if (typeof element.style.MozUserSelect!="undefined") //Firefox route
			element.style.MozUserSelect="none";
}});

Object.extend(Element, {
	copyHTMLElement:function (ele){
		if(document.all){
			return $D(ele.outerHTML);
		}else{
			return $D(ele.xml);
		}
}});

Object.extend(Event, {
	relatedElement: function(event){
		return event.toElement || event.relatedTarget;
	}
});

Object.extend(Number.prototype, {
	toHex: function(){
		var hexstring="0123456789abcdef";
		var value = this;
		var ret='';
		while(true){
			ret = hexstring.charAt(value%16) + ret;
			value = parseInt(value/16);
			if(value==0) return ret;
		}
	}
});

Object.extend(Number.prototype, {
	floatPos: function(pos){
		return parseInt((this*Math.pow(10, pos)).round())/Math.pow(10, pos);
	}
});

Object.extend(Number.prototype, {
	newTimeFormat: function(){
		var sec = 1000;
		var min = sec * 60;
		var hour = min * 60;
		var day = hour * 24;
		var month = day * 30;
		var year = month * 12;
		
		var txt = "以前";
		
		var now = new Date().getTime();
		var diff = now - this * 1000;
		
		var ret = '';
		var unit = '';
		var rule;
		if(diff >= year){
			rule = year;
			unit = '年';
		}else if(diff >= month){
			rule = month;
			unit = '月';
		}else if(diff >= day){
			rule = day;
			unit = '天';
		}else if(diff >= hour){
			rule = hour;
			unit = '小时';
		}else if(diff >= min){
			rule = min;
			unit = '分钟';
		}else{
			rule = sec;
			unit = '秒';
		}
		ret = parseInt(diff/rule) + unit + txt;
		
		if(diff<1000){
			ret = "1秒以前";
		}
		return ret;
	}
});

Object.extend(String.prototype, {
	fill: function(c, length){
		if(this.length>=length) 
			return this;
		else{
			return $R(0, length-this.length).map(function(value){ return c;}).join("") + this;
		}
			
	}
});

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;