var gScriptSeq = 0; 
var gBrowser = setBrowser();
var thisTop = window;

function getPath(cType,cFile) {   
  var cPath;
  var cFileCaps = cFile.toUpperCase();
  var cHiResImagesCaps = ""; // gHiResImages.toUpperCase();

  // Set cPath to either the default path or the Developers work dir
  if (cType == 'img') {
    if ((cHiResImagesCaps.indexOf('^' + cFileCaps + '^') > 0) && (hiResScreen == 'yes')) {
         cPath = gDfltImgPath + 'HI';
    } else {
         cPath = gDfltImgPath;
    }
  } else {
    if (cType == 'wo') {
      cPath = '';
    } else {
      if (cType == 'htm') {
        cPath = gDfltHtmPath;
      }
    }
  } 

  // String together the full path + file name for either WO,HTM,NSHTM, or IMG
  if (cType == 'wo') { 
    return gProtocol + gHost + gMessenger + cPath + cFile;
  } else {
    return gProtocol + gHost + cPath + cFile;        
  } 
} // getPath()


function canRun(iSeq) {
  if (iSeq > gScriptSeq) {
    gScriptSeq = iSeq; 
    return true; 
  } 
  else return false; 
} 

// Sumbit the updateFrame to the queryFrame
function submitWO(cHtmDoc,cWo,cRequest,cWOParams,submitForm) {
    // Parse just the htm doc name from the full url. 
    //alert('submit wo');
    var cUrl = "" + cHtmDoc + ""
    var urlArray = cUrl.split("/")
    cHtmDoc = urlArray[urlArray.length - 1]

    // String the Current htm doc, and any params together.
    // This string, plus the WebObj will be submitted as an action of the updateForm (target DataFrame)
    
    var cURL = thisTop.getPath('wo',cWo);

    cURL = cURL + "?Current=" + cHtmDoc;
    cURL = cURL + "&Request=" + cRequest;
    cURL = cURL + "&scriptSeq=" + (gScriptSeq + 1);

    numParams = submitWO.arguments.length
    if (numParams > 0) {
        for (c=3; c < numParams; c++) {
            cURL = cURL + "&" + submitWO.arguments[c]
        }
    }        

    if (submitForm == null)
      submitForm = thisTop.updateFrame.document.updateForm;
    
    // Set the action of updateForm to fire the WebObj plus the htm doc and any params, then submit.
    submitForm.action=cURL;

    //alert("Submitting:\n" + thisTop.updateFrame.updateForm.action);
    //alert(thisTop.updateFrame.document.updateForm.action);    
    submitForm.submit();
}
function showCallbackError(name) {
  thisTop.showError('error','Function Callback Error','<tr><td>Unable to complete request, callback function [' + name + '] is no longer available.  You may have clicked on another link before this request finished processing</td></tr>');
}

function pleaseWait(frameObj, sw, code) {
  if (sw == "on") {
    frameObj.document.location.replace(thisTop.pathToCommon + "pleaseWait.html");
    //alert("Please wait turned on: " + frameObj.document.location);
    if (code != null && code != '')
      eval(code);
  }
  else if (sw == "off") {
    frameObj.document.location.replace(thisTop.pathToCommon + "blank.html");
    //alert("Please wait turned OFF: " + frameObj.document.location);
    if (code != null && code != '')
      eval(code);
  }
  else 
    frameObj.document.location.replace(sw);
}

// Used by encodeString
function toHex(dec) {
   var i = 0;
   var j = 0;
   var result = "%";
   var hexChars = "0123456789ABCDEF";

   if (dec > 255)
      return null;

   i = dec % 16;
   j = (dec - i) / 16;
   result += hexChars.charAt(j);
   result += hexChars.charAt(i);
   return result;
}
function encodeString (theString) {
  // This function will convert all special chars to their HEX value.
  // It can be used to encode params that are passed to SubmitWo.
  var cRtn = ''
  var j = theString.length
  for (i=0; i < j; i++) {
    var x = theString.charCodeAt(i)

    // These chars can cause problems when sending back to a WebObj via SubmitWo
    //           # 35       & 38       + 43       = 61       \ 92       { 124       } 126
    cRtn += ( x == 35 || x == 38 || x == 43 || x == 61 || x == 92 || x == 124 || x == 126 )
         ? toHex(x)
         : theString.substr(i,1)     
  }
  return cRtn
}

// ***************************************************
// Generic Form Data Validation
// ***************************************************
function validateForm(form,errWindowName,errTitle) {
  var valid = true;
  var fldError = "";
  var errMsg = "<tr><td>";
  for (var i=0;i<form.length;i++) {
  
    var e = form.elements[i];
    fldError = validateElement(e,"quiet");
    if (fldError != "") {
      errMsg += "<b>"
      if (e.label)
        errMsg += e.label;
      else
        errMsg += e.name
      errMsg += "</b> " + fldError + "</td></tr><tr><td>";

      fldError = "";
     
      if (gBrowser.layerSupport) 
      {//stupid netscape will not change the background colors of form elements
       	if (e.layer != null)
        {		
            e.layer.bgColor = "lightgrey";
        }
      }
      else if (gBrowser.allSupport)
        e.style.backgroundColor = "lightgrey";
      if (valid){
        if (e.type == "text")
          eval("e.select();"); // place cursor at first field with an error
        valid = false;
      }
    } 
    else {
      if (gBrowser.layerSupport) {
               if (e.layer != null && e.layer.bgColor == "lightgrey")
            e.layer.bgColor = "white";
      }
      else if (gBrowser.allSupport){
        if (e.style.backgroundColor == "lightgrey")
          e.style.backgroundColor = "white";
      }
    }
  }
  if (!valid) {
    errMsg += "</td></tr>";
    showError(errWindowName,errTitle,errMsg);
  }
  return valid;
} // validateForm


function isGreater(greaterfield,lesserfield)
{
	var greaterValue = parseInt(greaterfield.value); 
	var lesserValue = parseInt(lesserfield.value);
	var valid = true;

	if (greaterValue < lesserValue)
	{
		var ErrorMessage = greaterfield.label + " must be greater than or equal to " + lesserfield.label;
		showError("ErrorMessage","ErrorMessage",ErrorMessage);
		valid = false;
	}
	else
	{
		if (greaterValue >= lesserValue)
		valid = true;
	}
	return valid;
}//ends is Greater

function dateGreaterThanToday(datefield,currentDateField)
{
	var todaysDateVal = new Date(currentDateField.value);
	var datefieldVal = new Date(datefield.value);
	var valid = true;
	
	if (datefieldVal <= todaysDateVal) 
	{	
		var ErrorMessage = "<b>Approximate Start Date</b> must be greater than today's date";
		showError("ErrorMessage","ErrorMessage",ErrorMessage);
		valid = false;
	}
	else if (datefieldVal > todaysDateVal)
	{	
		valid = true;
	}
	return valid;
}//ends is dateGreaterThanToday


function showError(windowName,title,eMessage) {
  if (eMessage == null || eMessage == '') return false;

  var coords = "";

  if (gBrowser.IE)
    coords = "";
  else
    coords = ",screenX=" + window.screenX + ",screenY=" + window.screenY;

  if (eMessage.substring(1,1) != "<") {
    eMessage = "<tr><td>" + eMessage + "</td></tr>";
  }
  var ew = window.open("",windowName,"height=200,width=300,resizable=yes,scrollbars=yes" + coords,false);
  ew.document.open();
  ew.document.writeln("<html><head><title>Notification</title></head><body><table border=0><th>" + title + "</th>" + eMessage + "</table></body></html>");
  ew.document.close();
  ew.focus();
  return true;
}

function clearFormErrors(f) {
  for (var i=0;i<f.length;i++) {
    if (gBrowser.layerSupport) {
      if (f.elements[i].layer != null && f.elements[i].layer.bgColor == "lightgrey")
        f.elements[i].layer.bgColor = "white";
    }
    else if(gBrowser.allSupport){
      if (f.elements[i].style.backgroundColor == "lightgrey")
        f.elements[i].style.backgroundColor = "white";
    }
    else break;
  }
}

function validateElement(e,mode) {
  var fldError = "";
  if (!validateLength(e))
    fldError = "is too short.  It must be at least " + e.minLength + " characters long.";
  else if (!validateType(e))
    fldError = "has invalid characters";
  else if (!validateRequired(e))
    fldError = "is required";
  else if (!validateMaxValue(e))
    fldError = "is too large.  It has a maximum value of: " + e.maxValue;
  else if (!validateMinValue(e))
    fldError = "is too small.  It has a minimum value of: " + e.minValue;
  else if (e.validate) {
    fldError = eval(e.validate);
  }
  if (mode == "quiet")
    return fldError;
  else if (mode == "showError") {
   // alert(e.label + " " + fldError);
    return false;
  }
  else if (fldError != "")
    return false;
  else
    return true;
}

function validateType(element) {
  if (!element.dataType) return true;

  if (element.value == "") return true;
  if (element.dataType == "date")
    return validateDate(element.value);
  else if (element.dataType == "int") {
    return validateInt(element.value);
  }
  else if (element.dataType == "dec")
    return validateDec(element.value);
  else if (element.dataType == "phone")
    return validatePhone(element);
  else if (element.dataType == "email")
  	return validateEmail(element);


  return true;
}

function validateLength(element) {
  if (element.value == "") return true;
  if (!element.minLength) return true;
  var s = new String(element.value);
  if (s.length < element.minLength) return false;
  return true;
}

function validateRequired(element) {
  if (!element.required) 
  return true;
 
  var selectValue = "";
   
  if (element.required == true) 
  { 
	if ((element.type == "select-one") || (element.type == "select-multiple"))
	{
		for (var i = 0; i < element.length; i++)
		 {
		 	if (element[i].selected)
		 	{
		 		 selectValue = element[i].value + "," + selectValue;
		 	}
		 }//ends for loop
		 if ((selectValue == ",") || (selectValue == "-999,"))
		 return false;
	}
	else if ((element.value == null) || (element.value == "") || isBlank(element.value))
          return false;
      
  }
  return true;
}

function validateMinValue(element) {
  if (!element.minValue) return true;
  if (parseFloat(element.value) < parseFloat(element.minValue)) return false;
  return true;
}

function validateMaxValue(element) {
  if (!element.maxValue) return true;
  if (parseFloat(element.value) > parseFloat(element.maxValue)) return false;
  return true;
}

function validateDate(dateString) {
  if (dateString == "") return true;

  if (isNaN(Date.parse(dateString)))
    return false;

  var compDate = new Date(dateString);

  var dayString = dateString.slice( dateString.indexOf("/") + 1,dateString.lastIndexOf("/"));
  var monthString = dateString.slice( 0,dateString.indexOf("/"));

  var i;
  for (i = 0;dayString.charAt(i) == "0";i++);
  var day = parseInt(dayString.substr(i));

  for (i = 0;monthString.charAt(i) == "0";i++);
  var month = parseInt(monthString.substr(i));

  if (day == compDate.getDate() && month == compDate.getMonth()+1) {
    return true;
  }
  else
    return false;
}

function validateInt(intString) {
  var v = parseInt(intString);
  //if (isNaN(v)) return false;
  if (!isNumber(intString,"int")) return false;
  return true;
}

function validateDec(decString) {
  var v = parseFloat(decString);
  //if (isNaN(v)) return false;
  if (!isNumber(decString,"dec")) return false;
  return true;
}

function isNumber(n,type) {
  for (var i=0;i<n.length;i++) {
    var c = n.charAt(i);
    if (c != "." || type == "int") {
      var v = parseInt(c);
      if (isNaN(v)) return false;
    }
  }
  return true;
}

function validateEmail(e) {
  var v = e.value;
  //alert("I am in validate email")
  if (v == "" || v == null) return true;
  for (var i=1;i<v.length;i++) {
  	var c = v.charAt(i);
  	if (c == '@') {
  		//if (!isLetter(v.slice(0,i)) || !isLetter(v.slice(i+1,v.length))) return false;
  		for (var j=i+2;j<v.length;j++) {
				c = v.charAt(j);
				if (c == '.') {
					if (v.length-1<=j) return false;
					return true;
				}
			}
			return false;
		}
  }
  return false;
}

function isBlank(s) {
  for (var i=0;i<s.length;i++) {
    var c = s.charAt(i);
    if ((c!=' ') && (c!='\t') && (c!='\n')) return false;
  }
  return true;
}

function validatePhone(e) {
  //alert('1');
  if (e.value == "" || e.value == null) return true;
  var nv = "";
  var v = e.value;
  nv = stripPhone(v);
  if (nv.length < 10) {
    alert("Phone Number is too short");
    e.select();
    return false;
  }
  if (nv.length > 10) {
    alert("Phone Number is too long");
    e.select();
    return false;
  }
  e.value = formatPhone(nv);
  return true;
}

function formatPhone(nv) {
  if (nv == "" || nv == null) return "";
  return (nv.slice(0,3) + "-" + nv.slice(3,6) + "-" + nv.slice(6,10));
}

function stripPhone(v) {
  var nv = "";
  for (var i=0;i<v.length;i++) {
    var c = v.charAt(i);
    if (!isNaN(parseInt(c)))
      nv = nv + c;
  }
  return nv;
}

function setBrowser() {
  var browser = new Object();
  browser.name = navigator.appName;
  browser.version = navigator.appVersion.charAt(0);
  browser.IE = false;
  browser.NS = false;
  browser.other = false;
  browser.styles = false;
  browser.layerSupport = false;
  browser.allSupport = false;
  browser.hiResScreen = false;
  browser.downColor = "";
  browser.downShadow = "";

  if (navigator.appName.indexOf("Netscape") > -1) {
    browser.NS = true;
  }
  else if (navigator.appName.indexOf("Microsoft") > -1) {
    browser.IE = true;
  }
  else {
    browser.other = true;
  }

  if ((browser.IE == true && browser.version >= 3) || (browser.NS == true && browser.version >= 4)) { 
    browser.styles = true; 
  }

  if (document.layers!=null)
    browser.layerSupport = true;

  if (document.all!=null)
    browser.allSupport = true;


  if (browser.version > 3) {
    if (screen.colorDepth > 8) {
      browser.hiResScreen = true;
      browser.downColor = '#ffffff';
      browser.downShadow = '#000000';
    } 
    else {
      browser.hiResScreen = false;
      browser.downColor = '#000000';
      browser.downShadow = '#ffcc33';
    }
  }

  return browser;
} // setBrowser

