var lastMouseX;
var lastMouseY;
var curPopupWindow = null;
var helpWindow = null;

function setLastMousePosition(e) {
	if (navigator.appName.indexOf("Microsoft") != -1) e = window.event;
	lastMouseX = e.screenX;
	lastMouseY = e.screenY;
}

function openClickout(url) {
		// Taken out due to inconsistent escape results between java and javascript
        //window.open('/sales/linkout.jsp?url='+escape(url), "_blank", 'width=640,height=480,dependent=no,resizable=yes,toolbar=yes,status=yes,directories=yes,menubar=yes,scrollbars=1', false);
	window.open(url, "_blank", 'width=640,height=480,dependent=no,resizable=yes,toolbar=yes,status=yes,directories=yes,menubar=yes,scrollbars=1', false);
}

function openPopup(url, name, pWidth, pHeight, features, snapToLastMousePosition) {
   closePopup();
	if (snapToLastMousePosition) {
		if (lastMouseX - pWidth < 0) {
			lastMouseX = pWidth;
		}
		if (lastMouseY + pHeight > screen.height) {
			lastMouseY -= (lastMouseY + pHeight + 50) - screen.height;
		}
                lastMouseX -= pWidth;
                lastMouseY += 10;
		features +=	"screenX=" + lastMouseX + ",left=" + lastMouseX + "screenY=" + lastMouseY + ",top=" + lastMouseY;
	}
	curPopupWindow = window.open(url, name, features, false);

}

function closePopup() {
	if (curPopupWindow != null) {
	   
		if (!curPopupWindow.closed) {
			curPopupWindow.close();
		}
		curPopupWindow = null;
	}
}

function openLookup(baseURL,modified,searchParam) {
	if (modified == '1') baseURL = baseURL + searchParam;
	openPopup(baseURL, "lookup", 350, 300, "width=430,height=300,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no", true);
}

function pick(form,field,val) {
	eval("document."+form+"[\""+field+"\"].value=" + "\""+val+"\"");
   closePopup();
	return false;
}

function openCalendar(url) {
	openPopup(url, "Calendar", 193, 145, "width=193,height=145,dependent=yes,resizable=yes,toolbar=no,status=no,directories=no,menubar=no", true);
}

function openComboBox(url) {
	openPopup(replaceChar(url, ' ', '%'), "Select", 220, 270, "width=270,height=200,dependent=yes,resizable=yes,toolbar=no,status=no,directories=no,menubar=no,scrollbars=1", true);
}

function replaceChar(s, oldchar, newchar) {
	var retval = '';
	for (i = 0; i < s.length; i++) {
		if (s.charAt(i) == ' ') {
			retval = retval + '%';
		} else {
			retval = retval + s.charAt(i);
		}
	}	
	return retval;
}

function openHelp(url) {
	url = url.replace("#", "%23");
	var browserName = navigator.appName;
	if (helpWindow != null && browserName != "Netscape") { helpWindow.close(); }
	var w = window.open(url, "Help", "width=500,height=400,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,screenX=" + window.screenX + ",left=" + window.screenX + "screenY=" + window.screenY + ",top=" + window.screenY, true);
    	w.focus();
	helpWindow = w;
}

function doPrint() {
	alert("This dialog will be replaced by a new browser window containing a printable version" +
		  " of the current page. The user can then select print from the browsers file menu to"+
		  " print the page. Alternatively, this could be an automatically generated Acrobat file.");
}

function doExport() {
	alert("This dialog will be replaced by a File-Save As dialog. Clicking on save in this dialog will save the contents of the current page to a file (in .csv format).");
}

function listProperties(obj) {
	var names = "";
	for (var i in obj) names += i + ", ";
	alert(names);
}

function lookupPick(formName, parentIdElementName, parentEditElementName, id, display) {
    
	var parentIdElement = "document." + formName + "[\"" + parentIdElementName + "\"]";
	var parentEditElement = "document." + formName + "[\"" + parentEditElementName + "\"]";
	var parentEditOldValueElement = "document." + formName + "[\"" + parentEditElementName + "_lkold" + "\"]";
	if (eval(parentIdElement + ".type") == "select-one") {
		var found = false;
		for (i = 0; i < eval(parentIdElement + ".options.length"); i++) {
			if (eval(parentIdElement + ".options[" + i + "].value") == id ) {
				eval(parentIdElement + ".selectedIndex=" + i);
				found = true;
				break;
			}
		}
		if (!found) {
			eval(parentIdElement + ".options[" + parentIdElement + ".options.length] = new Option('" + display + "','" + id + "')");
			eval(parentIdElement + ".selectedIndex=" + parentIdElement + ".options.length - 1");
		}
		eval(parentEditElement + ".value = " + "\"" + display +"\"");    
		eval(parentEditOldValueElement + ".value = " + "\"" + display +"\"");
	} else {
		eval(parentIdElement + ".value = " + "\"" + id +"\"");    
		eval(parentEditElement + ".value = " + "\"" + display +"\"");
		eval(parentEditOldValueElement + ".value = " + "\"" + display +"\"");
	}
	 	
		var parentSubmitParam = parentEditElementName+"_lspf";		
	    var doPost = eval("document."+formName+"[\""+ parentSubmitParam + "\"].value");
	   	if (doPost == '1') {
	   		eval("document."+formName+".submit()");	   
		}
		closePopup();
  
		return false;
}

function insertTS(field,datetime,alias) {
	field.value = "---------------------------------\n"+ alias + " " +datetime + "\n\n\n" + field.value;
}

function setFocus() {
    var sidebarSearch;
	// search for a tabIndexed field to focus on
    for(var firstIndex=1; firstIndex < 5; firstIndex ++ ){
	    var nextIndex = firstIndex;
        for (var frm = 0; frm < document.forms.length; frm++) {
            for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
                var elt = document.forms[frm].elements[fld];
			    if ( elt.tabIndex != nextIndex ) continue;
                if ((elt.type == "text" || elt.type == "textarea" || elt.type == "password")
                   && elt.name != "sbstr" &&  elt.name.indexOf("owner") != 0) {
				    elt.focus();
	                if (elt.type == "text") {
	                    elt.select();
	                }
	                return true;
			    } else {
				    nextIndex++;
				    fld = 0;
			    }
		    }
	    }
    }

	// failed to find a tabIndexed field, try to find the field based on it's natural position.
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            // skip buttons, radio, or check-boxes
            // to skip "select" types, remove from if statement
            if (elt.type == "text" || elt.type == "textarea" || elt.type == "password") {
                if (elt.name == "sbstr" && document.forms[frm].name == "sbsearch") { 
                    sidebarSearch = elt; 
                } else if (elt.name.indexOf("owner") != 0) {
                    elt.focus();
                    // select text in text field or textarea
                    if (elt.type == "text") {
                        elt.select();
                    }
                    return true;
                }
            }
        }
    }

    return true;
}

function setNamedFocus(element_name) {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == element_name) {
                elt.focus();
                if (elt.type == "text") {
                    elt.select();
                }
                return true;
            }
        }
    }
    return true;
}

// removes the leading and trailing spaces from a string, 
// similar to the java.lang.String.trim() function
// added by lturetsky, taken from http://www.voy.com/1888/58.html
function trim(st) {
	var len = st.length
	var begin = 0, end = len - 1;
	while (st.charAt(begin) == " " && begin < len) {
		begin++;
	}
	while (st.charAt(end) == " " && begin < end) {
		end--;
	}
	return st.substring(begin, end+1);
}


function formatPhone (field) {
	field.value = trim(field.value);

    var ov = field.value;
    var v = "";
    var x = -1;

	// is this phone number 'escaped' by a leading plus?
	if (0 < ov.length && '+' != ov.charAt(0)) {	// format it
	    // count number of digits
	    var n = 0;
		if ('1' == ov.charAt(0)) {	// skip it
			ov = ov.substring(1, ov.length);
		}

	    for (i = 0; i < ov.length; i++) {
	        var ch = ov.charAt(i);

	        // build up formatted number
	        if (ch >= '0' && ch <= '9') {
	            if (n == 0) v += "(";
	            else if (n == 3) v += ") ";
	            else if (n == 6) v += "-";
	            v += ch;
	            n++;
	        }
	        // check for extension type section; 
	        // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
	        if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
	            x = i;
	            break;
	        }
	    }
	    // add the extension
	    if (x >= 0) v += " " + ov.substring(x, ov.length);

	    // if we recognize the number, then format it
	    if (n == 10 && v.length <= 40) field.value = v;
	}
    return true;
}

function dc () {
    return window.confirm('Are you sure?');
}

function clearcols () {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == "c" || elt.name.substring(0,2) == "c_") {
                elt.checked = false;
            }
        }
    }
}

function setcols () {
    for (var frm = 0; frm < document.forms.length; frm++) {
        for (var fld = 0; fld < document.forms[frm].elements.length; fld++) {
            var elt = document.forms[frm].elements[fld];
            if (elt.name == "c" || elt.name.substring(0,2) == "c_") {
                elt.checked = true;
            }
        }
    }
}

function setUsername(uname, fname, lname, suffix) {
	if (uname.value.length == 0) {
		uname.value = 
					fname.value.substring(0,1).toLowerCase() 
					+ lname.value.toLowerCase()
					+ "@"
					+ suffix.value;
	}
}
function setAlias(alias, fname, lname) {
	if (alias.value.length == 0) {
		alias.value = fname.value.substring(0,1).toLowerCase() +
					  lname.value.substring(0,4).toLowerCase();
	}
}

// POPUP WINDOW NUMBER 1 
function popWin(url) {
  	closePopup();
  	curPopupWindow = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=550,height=300",false);
}
function popWin2(url) {
   win = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=720,height=500",false);
   //self.name = "tutWindow";
}
function adminWin(url) {
   win = window.open(url,"win","toolbar=1,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600",false);
}
function privacyWin(url) {
  	closePopup();
  	curPopupWindow = window.open(url,"win","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=550,height=350",false);
}

// DS2  9/12/2001  Added this to circumvent closing pop-ups.
function openWindow(url, name, pWidth, pHeight, features) {
    window.open(url, name, features, false);
}

// Changed name of window for printWin so that Printable views do not disappear
// Newname is popWin, Oldname(changed) was curPopupWindow
function printWin(url) {
  popWin = window.open(url,"win","dependent=no,toolbar=1,directories=0,location=0,status=1,menubar=1,scrollbars=1,resizable=1,width=705,height=400",false);
  popWin.focus();
}

function moveSelectElement2(sourceSelect, targetSelect, sourceLabel, targetLabel) {
	moveSelectElement3(sourceSelect, targetSelect, sourceLabel, targetLabel, false);
}


function moveSelectElement3(sourceSelect, targetSelect, sourceLabel, targetLabel, keepTarget) {
	if (sourceSelect.selectedIndex > -1) {
		for (i=0; i < sourceSelect.length; ++i) {  
			var selectedOption = sourceSelect.options[i];
			if (selectedOption.selected) {
				if (selectedOption.text != sourceLabel) {
					var newOption = new Option(selectedOption.text, selectedOption.value);
					if (targetSelect.options.length > 0 && targetSelect.options[0].text == targetLabel) {
						targetSelect.options[0] = newOption;
                        targetSelect.selectedIndex = 0;
					} else {
						targetSelect.options[targetSelect.options.length] = newOption;
                        targetSelect.selectedIndex = targetSelect.options.length - 1;
					}
				} else {
					sourceSelect.selectedIndex = -1;
				}
			}
		}
		if(!keepTarget)
		{	removeSelectElement3(sourceSelect, sourceLabel);
		}
	}
}

function moveOption (sourceSelect, targetSelect, 
                     keepSourceLabel, unmovableSourceValues, 
                     keepTargetLabel) {

    var sourceOptions = sourceSelect.options;
    
    var canMove;
    var option;
    
    // find which ones are selected...
    var selectedIds = new Array ();
    var index = 0;
    for (var i = 0; i < sourceSelect.length; i++) {
        option = sourceOptions[i];
        if (option.selected) {
            canMove = (option.text != keepSourceLabel);
            if (canMove && unmovableSourceValues != null) {
                // make sure we don't move any options defined as unmovable
                for (var j = 0; j < unmovableSourceValues.length; j++) {
                    if (unmovableSourceValues[j] == option.value) {
                        canMove = false;
                        break;
                    }
                }
            }

            // if this option can be moved we add it to our array of elements to move
            if (canMove) {
                selectedIds[index] = i;
                index++;
            } else {
                // if we can't move this option, then unselect it
                option.selected = false;
            }
        }
    }

    // move them over one by one
    var targetOptions = targetSelect.options;
    if (selectedIds.length > 0) {
        targetSelect.selectedIndex = -1;
        for (var i = 0; i < selectedIds.length; i++) {
            option = new Option (sourceOptions[selectedIds[i]].text, sourceOptions[selectedIds[i]].value);
            
            // replace the target value if its the last one
            if (targetOptions.length == 1 && targetOptions[0].text == keepTargetLabel) {
                targetOptions[0] = option;
                targetOptions[0].selected = true;
            } else {
                targetOptions[targetOptions.length] = option;
                targetOptions[targetOptions.length-1].selected = true;
            }
        }
    }
        
    // remove values from the source 
    for (var i = selectedIds.length; i > -1; i--) {
        sourceOptions[selectedIds[i]] = null;
    }

    // make sure we don't get an empty list
    if (sourceOptions.length == 0) {
        sourceOptions[0] = new Option (keepSourceLabel, keepSourceLabel);
    }

    // if we moved anything, put the focus on the target list box
    if (selectedIds.length > 0) targetSelect.focus ();
}

function removeSelectElement3(sourceSelect, sourceLabel)
{	if (sourceSelect.selectedIndex > -1)
	{	for (i=sourceSelect.length-1; i > -1; i--) 
		{	if (sourceSelect.options[i].selected) sourceSelect.options[i] = null;
		}
		if (sourceSelect.length == 0) 
		{	var placeHolder = new Option(sourceLabel, sourceLabel);
			sourceSelect.options[0] = placeHolder;
		}
	}
}


function moveUp(sourceSelect) {
    if (sourceSelect.length > 1) {
        var options = sourceSelect.options;

        // find which ones are selected...
        var selectedIds = new Array ();
        var index = 0;
        for (var i = 1; i < sourceSelect.length; i++) {
            if (options[i].selected) {
                selectedIds[index] = i;
                index++;
            }
        }

        // move each selected option up 
        var selId;
        for (var i = 0; i < selectedIds.length; i++) {
            selId = selectedIds[i];
            privateMoveUp (options, selId);
            options[selId].selected = false;
            options[selId-1].selected = true;
        }

        sourceSelect.focus ();
    }
}

function moveDown(sourceSelect) {
    if (sourceSelect.length > 1) {
        var options = sourceSelect.options;

        // find which ones are selected
        var selectedIds = new Array ();
        var index = 0;
        for (var i = sourceSelect.length-2; i >= 0; i--) {
            if (sourceSelect.options[i].selected) {
                selectedIds[index] = i;
                index++;
            }
        }

        // move each selected element down
        var selId;
        for (var i = 0; i < selectedIds.length; i++) {
            selId = selectedIds[i];
            privateMoveDown (options, selId);
            options[selId].selected = false;
            options[selId+1].selected = true;
        }
        
        sourceSelect.focus ();
	}
}


function moveTop(sourceSelect) {
    var selIndex = sourceSelect.selectedIndex;

    if (sourceSelect.length > 1 && selIndex > 0) {
        var options = sourceSelect.options;

        for (var i = selIndex; i > 0; i--) {
            privateMoveUp (options, i);
        }
        
        sourceSelect.focus ();
        sourceSelect.selectedIndex = 0;
    }
}

function moveBottom(sourceSelect) {
    var selIndex = sourceSelect.selectedIndex;

    // gots to have at least 2 items and something selected, but not the last one 
    if (sourceSelect.length > 1 && selIndex > -1 && selIndex < sourceSelect.length - 1) {
        var options = sourceSelect.options;
      
        for (var i = selIndex; i < sourceSelect.length - 1; i++) {
            privateMoveDown (options, i);
        }

        sourceSelect.focus ();
        sourceSelect.selectedIndex = sourceSelect.length - 1;
    }
}

/*
 * Do not call this function directly. 
 * As it does NO bounds checking.
 * Please use the moveUp or moveTop calls.
 */
function privateMoveUp (options, index) {
    var newOption = new Option (options[index-1].text, options[index-1].value);
    options[index-1].text = options[index].text;
    options[index-1].value = options[index].value;
    options[index].text = newOption.text;
    options[index].value = newOption.value;
}

/*
 * Do not call this function directly. 
 * As it does NO bounds checking.
 * Please use the moveDown or moveBottom calls.
 */
function privateMoveDown (options, index) {
    var newOption = new Option (options[index+1].text, options[index+1].value);
    options[index+1].text = options[index].text;
    options[index+1].value = options[index].value;
    options[index].text = newOption.text;
    options[index].value = newOption.value;
}


function saveSelected(fromSelObj, toHidObj, delim, empty_label) {
    var i;
	toHidObj.value = '';
    for (i=0; i<fromSelObj.length; i++) {
        if (i > 0) {
            toHidObj.value += delim;
        }
        if (!(fromSelObj.length == 1 && fromSelObj.options[0].value == empty_label)) {
            toHidObj.value += fromSelObj.options[i].value;
        }
    } 
}

/**
 * Used when submitting a dueling list boxes element. 
 * Stores all the values into hidden form parameters so we can get them out
 */
function saveAllSelected (fromSelectArray, toArray, delim, emptyLabel) {
    var i,j;
    // loop through all the select elements
    for (i = 0; i < fromSelectArray.length; i++) {
        toArray[i].value = ''; // clear out the value to start
        // now loop through all the values in the select element
        for (j = 0; j < fromSelectArray[i].length; j++) {
            // copy over the value as long as it is not the emptyLabel
            if (!(fromSelectArray[i].length == 1 && fromSelectArray[i].options[0].value == emptyLabel)) {
                toArray[i].value += fromSelectArray[i].options[j].value;
            }

            // add the delimiter (except after the last one)
            if (j + 1 < fromSelectArray[i].length) {
                toArray[i].value += delim;
            }
        }
    }
}

function openwizard(url, name, resizable) {
  var win = window.open('', name, 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable='+resizable+',width=675,height=550,screenx=50,screeny=10,left=50,top=10',false)
  if ((win.document.URL == '') || (win.document.URL == 'about:blank')) win.location = url; 
  win.focus ();
}

function escapeUTF(src) {
	var ret = "";
	for (i = 0; i < src.length; i++) {
		var ch = src.charCodeAt(i);
		if (ch <= 0x7F) {
			ret += escape(src.charAt(i));
		} else if (ch <= 0x07FF) {
			ret += '%' + ((ch >> 6) | 0xC0).toString(16) + '%' + ((ch & 0x3F) | 0x80).toString(16);
		} else if (ch >= 0x0800) {
			ret += '%' + ((ch >> 12) | 0xE0).toString(16) +
				   '%' + (((ch >> 6) & 0x3F) | 0x80).toString(16) + '%' + ((ch & 0x3F) | 0x80).toString(16);
		}
	}
	return ret;
}

function openRefer(url) {
	window.open(url, 'referv2', 'resizable=no,toolbar=no,status=no,directories=no,scrollbars=yes,width=420,height=500', false); 
}

function changeOpenerWindowLocation (url) {
    if ((window.top.opener == null) || window.top.opener.closed) {
        window.top.open (url);
    } else {
        window.top.opener.location.href = url;
        window.top.opener.focus ();
    }	
}

function verifyChecked(form, element_name, errorMessage) {
    for (i = 0; i < form.elements.length; i++) {
        if ((form.elements[i].name == element_name) && form.elements[i].checked) {
            return true;
        }
    }

	// if we haven't returned yet, it's not checked
    alert(errorMessage);
    return false;
}

function submitFormActionURL (form, url) {
	form.action = url;
	form.submit();
}

function SelectChecked(form, element_name, value)
{
    var i = 0;
    for (i = 0; i < form.elements.length; i++) {
    	if (form.elements[i].name == element_name) {
    		form.elements[i].checked = value;
    	}
    }
}

function getLoginCookieValue() 
{
    var c = document.cookie;
    var idx = c.indexOf('login=');
    if ( idx == -1) return "";
    idx += 'login='.length;
    var end = c.indexOf(';',idx);
    if ( end == -1) end = c.length;
    return c.substring(idx,end);
}
        
function loader() 
{
     var username = getLoginCookieValue();
     if (username.length > 0) {
         document.login_noop.un_noop.value = username;
         document.login.un.value = username;
         document.login.pw.focus();
     } else {
         document.login_noop.un_noop.focus();
     }
     document.login.width.value=screen.width;
     document.login.height.value=screen.height;
}

