// this will be used to save class names when changing to validation-failure indication,
// so we can change back.  If there is no inputsToCheck array, then we do not
// need this.  Since we cannot rely on inputsToCheck being defined, we cannot use
// inputsToCheck.size as the array size.  So we arbitrarily limit to 99.
var inputClasses = new Array(99);

function checkInput(indexIntoValArray) 
{
    var elemId = inputsToCheck[indexIntoValArray][0];
    var elemRegex = inputsToCheck[indexIntoValArray][1];
    var elemRegex2 = inputsToCheck[indexIntoValArray][2];
    var allowEmpty = inputsToCheck[indexIntoValArray][3];
    if ( inputsToCheck[indexIntoValArray].length > 4 )
        var errMsg = inputsToCheck[indexIntoValArray][4];
    
    var isOkay = true;
    
    // The convention you must follow is this:
    // For every field to be validated, you _can_ also provide an element whose
    // ID is the ID of the element to be tested plus "alert_msg".  That element
    // should contain the alert text in an appropriate location (such as just above the
    // element to be tested).  The alert msg should have style="display:none".
    // The alert message element is optional.  I am inclined to not bother with it.
    // The field with the bad input will be highlighted, and the popup will indicate
    // an error.
    
    // You must provide an array of the the inputs to check as a global javascript var.
    // The array is three dimensional, and is called "inputsToCheck".
    // The items in the first  row of the matrix are the item ids to be validated.
    // The items in the second row are regular expressions to check against.
    // The items in the third row are regular expressions to check against.
    // The fourth row, which is optional, contains error text (e.g. "Invalid Data").
    // Both regex's must match.
    // All the items in the array will be checked at submission time (by calling validateInputs() at
    // submit time).  You can also check each
    // item individually when the focus leaves the item by calling checkInput() with
    // the item's index in the array.
    
    // See security_edit.jsp for an example.
    
    var errElemId = elemId + "alert_msg";
    
    // A bit of cheatery - if the err element id ends with _HI and a number,
    // I will replace the HI with a LOW.  This allows us to have just one error
    // row per row of inputs (see select_map_edit.jsp).  Ugly, I know.
    if ( errElemId.indexOf("ValHi") > 0 )
    {
        ind = errElemId.indexOf("ValHi");
        errElemId = errElemId.substring(0, ind) + "ValLo" + errElemId.substring( ind + 5 );
        // alert( errElemId );
    }
    
    var elemErr = document.getElementById(errElemId);
	var elem = document.getElementById(elemId);
    
    // If item is disabled, don't validate
    if ( elem.disabled )
    {
        return true;
    }
    
    // alert( elemRegex + "..." + elemRegex2 );
    
    if ( elem.value == "" ) 
    {
        if ( ! allowEmpty )
            isOkay = false;
    }
    // check regexes if non blank...
    else if ( (elem.value.match(elemRegex) == null) || (elem.value.match(elemRegex2) == null) ) 
    {
		isOkay = false;
    }

    if ( isOkay ) 
    {
        if ( elemErr != null )
            elemErr.style.display = "none";
        // if it has the "failed" look, change it back
        if ( elem.className == "failedValidation" )
        {
            elem.className = inputClasses[indexIntoValArray];
        }
        return true;
    }    
    else
    {
        if ( elemErr != null )
            elemErr.style.display = "block";
        // save current style
        if ( elem.className != "failedValidation" )
        {
            inputClasses[indexIntoValArray] = elem.className;
            elem.className = "failedValidation";
        }
        elem.focus();
        return false;
    }
    
}
 
function validateInputs() 
{

    var errText = "";
    
    // if action is to cancel, don't do this.
    elemAction = document.getElementById("action");

    if ( elemAction && elemAction.value == "Cancel" )
    {
        // alert( "ch2" );
        return true;
    }
    
    var badItems = 0;
    
    var firstBadItem = null;
    
    for ( i = 0 ; i < inputsToCheck.length ; i ++ )
    {
        // alert( inputsToCheck[i][0] +"..." + inputsToCheck[i][1] );
        isGood = checkInput(i);
        if ( ! isGood )
        {
            badItems ++;
            if ( firstBadItem == null )
            {
                firstBadItem = inputsToCheck[i][0];
                if ( inputsToCheck[i].length > 4 && inputsToCheck[i][4] != null && inputsToCheck[i][4] != "" )
                    errText = inputsToCheck[i][4]
            }
        }
        // alert( "ch " + isGood );
    }
    
    if ( errText != "" )
    {
        errText = " - " + errText;
    }    
    
    if ( badItems == 1 )
    {
       nmAlert( "There is an error in the data you entered" + errText + ".  Please correct the highlighted item.", firstBadItem );
       return false;
    }
    else if ( badItems > 1 )
    {
       nmAlert( "There are errors in the data you entered" + errText + ".  Please correct the highlighted items.", firstBadItem );
       return false;
    }
    else
    {
       return true;
    }
    
}


// validate, but stop after one invlalid is found.
function validateInputsUntilFailure() 
{
    var errText = "";
    
    // if action is to cancel, don't do this.
    elemAction = document.getElementById("action");

    if ( elemAction && elemAction.value == "Cancel" )
    {
        // alert( "ch2" );
        return true;
    }
    
    var badItems = 0;
    
    var firstBadItem = null;
    
    for ( i = 0 ; i < inputsToCheck.length ; i ++ )
    {
        // alert( inputsToCheck[i][0] +"..." + inputsToCheck[i][1] );
        isGood = checkInput(i);
        if ( ! isGood )
        {
            badItems ++;
            if ( firstBadItem == null )
            {
                firstBadItem = inputsToCheck[i][0];
                if ( inputsToCheck[i].length > 4 && inputsToCheck[i][4] != null && inputsToCheck[i][4] != "" )
                    errText = inputsToCheck[i][4]
            }            
            break;
        }
        // alert( "ch " + isGood );
    }
    
    if ( errText != "" )
    {
        errText = " - " + errText;
    }
    
    if ( badItems == 1 )
    {
       nmAlert( "There is an error in the data you entered" + errText + ".  Please correct the highlighted item.", firstBadItem );
       return false;
    }
    else if ( badItems > 1 )
    {
       nmAlert( "There are errors in the data you entered" + errText + ".  Please correct the highlighted items.", firstBadItem );
       return false;
    }
    else
    {
       return true;
    }
    
}



//-------------------------------------------------------------------
// Trim functions
//   Returns string with whitespace trimmed
//-------------------------------------------------------------------
function LTrim(str) 
{
	for (var i=0; str.charAt(i)==" "; i++);
	return str.substring(i,str.length);
}
function RTrim(str) 
{
	for (var i=str.length-1; str.charAt(i)==" "; i--);
	return str.substring(0,i+1);
}
function Trim(str) 
{
	return LTrim(RTrim(str));
}
	
//-------------------------------------------------------------------
// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
function isInteger(val) 
{
    // alert( "ch1" );
	for (var i=0; i < val.length; i++) 
    {
		if ( !isDigit(val.charAt(i)) ) 
        { 
           return false; 
        }
	}
	return true;
}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num) 
{
	var string="1234567890";
	if (string.indexOf(num) != -1) 
    {
		return true;
	}
	return false;
}

// This is temporary
function isNonZero(val) 
{

    // alert( "ch1" );
    val = Trim(val);
	for (var i=0; i < val.length; i++) 
    {
		if ( val.charAt(i) != '0' ) 
        { 
           return true; 
        }
	}

	return false;
}

// An "alert" function that presents a nextmark-branded dialog rather than the generic
// alert() dialog.
// The problem with overriding the alert function is this:
// With alert(), I can a) set the focus to a field, then b) call alert().  When
// the alert is acknowledged, the focus will be on the field.  I could correct that
// by setting the focus after I call alert().  But that means changing some code outside
// of this method override.  Another related problem:  I can't reliably test every place that
// uses alert.  In other words, overriding alert() might break something.
// So instead we have this new method called nmAlert() that is available for use.  We
// can phase it in as needed.
// We also have a version that takes an element that should recieve the focus after this
// alert is closed.
//

var ALERT_TITLE = "NextMark Alert";
var ALERT_TITLE_HH = "";
var CONFIRM_TITLE = "Please Confirm";
var ALERT_YES_BUTTON_TEXT = "Yes";
var ALERT_NO_BUTTON_TEXT = "No"
 
// txt - text to display in alert
// badItem - element or its id to get focus after alert is closed (or null)
function nmAlert( txt, badItem ) 
{

    // remove in case close was used and did not remove it (it does now...).
    // alert( $("#alertMessageDiv").attr("id") );
    $("#alertMessageDiv").remove();
    $("body").prepend( '<div id="alertMessageDiv"><p>' + txt + '</p></div>' );
    
    // $(".ui-widget-header").css("background-color", "#00dd00");  // "#f6a828");   
    
    $("#alertMessageDiv").dialog({
        bgiframe: true, 
        autoOpen: false, 
        height: 'auto', 
        modal: true,
        resizable: false,
        show: 'fade',
        // hide: 'clip',
        title: ALERT_TITLE,
        buttons: {
            Ok: function() 
                {
                    $(this).dialog('close');
                    $(this).dialog('destroy');

            if(badItem != null) {
		    if (typeof badItem == 'string')
                        $("#" + badItem).focus();
		    else if (typeof badItem == 'object' && badItem.focus)
			badItem.focus();
            }

                    // remove that div
                    $("#alertMessageDiv").remove();                   
                }
            },
        close: function() 
                {
            	if(badItem != null) {
		    if (typeof badItem == 'string')
                        $("#" + badItem).focus();
		    else if (typeof badItem == 'object' && badItem.focus)
			badItem.focus();
            	}

                    // remove that div
                    $("#alertMessageDiv").remove();                   
                }
            
    });
    
    // I have not figured out how to use the "dialogClass" option.  So I tweaked
    // the colors a bit in jquery-ui.css (.ui-dialog .ui-dialog-titlebar).  But the 
    // default looks good, and might be worth sticking to.
            
    $("#alertMessageDiv").dialog('open');    
    
    // since the upgrade to jqueryui 1.8.10, the dialog is too small in IE.  height:auto is not working.
    if ( $.browser.msie ) 
    {
        var dh = jQuery("#alertMessageDiv").css('height');
        dhInd = dh.indexOf( 'px' );
        if ( dhInd >= 0 )
            dh = dh.substring( 0, dhInd );
        var dhNum = 45 + Number(dh);;
        jQuery("#alertMessageDiv").css('height', dhNum);
        //alert( jQuery("#confirmMessageDiv").css('height') );
    }    
    
    
}

// version for iPhone etc.
// txt - text to display in alert
// badItem - element or its id to get focus after alert is closed (or null)
function nmAlertHH( txt, badItem ) 
{
    // this looks best on iPhone
    alert( txt );
    
    $("#" + badItem).focus();

/******************** trying iwebkit popup...
    $("#alertMessageDiv").remove();
    $("body").prepend( 
        '<div id="alertMessageDiv" class="popup">'
      + '    <div id="fullscreenfix" class="fullscreenfixclosed">'
      + '    </div>'
      + '    <div id="frame" class="confirm_screenclose">'
      + '      <span>popup example</span>'
      + '      <a href="index.html">'
      + '          <span class="gray">Home</span></a><a href="storelist.html"><span class="red">Previous feature</span>'
      + '      </a>'
      + '      <a class="noeffect" onclick="iWebkit.closepopup()">'
      + '           <span class="black">Cancel</span>'
      + '      </a>'
      + '    </div>'
      + '</div>' );
    
    iWebkit.popup();
***********************/    
    
    // $(".ui-widget-header").css("background-color", "#00dd00");  // "#f6a828");   
    
    /*****************
    jquery dialog....

    $(".ui-dialog .ui-dialog-titlebar").css("background-color", "#3A3DB0");
    $(".ui-dialog .ui-dialog-titlebar").css("color", "#3A3DB0");
    $(".ui-dialog .ui-dialog-title").css("background-color", "#3A3DB0");
    $(".ui-dialog .ui-dialog-content").css("background-color", "#D0D0D0");
    
    // remove in case close was used and did not remove it (it does now...).
    $("#alertMessageDiv").remove();
    $("body").prepend( '<div id="alertMessageDiv"><p>' + txt + '</p></div>' );
    
    
    $("#alertMessageDiv").dialog({
        bgiframe: true, 
        autoOpen: false, 
        height: 'auto', 
        width: 220,
        modal: true,
        resizable: false,
        show: 'fade',
        // hide: 'clip',
        title: ALERT_TITLE_HH,
        buttons: {
            Ok: function() 
                {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    if ( badItem != null )
                        $("#" + badItem).focus();
                    // remove that div
                    $("#alertMessageDiv").remove();                   
                }
            },        
        close: function() 
                {
                    if ( badItem != null )
                        $("#" + badItem).focus();
                    // remove that div
                    $("#alertMessageDiv").remove();                   
                }

    });
    
    // I have not figured out how to use the "dialogClass" option.  So I tweaked
    // the colors a bit in jquery-ui.css (.ui-dialog .ui-dialog-titlebar).  But the 
    // default looks good, and might be worth sticking to.
            
    $("#alertMessageDiv").dialog('open');    

    **********************/
    
}



var SaveTop = 0;
// nmConfirm - a modal dialog with a yes and no button
// params:
// txt - the text to display in the box - usually in the form of a question, such as "Are you sure you want to delete such and such?
// txt2 - a second line of text, or null if you don't need it.
// formName - the name of the form we are acting from
// actionToTake - whatever is here will be put in form.action.  It will be done if "Yes" is clicked.
function nmConfirm( txt, formName, actionToTake, txt2 ) 
{
  
    // remove in case close was used and did not remove it (it doesn't - but the buttons do).
    // alert( $("#confirmMessageDiv").attr("id") );
    $("#confirmMessageDiv").remove();

    var divTag = '<div id="confirmMessageDiv">'
                  + '<p>' + txt + '</p>';
    if ( txt2 != null )
        divTag += '<p>' + txt2 + '</p>';
    divTag += '</div>';
    
    $("body").prepend( divTag );
    
    jQuery("#confirmMessageDiv").dialog({
        bgiframe: true, 
        autoOpen: false, 
        height: 'auto', 
        modal: true,
        resizable: false,
        show: 'fade',
        // hide: 'clip',
        title: CONFIRM_TITLE,
        buttons: {
            No: function() 
                {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    // remove that div
                    $("#confirmMessageDiv").remove();                   
                },            
            Yes: function() 
                {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    // remove that div
                    $("#confirmMessageDiv").remove();
                    document.forms[formName].action=actionToTake;document.forms[formName].submit();;
                   
                }
                
            }
    });
    
    // I have not figured out how to use the "dialogClass" option.  We could tweak
    // the colors a bit in jquery-ui.css (.ui-dialog .ui-dialog-titlebar).  But the 
    // default looks good, so let's stick with them.  If we do want to change them, Themeroller
    // is the thing to use, they say.
            
    $("#confirmMessageDiv").dialog('open');        
    
    // since the upgrade to jqueryui 1.8.10, the dialog is too small in IE.  height:auto is not working.
    if ( $.browser.msie ) 
    {
        var dh = jQuery("#confirmMessageDiv").css('height');
        dhInd = dh.indexOf( 'px' );
        if ( dhInd >= 0 )
            dh = dh.substring( 0, dhInd );
        var dhNum = 45 + Number(dh);;
        jQuery("#confirmMessageDiv").css('height', dhNum);
        //alert( jQuery("#confirmMessageDiv").css('height') );
    }    

}

//nmConfirm2 - a modal dialog with a yes and no button.  This one does not do a form submit.
//params:
//txt - the text to display in the box - usually in the form of a question, such as "Are you sure you want to delete such and such?
// actionToTake - javascript function to call if "yes".  It will be done if "Yes" is clicked.
// actionParam1, 2 - parameters to actionToTake()
function nmConfirm2( txt,actionToTake, actionParam1, actionParam2 ) 
{

    // remove in case close was used and did not remove it (it doesn't - but the buttons do).
    // alert( $("#confirmMessageDiv").attr("id") );
    $("#confirmMessageDiv").remove();
    
    $("body").prepend( '<div id="confirmMessageDiv"><p>' + txt + '</p></div>' );
    
    jQuery("#confirmMessageDiv").dialog({
        bgiframe: true, 
        autoOpen: false,
        height: 'auto', 
        modal: true,
        resizable: false,
        show: 'fade',
        // hide: 'clip', - do not use any hide effect! It messes things up, re focus, resizing, etc.
        title: CONFIRM_TITLE,        
        buttons: {
            Yes: function() 
                {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    // remove that div
                    $("#confirmMessageDiv").remove();
                    actionToTake(actionParam1, actionParam2);
                   
                },
            No: function() 
                {
                    $(this).dialog('close');
                    $(this).dialog('destroy');
                    // remove that div
                    $("#confirmMessageDiv").remove();                   
                }                
                
            }
    });
        
    // I have not figured out how to use the "dialogClass" option.  We could tweak
    // the colors a bit in jquery-ui.css (.ui-dialog .ui-dialog-titlebar).  But the 
    // default looks good, so let's stick with them.  If we do want to change them, Themeroller
    // is the thing to use, they say.
            
    $("#confirmMessageDiv").dialog('open');        

    // since the upgrade to jqueryui 1.8.10, the dialog is too small in IE.  height:auto is not working.
    if ( $.browser.msie ) 
    {
        var dh = jQuery("#confirmMessageDiv").css('height');
        dhInd = dh.indexOf( 'px' );
        if ( dhInd >= 0 )
            dh = dh.substring( 0, dhInd );
        var dhNum = 45 + Number(dh);;
        jQuery("#confirmMessageDiv").css('height', dhNum);
        //alert( jQuery("#confirmMessageDiv").css('height') );
    }
}



// THIS is not ready - the idea was to put a message up while doing a very long client-side validation.
// 
function nmInfo( txt ) 
{

    
}

// The main concern here is to distinguish IE from FireFox, and pre-7.0 IE from 7.x.
// (because we only support IE and FF).

function EarlyIE()
{
  
  var agt = navigator.userAgent.toLowerCase();
  var is_op = (agt.indexOf("opera") != -1);
  var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;    
    
  if ( is_ie ) 
  {
    var v = gff(agt, "msie ");
    // alert (" v is " + v );
    if ( (v == null) || (v < 7) ) 
        return true;
  }
  return false;

}

function AnyIE()
{
  var agt = navigator.userAgent.toLowerCase();
  var is_op = (agt.indexOf("opera") != -1);
  var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;    
    
  if ( is_ie ) 
  {
      // alert( "is ie " + agt );
      return true;
  }
  return false;

}

function gff(str, pfx) 
{
    var i = str.indexOf(pfx);
    if (i != -1) 
    {
        var v = parseFloat(str.substring(i + pfx.length));
        if (!isNaN(v))
        {
            return v;
        }
    }
    return null;
}

