
//字符串对象扩展
String.prototype.trim= function()
{
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

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

Array.prototype._push = Array.prototype.push;

Array.prototype.push = function(value){
	if( this._push ){
		this._push( value );
	} else {
		this[this.length] = value;
	}
}

//处理参数形式的字符串
String.prototype.get = function(key){
	var keys = this.parseQuery();
	return keys[key];
}

//处理参数形式的字符串
String.prototype.put = function(key, value){
	
	var keys = this.toQueryParams();
	if( this.trim() == "" ){
		keys = new Array();
	}
	keys[key] = value;
	var ret;
	args = $A(arguments);
	if( args[2]==true ){
		ret = decodeURIComponent($H(keys).toQueryString());
	}else{
		ret = $H(keys).toQueryString(); 
	}
	return ret;
}

function ascii2native(str) 
 {
 	var list = str.split("&#");
 	var result = "";
 	
 	for (i=0; i<list.length; i++) {
 		
 		var s = list[i];
 		
 		if (s.trim().length == 0) {
 			continue;
 		}
 		
 		if (s.substring(s.length -1, s.length) == ';') {
 			result += String.fromCharCode(parseInt(s));
 		}
 		else
 		{
 			result += s;
 		}
 	
 	}
 	return result;
 }



//解决IE与其它浏览器兼容问题

//是否为IE浏览器
function isIE()
{

    if (document.uniqueID ) {
        return true;
    }
    else
    {

        return false;
    }

}



if(window.addEventListener)
{
	FixPrototypeForGecko();
}
function FixPrototypeForGecko()
{
	HTMLElement.prototype.__defineGetter__("runtimeStyle",element_prototype_get_runtimeStyle);
	window.constructor.prototype.__defineGetter__("event",window_prototype_get_event);
	Event.prototype.__defineGetter__("srcElement",event_prototype_get_srcElement);
}
function element_prototype_get_runtimeStyle()
{
	//return style instead...
	return this.style;
}
function window_prototype_get_event()
{
	return SearchEvent();
} 
function event_prototype_get_srcElement()
{
	return this.target;
}

function SearchEvent()
{
	//IE
	if(document.all)
		return window.event;
		
	func=SearchEvent.caller;
	while(func!=null)
	{
		var arg0=func.arguments[0];
		if(arg0)
		{
			if(arg0.constructor==Event)
				return arg0;
		}
		func=func.caller;
	}
	return null;
}






function AttachEvent(element, eventName, callback)
{
	if ( isIE() ) {
		element.attachEvent( eventName, callback );
	}
	else
	{
		var exOn = eventName.substring( 0, 2);
		if ( exOn == "on" ) {
			element.addEventListener(eventName.substring(2,eventName.length), callback, false)
		}
		else
		{
		
			element.addEventListener(eventName, callback, false);
		}
	
	}	
	

}



function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
    obj.className = newStyle;
}

function isUndefined(value) {
    var undef;
    return value == undef;
}

/* Function for showing and hiding elements that use 'display:none' to hide */
function toggleDisplay(targetId)
{
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.style.display == "none"){
    		target.style.display = "";
    	} else {
    		target.style.display = "none";
    	}
    }
}

// toggle visibility
function toggleVisibility(targetId) {
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.style.visibility == "hidden"){
    		target.style.visibility = "visible";
    	} else {
    		target.style.visibility = "hidden";
    	}
    }
}

function checkAll(theForm) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
		var eName = e.name;
    	if (eName != 'allbox' &&
            (e.type.indexOf("checkbox") == 0)) {
        	e.checked = theForm.allbox.checked;		
		}
	}
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
		if(element.type.indexOf("text") == 0 ||
				element.type.indexOf("password") == 0) {
					element.value="";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked=false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for(var j = 0; j < element.length ; j++) {
				element.options[j].selected=false;
			}
            element.options[0].selected=true;
		}
	}
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
    var query = "";
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("checkbox") == 0 ||
            element.type.indexOf("radio") == 0) {
            if (element.checked) {
                query += element.name + '=' + escape(element.value) + "&";
            }
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length ; j++) {
				if (element.options[j].selected) {
                    query += element.name + '=' + escape(element.value) + "&";
                }
			}
        } else {
            query += element.name + '='
                  + escape(element.value) + "&";
        }
    }
    return query;
}

/* Function to hide form elements that show through
   the search form when it is visible */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden
{
	for(var i = 0; i < frmObj.length; i++) {
		if (frmObj.elements[i].type.indexOf("select") == 0 || frmObj.elements[i].type.indexOf("checkbox") == 0) {
            frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
		}
	}
}

/* Helper function for re-ordering options in a select */
function opt(txt,val,sel) {
    this.txt=txt;
    this.val=val;
    this.sel=sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list,to) {
    var total=list.options.length;
    index = list.selectedIndex;
    if (index == -1) return false;
    if (to == +1 && index == total-1) return false;
    if (to == -1 && index == 0) return false;
    to = index+to;
    var opts = new Array();
    for (i=0; i<total; i++) {
        opts[i]=new opt(list.options[i].text,list.options[i].value,list.options[i].selected);
    }
    tempOpt = opts[to];
    opts[to] = opts[index];
    opts[index] = tempOpt
    list.options.length=0; // clear

    for (i=0;i<opts.length;i++) {
        list.options[i] = new Option(opts[i].txt,opts[i].val);
        list.options[i].selected = opts[i].sel;
    }

    list.focus();
}

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/* This function is used to select a checkbox by passing
 * in the checkbox id
 */
function toggleChoice(elementId) {
    var element = document.getElementById(elementId);
    if (element.checked) {
        element.checked = false;
    } else {
        element.checked = true;
    }
}

/* This function is used to select a radio button by passing
 * in the radio button id and index you want to select
 */
function toggleRadio(elementId, index) {
    var element = document.getElementsByName(elementId)[index];
    element.checked = true;
}


/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
	winName = window.open(url, winTitle, winParams);
    winName.focus();
}


/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
    var screenWidth = parseInt(screen.availWidth);
    var screenHeight = parseInt(screen.availHeight);

    var winParams = "width=" + screenWidth + ",height=" + screenHeight;
        winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

    openWindow(url, winTitle, winParams);
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

function setCookie30d(name, value) {
	var expires = new Date();
    expires.setTime(expires.getTime() + 24 * 30 * 60 * 60 * 1000); // sets it for approx 30 days.
    setCookie(name,value,expires);

}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "="
	var start = document.cookie.indexOf(prefix)

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length)
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end)
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// This function is for stripping leading and trailing spaces
function trim(str) {
    if (str != null) {
        var i;
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length);
                break;
            }
        }

        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1);
                break;
            }
        }

        if (str.charAt(0)==" ") {
            return "";
        } else {
            return str;
        }
    }
}

// This function is used by the login screen to validate user/pass
// are entered.
function validateRequired(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oRequired = new required();

    for (x in oRequired) {
        if ((form[oRequired[x][0]].type == 'text' || form[oRequired[x][0]].type == 'textarea' || form[oRequired[x][0]].type == 'select-one' || form[oRequired[x][0]].type == 'radio' || form[oRequired[x][0]].type == 'password') && form[oRequired[x][0]].value == '') {
           if (i == 0)
              focusField = form[oRequired[x][0]];

           fields[i++] = oRequired[x][1];

           bValid = false;
        }
    }

    if (fields.length > 0) {
       focusField.focus();
       alert(fields.join('\n'));
    }

    return bValid;
}

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
    var e = document.createElement(element);
    e.setAttribute("name", name);
    e.setAttribute("type", type);
    e.setAttribute("id", id);
    e.setAttribute("value", value);
    parent.appendChild(e);
}

function confirmDelete(obj) {
    var msg = "您确定要删除诿" + obj + "吿";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function highlightTableRows(tableId) {
    var previousClass = null;
    var table = document.getElementById(tableId);
    var tbody = table.getElementsByTagName("tbody")[0];
    if (tbody == null) {
        var rows = table.getElementsByTagName("tr");
    } else {
        var rows = tbody.getElementsByTagName("tr");
    }
    // add event handlers so rows light up and are clickable
    for (i=0; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[0];
            var link = cell.getElementsByTagName("a")[0];
            location.href = link.getAttribute("href");
            this.style.cursor="wait";
        }
    }
}

function highlightFormElements() {
    // add input box highlighting
    addFocusHandlers(document.getElementsByTagName("input"));
    addFocusHandlers(document.getElementsByTagName("textarea"));
}

function addFocusHandlers(elements) {
    for (i=0; i < elements.length; i++) {

        if (elements[i].type != "button" && elements[i].type != "submit" &&
            elements[i].type != "reset" && elements[i].type != "checkbox" && elements[i].type != "radio"
            && elements[i].type != "image") {
            if (elements[i].getAttribute('readonly') != "readonly" && elements[i].getAttribute('readonly') != "disabled") {
            	elements[i].className= this.type + 'Input';
            	elements[i].attachEvent("onfocus", function() {var obj = event.srcElement; obj.className= obj.type + 'Input focus';obj.select()});
            	elements[i].attachEvent("onblur", function() {var obj = event.srcElement; obj.className= obj.type + 'Input'});
            }
        }
    }
}

function radio(clicked){
    var form = clicked.form;
    var checkboxes = form.elements[clicked.name];
    if (!clicked.checked || !checkboxes.length) {
        clicked.parentNode.parentNode.className="";
        return false;
    }

    for (i=0; i<checkboxes.length; i++) {
        if (checkboxes[i] != clicked) {
            checkboxes[i].checked=false;
            checkboxes[i].parentNode.parentNode.className="";
        }
    }

    // highlight the row
    clicked.parentNode.parentNode.className="over";
}
/*    ??????JSF?????
window.onload = function() {
    highlightFormElements();
    if ($('successMessages')) {
        new Effect.Highlight('successMessages');
        // causes webtest exception on OS X : http://lists.canoo.com/pipermail/webtest/2006q1/005214.html
        // window.setTimeout("Effect.DropOut('successMessages')", 3000);
    }
    if ($('errorMessages')) {
        new Effect.Highlight('errorMessages');
    }
}
*/

// Show the document's title on the status bar
window.defaultStatus=document.title;


//修正弹出窗口中文乱码			
window._alert=window.alert;
window.alert=function(s) {
	_alert(s.replace(/&#(\d{5});/g,function(r,r1) {return String.fromCharCode(r1);}));
};

window._confirm=window.confirm;

window.confirm = function(s) {
	return _confirm(s.replace(/&#(\d{5});/g,function(r,r1) {return String.fromCharCode(r1);}));
};


function PanelHideFocus(PanelId)
{

   var panel = document.getElementById(PanelId)
   if(panel != null){
   		
	   var inputs = panel.getElementsByTagName("input")
	
	   for (var i=0; i<inputs.length; i++)
	   {
	   		var ctrl = inputs[i]
	        ctrl.hideFocus = true;
	   }
   }
}

function createHideField(fieldText){
	document.writeln("<a style='display:block' backValue='" + fieldText + "' href=\"javascript:\" onclick=\"showHideField()\">显示</a>");
	//document.writeln("<div><button type=\"button\" onclick=\"showHideField(" + row + ")\">显示</button</div>")
	
}

function showHideField(row){
	var field = event.srcElement;
	if( field.innerText == "显示"){
		field.innerHTML = field.backValue;
		
	}else{
		field.innerHTML = "显示";
	}
}


//------------------------------------------------------------------------------
//                       保持页面提交时的滚动条位罿
//------------------------------------------------------------------------------
function getFileName()
{
    var url = this.location.href;
    var pos = url.lastIndexOf("/");
    if(pos == -1)
        pos = url.lastIndexOf("\\");
    var filename = url.substr(pos+1);
    return filename;
}

function fnLoad()
{
    with(window.document.body)
    {
        style.behavior = "url(#default#userdata);";    // 使得body元素可以支持userdate
        try{
        load("scrollState" + getFileName());    // 获取以前保存在userdate中的状怿
		}catch(e){}
        scrollLeft = getAttribute("scrollLeft");    // 滚动条左位置
        scrollTop = getAttribute("scrollTop");

    }
}

function fnUnload()
{
    with(window.document.body)
    {
    	style.behavior = "url(#default#userdata);";
        setAttribute("scrollLeft",scrollLeft);
        setAttribute("scrollTop",scrollTop);
        try{
        save("scrollState" + getFileName());
        }catch(e){
        	
        }
        // 防止受其他文件的userdate数据影响，所以将文件名加上了
        // userdate里的数据是不能跨目录访问皿
    }
}

AttachEvent(window, "onload", fnLoad );
AttachEvent(window, "onunload", fnUnload);

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






//Calendar 重写处理

/* hides <select> and <applet> objects (for IE only) */
function jscalendarHideElement2( elmID, overDiv ){
  if( jscalendarIe ){
    for( i = 0; i < document.all.tags( elmID ).length; i++ ){
      obj = document.all.tags( elmID )[i];
      if( !obj || !obj.offsetParent )
        continue;

      // Find the element's offsetTop and offsetLeft relative to the BODY tag.
      objLeft   = obj.offsetLeft;
      objTop    = obj.offsetTop;
      objParent = obj.offsetParent;

      while( objParent.tagName.toUpperCase() != "BODY" && objParent.tagName.toUpperCase() != "HTML" ){
        objLeft  += objParent.offsetLeft;
        objTop   += objParent.offsetTop;
        objParent = objParent.offsetParent;
      }

      objHeight = obj.offsetHeight;
      objWidth = obj.offsetWidth;

      if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
      else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
      else if( overDiv.offsetTop >= ( objTop + objHeight ));
      else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
      else
        obj.style.visibility = "hidden";
    }
  }
}

function jscalendarPopUpCalendar_Show2(ctl){
	jscalendarOdateSelected = jscalendarDateSelected;
	jscalendarOmonthSelected = jscalendarMonthSelected;
	jscalendarOyearSelected = jscalendarYearSelected;

	var	leftpos = 0;
	var	toppos = 0;

	var aTag = ctl;
	do {
		aTag = aTag.offsetParent;
		leftpos	+= aTag.offsetLeft;
		toppos += aTag.offsetTop;
	} while(aTag.tagName!="BODY"&&aTag.tagName!="HTML");

	jscalendarCrossobj.left = jscalendarFixedX==-1 ? ctl.offsetLeft	+ leftpos + "px": jscalendarFixedX;
	jscalendarCrossobj.top = jscalendarFixedY==-1 ?	ctl.offsetTop +	toppos + ctl.offsetHeight +	2 + "px": jscalendarFixedY;
	jscalendarConstructCalendar (1, jscalendarMonthSelected, jscalendarYearSelected);
	jscalendarCrossobj.visibility=(jscalendarDom||jscalendarIe)? "visible" : "show";

	jscalendarHideElement( 'SELECT', document.getElementById("calendar") );
	jscalendarHideElement( 'APPLET', document.getElementById("calendar") );

	jscalendarBShow = true;
}
 

