/*
 * WebKit JavaScript utility functions.
 */
var didSubmitElement = false;

function WKCheckDate(elementName) {
    var f = WKGetElement(elementName);
	f.value = checkDate(f.value, "false");
	return false;
}

function WKUpdateElement(elementName, value) {
    var f = WKGetElement(elementName);
	f.value = checkDate(value, "false");
	return false;
}

function WKSelectElement(elementName) {
	var count = document.forms.length;
	for(var i = 0; i < count; i++) {
    var element = document.forms[i].elements[elementName] ;
		if (element != null) {
            element.focus();
            if (element.select)
                element.select();
		}
	}
	return false;
}

function WKClickElement(elementName) {
	var count = document.forms.length;
	for(var i = 0; i < count; i++) {
    var element = document.forms[i].elements[elementName] ;
		if (element != null) {
            element.focus();
            if (element.select)
                element.click();
		}
	}
	return false;
}

function WKSubmitElement(elementName) {
    if (didSubmitElement) return;
	var count = document.forms.length;
	for(var i = 0; i < count; i++) {
		if (document.forms[i].elements[elementName] != null) {
			document.forms[i].submit();
            didSubmitElement = true;
			return;
		}
	}
	return;
}

function WKGetElement(elementName) {
	var count = document.forms.length;
	for(var i = 0; i < count; i++) {
		var e = document.forms[i].elements[elementName];
		if (e != null) {
			return e;
		}
	}
	return null;
}

/*
 * WKCloseWindow ([closeAction], [closeAll])
 * Input: closeAction - the action for close window.
 *        closeAll - the flag for close all windows.
 */
function WKCloseWindow() {
//    var msg = "\nYou are going to exit this window\n\n" + "Are you shure to close this window??";
//    confirm(msg);
//    setTimeout(closeWindow(),5000);
	var thisWindow = self;
	var openerWindow = thisWindow.opener;
	if(openerWindow != null) {
		if(arguments[1] != null) {
			if(typeof openerWindow.ChildrenArray != 'undefined') {
				for(var i = 0; i < openerWindow.ChildrenArray.length; i++) {
					if(!(openerWindow.ChildrenArray[i].closed)) {
						openerWindow.ChildrenArray[i].close();
					}
				}
			} else {
				thisWindow.close();
			}
		} else {
			thisWindow.close();
		}
        openerWindow.focus();
		if(arguments[0] != null) {
			var closeAction = new Function(arguments[0]);
			closeAction();
		}
	} else {
        if(typeof thisWindow.ChildrenArray != 'undefined') {
            for(var i = 0; i < thisWindow.ChildrenArray.length; i++) {
                if(!(thisWindow.ChildrenArray[i].closed)) {
                    thisWindow.ChildrenArray[i].close();
                }
            }
        }
	}
}

/*
 * This function toggles the sort icon displayed by the WKFilterBar component
 */
function WKToggleFilterBarSortIcon(resourcesURL, fieldName, iconName) {
    var f = WKGetElement( fieldName );
    var i = document.images[ iconName ];
    if (f.value == 'A') { 
        i.src = resourcesURL + 'WKDescending.gif';
        f.value = 'D';
    } else if (f.value == 'D') {
        i.src = resourcesURL + 'WKUnsorted.gif';
        f.value = 'N';
    } else { 
        i.src = resourcesURL + 'WKAscending.gif';
        f.value = 'A'; 
    }
    return false;
}

/*
 * Print Func.
 */
function report_print() {
    var color = document.body.bgColor;
    document.body.bgColor = "white";
    document.body.scroll = 'yes';
    print();
    document.body.scroll = 'auto';
    document.body.bgColor = color;
}

/*
 * Show Description Func.
 */
function popUpDescr(evt, currElem, wi, hi) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        if (document.all) {
            docObj = "document.all.";
        } else {
            docObj = "document.";
        }
        popUpWin = eval(docObj + currElem);
    } else {
        popUpWin = document.getElementById(currElem);
    }
    popUpWin.style.width = wi;
    popUpWin.style.height = hi; 
    if (document.all) {
        var y = parseInt(evt.y) + 2;
        var x = parseInt(evt.x) + 2;
    } else {
        var y = parseInt(evt.pageY) + 2;
        var x = parseInt(evt.pageX) + 2;
    }
    if (navigator.appName.indexOf("Microsoft") != -1) {
        var ww = parseInt(window.document.body.clientWidth) - 5;
    } else {
        var ww = parseInt(window.innerWidth) - 20;
    }
    var ow = parseInt(popUpWin.style.width);
    popUpWin.style.top = y;
    popUpWin.style.left = Math.min(x, ww - ow);
    popUpWin.style.visibility = "visible";
    window.status = "";
}
function popDownDescr(currElem) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        if (document.all) {
            docObj = "document.all.";
        } else {
            docObj = "document.";
        }
        popUpWin = eval(docObj + currElem);
    } else {
        popUpWin = document.getElementById(currElem);
    }
    popUpWin.style.visibility = "hidden";
}
function clickDescr(currElem) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        if (document.all) {
            docObj = "document.all.";
        } else {
            docObj = "document.";
        }
        popUpWin = eval(docObj + currElem + 'Action');
        popUpWin.click();
    } else {
        popUpWin = document.links[currElem + "Action"];
        window.location = popUpWin;
    }
}

/*
 * Menu Over Func.
 */
function jumpPage(newLoc) {
    newPage = newLoc.options[newLoc.selectedIndex].value
    if (newPage != "") {
        window.location.href = newPage
    }
}
function getPos( el, sProp ) {
    var iPos = 0;
    while (el != null) {
        iPos += el["offset" + sProp];
        el = el.offsetParent;
    }
    return iPos;
}
function moveTo( elem, posX, posY ){
    // moves layer directly to new position
    elem.style.left = posX + "px";
    elem.style.top = posY + "px";
}
function showElement( elem ) {
    elem.style.visibility = "visible";
}
function hideElement( elem ) {
    elem.style.visibility = "hidden";
}
function menuOver( menuElem, subMenu, subMenuClassName ) {
    subMenuElem = document.getElementById(subMenu);
    var mw = parseInt(menuElem.offsetWidth);
    var smw = parseInt(subMenuElem.offsetWidth);
    if ( smw <= mw ) subMenuElem.style.width = mw;
    var l = getPos( menuElem, "Left" );
    if (navigator.appName.indexOf("Microsoft") != -1) {
        var ww = parseInt(window.document.body.clientWidth) - 5;
    } else {
        var ww = parseInt(window.innerWidth) - 20;
    }
    if (ww < (l + smw)) l = ww - smw;
    var t = getPos( menuElem, "Top" ) + menuElem.offsetHeight;
    moveTo( subMenuElem, l, t );
    subMenuElem.className = subMenuClassName;
    showElement( subMenuElem );
}
function menuOut( menuElem, subMenu, subMenuClassName ) {
    subMenuElem = document.getElementById(subMenu);
    subMenuElem.className = subMenuClassName;
    hideElement( subMenuElem );
}
function subMenuOver( mainMenu, subMenu ) {
    mainMenuElem = document.getElementById(mainMenu);
    subMenuElem = document.getElementById(subMenu);
    hideElement( mainMenuElem );
    mainMenuElem.style.position="absolute";
    showElement( subMenuElem );
    subMenuElem.style.position="relative";
}
function subMenuOut( mainMenu, subMenu ) {
    mainMenuElem = document.getElementById(mainMenu);
    subMenuElem = document.getElementById(subMenu);
    hideElement( subMenuElem );
    subMenuElem.style.position="absolute";
    showElement( mainMenuElem );
    mainMenuElem.style.position="relative";
}

/*
 * Menu for right mouse button (IE Only).
 */
function deru() {
    rightMouseMenuElem = document.getElementById("RightMouseMenu");
    var migi = document.body.clientWidth-event.clientX;
    var sita = document.body.clientHeight-event.clientY;
    if (migi < rightMouseMenuElem.offsetWidth) {
        rightMouseMenuElem.style.left = document.body.scrollLeft + event.clientX - rightMouseMenuElem.offsetWidth;
    } else {
        rightMouseMenuElem.style.left = document.body.scrollLeft + event.clientX;
    }
    if (sita < rightMouseMenuElem.offsetHeight) {
        rightMouseMenuElem.style.top = document.body.scrollTop + event.clientY - rightMouseMenuElem.offsetHeight;
    } else {
        rightMouseMenuElem.style.top = document.body.scrollTop + event.clientY;
        rightMouseMenuElem.style.visibility = "visible";
    }
    return false;
}
function omenu() {
    rightMouseMenuElem = document.getElementById("RightMouseMenu");
    rightMouseMenuElem.style.visibility = "hidden";
}
function scol(className, color, backgroundColor) {
    if (event.srcElement.className == className) {
        event.srcElement.style.backgroundColor = backgroundColor;
        event.srcElement.style.color = color;
    }
}
function ocol(className, color, backgroundColor) {
    if (event.srcElement.className == className) {
        event.srcElement.style.backgroundColor = backgroundColor;
        event.srcElement.style.color = color;
        window.status = "";
    }
}
function tu(className) {
    if (event.srcElement.className == className) {
        if (event.srcElement.getAttribute("target") != null) {
            window.open(event.srcElement.url, event.srcElement.getAttribute("target"));
        } else {
            window.location = event.srcElement.url;
        }
    }
}

/*
 * Add Bookmark.
 */
function AddBookmark(url, name) {
    window.external.AddFavorite(url, name)
}

/*
 * This is for Hola.
 */
function commaFormat(number) {
   originalStr = String(number);
   if (originalStr == "") originalStr = String("0");
   commaStr = "";
   for (i=originalStr.length - 3; i>0; i -= 3) {
       commaStr = "," + originalStr.substring(i,i + 3) + commaStr;
   }
   reminder = originalStr.substring(0, i + 3);
   return reminder + commaStr;
}

function dollarFormat(aField) {
   var number = String(aField.value.replace(/[^0123456789.]/g,""));
   var intPart = String(number.match(/\d*/));
   var decPart = String(number.replace(/\d*/,"").replace(/\./g,"") + "00");
   aField.value = "$" + commaFormat(intPart) + "." + decPart.substring(0,2);
}

/*
 * formatCurrency(value [,message [,field]])
 *
 * Input: value - the value portin of the textfield or textarea (i.e this.value)
 *        message (optional) - displays this message if the amount is invalid
 *        field  (optional) - refocus to this field is the amount is invalue
 *
 * Output: return the field as format currency (i.e. $9,999.99) 
 * 
 * Use: this.value = formatCurrency(this.value, 'This is an incorrect amount')
 *
 * Notes: Use field parameter with cation. It may cause infinite looping
 */
function formatCurrency(ogValue){
  var negative = false;
  var cents = ".00";
  var decOffset;
  var dollars = 0;

  //returns zeros if field is empty
  if (ogValue==null){
	return "$0.00";
  }

  //insures that amount is a string
  amount=ogValue.toString();
  
  //removes currency formatting
  amount = stripCurrency(amount);
  if (isValidFormat("^-?\\d*\\.?\\d*$", amount)){
	if ( amount.charAt(0) == '-'){
	  negative=true;
	  amount = amount.substring(1);
	}
 
	// extract decimal part of number
	decOffset = amount.indexOf(".");
	if (decOffset != -1){
	  cents = amount.substring(decOffset,decOffset+2);
	  //validate decPart and foramt decimal
	  while (cents.length < 3){
		cents += "0";
	  }
	}  
  
	// extract dollars
	if (decOffset != -1)
	  {dollars = amount.substring(0,decOffset)}
	else 
	  {dollars = amount}
	
	// insert commas in wholeAmount
	var flen=dollars.length;
	for (var i=(flen-3); i>0; i-=3 ){
	  dollars = dollars.substring(0,i) + "," + dollars.substring(i,flen++);
	}
  
	// put it all back together
	if (negative)
	  {amount = "(" + "$" + dollars + cents + ")"}
	else  
	  {amount = "$" + dollars + cents }
	return amount;
  }
  else{
	if (arguments[1] != null)
		alert(arguments[1]);
	else 
		alert("You have entered an invalid dollar amount.");
	
	if (arguments[2] != null)
		arguments[2].focus();
	return ogValue;
  }
}

/*
 * checkdate(value [,flag [,field [,message]]])
 *
 * Input: value - the value portin of the textfield or textarea (i.e this.value)
 *        flag  (optional) - return without invalid messages.
 *        field  (optional) - refocus to this field is the amount is invalue
 *        message (optional) - displays this message if the amount is invalid
 *
 * Output: return the field as format date (i.e. 99/99/9999) 
 * 
 * Usaage: this.value = checkDate(this.value)
 *
 * Notes: Use field parameter with cation. It may cause infinite looping
 */
function checkDate(field){
	//******Cut off Date*******//
	var y2kCut = 70
		
	var formated_date
	var month 
	var day
	var year

	//makes sure variable is a string
	field = field.toString()
	
	if (field.length > 0){

		//parses month day and year when enter in 'mm/dd/yyyy' format
		//fisrt occurence of '/'
		var indexf1 = field.indexOf('/')
		var indexf2 = field.indexOf('-')
		
		// M/D/Y
		if (indexf1 > -1) {  //parse date string
			month = field.substring(0,indexf1)
			var index2 = field.indexOf('/', (indexf1+=1) )
			day = field.substring(indexf1,index2)
			year = field.substring((index2+=1),field.length)
		}
		// M-D-Y
		else if (indexf2 > -1) {  //parse date string
			month = field.substring(0,indexf2)
			var index2 = field.indexOf('-', (indexf2+=1) )
			day = field.substring(indexf2,index2)
			year = field.substring((index2+=1),field.length)
		}
		//invalid format
		else {  
			if (arguments[1] != null)
				return field

			if (arguments[3] != null)
				alert(arguments[3]);
			else 
				alert ("Date must be in the form 'mm/dd/yyyy'.")

			if (arguments[2] != null)
				arguments[2].focus();
					
			return field
		} 
			
		//pad month and day with zeros
		if ( (month.valueOf() < 10) && (month.length < 2) )
			month = "0" + month
		if ( (day.valueOf() < 10) && (day.length < 2) )
			day = "0" + day
		//convert year to 2000 if > 70 and 1900 if < 70
		if ( (year.valueOf() < 10) && (year.length < 2) )
			year = "0" + year 
		if ( (year.valueOf() < 100) && (year.valueOf() > y2kCut) )
			year = "19" + year
		else if (year.valueOf() < 100)
			year= "20" + year
  
		//verify date before returing
		formated_date = month + "/" + day + "/" + year
		if(!isValidFormat("^\\d\\d/\\d\\d/\\d\\d\\d\\d$",formated_date)){
			if (arguments[1] != null)
				return field

			if (arguments[3] != null)
				alert(arguments[3]);
			else 
				alert ("Date must be in the form 'mm/dd/yyyy'.")

			if (arguments[2] != null)
				arguments[2].focus();
					
			return field
		}
		return formated_date
	}         
	return field
}

/*******************************************
 *NEW FUNCTIONS                            *
 *******************************************/
function newWindow(url, windowName,windowArgs,currentRow){
   	winHandle = open(url, windowName, windowArgs);
    winHandle.focus();
	highlightRowUp(currentRow);
}

/*******************************************
 *Private functions                        *
 *******************************************/
function isValidFormat(regExp,str){
  _regExp = new RegExp(regExp, "i")
  if (str.match(_regExp) == null)
	return false
  else
	return true
}

function stripCurrency(amount){
  var negative = false
  
  //strips off dollar sign
  indexDollar = amount.indexOf("$")
  if (indexDollar != -1) {
	amount = amount.substring(0,indexDollar) + amount.substring(indexDollar+1,amount.length)
  }

  //left bracket indicate number is negitive
  if (amount.substring(0,1) == "(") {
	amount = amount.substring(1,amount.length)
	negative = true
  }
  //right bracket, doesn't indicate negitive number
  if (amount.substring(amount.length-1,amount.length) == ")") {
	  amount = amount.substring(0,amount.length-1)
  }
  
  //strips off commas
  index = amount.indexOf(',')
  while (index != -1){
	amount = amount.substring(0,index) + amount.substring(index+1,amount.length)
	index = amount.indexOf(',')
  }  
		
  if (negative){
	amount = '-' + amount 
  }
		
  return amount
}


/***************************************
 * Unused functions                    *
 ***************************************/
function checkField(mask,field, msg){
  if (!isValidFormat(mask,field)){
	alert(msg);
		return false
  }
	return true
}
