var _SARISSA_IS_IE = document.all && window.ActiveXObject && navigator.userAgent.toLowerCase().indexOf("msie") > -1  && navigator.userAgent.toLowerCase().indexOf("opera") == -1;

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];}
}

function isChinese(value) {
    if (value.length == 0) {
    	return false;
    }
    for(n=0; n < value.length; n++) {
        var c=value.charCodeAt(n);
        if (c>127) {
        	return true;
        }
    }
	return false;
}

function Pause(duration, busy){
    this.duration= duration * 1000;
    this.busywork = null; // function to call while waiting.
    this.runner = 0;

    if (arguments.length == 2) {
       this.busywork = busy;
    }

    this.pause(this.duration);

 }

 /** pause method

     @param duration: integer in seconds

  */
 Pause.prototype.pause = function(duration){
    if ( (duration == null) || (duration < 0)) {return;}

    var later = (new Date()).getTime() + duration;

    while(true){
       if ((new Date()).getTime() > later) {
          break;
       }

       this.runner++;

       if (this.busywork != null) {
          this.busywork(this.runner);
       }

    } // while

 } // pause method
 
 /* 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 set cookies */
function setCookie(name,value,path,expires,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* 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";
  }
}

//used for left menu
function toggleMenu(subMenuId) {
    var subMenu = document.getElementById(subMenuId);
    if (subMenu && (subMenu.style.display == "" || subMenu.style.display == "block")) {
        subMenu.style.display = "none";
    } else if (subMenu && subMenu.style.display == "none") {
        subMenu.style.display = "block";
    }
}

function checkMsisdnGpcode(pbkStr){ //pbkStr maybe a msisdn ,maybe a pbk group number.
  	var strReg;
  	if (pbkStr == '') {
  		return false;
  	}

  	if(pbkStr.substring(0,1)=="+"){ //international phone number, followed by 15 number
  		strReg = /^\d{5,15}$/;
  		if (strReg.test(pbkStr.substring(1,pbkStr.length))) {
    		strReg = /^886\d{2,12}$/;
	  		if (strReg.test(pbkStr.substring(1,pbkStr.length))) {
	  			//Domestic phone number
	  			strReq = /^8869\d{8}$/;
	  			if(!strReq.test(pbkStr.substring(1,pbkStr.length))) {
	  				//Phone number doesn't start with +8869, for instance, +8862
	  				return false;
	  			}
	  		}
	  		return true;
    	} else {
    		return false;
    	}
  	} else if(pbkStr.length<5){ //group number
		if (!isNaN(pbkStr)) {  //group code is a number and can't be larger than 9999
    		return true;
    	}
  	} else { //msisdn
  		strReg = /^09\d{8}$/;
  		if (strReg.test(pbkStr)) {
    		return true;
  		}
  	}
  	return false;
}

function checkDomesticMsisdnGpcode(pbkStr){ //pbkStr maybe a msisdn ,maybe a pbk group number.
  	var strReg;
  	if (pbkStr == '') {
  		return false;
  	}
  	if(pbkStr.substring(0,1)=="+"){ //Domestic phone number
  		strReq = /^8869\d{8}$/;
		if(strReq.test(pbkStr.substring(1,pbkStr.length))) {
			//Phone number doesn't start with +8869, for instance, +8862
			return true;
		}
  	} else if(pbkStr.length<5){ //group number
		if (!isNaN(pbkStr)) {  //group code is a number and can't be larger than 9999
    		return true;
    	}
  	} else { //msisdn
  		strReg = /^09\d{8}$/;
  		if (strReg.test(pbkStr)) {
    		return true;
  		}
  	}
  	return false;
}

/**
 * return string bytes count
 */
function getStringLengthByBytes(str) {
    value = trim(str);
    if (value.length == 0) {
    	return 0;
    }
    intLength = 0;
    for(n=0; n < value.length; n++) {
        var c=value.charCodeAt(n);
        if (c<128) { // 0-127 => 1byte
            intLength += 1;
        } else if((c>127) && (c<2048)) { // 127 -  2047 => 2byte
            intLength += 2;
        } else { // 2048 - 66536 => 3byte
            intLength += 3;
        }
    }
    return intLength;
}

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

/* Function to get a form's values in a string */
function trimFormFields(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("text") == 0 ||
            element.type.indexOf("textarea") == 0 ||
            element.type.indexOf("password") == 0) {
            element.value = trim(element.value);
		}
    }
}

//check date text arange: if it is between beginNum and endNum
function checkDateText(elm,beginNum,endNum){
	elm.value = trim(elm.value);
	var  num = new  Number(elm.value);
	if(num.toString().length==""){
		return;
	}
	if(num.toString() == "NaN"){
		//alert("your input not Number");
		elm.value=elm.value.replace(/\D/gi,"");
		checkDateText(elm,beginNum,endNum);
	}else{
		if(num<beginNum){
			//alert("invalid input!");
			elm.value="";
			elm.focus();
		} else if(num>endNum){
			elm.value = elm.value.substring(0,elm.value.length-1);
			elm.focus();
		}
	}
}

//check input Text Number
function checkTextNum(elm){
	elm.value = trim(elm.value);
	var  num = new  Number(elm.value);
	if(num.toString().length==""){
		return;
	}
	if(num.toString() == "NaN"){
		//alert("your input not Number");
		elm.value=elm.value.replace(/\D/gi,"");
		checkTextNum(elm);
	}
}

//check date validaty,dateStr formate: YYYY/MM/DD
//need to check leap year like 1900/1700/2100
function checkDateValidate(dateStr){
	var strTest = /^((\d{2}(([02468][048])|([13579][26]))[\/\/\s]?((((0?[13578])|(1[02]))[\/\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\/\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\/\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\/\/\s]?((((0?[13578])|(1[02]))[\/\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\/\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\/\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))?$/;
        if(strTest.test(dateStr)){
                var y = dateStr.substring(0,dateStr.indexOf("/"));
                var m = dateStr.substring(dateStr.indexOf("/")+1,dateStr.lastIndexOf("/"));
                var d = dateStr.substring(dateStr.lastIndexOf("/")+1);
                if(d==29 && m==2){
                  if(y%100==0 && y%400!=0) return false;
                }
		return true;
	} else {
		return false;
	}
}

/**
 *  Returns true if element's value only contains spaces
 */
function isBlank(element){
	val = element.value;
	if(val == null){
		return true;
	}
	val = trim(val);
	element.value = val;
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){
			return false;
		}
	}
	return true;
}

/**
 * Check msisdn format for Taiwan and internation
 */
function isValidMsisdn(elm, canEmpty) {
	if (canEmpty == null) {
		canEmpty = true;
	}
	if (isBlank(elm)) {
		if (canEmpty) {
			return true;
		} else {
			return false;
		}
	}
	var msisdnPartten = /(((^8869)|(^09)|(^9))\d{8}$)|(^[+]\d{10,15}$)/;
	return msisdnPartten.test(elm.value);
}

//To Chinese chars,which's length will be considered as 2
function cacLenSpecial(value){
   	if (value=="" || value == null) {
  		return 0;
    }
   	var rtnResult=0;
   	for(n=0; n < value.length; n++) {
       	var c=value.charCodeAt(n);
    	if (c<128) { // 0-127 => 1byte
           	rtnResult++;
       	} else if((c>127) && (c<2048)) { // 127 -  2047 => 2byte
           	rtnResult += 2;
       	} else if((c>=19968)&&(c<=40959)){//Chinese chars
           	rtnResult += 2;
       	} else{
       	    rtnResult += 3;
       	}
    }
   	return rtnResult;
}


function filterInValidChars(event){
	var e;
	var key ;
	if(!_SARISSA_IS_IE){ //firefox
	    e = event;
	    key = e.which;
	}else {
	    e = window.event;
	    key = e.keyCode;
	}
	//if press shift+3(#),shift+8(*),shift+=(+) then show normally.
	//else will ignore user's input.
	// 51<-->3#;56<-->8*
	//there has a issue puzzles me,In IE and Firefox,for the same key,they return the different keyCode.
	//for key '=',IE returns keyCode 187 and Firefox returns keyCode 61.
    if(e.shiftKey){
       if(key!=51 && key!=56 && key!=187 && key!=61){
         if(!_SARISSA_IS_IE){
            e.preventDefault();
         } else{
            e.returnValue=false;
         }
       }
       return;
     }
     if(e.ctrlKey){
       if(key!=67 && key!=86 && key!=88){
         if(!_SARISSA_IS_IE){
            e.preventDefault();
         } else{
            e.returnValue=false;
         }
       }
       return;
     }
     //48<-->0;57<-->9;
     //96<-->0(in numpad);105<-->9(in numpad)
     //106-->*(in numpad);107<-->+(in numpad);
     //8<-->backspace;46-->delete;37-->left arrow;39-->right arrow
     if(!((key>=48 && key<=57) || (key>=96 && key<=105)
    || key==106 || key==107 ||key==8||key==46||key==37 ||key==39 ||key==9))
     {
         if(!_SARISSA_IS_IE){
            e.preventDefault();
         } else{
            e.returnValue=false;
         }
     }
}

//When Chinese chars were saved into DB,they will use 3 bytes
function cacLen(value){
   	if (value=="" || value == null) {
  		return 0;
    }
   	var rtnResult=0;
   	for(n=0; n < value.length; n++) {
       	var c=value.charCodeAt(n);
    	if (c<128) { // 0-127 => 1byte
           	rtnResult++;
       	} else if((c>127) && (c<2048)) { // 127 -  2047 => 2byte
           	rtnResult += 2;
       	} else { // 2048 - 66536 => 3byte
           	rtnResult += 3;
       	}
    }
   	return rtnResult;
}

function checkFileExtension(elm, exts, emptyAlertMsg) {
	var value = trim(elm.value);
	var ix = value.lastIndexOf(".");
	if (ix == -1) {
		alert(emptyAlertMsg);
		elm.focus();
		return false;
	}
	var ext = value.substring(ix+1).toLowerCase();
	for (var i = 0; i < exts.length; i++) {
		if(exts[i] == ext){
			return true;
		}
	}
	alert(emptyAlertMsg);
	elm.focus();
	return false;
}

function checkEmailAddr(elm, fCanEmpty) {
    var email;
    if (elm.value == null) { //it's just a variable
        elm = trim(elm);
        email = elm;
    } else { //it's a control
        elm.value = trim(elm.value);
        email = elm.value;
    }

    if (fCanEmpty == null) fCanEmpty = true;
    if (fCanEmpty == true && email.length == 0) return true;
	//    alert("email:" + email);
	for ( var i = 0; i < email.length; i++) {
		var c = email.charCodeAt(i);
		if (!isEngDigit(c)&&!(c==64 || c== 46||c==95)) {
				return false;
		}
	}
    var data = email.match(/^\S+@\S+\.\S+$/);
    if (!data || !email) return false;
    return true;
}

function isEngDigit(c) {
	if ( (c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x5a) || (c >= 0x61 && c<= 0x7a)) {
		return true
	} else {
		return false;
	}
}


/**
 * Add option to SELECT object
 */
function optionAddChildNode(obj, value, display) {
	//duplicate
    var len=obj.length;
    for(var i=0;i<len;i++)
    {
       if (obj.options[i].value==value) {
       		return;
       }
    }

	//add
	obj.options.add(new Option(display, value))
}

/**
 * Remove options from SELECT object
 */
function optionRemoveChildNodes(obj)
{
    var len=obj.length;
    for(var i=len-1;i>=0;i--)
    {
        if(obj.options[i].selected)
        {
            obj.remove(i);
        }
    }
}

/**
 * Select all options on SELECT object
 */
function optionSelectAll(obj)
{
    var len=obj.length;
    for(var i=0;i<len;i++)
    {
        obj.options[i].selected=true;
    }
}

function optionUnSelectAll(obj)
{
    var len=obj.length;
    for(var i=0;i<len;i++)
    {
        obj.options[i].selected=false;
    }
}



/**
 * Remove all options from SELECT object
 */
function optionClearListObj(obj)
{
    var len=obj.length;
    for(var i=0;i<len;i++) obj.remove(0);
}

/**
 * Remove options from SELECT object when user click 'del' key. example:
 * <SELECT NAME="targetSelect" size="10" style="WIDTH: 12em" multiple
 * onkeydown="optionDelete(this)">
 */
function optionDelete(obj) {
	var ev = window.event
	if (ev.keyCode == 46) {
		optionRemoveChildNodes(obj);
		obj.focus();
	}
}

function optionMoveAll(source, target) {
	optionSelectAll(source);
	optionCopy(source, target);
	optionRemoveChildNodes(source);
}

function optionMove(source, target) {
	optionCopy(source, target);
	optionRemoveChildNodes(source);
}

function optionCopy(source, target) {
	var values = getStringTokens("|", getControlValue(source));
	var labels = getStringTokens("|", getControlText(source));
	for (var i=1; i<values.length; i++) {
		optionAddChildNode(target, values[i], labels[i]);
	}
}

function getControlValue(control) {
    if (control.type == 'checkbox' || control.type == 'radio') {
        //alert(control.type + "/" + control.name + "/" + control.value + " = " + control.checked);
        return control.checked;
    } else if (control.type == 'select-multiple') {
        var out = "";
        for(var i=0; i<control.options.length; i++) {
            if (control.options[i].selected) {
                out += "|" + control.options[i].value;
            }
        }
        return out;
    } else if (control.type == 'select-one') {
        return control.options.selectedIndex;
    } else {
        return trim(control.value);
    }
}

function getControlText(control) {
    if (control.type == 'checkbox' || control.type == 'radio') {
        //alert(control.type + "/" + control.name + "/" + control.value + " = " + control.checked);
        return control.checked;
    } else if (control.type == 'select-multiple') {
        var out = "";
        for(var i=0; i<control.options.length; i++) {
            if (control.options[i].selected) {
                out += "|" + control.options[i].text;
            }
        }
        return out;
    } else if (control.type == 'select-one') {
        for(var i=0; i<control.options.length; i++) {
            if (control.options[i].selected) {
                return control.options[i].text;
            }
        }
        return control.options[0].value;
    } else {
        return trim(control.value);
    }
}

function getStringTokens(delim, str) {
    var token   = new Array();
    var testStr = trim(str);

    if (delim == null || delim.length == 0) {
        token[0] = testStr;
        return token;
    }

    var delimIndex = testStr.indexOf(delim);
    var tokenIndex = 0;
    if (delimIndex == -1 && testStr.length != 0) token[0] = testStr;

    while(delimIndex != -1) {
        token[tokenIndex] = testStr.substring(0, delimIndex);
        if (delim != " ") token[tokenIndex] = trim(token[tokenIndex]);
        tokenIndex += 1;
        testStr = testStr.substring(delimIndex + 1);
        delimIndex = testStr.indexOf(delim);
        if (delimIndex == -1) {
            token[tokenIndex] = testStr;
            if (delim != " ") token[tokenIndex] = trim(token[tokenIndex]);
        }
    }

    return token;
}

/**
 * get object position
 */
function getAbsolutePos(el) {
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent) {
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

//just for single form element.
//for those can not validate in 'function validateInput(form)'
var errorBgColor = "#F26522";
function dealWithHighLight4SingleElement(elementNeedValidate,isValid){
   if(elementNeedValidate==null || elementNeedValidate==undefined){
      return;
   }
   if(isValid==null || isValid==undefined || isValid==false || isValid =='false'){
      elementNeedValidate.style.backgroundColor = errorBgColor;
      return;
   } else{
      elementNeedValidate.style.backgroundColor = 'White';
   }
}

function dcsMultiTrackExt(arg1, arg2, arg3, arg4) {
	//DCS = new Object(); 
    //WT = new Object(); 
	//DCSext = new Object();
	dcsMultiTrack ('DCS.dcsuri','/CTR.dat','DCSext.WTlayout_block',arg1,'DCSext.WTlayout_type',arg2,'DCSext.WTlayout_type2',arg3,'DCSext.WTlayout_type3',arg4);
}

function resizeImg(imgElm, maxWidthValue, maxHeightValue){
    var w = imgElm.width;
    var h = imgElm.height;
    if(w != null && w > maxWidthValue){
        w = maxWidthValue;
        h = h * w/imgElm.width;
        if (h > maxHeightValue) {
        	h = maxHeightValue;
        }
    }

    imgElm.style.width=w+"px";
    imgElm.style.height=h+"px";
}

function ajaxLoadPage(url, params, targetDiv, method) {
	if (method == null) {
		method = "post";
	}
	//showAjaxLoading();
	new Ajax.Request(url, {	 
		method: method,
		parameters: params, 
		onSuccess: function(transport) {
			//hideAjaxLoading();
			var response = transport.responseText || "no response text";
			//alert(response);
			$(targetDiv).innerHTML = response;
			//execute javascripts
			var scriptArr = $(targetDiv).select('script');
			if (scriptArr.length && scriptArr.length > 0) {
				for (var i = 0; i < scriptArr.length ; i++) {
					eval(scriptArr[i].innerHTML);
				}
			}
			var msg = trim($('ajax.loaded.msg').innerHTML);
			//if (msg != "") {
			//	showAjaxMsg(msg);
			//}
		},
		onFailure: function failure(){ 
			//hideAjaxLoading();
		//	showAjaxMsg("Ajax Error. Please re-login and try again.", true);
		}   
	});
}
