/**
 * This function is to do:
 * 1. parse a given formatted string and set value to form fields(one argument).
 *    E.g. setBatchFormField("field1=value1&field2=value2&field3=value3");
 * OR
 * 2. set a serial of arguments to form fields(more than one argument, should be even).
 *    As httpunit(1.5.4) cannot support document.getElementById(...).value, we pass the element directly
 *    E.g. setBatchFormField(document.forms[0].field1,"value1",document.forms[0].field2,"value2",document.forms[0].field3,"value3");
 */
function setBatchFormField() {
    if (arguments.length == 1) {    // one argument: the first case
        // split into key value pairs
        var keyValuePairs = arguments[0].split("&");

        // loop the key value pairs
        for (i=0; i<keyValuePairs.length; i++) {
            // if there is a key value pair, pass it and set the form field
            var indexEqualSign = keyValuePairs[i].indexOf("=");

            if ( indexEqualSign > -1) {
                document.getElementById(keyValuePairs[i].substr(0, indexEqualSign)).value =
                    keyValuePairs[i].substr(indexEqualSign + 1, keyValuePairs[i].length);
            }
        }
    } else {    // more than one argument: the second case
        // loop through the arguments, get key-values by pair and set
        for (i=0; i<arguments.length - 1; i+=2) {
            arguments[i].value = arguments[i + 1];
        }
    }
}

// Check/Uncheck the checkboxes with the specified id
// to make it the same as the "All" checkbox
// Here, we don't use getElementsByName, because:
// <li>IE: will get all element when id==value or name==given value
// <li>Mozilla: will get all element only when id==given value
function checkAll(allObj, subObjId) {
    // get the element list and length
    var elementList = this.document.forms[0].elements;
    var elementListLength = elementList.length;

    for (var i=0; i< elementListLength; i++) {
        if (elementList[i].id==subObjId || elementList[i].name==subObjId) {
            elementList[i].checked=allObj.checked;
        }
    }
}


// check the length of textarea
function checkTextArea(sField, iLen) {
    // for some browser like Mozilla, return is "\n" instead of "\r\n"
    // but when they commit, it passes "\r\n". so convert "\n" to "\r\n" here
    var oldValue = sField.value.replace(/\n/g, "\r\n");
    oldValue = oldValue.replace(/\r\r\n/g, "\r\n");

    if ( oldValue.length > iLen ) {
        var newValue = oldValue.substring(0,iLen);

        // this is for a special case: ended by \r\n before cut, ended by \r after cut
        if (newValue.charCodeAt(newValue.length - 1) == 13) {
            newValue = newValue.substring(0, iLen - 1);
        }

        alert(MSG_HTMLEDITOR_LENGTH_LIMIT_TEXT.replace(/(#MAX_LENGTH#)/g,iLen));

        sField.value = newValue;
    }
}

/**
 * open the calendar page
 */
var nsContextPath;
var nsFormName;
var nsDateField;
var nsMonthField;
var nsYearField;
function openCalendar(yearField, monthField, dateField, formName, contextPath){
    if(navigator.appName=="Netscape") {
        nsContextPath = contextPath;
        nsFormName = formName;
        nsDateField = dateField;
        nsMonthField = monthField;
        nsYearField = yearField;
        document.onclick = openCalenderInNetscape;
    } else {
        var URL;
        URL = contextPath + '/jsp/common/calendar.jsp?Form=' + formName + '&Day=' + dateField + '&Month=' + monthField + '&Year=' + yearField;
        var leftPosition = window.event.screenX;
        var topPosition = window.event.screenY;
        var screenWidth = screen.availWidth;
        var screenHeight = screen.availHeight;

        if ((leftPosition + 210) > screenWidth) {
           leftPosition  = screenWidth - 210;
        }

        if ((topPosition + 260) > screenHeight) {
            topPosition = screenHeight - 260;
        }

        var left="left=" + leftPosition;
        var top="top=" + topPosition;

        var features = "width=200,height=225,scrollbars=0,toolbar=0,location=0,resizable=0," + left + "," + top;
        window.open(URL, 'popupCalendar', features);
    }
}

function openCalenderInNetscape(e) {
     var URL;
     URL = nsContextPath + '/jsp/common/calendar.jsp?Form=' + nsFormName + '&Day=' + nsDateField + '&Month=' + nsMonthField + '&Year=' + nsYearField;
     var left="left=" + (e.screenX);
     var top="top=" + (e.screenY);
     var features = "width=200,height=225,scrollbars=0,toolbar=0,location=0,resizable=0," + left + "," + top;
     window.open(URL, 'popupCalendar', features);
     document.releaseEvents(Event.CLICK);
     document.onclick = "";
}

/**
 * change the url(form.action) and submitAction, then submit the form
 */
function doSubmit(url, submitAction, formName){

    if (formName == null) {formName = 0; }

    document.forms[formName].action = url;
    document.forms[formName].target = "_self";
    document.forms[formName].submitAction.value = submitAction;
    document.forms[formName].submit();
}

/**
 * change the url(form.action), then submit the form
 */
function doSubmitUrl(url, formName){

    if (formName == null) { formName = 0; }

    document.forms[formName].action = url;
    document.forms[formName].submit();
}

/**
 * change the submitAction, then submit the form
 */
function doSubmitAction(submitAction, formName){

	if (formName == null) { formName = 0; }

    document.forms[formName].submitAction.value = submitAction;
    document.forms[formName].submit();
}

/**
 * check the number
 */
function checkThisNum(sField)
{
	var temp;
	temp = sField.value;

	if( isNaN(temp)  )
	{
		alert( "Please enter a numeric value" );
		sField.value = 0;
	}

	if( ( temp % 1 ) > 0 )
	{
		alert( "Please enter an integer value" );
		sField.value = 0;

	}
	if( temp < 0 )
	{
		alert("Please enter a number greater than zero.")
		sField.value = 0;
	}
	if( temp == 0 )
	{
		sField.value = "";
	}
}

/**
 * clear the field
 */
function clearField(sField)
{
	if ( sField.value == 0  )
	  sField.value  = "";
}

function HelpPopUp(url){
	sealWin=window.open(url,'win','toolbar=1,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,fullscreen=no,dependent=yes,width=700,height=480'	);
	self.name = "mainWin";
}


function newpopup(popupName, href) {
	var pepopup = popupName;

	if (pepopup == null || pepopup.closed || pepopup.location != href) {
		pepopup = window.open(href, 'peopen','toolbar=no,directories=no,menubar=no,status=no,resizable=yes,scrollbars=yes,width=500,height=450');

	 if (pepopup != null) {
	   pepopup.focus();
	   if (pepopup.opener == null)
	     pepopup.opener = self;
	   }
     }
    else {
		 pepopup.focus();
		 pepopup.document.location.reload();
	}
}

function popupPreview(popupName, href, param){
   var pepopup = popupName;

	if (pepopup == null || pepopup.closed || pepopup.location != href) {
		pepopup = window.open(href+param, 'peopen','toolbar=yes,menubar=yes,scrollbars=yes,width=750,height=500,screenX=50,screenY=50,resizable=yes,status=yes');

	 if (pepopup != null) {
	   pepopup.focus();
	   if (pepopup.opener == null)
	     pepopup.opener = self;
	   }
     }
    else {
		 pepopup.focus();
		 pepopup.document.location.reload();
	}
}

function submitPopupPreview(popupName, href, param){
    document.forms[0].action = document.forms[0].action + "?op=save";
    document.forms[0].submit();
    popupPreview(popupName,href,param);
}

function checkForMoney(sField)
{
		var temp;
		temp = sField.value;

		if( isNaN(temp)  )
		{
			alert( "Please enter a numeric value" );
			sField.value = "";
		}

		if( temp < 0 )
		{
			alert("Please enter a number greater than zero.")
			sField.value = 0;
		}
}

var msgwindow;
function msgPopupWithScroll(strURL, intWidth, intHeight){
         if (msgwindow == null || msgwindow.closed || msgwindow.location != strURL) {
	    msgwindow = window.open(strURL, 'msgopen', 'width=' + intWidth + ',height=' + intHeight + ',screenX=200,screenY=50,left=200,top=50,scrollbars=yes,resizable=yes');
		if (msgwindow != null) {
		  msgwindow.focus();
		  if (msgwindow.opener == null)
		    msgwindow.opener = self;
		}
	  }
	  else {
		msgwindow.focus();
		msgwindow.document.location.reload();
	  }
}

function usopen2(href, i_height, i_width) {
	uspopup = window.open(href, 'usopen2', 'menubar=no,scrollbars=yes,width=' + i_width + ' ,height=' + i_height + ' ,screenX=40,screenY=40,top=40,left=40,resizable=yes,status=no');
	if  (uspopup != null) {
		if  (uspopup.opener == null)
			uspopup.opener = self;
		else
			uspopup.focus();
	}
}

function validate (tempnum) {
    var valid = "0123456789"
    var mynum = eval(tempnum.length);
    var ok = "yes";
    var temp;

    for (var i=0; i<mynum; i++) {
        temp = "" + tempnum.substring(i, i+1);
        if (valid.indexOf(temp) == "-1") ok = "no";
    }

    if (ok == "no") {
          return 0;
    } else {
          return 1;
    }
}

function popCal (parm,opti,contextPath) {

    /// split the opti..
	opieces   = opti.split("/");
    outmonth  = "";
    outyear   = "";
                //if(opti.length==0){
                var dater = new Date();
                outyear=dater.getFullYear();
                outmonth=dater.getMonth();
                //}

	if (opieces.length > 2) {

	    ver1 = validate(opieces[0]);
        if (ver1 != 0) { outmonth = (opieces[0]-1); }
	    ver2 = validate(opieces[2]);
        if (ver2 != 0) { outyear  = opieces[2];     }
    }

	if ((outyear > 0) && (outyear < 100))
	{
		outyear = (outyear < 50)?(eval(outyear) + 2000):(eval(outyear) + 1900);
	}

	var url = contextPath + '/accor/jsp/common/cal.jsp?id=' + parm + "&year=" + outyear + "&month=" + outmonth;

	var winnn = window.open(url, 'cal','toolbar=no,directories=no,menubar=no,status=no,resizable=no,scrollbars=auto,width=200,height=200')
	if (navigator.appName == "Netscape") {
	    winnn.focus();
    }
}

function popCalEx(param1,param2,param3,opti,contextPath) {

    /// split the opti..
	opieces   = opti.split("/");
    outmonth  = "";
    outyear   = "";
                //if(opti.length==0){
                var dater = new Date();
                outyear=dater.getFullYear();
                outmonth=dater.getMonth();
                //}

	if (opieces.length > 2) {

	    ver1 = validate(opieces[0]);
        if (ver1 != 0) { outmonth = (opieces[0]-1); }
	    ver2 = validate(opieces[2]);
        if (ver2 != 0) { outyear  = opieces[2];     }
    }

	if ((outyear > 0) && (outyear < 100))
	{
		outyear = (outyear < 50)?(eval(outyear) + 2000):(eval(outyear) + 1900);
	}

	var url = contextPath + '/accor/jsp/common/cal.jsp?id=' + param1 + '&id2=' + param2 + '&id3=' + param3 + "&year=" + outyear + "&month=" + outmonth;

	var winnn = window.open(url, 'cal','toolbar=no,directories=no,menubar=no,status=no,resizable=no,scrollbars=auto,width=200,height=200')
	if (navigator.appName == "Netscape") {
	    winnn.focus();
    }
}

function popCal1(parm,opti,contextPath) {

    /// split the opti..
	opieces   = opti.split("/");
    outmonth  = "";
    outyear   = "";

    var dater = new Date();
    outyear=dater.getFullYear();
    outmonth=dater.getMonth();

	if (opieces.length > 2) {
	    ver1 = validate(opieces[0]);
        if (ver1 != 0) { outmonth = (opieces[0]-1); }
	    ver2 = validate(opieces[2]);
        if (ver2 != 0) { outyear  = opieces[2];     }
    }

	if ((outyear > 0) && (outyear < 100)) {
		outyear = (outyear < 50)?(eval(outyear) + 2000):(eval(outyear) + 1900);
	}

	var url = contextPath + '/jsp/common/cal1.jsp?id=' + parm + "&year=" + outyear + "&month=" + outmonth;

	var winnn = window.open(url, 'cal','toolbar=no,directories=no,menubar=no,status=no,resizable=no,scrollbars=auto,width=200,height=200');

	if (navigator.appName == "Netscape") {
	    winnn.focus();
    }
}

function goFilter(){

     if(document.forms[0].filterType.value != "defaultSelection"){
		  if(document.forms[0].filterValue.value == ""){
		      alert('Please enter a value to filter by.');
		   }else{
		      doSubmitAction("dofilter");
		   }
	  }else{
         if(document.forms[0].filterValue.value != ""){
			  alert('Please select a filter type.');
           }else{
		      doSubmitAction("dofilter");
		   }
	  }
 }

function resetFilterValue(){

	//if it's "Show All" then clear the filter value box:
	if(document.forms[0].filterType.value == "defaultSelection"){
	   document.forms[0].filterValue.value = "";
	}
}

function popNavi(){

	var winnav;

  	if (top.navwindow)
  	{
  		winnav = top.navwindow;
  		if ((winnav == null) || (winnav.closed == true))
  			top.modelesswin();
  		else
  			winnav.focus();
  	}else{
  		top.modelesswin(); // bug fix for accor, topnavwindow is false - accor doesnt open the nav window on login
  	}
}


function popupvar (link, name, sizew, sizeh) {
     var WinPop = window.open(link, name, "toolbar=no,directories=no,menubar=no,status=no,resizable=no,scrollbars=yes,width=" + sizew + ",height=" + sizeh);
     if (navigator.appName == "Netscape") WinPop.focus();
}

function notepopup(page) {
    var WinPop = window.open(page, 'pop', 'toolbar=no,directories=no,menubar=no,status=no,resizable=yes,scrollbars=yes,width=250,height=250');
}

function isNumberString (InString)
{
	if(InString.length==0)
		return (false);
	RefString="1234567890";
	for (Count=0; Count < InString.length; Count++)
	{
		TempChar= InString.substring (Count, Count+1);
		if (RefString.indexOf (TempChar, 0)==-1)
			return (false);
	}
	return (true);
}

function validateDisplayOrder(orderNamePrefix,orderNameNewPrefix,numberAlert) {
     var itemLength = orderNamePrefix.length;
     var newItemLength = orderNameNewPrefix.length;
     var felements=document.forms[0].elements;
     for(i=0; i < felements.length; i++){
         var getStr = felements[i].name.substring(0,itemLength);
         var getStrNew = felements[i].name.substring(0,newItemLength);
         if((getStr==orderNamePrefix)||(getStrNew==orderNameNewPrefix)){
            var orderValue = document.getElementsByName(felements[i].name)[0].value;
            if((orderValue.length==0) && (getStrNew==orderNameNewPrefix)) {
              //do nothing.
            } else if(!isNumberString(orderValue)){
                alert(numberAlert);
                document.getElementsByName(felements[i].name)[0].focus();
		        return false;
            }
         }
     }
     return true;
}

// Function to check to see if the user presses the enter key to submit the form which starts the search.
function checkForEnter(keyStroke){
	_ns6 = (document.getElementsByTagName) ? 1:0;
	_ie  = (document.all) ? 1:0;

	if (_ie)
		eventChooser = event.keyCode
	else if (_ns6)
		eventChooser = keyStroke.which;

	if (eventChooser == 13)
	{
		doFilter();
	}
}
