/**
    Author      :       Bhaskara K

    Date        :       4th June 2001

    Comment     :       This file will have all the common javascript related
                        functions that would be needed in many cases.

    Project     :       CoreCommonScript FrameWork
*/


/**
    function to replace a given character or string in the source string with
    another character or string

    input:
            sSrcString - source string to replace the specified string or char.
            sFindString - string to find with in the source string.
            sReplaceString - to replace the above found string with this.
    output:
            String with the new string or char at the old one that has been
                found in the source string
*/

function replace(sSrcString, sFindString, sReplaceString)
{
    var sLocalSrc   = sSrcString;
    var iIndex      = 0;
    var iNext       = 0;
    while((iIndex = sLocalSrc.indexOf(sFindString,iNext)) >= 0)
    {
        sSrcString = sSrcString.substring(0,iIndex) + sReplaceString + sSrcString.substring(iIndex+sFindString.length,sSrcString.length);
        sLocalSrc = sLocalSrc.substring(0,iIndex) + sReplaceString + sLocalSrc.substring(iIndex+sFindString.length,sLocalSrc.length);
        iNext = iIndex + sReplaceString.length;if (iNext >= sLocalSrc.length);
        {
            break;
        }
    }
    return sSrcString;
}


/**
    function that will remove the leading and ending spaces in the
    input string data.

    input   : String data has to be passed as input
    output  : String that is formatted
*/
function trim(sSrcString)
{
    if (sSrcString == null) return "";
    var iSrcLength  = sSrcString.length;
    var iIndex      = 0;

    while(iIndex < iSrcLength)
    {
        if(sSrcString.charAt(iIndex)!=" ")
            break;
        iIndex++;
    }

    sSrcString=sSrcString.substring(iIndex,iSrcLength);
    iSrcLength      = sSrcString.length;
    while(iSrcLength > 0)
    {
        if(sSrcString.charAt(iSrcLength-1) !=" ")
            break;
        iSrcLength--;
    }
    sSrcString      = sSrcString.substring(0,iSrcLength);

    return sSrcString;
}


/**
    function to validate the email attribute.
    input:
            sEmail - string email that has to be validated for proper values
    output:
            boolean - true in case the email id is valid
            false in case the email is not valid
*/

function validateEmail(sEmail)
{
    var sInvalidEmailExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

    if (!isValid(sInvalidEmailExp,sEmail))
    {
        return false
    }
    return true;
}


/**
    function that will be used by validateEmail to check if the format
    of the email is proper or not.

    input:
            sPattern - string of the pattern that should not exists.
            sSrcString - above mentioned pattern should not exist in this string
    output:
            boolean - that says whether the input source has the mentioned
            pattern or not.
*/
function isValid(sPattern, sSrcString)
{
    return sPattern.test(sSrcString)
}



/**
    function that will check if the input data is number or not?
    this function is written in line with isNan, but this is
    browser compatible.

    input:
            sSrsString - that has to be checked if its number.
    output:
            boolean - true in case the string is not a number
            false if the string is a number.
*/
function isNotNumeric(sSrcString)
{
    var iAlphaCtr   = 0;
    var sArwPos     = "";
    var sFound      = "";
    var sSpace      = "";
    var sTempStr    = "";
    var sNumToCheck = "0123456789.";

    for (var i=0;i<sSrcString.length;i++)
    {
        sTempStr    = sSrcString.substring(i,i+1)
        if (sNumToCheck.indexOf(sTempStr) < 0)
        {
            iAlphaCtr++;
            sFound+=" "+sTempStr;
            sSpace+=sTempStr;
            sArwPos+="^";
        }
        else
        {
            sArwPos+="_";
        }
    }
    if (iAlphaCtr!=0)
    {
        if (sSpace.indexOf(" ")>-1)
        {
            sFound+=" and a space";
        }
        return true;
    }
    return false;
}


/**
    function that will check if the input string is within
    a to z or 0 to 9.

    input:
            sSrcString - string that has to be checked falls with the alpha numeric range
    output:
            boolean - true in case the input is not a alpha numeric string
            false if its alpanumeric
*/
function isNotAlphabetic(sSrcString)
{
    var iAlphaCtr           = 0;
    var sArwPos             = "";
    var sFound              = "";
    var sSpace              = "";
    var sTempStr            = "";
    var sAlphaNumToCheck    = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i=0;i<sSrcString.length;i++)
    {
        sTempStr            = sSrcString.substring(i,i+1)
        if (sAlphaNumToCheck.indexOf(sTempStr) < 0)
        {
            iAlphaCtr++;
            sFound+=" "+sTempStr;
            sSpace+=sTempStr;
            sArwPos+="^";
        }
        else
        {
            sArwPos+="_";
        }
    }
    if (iAlphaCtr!=0)
    {
        if (sSpace.indexOf(" ") > -1)
        {
            sFound+=" and a space";
        }
        return true;
    }
    return false;
}


/**
    function that checks if the input number is a leap year

    input:
            iYear - to check whether this year is leap year or not.
    output:
            boolean - true in case iYear is found to be leap year
            false if its not.
*/
function isLeap(iYear)
{
    var iFlag = 0
    if (iYear % 4 == 0)
      iFlag = 1
    return iFlag
}


/**
    Function that moves options from one selection box (list box) to another
    removes the all selected options from one combo box and adds them to the second list box

    input:
            fromCombo and toCombo in terms of formName.ElementName.
    output:
            none
*/

function MoveElements(FromCombo,ToCombo)
{


        var to_remove_counter=0; //number of options that were removed (num selected options)
        var iSelectedcount=0;
        var iExistingcount=0;


        for (var i=0;i<FromCombo.options.length;i++)
        {
            if (FromCombo.options[i].selected==true)
            {
                iSelectedcount++;
            }
        }

        //move selected options to right select box (to)
        for (var i=0;i<FromCombo.options.length;i++)
        {
            if ((FromCombo.options[i].selected == true) && (FromCombo.options[i].value != 0))
            {
                var addtext=FromCombo.options[i].text;
                var addvalue=FromCombo.options[i].value;
                ToCombo.options[ToCombo.options.length]=new Option(addtext,addvalue);
                FromCombo.options[i].selected=false;
                ++to_remove_counter;
            }
            else
            {
                FromCombo.options[i-to_remove_counter].selected=false;
                FromCombo.options[i-to_remove_counter].text=FromCombo.options[i].text;
                FromCombo.options[i-to_remove_counter].value=FromCombo.options[i].value;
            }
        }

        //now cleanup the last remaining options
        var numToLeave=FromCombo.options.length-to_remove_counter;
        for (i=FromCombo.options.length-1;i>=numToLeave;i--)
        {
            FromCombo.options[i]=null;
        }

    return true;
}

/**
* Function which will check all the checkboxes.
*/
function SelectAllFromCheck(FromCheck)
{

    if (FromCheck.length>1)
    {
        for (var i=0;i<FromCheck.length;i++)
        {
            FromCheck[i].checked=true;
        }
    }
    else
    {
        FromCheck.checked=true;
    }
     return true;
}

/**
* Function which will Deselect all  the  checkboxes.
*/
function DeSelectAllFromCheck(FromCheck)
{

    if (FromCheck.length>1)
    {
        for (var i=0;i<FromCheck.length;i++)
        {
            FromCheck[i].checked=false;
        }
    }
    else
    {
        FromCheck.checked=false;
    }
     return true;
}


/**
* Function which will select all the options in
* a list box.
*/

function SelectAllFromList(combo)
{
   if(combo!=null)
   {
    for (var i=0;i<combo.options.length;i++)
    {

        combo.options[i].selected=true;
    }
   }
}

/**
    Used to update the button name that has been clicked
    to a hidden variable that will help in doing the validations
*/

function updateActionName(inForm, sAction)
{
    inForm.actionname.value = sAction;
}


function doActivity()
{
    document.forms[0].submit();
}

/**
    To implement the radio button kind of feature using
    two check boxes.
*/

function doUnCheck(PeerCheckBox)
{
    PeerCheckBox.checked = false;
}

/**
* function  to check atleast one check box is checked.
* returns true if checked,false if not.
*/
function validateCheckBox(index,obj)
{
    if(obj)
    {
        if (obj.length>1)
        {
            for (var i=0;i<obj.length;i++)
            {
                //If atleast one is checked,
                if(obj[i].checked==true)
                return true;
            }
        }
        else
        {
            if (!obj.checked)
            {
                alert(sMessageArr[index]);
                return false;
            }
            else
            {
                return true;
            }
        }
        alert(sMessageArr[index]);
        return false;
    }
    return true;
}


/**
Useful for the multi select listboxes.. this will help to select
all the items in the listbox
*/
function selectAllFromList(combo)
{
  if(combo!=null)
  {
    for (var i=0;i<combo.options.length;i++)
    {
        combo.options[i].selected=true;
    }
  }

}
/**
* to check for float/double
* returns true if float
*/
function isFloat(sSrcString)
{
    var iAlphaCtr   = 0;
    var sArwPos     = "";
    var sFound      = "";
    var sSpace      = "";
    var sTempStr    = "";
    var sNumToCheck = ".0123456789";

    for (var i=0;i<sSrcString.length;i++)
    {
        sTempStr    = sSrcString.substring(i,i+1)
        if (sNumToCheck.indexOf(sTempStr) < 0)
        {
            iAlphaCtr++;
            sFound+=" "+sTempStr;
            sSpace+=sTempStr;
            sArwPos+="^";
        }
        else
        {
            sArwPos+="_";
        }
    }
    if (iAlphaCtr!=0)
    {
        if (sSpace.indexOf(" ")>-1)
        {
            sFound+=" and a space";
        }
        return false;
    }
    return true;
}


/** function which checks and un checks all the check boxes
by checking single check box
*/

function SelectUnSelectAll( my_form, field_name )
{
    if(my_form.clickcontrol.checked)
    {
       flag = true;
    }
    else
    {
       flag = false;
    }
    len     =       my_form.elements.length;
    var     index   =       0;
    for( index=0; index < len; index++ )
    {
        if( my_form.elements[index].name == field_name )
        {
            my_form.elements[index].checked=flag;
        }
    }
}

/**
This function will check all the checkboxes that are in
between 2 checked ones
*/

function checkRange(inFormCheckBox)
{
    var iChecked = 0;
    var iFirstCheck = 0;
    var iSecondCheck = 0;
    for (i=0;i<inFormCheckBox.length;i++)
    {
        if (inFormCheckBox[i].checked)
        {
            iChecked = iChecked + 1;
            if (iChecked == 2)
            {
                iSecondCheck = i;
                break;
            }
            iFirstCheck = i;
        }
    }

    for (i=iFirstCheck;i<iSecondCheck;i++)
    {
        inFormCheckBox[i].checked = true;
    }
}


/** Code to validate the date **/

/**

URL -- http://javascript.internet.com/forms/val-date.html
The code below needs some changes, as of now it shows some default
error message and also has some additional codes to compare 2 dates

**/

function checkdate(objName) {
var datefield = objName;
if (chkdate(objName) == false) {
datefield.select();
alert("That date is invalid.  Please try again.");
datefield.focus();
return false;
}
else {
return true;
   }
}
function chkdate(objName) {
var strDatestyle = "US"; //United States date style
//var strDatestyle = "EU";  //European date style
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = "Jan";
strMonthArray[1] = "Feb";
strMonthArray[2] = "Mar";
strMonthArray[3] = "Apr";
strMonthArray[4] = "May";
strMonthArray[5] = "Jun";
strMonthArray[6] = "Jul";
strMonthArray[7] = "Aug";
strMonthArray[8] = "Sep";
strMonthArray[9] = "Oct";
strMonthArray[10] = "Nov";
strMonthArray[11] = "Dec";
strDate = datefield.value;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
if (strYear.length == 2) {
strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
}
}
else {
if (intday > 28) {
err = 10;
return false;
}
}
}
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}
return true;
}

function LeapYear(intYear)
{
    if (intYear % 100 == 0)
    {
        if (intYear % 400 == 0)
        {
            return true;
        }
    }
    else
    {
        if ((intYear % 4) == 0)
        {
            return true;
        }
    }
    return false;
}

function doDateCheck(from, to) {
if (Date.parse(from.value) <= Date.parse(to.value)) {
alert("The dates are valid.");
}
else {
if (from.value == "" || to.value == "")
alert("Both dates must be entered.");
else
alert("To date must occur after the from date.");
   }
}

/** Code to validate the date **/


/*
    This function is for date validation assuming the month
    and day has been passed with dropdowns and the year being a
    text box

    inputs:
        html elements for Month, Day & Year are the inputs
*/
function validateDate(Month, Day, Year)
{
    if (Year.value.length != 4)
    {
        alert("Enter 4 digit year");
        return false;
    }
    var intMonth = Month.options[Month.selectedIndex].value;
    var intday = Day.options[Day.selectedIndex].value;
    var intYear = Year.value;

    //this validation will not be used in this case -- but kept here for future use
    if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
    {
        alert("Date cannot be less than 1 & greater than 31");
        return false;
    }

    if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
    {
        alert("Date cannot be greater than 30");
        return false;
    }

    if (intMonth == 2)
    {
        if (intday < 1)
        {
            err = 8;
            return false;
        }

        if (LeapYear(intYear) == true)
        {
            if (intday > 29)
            {
                alert("Date cannot be greater than 29");
                return false;
            }
        }
        else
        {
            if (intday > 28)
            {
                alert("Date cannot be greater than 28");
                return false;
            }
        }
    }
    return true;
}


function gotoURL(SURL)
{
    window.name = "self";
    window.open(SURL, "self");
}


/**
This function will bring up a new page
*/




function MM_goToURL()
{ //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}



/**
This function will bring up a new window
*/


function MM_openBrWindow(theURL,winName,features)
{ //v2.0
  window.open(theURL,winName,features);
}



/*
    This is to move up the combo box item up by one index position
*/
function moveUp(combo)
{
    i=combo.selectedIndex;
    if (i>0)
    {
        swap(combo,i,i-1);
        combo.options[i-1].selected=true;
        combo.options[i].selected=false;
    }
}

/*
    This is to move down the combo box item up by one index position
*/
function moveDown(combo)
{
    i=combo.selectedIndex;
    if ((i>=0) && (i<combo.options.length-1))
    {
        swap(combo,i+1,i);
        combo.options[i+1].selected=true;
        combo.options[i].selected=false;
    }
}


/*
    This function will swap the element between the two given
    locations of the combox box index
*/
function swap(combo, iFromIndex, iToIndex)
{
    var STemp = combo.options[iFromIndex].value;
    var STempText = combo.options[iFromIndex].text;

    combo.options[iFromIndex].value = combo.options[iToIndex].value;
    combo.options[iFromIndex].text = combo.options[iToIndex].text;

    combo.options[iToIndex].value = STemp;
    combo.options[iToIndex].text = STempText;
}


/*
    Added on : 2nd May 2002

    This function will validate all the mandatory fields that are passed in as parameter
    to this function on any given form.
    Currently its working for select, textbox & textarea -- need to enhance this for radio button
    and checkbox selection!!
*/
function formCheck(inForm, fieldRequired, fieldDescription)
{
    //1) Enter name of mandatory fields
    //var fieldRequired = Array("FirstName", "LastName");
    //2) Enter field description to appear in the dialog box
    //var fieldDescription = Array("First Name", "Last Name");
    //3) Enter dialog message

    var alertMsg = "Please complete the following fields:\n";

    var l_Msg = alertMsg.length;

    for (var i = 0; i < fieldRequired.length; i++)
    {
        var obj = inForm.elements[fieldRequired[i]];
        if (obj)
        {
            switch(obj.type)
            {
                case "select-one":
                    if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == "")
                    {
                        alertMsg += " - " + fieldDescription[i] + "\n";
                    }
                    break;
                case "select-multiple":
                    if (obj.selectedIndex == -1)
                    {
                        alertMsg += " - " + fieldDescription[i] + "\n";
                    }
                    break;
                case "text":
                case "textarea":
                    if (obj.value == null || trim(obj.value) == "")
                    {
                        alertMsg += " - " + fieldDescription[i] + "\n";
                    }
                    break;
                default:
                    if (obj.value == null || trim(obj.value) == "")
                    {
                        alertMsg += " - " + fieldDescription[i] + "\n";
                    }
            }
        }
    }

    if (alertMsg.length == l_Msg)
    {
        return true;
    }else
    {
        alert(alertMsg);
        return false;
    }
}
/**
* Global function  to check atleast one check box is checked.
* returns true if checked,false if not.
*/
function validateGlobalCheckBox(index,obj)
{
    if(obj)
    {
        if (obj.length>1)
        {
            for (var i=0;i<obj.length;i++)
            {
                //If atleast one is checked,
                if(obj[i].checked==true)
                return true;
            }
        }
        else
        {
            if (!obj.checked)
            {
                alert(sGlobalMessageArr[index]);
                return false;
            }
            else
            {
                return true;
            }
        }
        alert(sGlobalMessageArr[index]);
        return false;
    }
    return true;
}


/**
    Function that moves options from one selection box (list box) to another
    removes the all selected options from one combo box and adds them to the second list box

    input:
            fromCombo , toCombo and conditionObj in terms of formName.ElementName.
    output:
            none
*/

function MoveElementsFromDistinctTypes(FromCombo,ToCombo,conditionValue)
{
    //cleanup the ToCombo options first
    if(ToCombo.options != null)
    {
        var numToLeave=ToCombo.options.length;
        for (i = numToLeave; i >= 1 ; i--)
        {
            ToCombo.options[i]=null;
        }
    }
    for (var i=0, j=0;i<FromCombo.options.length;i++)
    {
        if (FromCombo.options[i].checkValue == conditionValue)
        {
            ToCombo.options[j++]=new Option(FromCombo.options[i].text,FromCombo.options[i].value);
        }
    }
    return true;
}


function highlightRecord(currentTRObject, previousTRObject, currentBGColorValue, previousBGColorValue)
{
    if(currentBGColorValue == null || currentBGColorValue == '')
    {
        currentBGColorValue = '#EFEEED';
    }

    if(previousBGColorValue == null || previousBGColorValue == '')
    {
        previousBGColorValue = '#ffffff';
    }

    if(previousTRObject != null)
    {
        previousTRObject.style.backgroundColor = previousBGColorValue;
    }

    if(currentTRObject != null)
    {
        currentTRObject.style.backgroundColor = currentBGColorValue;
    }
}


function differenceInDays(StartDate, EndDate)
{
    return (1 + (((((EndDate - StartDate) / 1000) / 60) / 60 )/ 24) );
}

function disableObjectAndSubmit(obj)
{
    if (eval(obj))
    {
        obj.disabled = true;
        if (eval(obj.form))
            obj.form.submit();
    }
}

function checkDates(value1,value2)
{
    var date1 = new Date(value1);
    var date2 = new Date(value2);

    return date1 - date2;
}

function checkPasswordBlank(){
    if (eval(document.Login.loginname))
    {
        if(document.Login.loginname.value==''){
        alert("Login field should not be blank.");
        return false;
        }
    }

    if (eval(document.Login.password))
    {
        if(document.Login.password.value==''){
        alert("Password field should not be blank.");
        return false;
        }
    }


}

/**
 * DHTML email validation script. introduced in resend confirmation
 *
 */

function echeck(str) {
		var at="@";
		var dot=".";
		var lat=str.indexOf(at);
		var lstr=str.length;
		var ldot=str.indexOf(dot);
		
		if (str.indexOf(at)==-1){
			return false;
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr-1){
		  // alert("Invalid E-mail ID");
		   return false;
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr-1){
		    //alert("Invalid E-mail ID");
		    return false;
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid E-mail ID");
		    return false;
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail ID");
		    return false;
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail ID");
		    return false;
		 }
		
		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail ID");
		    return false;
		 }

 		 return true	;				
	}


//used for validating Partner site login form
function validateLoginForm()
{
	if (eval(document.SendMe.accountid))
    {
        if(document.SendMe.accountid.value==''){
        alert("Account field should not be blank.");
        return false;
        }
    }
    if (eval(document.SendMe.loginname))
    {
        if(document.SendMe.loginname.value==''){
        alert("Login field should not be blank.");
        return false;
        }
    }

    if (eval(document.SendMe.password))
    {
        if(document.SendMe.password.value==''){
        alert("Password field should not be blank.");
        return false;
        }
    }
}