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 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", 450, 350, "width=450,height=350,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=yes, scrollbars=1", true);
}

function pick2(form,field,field_display,id,display) {
	eval("document."+form+"[\""+field+"\"].value=" + "\""+id+"\"");
	eval("document."+form+"[\""+field_display+"\"].value=" + "\""+display+"\"");
   closePopup();
	return false;
}

function pick_customer(form,value,value1,value2,value3,value4,value5,value6,value7) {
	eval("document."+form+".customerid.value=" + "\""+value+"\"");
	eval("document."+form+".lastname.value=" + "\""+value1+"\"");
	eval("document."+form+".firstname.value=" + "\""+value2+"\"");
	eval("document."+form+".email.value=" + "\""+value3+"\"");
	eval("document."+form+".phone1.value=" + "\""+value4+"\"");
	eval("document."+form+".phone2.value=" + "\""+value5+"\"");
	eval("document."+form+".mobilephone.value=" + "\""+value6+"\"");
	eval("document."+form+".customerinternalnotes.value=" + "\""+value7+"\"");
   closePopup();
	return false;
}

function pick_date(form,value,value1,value2,value3) {
	eval("document."+form+".date.value=" + "\""+value+"\"");
	eval("document."+form+".starttime.value=" + "\""+value1+"\"");
	eval("document."+form+".endtime.value=" + "\""+value2+"\"");
	eval("document."+form+".resourceid.value=" + "\""+value3+"\"");
   closePopup();
	return false;
}

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 insertTS(field,datetime,alias) {
	field.value = "---------------------------------\n"+ alias + " " +datetime + "\n\n\n" + field.value;
}

function setFocus() {
    var search;
	// search for tabIndex == 1
	var nextIndex = 1;
    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.focus();
	            if (elt.type == "text") {
	                elt.select();
	            }
	            return true;
			} else {
				nextIndex++;
				fld = 0;
			}
		}
	}

	// tabIndex == 1 not found, get the first text or textarea
    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")) {
                if (elt.name == "substring") {
                   search = elt;
                }
                if (elt.name != "substring" && elt.name != "searchtype" &&  
                    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?');
}


// 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 printWin(url) {
   closePopup();
   curPopupWindow = window.open(url,"win","toolbar=1,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=705,height=400",false);
}

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;
					} else {
						targetSelect.options[targetSelect.options.length] = newOption;
					}
				} else {
					sourceSelect.selectedIndex = -1;
				}
			}
		}
		if(!keepTarget)
		{	removeSelectElement3(sourceSelect, sourceLabel);
		}
	}
}


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)
{	var sel_id;
	sel_id = sourceSelect.selectedIndex;
	if (sourceSelect.length > 1 && sel_id > 0) //got to have at least 2 items and not the first one is selected
	{	var prevOption = sourceSelect.options[sel_id-1];
		var newOption = new Option(prevOption.text, prevOption.value);
		var selectedOption = sourceSelect.options[sel_id];
		sourceSelect.options[sel_id-1] = new Option(selectedOption.text, selectedOption.value);
		sourceSelect.options[sel_id] = newOption;
		sourceSelect.focus();
		sourceSelect.selectedIndex = sel_id -1;
	}
}


function moveDown(sourceSelect)
{	var sel_id;
	sel_id = sourceSelect.selectedIndex;
	if (sourceSelect.length > 1 && sel_id < sourceSelect.length -1) //got to have at least 2 items and not the last one is selected
	{	var nextOption = sourceSelect.options[sel_id+1];
		var newOption = new Option(nextOption.text, nextOption.value);
		var selectedOption = sourceSelect.options[sel_id];
		sourceSelect.options[sel_id+1] = new Option(selectedOption.text, selectedOption.value);
		sourceSelect.options[sel_id] = newOption;
		sourceSelect.focus();
		sourceSelect.selectedIndex = sel_id + 1;
	}
}

function saveSelected(fromSelObj, toHidObj, delim, empty_label) {
    var i;
    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;
        }
    } 
}

function openwizard(url) {
	window.open(url,'wiz','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=780,height=550',false)
}


// INSERTED BY CB

function CheckField(field) {
	field.value = trim(field.value);
	if(field.value.length > 0 )	
		if ( !(isInteger(field.value)) ){
			alert('No characters allowed!');
			field.value='';
			return false;
			}
}


   //-----------------------------------------------------------
   // isInteger() returns true if the variables passed is an 
   // integer or false if the variable is not a integer
   //-----------------------------------------------------------
function isInteger(val)
   {
      var integerList = '0123456789.';
      var isInteger = false;

      for (var i = 0; i < val.length; i++) {
         isInteger = false;
         for (var j = 0; j < integerList.length; j++) {
            if (integerList.charAt(j) == val.charAt(i)) {
               isInteger = true;
               break;
            } 
         } 
         if (!isInteger) {
            break;
         } 
      } 
      return isInteger;
}

function saveForm3(val, formName)
{
//	alert(val)
//	alert(formName)
	var EditElementName = "redirect";
	var EditElement = "window.top.main." + formName + "[\"" + EditElementName + "\"]";
	eval(EditElement + ".value = " + "\"" + val +"\"");

	var submitElement = "window.top.main." + formName + ".submit()"
	eval(submitElement);
//	Return true;
}


function saveForm(val, formName)
{
//	alert(val)
//	alert(formName)
	var EditElementName = "redirect";
	var EditElement = "document." + formName + "[\"" + EditElementName + "\"]";
	eval(EditElement + ".value = " + "\"" + val +"\"");

	var submitElement = "document." + formName + ".submit()"
	eval(submitElement);
//	Return true;
}

function submitForm(elementname, val, formName)
{
//	alert(val)
//	alert(formName)
	var EditElementName = elementname;
	var EditElement = "document." + formName + "[\"" + EditElementName + "\"]";
	eval(EditElement + ".value = " + "\"" + val +"\"");

	var submitElement = "document." + formName + ".submit()"
	eval(submitElement);
//	Return true;
}



function calcGP(costpricefld,salespricefld,gpfld)
{
	var salesprice = salespricefld.value;
	var costprice = costpricefld.value;
	var GP = 0;

	if(salesprice > 0)
	{
		with (Math)
		{
			GP = round((salesprice - costprice)/salesprice*10000)/100;
		}
	}
	else
	{
		GP = 0;
	}
	gpfld.value = GP
}


function calcCostPrice(costpriceunitfld,uomfld)
{
	var costpriceunit = costpriceunitfld.value;
	var uom = uomfld.value;
	var field = "ite_costprice"
	var form = "item"
	var costprice = 0;

	if(costpriceunit > 0)
	{
		with (Math)
		{
			 costprice = round(costpriceunit/uom*100)/100;
		}
	}
	else
	{
		costprice = 0;
	}
	eval("document."+form+"[\""+field+"\"].value=" + "\""+costprice+"\"");
}



function calcSalesPrice(salespricefld, netfld)
{
	var salesprice = salespricefld.value;
	var net = 0;

	if(salesprice > 0)
	{
		with (Math)
		{
			net = round(salesprice/1.175*100)/100;
		}
	}
	else
	{
		net = 0;
	}
	netfld.value = net
}



function calcOrderQty(parlevelfld, stocklevelfld, qtyfld)
{
	var parlevel = parlevelfld.value;
	var stocklevel = stocklevelfld.value;
	var qty = 0;

	if((parlevel - stocklevel) > 0)
	{
		with (Math)
		{
			qty = round(parlevel - stocklevel);
		}
	}
	else
	{
		qty = 0;
	}
	qtyfld.value = qty;
}

function calcStockUsage(startfld, endfld, trxfld, usagefld)
{
	var start = startfld.value/1;
	var end = endfld.value/1;
	var trx = trxfld.value/1;
	var usage = 0;

	with (Math)
	{
		usage = start + trx - end;
	}
	usagefld.value = usage;
}


function calcStockDiff(usagefld, posfld, difffld)
{
	var usage = usagefld.value;
	var pos = posfld.value;
	var diff = 0;

	diff = pos - usage;
	difffld.value = diff;
}


function calcTotal(qtyfld, pricefld, discountfld, totalfld)
{
	var qty = qtyfld.value/1;
	var price = pricefld.value/1;
	var discount = discountfld.value/1;
	var total = 0;
//	alert(ratio);
	with (Math)
	{
		var total = round(((qty*price) - discount)*100) / 100;
	}
	totalfld.value = total;
}


function clearLookup(fld, displayfld)
{
	fld.value = '';
	displayfld.value ='';
}



function reset()
{
	var type = '';
	var name, i, tmp;
	var itemqtyctr = 0;

//	document.forms[0].reset();
			
	for (i = 0; i < document.forms[0].elements.length; i++)
	{
		name = (document.forms[0].elements[i].name).toLowerCase();
		tmp = "item_id" + i
		Alert(tmp)
		if (name == ("qty" + i)){
			document.forms[0].elements[i].selectedIndex = 0;
		}
		else if (name == ("stock_level" + i)){
			document.forms[0].elements[i].selectedIndex = 0;
		}
	}
}


function showStatus(text)
{
  window.event.returnValue = true;
  window.status = text;
}

function CheckAll()
{
	for (var i=0;i<document.message.elements.length;i++)
	{
		var e = document.message.elements[i];
		if ((e.name != 'allbox') && (e.type=='checkbox'))
		e.checked = document.message.allbox.checked;
	}
}
