var codex;
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function hideDiv(id){
	//if (document.getElementById(id)) {
        document.getElementById(id).style.display='none';
    //}
}
function showDiv(id){
    //if (document.getElementById(id)) {
	    document.getElementById(id).style.display='block';
    //}
}
function writeDiv(id,text) {
	if (document.getElementById(id)) {
		document.getElementById(id).innerHTML=text;
	}
}
var ge_var=0;
function ge(id) {
	while (!document.getElementById(id) && ge_var<=15) {
		ge_var++;
		return ge(id);
	}
	return document.getElementById(id);
}
function elem(id) {
	return document.getElementById(id);
}
function toggleDivVis(id) {
	if (ge(id)) {
		if (ge(id).style.display=='none') {
			ge(id).style.display='block';
			stat='open';
		} else {
			ge(id).style.display='none';
			stat='close';
		}
		takePost('ajax/set_sessions.php','','stat='+stat+'&div='+id);
	}
}
function toggleDiv(id) {
	if (ge(id)) {
		if (ge(id).style.display=='none') {
			ge(id).style.display='block';
		} else {
			ge(id).style.display='none';
		}
	}
}
function changeArrow(div,el) {
	if (ge(div)) {
		if (ge(div).style.display=='none')  {
			applyClass(el,'desktop_arrow_up');
		} else {
			applyClass(el,'desktop_arrow_down');
		}
	}
}
function applyClass(elId,classN) {
	if (ge(elId)) {
		ge(elId).className=classN;
	}
}
function checkEnterKey(event) {
	var charCode = event.keyCode ? event.keyCode : event.which;
	if (charCode==13) return true;
	return false;
}
function checkTabKey(event) {
	var charCode = event.keyCode ? event.keyCode : event.which;
	if (charCode==9) return true;
	return false;
}
//STOP PROPAGATION
function stopEvent(event)
{
	if(event.stopPropagation) {event.stopPropagation();}
	event.cancelBubble = true;
}
function stopPropOnEnter(event) {
	if (checkEnterKey(event)) {
		return false;
	}
	return true;
}
function stopTab(event) {
	if (checkTabKey(event)) {
		return false;
	}
	return true;
}
//print_r pt javascript
function print_r(name,array){
	var buffer=name;
	for(i in array){
		buffer+='\n'+i+'=>'+array[i];
	}
	alert(buffer);
}
function take(file,func,qs){
	var xmlhttp;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	  try {
	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	 } catch (e) {
	  try {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	  } catch (E) {
	   xmlhttp=false
	  }
	 }
	@else
	 xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
				xmlhttp = new XMLHttpRequest();
			} catch (e) {
				xmlhttp=false
			}
	}
	xmlhttp.open("GET", file+"?"+qs,true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
		xxx=xmlhttp.responseText;
		runScript(xxx);
		if (func.length>0)
			eval(func+"('"+escape(encodeURIComponent(xxx))+"');");
		//document.getElementById(div).style.display='';
		//return false;

  //xmlhttp.readyState=0;
	}
 }
  xmlhttp.send(null)
}
function takePost(file,func,qs,aux){
	var xmlhttp;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try {
	xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	} catch (e) {
	try {
	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	} catch (E) {
	xmlhttp=false
	}
	}
	@else
	xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp=false
		}
	}
	xmlhttp.open("POST", file+'?'+qs,true);
	xmlhttp.setRequestHeader("Content-Type",
	"application/x-www-form-urlencoded");

	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			xxx=xmlhttp.responseText;
//			alert(xxx);
			runScript(xxx);
			if (func.length>0)
			eval(func+"('"+escape(encodeURIComponent(xxx))+"','"+aux+"');");
		}
	}
	xmlhttp.send(qs);
}

function loadAjax(div,file,qs,topDistance) {
	if (topDistance && !isNaN(topDistance)) {
		var topPad = topDistance;
	} else {
		var topPad = 50;
	}
	if (divEl = ge(div)) {
		divEl.innerHTML='';
		var newDiv = document.createElement("div");
		newDiv.style.textAlign = "center";
		newDiv.style.paddingTop = topPad+"px";
		newDiv.style.paddingBottom = topPad+"px";
		var image=document.createElement("img");
		image.src=rootDir+'images/ajax-loader.gif';
		image.border=0;
		newDiv.appendChild(image);
		divEl.appendChild(newDiv);
		takePost(file,'',qs+'&div='+div);
	}
}

function decode_ajax(xxx) {
	xxx=unescape(xxx);
	xxx=decodeURIComponent(xxx);
    return xxx;
}
function runScript(text)
{
	if(text)
	{
		var prs=text.match(/<script>.*<\/script>/gim);
		if(prs)
		for(i=0; i<prs.length; i++)
		{
			var code=prs[i].split("</script>")[0].split("<script>")[1];
			eval(code);
		}
	}
}

function submit_form(formID,method,action,target) {
	var myform = ge(formID);
	myform.method=method;
	if (action) 
		myform.action=action;
	if (target)
		myform.target=target;
	myform.submit();
}

function getWidth(/* Object */ el, /* boolean */ includePadding, /* boolean */ includeBorder) {
    var width;
    el = (typeof(el) == "string") ? document.getElementById(el) : el;    
    
    if(window.getComputedStyle) { // FF, Safari, Opera
        var style = document.defaultView.getComputedStyle(el, null);
        if(style.getPropertyValue("display") == "none")
            return 0;
        width = parseInt(style.getPropertyValue("width"));
        
        if(navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
            // opera includes the padding and border when reporting the width/height - subtract that out
            width -= parseInt(style.getPropertyValue("padding-left"));
            width -= parseInt(style.getPropertyValue("padding-right"));
            width -= parseInt(style.getPropertyValue("border-left-width"));
            width -= parseInt(style.getPropertyValue("border-right-width"));
        }
        
        if(includePadding) {
            width += parseInt(style.getPropertyValue("padding-left"));
            width += parseInt(style.getPropertyValue("padding-right"));
        }
        
        if(includeBorder) {
            width += parseInt(style.getPropertyValue("border-left-width"));
            width += parseInt(style.getPropertyValue("border-right-width"));
        }
    } else { // IE
        if(el.currentStyle["display"] == "none")
            return 0;
        var widthCSS = el.currentStyle["width"];
        var bRegex = /thin|medium|thick/; // regex for css border width keywords
        width = el.offsetWidth; // currently the width including padding + border
        
        if(!includeBorder) {
            var borderLeftCSS = el.currentStyle["borderLeftWidth"];
            var borderRightCSS = el.currentStyle["borderRightWidth"];
            var temp = document.createElement("DIV");
            if(!bRegex.test(borderLeftCSS)) {
                temp.style.width = borderLeftCSS;
                el.parentNode.appendChild(temp);
                width -= Math.round(temp.offsetWidth);
                el.parentNode.removeChild(temp);
            } else if(bRegex.test(borderLeftCSS)) {
                if(el.offsetWidth > el.clientWidth && el.currentStyle["borderLeftStyle"] != "none") {
                    temp.style.width = "10px";
                    temp.style.border = borderLeftCSS + " " + el.currentStyle["borderLeftStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    width -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
            if(!bRegex.test(borderRightCSS)) {
                temp.style.width = borderRightCSS;
                el.parentNode.appendChild(temp);
                width -= Math.round(temp.offsetWidth);
                el.parentNode.removeChild(temp);
            } else if(bRegex.test(borderRightCSS)) {
                if(el.offsetWidth > el.clientWidth && el.currentStyle["borderRightStyle"] != "none") {
                    temp.style.width = "10px";
                    temp.style.border = borderRightCSS + " " + el.currentStyle["borderRightStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    width -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
        }
        
        if(!includePadding) {
            var paddingLeftCSS = el.currentStyle["paddingLeft"];
            var paddingRightCSS = el.currentStyle["paddingRight"];
            var temp = document.createElement("DIV");
            temp.style.width = paddingLeftCSS;
            el.parentNode.appendChild(temp);
            width -= Math.round(temp.offsetWidth);
            temp.style.width = paddingRightCSS;
            width -= Math.round(temp.offsetWidth);
            el.parentNode.removeChild(temp);
        }
    }
    
    return width;
}

function getHeight(/* Object */ el, /* boolean */ includePadding, /* boolean */ includeBorder) {
    var height;
    el = (typeof(el) == "string") ? document.getElementById(el) : el;
    
    if(window.getComputedStyle) { // FF, Safari, Opera
        var style = document.defaultView.getComputedStyle(el, null);
        if(style.getPropertyValue("display") == "none")
            return 0;
        height = parseInt(style.getPropertyValue("height"));
        
        if(navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
            // opera includes the padding and border when reporting the width/height - subtract that out
            height -= parseInt(style.getPropertyValue("padding-top"));
            height -= parseInt(style.getPropertyValue("padding-bottom"));
            height -= parseInt(style.getPropertyValue("border-top-width"));
            height -= parseInt(style.getPropertyValue("border-bottom-width"));
        }
        
        if(includePadding) {
            height += parseInt(style.getPropertyValue("padding-top"));
            height += parseInt(style.getPropertyValue("padding-bottom"));
        }
        
        if(includeBorder) {
            height += parseInt(style.getPropertyValue("border-top-width"));
            height += parseInt(style.getPropertyValue("border-bottom-width"));
        }
    } else { // IE
        if(el.currentStyle["display"] == "none")
            return 0;
        var heightCSS = el.currentStyle["height"];
        var bRegex = /thin|medium|thick/; // regex for css border width keywords
        height = el.offsetHeight; // currently the height including padding + border
        
        if(!includeBorder) {
            var borderTopCSS = el.currentStyle["borderTopWidth"];
            var borderBottomCSS = el.currentStyle["borderBottomWidth"];
            var temp = document.createElement("DIV");
            if(!bRegex.test(borderTopCSS)) {
                temp.style.width = borderTopCSS;
                el.parentNode.appendChild(temp);
                height -= Math.round(temp.offsetWidth);
                el.parentNode.removeChild(temp);
            } else if(bRegex.test(borderTopCSS)) {
                if(el.offsetHeight > el.clientHeight && el.currentStyle["borderTopStyle"] != "none") {
                    temp.style.width = "10px";
                    temp.style.border = borderTopCSS + " " + el.currentStyle["borderTopStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    height -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
            if(!bRegex.test(borderBottomCSS)) {
                temp.style.width = borderBottomCSS;
                el.parentNode.appendChild(temp);
                height -= Math.round(temp.offsetWidth);
                el.parentNode.removeChild(temp);
            } else if(bRegex.test(borderBottomCSS)) {
                if(el.offsetHeight > el.clientHeight && el.currentStyle["borderBottomStyle"] != "none") {
                    temp.style.width = "10px";
                    temp.style.border = borderBottomCSS + " " + el.currentStyle["borderBottomStyle"] + " #000000";
                    el.parentNode.appendChild(temp);
                    height -= Math.round((temp.offsetWidth-10)/2);
                    el.parentNode.removeChild(temp);
                }
            }
        }
        
        if(!includePadding) {
            var paddingTopCSS = el.currentStyle["paddingTop"];
            var paddingBottomCSS = el.currentStyle["paddingBottom"];
            var temp = document.createElement("DIV");
            temp.style.width = paddingTopCSS;
            el.parentNode.appendChild(temp);
            height -= Math.round(temp.offsetWidth);
            temp.style.width = paddingBottomCSS;
            height -= Math.round(temp.offsetWidth);
            el.parentNode.removeChild(temp);
        }
    }
    
    return height;
}

function generalGetCountries(countryField,stateField,cityField,zipField,country,className) {
	takePost('ajax/general_get_countries','','country_field='+countryField+'&state_field='+stateField+'&city_field='+cityField+'&zip_field='+zipField+'&country='+country+'&className='+className);
}
function generalGetStates(countryField,stateField,cityField,zipField,country,state,className) {
	if (!country) {
		if (ge(countryField)) {
			country=ge(countryField).value;
		} else {country='';}
	}
	takePost('ajax/general_get_states','','country_field='+countryField+'&state_field='+stateField+'&city_field='+cityField+'&zip_field='+zipField+'&country_code='+country+'&state='+state+'&className='+className);
}
function generalGetCities(countryField,stateField,cityField,zipField,state,city,className) {
	if (!state) {
		if (ge(stateField)) {
			state=ge(stateField).value;
		} else {state=0;}
	}
	takePost('ajax/general_get_cities','','country_field='+countryField+'&state_field='+stateField+'&city_field='+cityField+'&zip_field='+zipField+'&state_code='+state+'&city='+city+'&className='+className);
}
function generalGetZips(countryField,stateField,cityField,zipField,city,zip,className) {
	if (!city) {
		if (ge(cityField)) {
			city=ge(cityField).value;
		} else {city=0;}
	}
	takePost('ajax/general_get_zips','','country_field='+countryField+'&state_field='+stateField+'&city_field='+cityField+'&zip_field='+zipField+'&city_code='+city+'&zip='+zip+'&className='+className);
}
function makeInvisible(id,seconds,parrent,type) {
	if (!document.getElementById(parrent)) {
		var el=ge(id);
	} else {
		if (!type || type.length<=0) type='div';
		var el=returnElement(id,parrent,type);
	}
	el.style.display='block';
	window.setTimeout("doInvisible('"+id+"','"+parrent+"','"+type+"')",parseInt(seconds)*1000);
}
function doInvisible(id,parrent,type) {
	if (document.getElementById(parrent)) {
		var el=returnElement(id,parrent,type);
	} else {
		var el=ge(id);
	}
	if (el)
		el.style.display='none';
}
function select_setboxes(check) {
    for (i=1; true; i++) {
        if (window.document.getElementById('select_'+i)) {
            window.document.getElementById('select_'+i).checked = check;
        } else {
            break;
        }
        if (i>1000)
            break;
    }
}
function select_setboxes2(check) {
    for (i=1; true; i++) {
        if (window.document.getElementById('select_'+i+'_2')) {
            window.document.getElementById('select_'+i+'_2').checked = check;
        } else {
            break;
        }
        if (i>1000)
            break;
    }
}
var toggle=false;
function toggleCheckbox(check,el) {
	var allElem = ge(el).getElementsByTagName("input");
	for (var d=0; d<allElem.length; d++) {
		var el=allElem[d];
		if (el.type=='checkbox') {
			el.checked=check;
		}
	}
}
function returnElement(element,parrent,type) {
	if (!parrent) return document.getElementById(element);
//	alert(parrent);
	var allElem = document.getElementById(parrent).getElementsByTagName(type);
	for (var d=0; d<allElem.length; d++) {
		var el=allElem[d];
		if (el.id==element) {
			return el;
		}
	}
}

var popupWindow;
function open_window(width,height,winURL,winName,addFeatures) {
	var cw=document.documentElement.clientWidth/2;
	var ch=document.documentElement.clientHeight/2;
	var x=Math.round(cw-width/2);
	var y=Math.round(ch-height/2);
	popupWindow = window.open(winURL,winName,'left='+x+',top='+y+',width='+width+',height='+height+addFeatures);
	return popupWindow;
}

<!-- Begin Password Generator
function getRandomNum(lbound, ubound) {
return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}
function getRandomChar(number, lower, upper, other, extra) {
var numberChars = "0123456789";
var lowerChars = "abcdefghijklmnopqrstuvwxyz";
var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var otherChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
var charSet = extra;
if (number == true)
charSet += numberChars;
if (lower == true)
charSet += lowerChars;
if (upper == true)
charSet += upperChars;
if (other == true)
charSet += otherChars;
return charSet.charAt(getRandomNum(0, charSet.length));
}
function getPassword(length, extraChars, firstNumber, firstLower, firstUpper, firstOther,
latterNumber, latterLower, latterUpper, latterOther) {
var rc = "";
if (length > 0)
rc = rc + getRandomChar(firstNumber, firstLower, firstUpper, firstOther, extraChars);
for (var idx = 1; idx < length; ++idx) {
rc = rc + getRandomChar(latterNumber, latterLower, latterUpper, latterOther, extraChars);
}
return rc;
}

//################################## SAVE ACQUISITION ORDER ##################################
function save_acqo() {
	ge('acq-order-set-up-form').target='iframe';
	ge('acq-order-set-up-form').action=rootDir+'acq-orders/set-up/?save_acqo=1';
	ge('acq-order-set-up-form').submit();
}
var save_order_int;
function save_order_at_interval(interval) {
	if (!interval) interval=30;
	clearInterval(save_order_int);
	save_order_int=setTimeout("save_acqo()",interval*1000);
}
function setMaskDim() {
	var shadow = document.getElementById("shadow");
	var el=document.getElementById('page_all_content_div');
	var w=getWidth(el,false,false);
	var h=getHeight(el,false,false);
	shadow.style.width = w+'px';
    shadow.style.height = (h+20)+'px';
}
//################################ END SAVE ACQUISITION ORDER ################################

//################################## SAVE ORDER ##################################
function keep_alive(){
	takePost('ajax/keep_alive.php','','');
}
function save_o() {
	ge('acq-order-set-up-form').target='iframe';
	ge('acq-order-set-up-form').action=rootDir+'orders/set-up/?save_acqo=1';
	ge('acq-order-set-up-form').submit();
}
var save_order_int_a;
function save_order_at_interval_a(interval) {
	if (!interval) interval=30;
	clearInterval(save_order_int_a);
//	save_order_int_a=setTimeout("save_o()",interval*1000);
	save_order_int_a=setTimeout("keep_alive()",interval*1000);
}
//################################ END SAVE ORDER ################################

//################################## GOODS IN ##################################
function enterToTab(formRef, focusAny) /*2843295374657068656E204368616C6D657273*/
{
 for(var i=0, e=formRef.elements, len=e.length, hasNext=true; i<len && hasNext; i++)
  if( e[i].type && /^text|password|file/.test( e[i].type ) )
  {
   for(var j=i+1; j<len &&  (!e[j].type || /submit|reset/.test(e[j].type)||( focusAny ? /hidden/.test(e[j].type): !/^text|password|file/.test(e[j].type)) ); j++)
   ;
   hasNext = j!=len;
   
   /*e[i].onkeypress=new Function("var ta=false,k=(arguments[0]?arguments[0].which:window.event.keyCode )!=13;\
   if(!k && !(ta=(this.type=='textarea'&&this.value.length>0)) && "+hasNext+")this.form.elements["+(j)+"].focus(); return k||ta;");*/
   var ta=false; k=false;
   if(!k && !(ta=(this.type=='textarea' && this.value.length>0)) && hasNext) e[i].setAttribute('nextId',e[i].form.elements[(j)].id);
  }  
}
function checkQTY(event,total,otherId,thisEl,msgDivId) {
	var other=parseInt(ge(otherId).value);
	var cur=parseInt(thisEl.value);
	var aux=total-other-cur;
	var flag=true;
	var msg='';
	var msgDiv=ge(msgDivId);
	if (isNaN(thisEl.value) || trim(thisEl.value)=='') {
		flag=false;
		msg='Invalid quantity (numeric value expected)';
	} else if (aux<0) {
		flag=false;
		msg='Invalid quantity ('+aux+')';
	} else if (other<0 || cur<0) {
		flag=false;
		msg='Invalid quantity (all values must be positive)';
	}
	if (!flag) {
		thisEl.value=0;
		msgDiv.innerHTML=msg;
		msgDiv.style.display='block';
		thisEl.focus();
		thisEl.select();
		return false;
	}
	msgDiv.style.display='none';
	msgDiv.innerHTML='';
	return true;
}
function getBarcode(curEl,qty1,qty2,msgDivId,tr,oid,pid) {
	var msgDiv=ge(msgDivId);
	var ok=true;
	var qty1El=ge(qty1);
	var qty2El=ge(qty2);
	var trEl=ge(tr);
	var qty1v=parseInt(qty1El.value);
	var qty2v=parseInt(qty2El.value);
	var opid=parseInt(ge(oid+'_product_opid['+pid+']').value);
	if (trim(curEl.value)=='') {
		curEl.value='';
		goToNextFocus(curEl.id);
	} else if (isNaN(curEl.value)) {
		curEl.value='';
		ok='Invalid Barcode';
	} else if (qty1v+qty2v<=0) {
		curEl.value='';
		ok='No quantities are entered.';
	} else if (curEl.value<=0) {
		curEl.value='';
		ok='Barcode cannot be negative.';
	}
	if (ok!==true) {
		msgDiv.innerHTML=ok;
		msgDiv.style.display='block';
		curEl.focus();
		curEl.select();
		return false;
	} else if (trim(curEl.value)!='') {
		msgDiv.style.display='none';
		msgDiv.innerHTML='';
		var brcode=trim(curEl.value);
		closeTr(qty1,qty2,curEl.id,tr);
		saveGoodsInP(oid,pid,brcode,qty1v,qty2v,qty1,qty2,curEl.id,tr,opid);
		return false;
	}
	msgDiv.style.display='none';
	msgDiv.innerHTML='';
	trEl.className='giTrOk';
	return false;
}
function saveGoodsInP(oid,pid,barcode,qty1,qty2,qty1Id,qty2Id,barcodeId,trId,opid) {
	takePost(rootDir+'ajax/savegoodsinp.php','','oid='+oid+'&pid='+pid+'&barcode='+barcode+'&qty1='+qty1+'&qty2='+qty2+'&qty1Id='+qty1Id+'&qty2Id='+qty2Id+'&barcodeId='+barcodeId+'&trId='+trId+'&opid='+opid);
}
function closeTr(qty1El,qty2El,curEl,trEl) {
	ge(qty1El).disabled=true;
	ge(qty2El).disabled=true;
	ge(curEl).disabled=true;
	ge(trEl).className='giTrEnd';
}
function openTr(qty1El,qty2El,curEl,trEl,divId,msg) {
	ge(qty1El).disabled=false;
	ge(qty2El).disabled=false;
	ge(curEl).disabled=false;
	ge(curEl).value='';
	ge(trEl).className='giTrErr';
	ge(divId).innerHTML=msg;
	ge(divId).style.display='block';
	ge(curEl).focus();
	ge(curEl).select();
}
function savedTr(trId) {
	ge(trId).className='giTrSaved';
}
function goToNextFocus(barcodeId) {
	var curEl=ge(barcodeId);
	var nextEl=null;
	while(nextEl=ge(curEl.getAttribute('nextId'))) {
		if (nextEl.disabled) {
			
		} else {
			nextEl.focus();
			break;
		}
		curEl=nextEl;
	}
}
//################################## END GOODS IN ##################################

//################################## AGENT ORDER ##################################
function checkAOQTY(total,alloc,thisEl,elId,pid,opid) {
	var total=parseInt(ge('product_maxqty['+opid+']').value);
	var alloc=parseInt(alloc);
	var cur=parseInt(thisEl.value);
	if (ge('oid')) var oid=ge('oid').value;
	else var oid=0;
	
	if (ge('carriage')) var carriage=parseFloat(ge('carriage').value);
	else var carriage=0;
	if (isNaN(carriage)) carriage = 0;
	
	if(ge('customer[d_location]')) var loc_id=ge('customer[d_location]').value;
	else var loc_id=0;
	
	thisEl.disabled=true;
	warningTr(elId,'Loading...');
	takePost(rootDir+'ajax/expected_stock.php','','total='+total+'&alloc='+alloc+'&entered='+cur+'&cur_id='+thisEl.id+'&container_id='+elId+'&pid='+pid+'&oid='+oid+'&opid='+opid+'&loc_id='+loc_id);
	var ddd='orders_'+opid+'_menu_div';
	closeGridMenu(opid,ddd,'orders_'+opid+'_main_tr','',true);
	if ((total)<cur) {
		
	} else {
		closeAOTr(elId);
	}
	return true;
}
function checkBackOrderP(divId,pid) {
	if (ge('product_pid['+pid+']')) {
		warningTr(divId,'Warning! The product is already inserted in this order. However, you can also add it to the current order.');
	} else {
		ge(divId).innerHTML='';
	}
}
function warningTr(elId,text) {
	ge(elId).innerHTML=text;
	ge(elId).style.backgroundColor='#FFFFCC';
	ge(elId).style.display='block';
	ge(elId).className='aoDivContainer';
}
function closeAOTr(elId) {
	ge(elId).style.display='none';
	ge(elId).innerHTML='';
	ge(elId).style.backgroundColor='';
	ge(elId).className='aoDivContainer';
}
function errTr(elId,text) {
	ge(elId).innerHTML=text;
	ge(elId).style.backgroundColor='#FBD0CA';
	ge(elId).style.display='block';
	ge(elId).className='aoDivContainer';
}
function change_status_mention(s) {
	var div=ge('change_status_message_div');
	div.style.display='block';
	switch(s) {
		case "pending": text='The despatch is awaiting further changes from you.';
			break;
		case "ready": text='WARNING!<br>The despatch will wait for authorization from the admins and, if authorized, all the products that are in stock will be shipped.<br>If you do this, you won\'t be able to edit this despatch.';
			break;
		case "authorized": text='WARNING!<br>This despatch will go directly to the despatch system.<br>No additional authorization required.';
			break;
		case "canceled": text='WARNING!<br>The despatch will be canceled and no other actions will be possible with it.';
			break;
		case "incomplete": text='The despatch has been partially delivered.';
			break;
		case "rejected": text='WARNING!<br>The despatch is rejected.';
			break;
		default: div.style.display='none';
	}
	warningTr(div.id,text);
}
function change_status_mention_return(s) {
	var div=ge('change_status_message_div');
	div.style.display='block';
	switch(s) {
		case "pending": text='The return is awaiting further changes from you.';
			break;
		case "ready": text='WARNING!<br>The return will wait for authorization from the admins.<br>If you do this, you won\'t be able to edit this return.';
			break;
		case "canceled": text='WARNING!<br>The return will be canceled and no other actions will be possible with it.';
			break;
		case "rejected": text='WARNING!<br>The return is rejected.';
			break;
		default: div.style.display='none';
	}
	warningTr(div.id,text);
}
function openAOComments(oid) {
	var divEl=ge('despatch_'+oid+'_menu_div');
	if (divEl.getAttribute("load")!='comments') {
		divEl.innerHTML='Loading. Please wait...';
		divEl.style.display='block';
		divEl.setAttribute("load","comments");
		takePost(rootDir+'ajax/order_comments.php','','id='+oid+'&divId='+divEl.id);
	} else {
		toggleDiv(divEl.id);
	}
}
//################################## END AGENT ORDER ##################################
//################################## DESPATCH ORDER ##################################
function openDOrderMenu(oid) {
	oid=parseInt(oid);
	var divId=oid+'_menu_div';
	var divEl=ge(divId);
	var trId=oid+'_main_tr';
	if (divEl.getAttribute("load")!='no' && divEl.style.display=='none') {
		//warningTr(divEl.id,'Loading. Please wait...');
		divEl.innerHTML='Loading. Please wait...';
		divEl.style.display='block';
		divEl.setAttribute("load","no");
		takePost(rootDir+'ajax/despatch_load_menu.php','','oid='+oid+'&divId='+divId+'&trId='+trId);
	} else {
		toggleDiv(divId);
	}
}
function checkDespatchQTY(thisEl,oid,pid) {
	oid=parseInt(oid); pid=parseInt(pid);
	var avl_qty=parseInt(ge(oid+'_avl_qty['+pid+']').value);
	var dem_qty=parseInt(ge(oid+'_exp_qty['+pid+']').value);
	var exp_qty=parseInt(thisEl.value);
	var msgDiv=ge('warn_'+oid+'_message_div['+pid+']');
	var flag=true;
	if (isNaN(thisEl.value) || trim(thisEl.value)=='') {
		flag=false;
		msg='Invalid quantity (numeric value expected)';
	} else if (exp_qty<0) {
		flag=false;
		msg='Invalid quantity (all values must be positive)';
	} else if (dem_qty<exp_qty) {
		flag=false;
		msg='The qty exceeds the demanded qty.';
	} else if (exp_qty>avl_qty) {
		flag=false;
		msg='The qty exceeds current level stock.';
	}
	
	if (!flag) {
		thisEl.value=0;
		msgDiv.innerHTML=msg;
		msgDiv.style.display='block';
		thisEl.focus();
		thisEl.select();
		return false;
	}
	msgDiv.style.display='none';
	msgDiv.innerHTML='';
	return true;
}
function getBarcodeDespatch(curEl,oid,pid) {
	oid=parseInt(oid); pid=parseInt(pid);
	var avl_qty=parseInt(ge(oid+'_avl_qty['+pid+']').value);
	var dem_qty=parseInt(ge(oid+'_exp_qty['+pid+']').value);
	var exp_qty=parseInt(ge(oid+'_product_qty['+pid+']').value);
	var msgDiv=ge('warn_'+oid+'_message_div['+pid+']');
	var trEl=ge(oid+'_tr['+pid+']');
	var brcode=trim(curEl.value);
	var ok=true;
	
	if (trim(curEl.value)=='') {
		curEl.value='';
		//goToNextFocus(curEl.id);
	} else if (isNaN(curEl.value)) {
		curEl.value='';
		ok='Invalid Barcode';
	} else if (exp_qty<=0) {
		curEl.value='';
		ok='No quantity is entered.';
	} else if (curEl.value<=0) {
		curEl.value='';
		ok='Barcode cannot be negative.';
	}
	if (ok!==true) {
		msgDiv.innerHTML=ok;
		msgDiv.style.display='block';
		curEl.focus();
		curEl.select();
		return false;
	} else if (trim(curEl.value)!='') {
		msgDiv.style.display='none';
		msgDiv.innerHTML='';
		closeDespatchTr(oid+'_product_qty['+pid+']',curEl.id,trEl.id);
		saveDespatchP(oid,pid,brcode,exp_qty);
		return false;
	}
	msgDiv.style.display='none';
	msgDiv.innerHTML='';
	trEl.className='giTrOk';
	return false;
}
function saveDespatchP(oid,pid,barcode,qty) {
	takePost(rootDir+'ajax/savedespatchp.php','','did='+oid+'&pid='+pid+'&barcode='+barcode+'&qty='+qty);
}
function closeDespatchTr(qtyEl,curEl,trEl) {
	ge(qtyEl).readOnly=true;
	ge(curEl).readOnly=true;
	ge(trEl).className='giTrEnd';
}
function openDespatchTr(qtyEl,curEl,trEl,divId,msg) {
	ge(qtyEl).readOnly=false;
	ge(curEl).readOnly=false;
	ge(curEl).value='';
	ge(trEl).className='giTrErr';
	ge(divId).innerHTML=msg;
	ge(divId).style.display='block';
	ge(curEl).focus();
	ge(curEl).select();
}
//################################## END DESPATCH ORDER ##################################
function openGridMenu(id,divId,trId,ajaxFile,qs) {
	if (!qs) qs='';
	var divEl=ge(divId);
	if (divEl.getAttribute("load")!=ajaxFile) {
		divEl.style.display='block';
		divEl.innerHTML='Loading. Please wait...';
		divEl.setAttribute("load",ajaxFile);
		takePost(rootDir+'ajax/'+ajaxFile,'','id='+id+'&divId='+divId+'&trId='+trId+qs);
	} else {
		toggleDiv(divEl.id);
	}
}
function closeGridMenu(id,divId,trId,color,reseT) {
	var divEl=ge(divId);
	var trEl=ge(trId);
	divEl.style.display='none';
	// set tr color
	var sec=0;
	switch (color) {
		case "red":
			color='#FBD0CA'; sec=5; break;
		case "green":
			color='#E4FDE3'; sec=3; break;
		default: color=false;
	}
	if (color) {
		var col=trEl.style.backgroundColor; 
		trEl.style.backgroundColor=color;
		setTimeout("ge('"+trId+"').style.backgroundColor='"+col+"';",(sec*1000));
	}
	if (reseT) {
		divEl.setAttribute("load","yes");
	}
}
function addCart(id,qty,loadmain,grab) {
	if (!qty) qty=0;
	if (!loadmain) loadmain='';
	if (!grab) grab='';
	loadAjax('cart_container',rootDir+'ajax/cart/add/','id='+id+'&qty='+qty+'&loadmain='+loadmain+'&grab='+grab);
}
function filterProducts(key,val) {
	var a = new Array();
	a['cid']='';
	a['q']='';
	a['s']='';
	a['p']='';
	a['t']='';
	a['page']='';
	for (i in a) {
		if (el = ge('products_f_'+i)) a[i] = el.value;
	}
	if (key) {
		eval('a["'+key+'"] = "'+val+'";');
		if (el = ge('products_f_'+key)) el.value = val;
	}
	var query='';
	for (i in a) {
		query+=i+'='+a[i]+'&';
	}
	query+='post=1';
	loadAjax('products',rootDir+'ajax/products/items/?'+query,'',200);
}

function pageJumpDoru(newPage) {
	var rg = /(\?|&)page=[0-9]+/i;
	var newLocation = window.location.href.replace(rg, "$1page=" + newPage);
	if (rg.lastIndex == 0) {
		if (newLocation.indexOf("?") != -1) newLocation += "&page=" + newPage;
		else newLocation += "?page=" + newPage;
	}
	window.location.href = newLocation;
}

// PRODUCT SUPPLIERS DROPDOWN //
  function removeOptionSelected(removerId,inserterId)
  {
	if (!document.getElementById(removerId) || !document.getElementById(inserterId)) return;
    var elSel = document.getElementById(removerId);
    var i;
    for (i = elSel.length - 1; i>=0; i--) {
      if (elSel.options[i].selected) {
		appendOptionLast(inserterId,{text:elSel.options[i].text, value:elSel.options[i].value});
        elSel.remove(i);
      }
    }
  }
  function appendOptionLast(inserterId, el)
  {
    var elOptNew = document.createElement('option');
    elOptNew.text = el.text;
    elOptNew.value = el.value;
    var elSel = document.getElementById(inserterId);
    try {
      elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew); // IE only
	}
  }
  function selectAllFromList(id)
  {
	if (!document.getElementById(id)) return;
    var elSel = document.getElementById(id);
    var i;
    for (i = elSel.length - 1; i>=0; i--) {
      elSel.options[i].selected=true;
    }
  }
  function same_addr_func() {
	ge('d_name').value=ge('i_name').value;
	ge('d_street1').value=ge('i_street1').value;
	ge('d_street2').value=ge('i_street2').value;
	ge('d_town').value=ge('i_town').value;
	ge('d_city').value=ge('i_city').value;
	ge('d_postcode').value=ge('i_postcode').value;
	ge('d_country').value=ge('i_country').value;
}

function check_min_qty(elm, carton_min_qty, product_name) {
	if (elm.value <= 0) return;
	if (elm.value < carton_min_qty && carton_min_qty > 1) {
		if (confirm('A minimum of ' + carton_min_qty + ' cartons are required to buy this product: ' + product_name + '!\nClick \'OK\' if you want to remove all of them, or \'Cancel\' if you want to keep the minimum quantity in your cart.\nMake sure you save any changes you have made, by clicking "Update cart"!')) {
			elm.value = 0;
		} else {
			elm.value = carton_min_qty;
		}
	}
}

