function addSeparatorsNF(nStr, inD, outD, sep){
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1){
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)){
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}


function input_maxvalue(elem, maxlimit){
	if(elem.value > maxlimit || elem.value < 0){
		elem.value = maxlimit;
	}
}


// Restrict user input in a text field
// create as many regular expressions here as you need:
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;
var usernameChars = /[0-9A-Za-z\._-]/g;

function restrictCharacters(myfield, e, restrictionType, checkdot) {
	if (!e) var e = window.event
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	var character = String.fromCharCode(code);

	// if they pressed esc... remove focus from field...
	if (code==27) { this.blur(); return false; }

	// ignore if they are press other keys
	// strange because code: 39 is the down key AND ' key...
	// and DEL also equals .
	if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
		if (character.match(restrictionType)) {
			if(checkdot == "checkdot"){
				return !isNaN(myfield.value.toString() + character);
			} else {
				return true;
			}
		} else {
		return false;
	}
}
}


function encodeHtml(inputtext) {
     encodedHtml = inputtext;
     encodedHtml = encodedHtml.replace(/\//g,"%2F");
     encodedHtml = encodedHtml.replace(/\?/g,"%3F");
     encodedHtml = encodedHtml.replace(/=/g,"%3D");
     encodedHtml = encodedHtml.replace(/&/g,"%26");
     encodedHtml = encodedHtml.replace(/@/g,"%40");
     return encodedHtml;
   }

function removeHTMLTags(inputtext){
	var strTagStrippedText = inputtext.replace(/<\/?[^>]+(>|$)/g, "");
	return strTagStrippedText;
}

function to4DecWithComma(num) {
	num="" + Math.floor(num*100.0 + 0.5)/100.0;

	var i=num.indexOf(".");

	if ( i<0 ) num+=".00";
	else {
		num=num.substring(0,i) + "," + num.substring(i + 1);
		var nDec=(num.length - i) - 1;
		if ( nDec==0 ) num+="00";
		else if ( nDec==1 ) num+="0";
		else if ( nDec>2 ) num=num.substring(0,i + 3);
	}

	return num;
}


function html_entity_decode(str) {
  var ta=document.createElement("textarea");
  ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
  return ta.value;
}


function detectChange (control, color, alertimage) {
	if (control.style) {
		if (control.value != control.defaultValue) {
		control.style.backgroundColor = color;
		if (alertimage != null) document.getElementById(alertimage).style.display = "inline";
		} else {
			control.style.backgroundColor = '';
			if (alertimage != null) document.getElementById(alertimage).style.display = "none";
		}
	}
}

function detectCheckChange (control, color, alertimage) {
	if (control.style) {
		if (control.checked != control.defaultChecked) {
		control.style.backgroundColor = color;
		if (alertimage != null) document.getElementById(alertimage).style.display = "inline";
		} else {
			control.style.backgroundColor = '';
			if (alertimage != null) document.getElementById(alertimage).style.display = "none";
		}
	}
}

function detectSelectChange (control, color, alertimage) {
	if (control.style) {
        listitem = control.options[control.selectedIndex];
		if (listitem.selected != listitem.defaultSelected) {
            control.style.backgroundColor = color;
            if (alertimage != null) document.getElementById(alertimage).style.display = "inline";
		} else {
			control.style.backgroundColor = '';
			if (alertimage != null) document.getElementById(alertimage).style.display = "none";
		}
	}
}


// Access controllers

function changeUserPassword(username) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_CHANGE_PASSWORD&xid="+Math.random()+"&uname="+encodeURI(username), 'changepassword_'+Math.floor(Math.random()*11), "resizable=yes, toolbar=no, width=600, height=300, menubar=no, scrollbars=yes");
}


function changeActivationUser(uid, username, currentstatus) {
	if(confirm('Are you sure you want to change the activation status?')){
	
		remotos = new datosServidor;
		var activationFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_CHANGE_USER_ACTIVATION&uid="+encodeURI(uid)+"&uname="+encodeURI(username)+"&currentstatus="+encodeURI(currentstatus)+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", activationFile);
		
		var URL = unescape(window.location.pathname)+"?page=manageusers&xid="+Math.random();
		window.location.href = URL;
		
	}
}


//---------------------Contacts--------------------

var xmlHttp
//counter = 1
function showDetails(str)
{ 
	if (document.getElementById("tag_01_"+str).innerHTML == "Hide details") 
	{
		document.getElementById("detailBox_"+str).innerHTML="" 
		document.getElementById("tag_01_"+str).innerHTML = "Show details"
	}
	else
	{
		boxid = str
		xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null)
		{
			alert ("Browser does not support HTTP Request. Please upgrade your web browser.")
			return
		}
		var url="ajaxFetcher.php"
		url=url+"?filetoken=FILENAME_AJAX_SHOWDETAILS&cid="+str
		url=url+"&xid="+Math.random()
		xmlHttp.onreadystatechange=c_showDetails_stateChanged 
		xmlHttp.open("GET",url,true)
		xmlHttp.send(null)
	}
}

function c_showDetails_stateChanged() 
{ 
	if (xmlHttp.readyState==1 || xmlHttp.readyState==2 || xmlHttp.readyState==3)
	{ 
		document.getElementById("detailBox_"+boxid).innerHTML="<small>Fetching data...</small>" 
	} 

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById("detailBox_"+boxid).innerHTML=xmlHttp.responseText 
		document.getElementById("tag_01_"+boxid).innerHTML="Hide details" 
		document.getElementById("conEdit_"+boxid).style.display = "none"
 
		if (typeof(lastboxid) == 'undefined')
		{
			lastboxid = boxid
		}
		else
		{
			if(lastboxid != boxid)
			{
				document.getElementById("detailBox_"+lastboxid).innerHTML="" 
				document.getElementById("tag_01_"+lastboxid).innerHTML="Show details" 
				lastboxid = boxid
			}
		}
		initialize();
		mapaddress = removeHTMLTags(document.getElementById("fulladdress").innerText);
		showLocation(mapaddress);
 
	} 
}

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}

	catch (e)
	{
		//Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	return xmlHttp;
}

function startEditing(cid) {
	document.getElementById("conEdit_"+cid).style.display = "";
	document.getElementById("conDetails_"+cid).style.display = "none";
}

function cancelEditing_cluster01(cid) {
	document.getElementById("editMessage_"+cid).innerHTML = "";
}

function cancelEditing(cid) {
	document.getElementById("conEdit_"+cid).style.display = "none";
	document.getElementById("conDetails_"+cid).style.display = "";
	document.getElementById("editMessage_"+cid).innerHTML = "No changes made.";
	setTimeout("cancelEditing_cluster01("+cid+")",1500);
}

function cancelAdding(cid) {
	if(confirm("This action will discard any change made to the form and will NOT save the data to the database. Are you sure?")){
		window.location = "http://bb.ews.com.my/blackbox/index.php?page=contacts&xid="+Math.random();
	}
}

function showSaveStatus(cid) {
	document.getElementById("saveStatus_"+cid).style.display = "";
}

function disableRow_cluster01(cid) {
	document.getElementById("resultRow_02_"+cid).style.display="none";
	document.getElementById("resultRow_01_"+cid).style.display = "none";
}

function disableRow(cid) {
	if (confirm("Are you sure you want to delete the record #"+cid+" ?"))
	{
		remotos = new datosServidor;
		var deleteContact = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_DELETE_CONTACT&cid="+cid+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", deleteContact);
		
		document.getElementById("detailBox_"+cid).style.color="white";
		document.getElementById("detailBox_"+cid).innerHTML="<div style='background-color:red;'><b>Record #"+cid+" deleted.</b></div>";		
		setTimeout("disableRow_cluster01("+cid+")", 2500);
	}
}

function openForQuote(qCustId) {
	urlBase_openForQuote = "ajaxFetcher.php?filetoken=FILENAME_AJAX_OPEN_FOR_QUOTE";
	remotos = new datosServidor;
	nn = remotos.enviar(urlBase_openForQuote+"&qCustId="+qCustId+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", nn);
}


function showCustomerHistory(cid) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_SHOW_CONTACT_HISTORY&cid="+encodeURI(cid)+"&xid="+Math.random(), 'contacthistory_'+cid, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


//------------------Quotations------------------


function selectAttrib(productid, rowid) {
	thisCountry = document.getElementById('custcountryholder').value;
	thisCustType = document.getElementById('custtypeholder').value;
	remotos = new datosServidor;
	var attribSelect = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_QUOTATION_SELECT_ATTRIB&pid="+productid+"&rowid="+rowid+"&thisCountry="+encodeURI(thisCountry)+"&thisCustType="+encodeURI(thisCustType)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", attribSelect);
}


function updatePrice(){
	if(document.getElementById('quoteTable') != null){
		document.body.style.cursor = 'wait';
		var table = document.getElementById('quoteTable');
		var divs = table.getElementsByTagName("div");
		
		for (var i=0; i<divs.length; i++){
			if(divs[i].id.substr(0,6) == "price_"){
				if(divs[i].innerHTML != ""){
					rowid = divs[i].id.substr(6,13);
					pid = document.getElementById('id_'+divs[i].id.substr(6,13)).innerHTML;
					aid = document.getElementById('attrib_'+divs[i].id.substr(6,13)).value;
					thisCountry = document.getElementById('custcountryholder').value;
					thisCustType = document.getElementById('custtypeholder').value;	
					rateResponse = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_UPDATE_QUOTATION_PRICE&pid="+encodeURI(pid)+"&aid=" +encodeURI(aid)+"&thisCountry="+encodeURI(thisCountry)+"&thisCustType="+encodeURI(thisCustType)+"&rowid=" +encodeURI(rowid),"");
					Spry.Utils.setInnerHTML('messages', rateResponse);
					var newTotal = parseFloat(document.getElementById('rate_'+divs[i].id.substr(6,13)).innerHTML) * parseFloat(document.getElementById('qty_'+divs[i].id.substr(6,13)).innerHTML);
					Spry.Utils.setInnerHTML('price_'+divs[i].id.substr(6,13), newTotal.toFixed(2));
					updateQuoteDb("update",pid,"",aid,parseFloat(document.getElementById('rate_'+divs[i].id.substr(6,13)).innerHTML),parseFloat(document.getElementById('qty_'+divs[i].id.substr(6,13)).innerHTML),newTotal.toFixed(2),"draft","",pid);
					updateTotal();
				}
			}
		}
		document.body.style.cursor = 'auto';
	}
}


function updateTotal(){
	var table = document.getElementById('quoteTable');
	var divs = table.getElementsByTagName("div");
	var subTotal = 0;
	for (var i=0; i<divs.length; i++){
		if(divs[i].id.substr(0,6) == "price_"){
			if(divs[i].innerHTML != ""){
				subTotal = subTotal + parseFloat(divs[i].innerHTML);
			}
		}
	}
	Spry.Utils.setInnerHTML(quoteTotal, subTotal.toFixed(2));

	if(subTotal != 0 && document.getElementById('custidholder').value != ''){
		document.submitform.generatebutton.disabled = false;
	} else {
		document.submitform.generatebutton.disabled = true;
	}
}


function q_addrow(str){
	//passThisQCID();
	el = str
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request. Please upgrade your web browser.")
		return
	}
	var url="ajaxFetcher.php"
	url=url+"?filetoken=FILENAME_AJAX_Q_ADDROW"
	//url=url+"&counter="+counter+"&xid="+Math.random()
	url=url+"&xid="+Math.random()
	xmlHttp.onreadystatechange=q_addrow_stateChanged 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}


function q_addrow_stateChanged() 
{ 
	if (xmlHttp.readyState==1 || xmlHttp.readyState==2 || xmlHttp.readyState==3)
	{ 
		
	} 

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		var table=document.getElementById(el);
		var row=table.insertRow(-1); 
		var cell=row.insertCell(-1); 
		cell.vAlign = "top";
		cell.align = "left";
		Spry.Utils.setInnerHTML(cell, xmlHttp.responseText);
		updateTotal();
 	} 
}


function q_subtractrow(identity,el,flag,ask,dbaction){
	//alert(el);
	//passThisQCID();
	var table=document.getElementById(el.parentNode.parentNode.parentNode.id);
	for (var y=0;y<table.rows.length;y++){
		if (table.rows[y].cells[0]==el){
			if(document.getElementById('desc_'+identity).innerHTML == "" || document.getElementById('desc_'+identity).innerHTML == "&nbsp;(click here to add product)" && flag == "check"){
			return;	
			}
			else{
				var productid = document.getElementById('id_'+identity).innerHTML
				if(ask == "ask"){
					if (confirm("Delete?")){
						if(dbaction != "noDb"){
							updateQuoteDb("delete",productid);
						}
						table.deleteRow(y);
						//counter = counter - 1;
						updateTotal();
						editbox_init();
					}
				}
				else {
					if(dbaction != "noDb"){
						updateQuoteDb("delete",productid);
					}
					table.deleteRow(y);
					//counter = counter - 1;
					updateTotal();
					editbox_init();
				}
			}
		}
	}
}


function selectCustomer(qCustId) {
	if(qCustId != ""){
		urlBase_qCid = "ajaxFetcher.php?filetoken=FILENAME_AJAX_UPDATE_QCID";
		remotos = new datosServidor;
		nn = remotos.enviar(urlBase_qCid+"&qCustId="+qCustId+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("customerInfo", nn);
	} else { document.body.style.cursor = 'auto'; }
}


function keypassThisQCID(evt) {
	evt = (evt) ? evt : window.event;
	if (evt.keyCode == 13) {
	passThisQCID();
	}
}


function passThisQCID() {
	document.body.style.cursor = 'wait';
	setTimeout('selectCustomer(document.getElementById("qcidInput").value)',100);
}


function discardQuote(landingpage){
	if(confirm('Are you sure you want to discard this Quotation? This process cannot be undone.')){
		window.location = landingpage;
	}
}


function generateQuote() {
	if(confirm('Are you sure you want to confirm this quotation?')){
		qnum = document.getElementById('quoteId').innerText;
		qdate = document.getElementById('quoteDate').value;
		qmonth = document.getElementById('quoteMonth').value;
		qyear = document.getElementById('quoteYear').value;
		qattn = document.getElementById('kindAttn').value;
		qprojRef = document.getElementById('projRef').value;
		qcustomerid = document.getElementById('custidholder').value;
		
		if(document.getElementById('icdcCheck').checked == true){
			icdc = 'yes';
		} else {
			icdc = 'no';
		}
		
		remotos = new datosServidor;
		var confirmQuotationFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_QUOTATION_CONFIRM_QUOTATION&qnum="+encodeURI(qnum)+"&qdate="+encodeURI(qdate)+"&qmonth="+encodeURI(qmonth)+"&qyear="+encodeURI(qyear)+"&qattn="+encodeURI(qattn)+"&qprojRef="+encodeURI(qprojRef)+"&qcustomerid="+qcustomerid+"&icdc="+icdc+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", confirmQuotationFile);
		
		qcustomer = document.getElementById('contactDetails').innerHTML;
		window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_QUOTATION_GENERATE_QUOTATION&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'quote_'+qnum, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");

		document.getElementById('icdcCheck').disabled = true;
		document.getElementById('discardButton').disabled = true;
		document.getElementById('kindAttn').disabled = true;
		document.getElementById('projRef').disabled = true;
		
		var table = document.getElementById('quoteTable');
		var divs = table.getElementsByTagName("div");
		var selects = table.getElementsByTagName("select");
		
		for (var i=0; i<selects.length; i++){
			selects[i].style.backgroundColor = '';
			selects[i].disabled = true;
		}
		
		for (var i=0; i<divs.length; i++){
			if(divs[i].className == "editText"){
				divs[i].onclick = "";
				divs[i].onfocus = "";
				divs[i].onmouseover = "";
				divs[i].onmouseout = "";
				divs[i].style.cursor = "auto";
				divs[i].title = "";
				divs[i].style.backgroundColor = "";
			}
		}
		window.location = "http://bb.ews.com.my/blackbox/index.php?page=processtracker";
	}
}


function saveprintQuote(qnum){
	var busrep = escape(document.getElementById('salesRep').innerText);
	
	remotos = new datosServidor;
	var saveRepFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_QUOTATION_SAVE_REP&qnum="+encodeURI(qnum)+"&busrep="+busrep+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", saveRepFile);
}


function saveprintDelivery(qnum,wholeDate){
	var deliverto = escape(document.getElementById('deliverAddressBox').innerHTML);
	var deliveryterm = escape(document.getElementById('termBox').innerText);
	var reparea = escape(document.getElementById('areaBox').innerText);
	
	remotos = new datosServidor;
	var saveDeliveryFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_DELIVERY_SAVE&qnum="+encodeURI(qnum)+"&deliverto="+deliverto+"&deliveryterm="+deliveryterm+"&reparea="+reparea+"&wholeDate="+encodeURI(wholeDate)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", saveDeliveryFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
}


function saveprintInvoice(qnum,wholeDate){
	remotos = new datosServidor;
	var saveInvoiceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_INVOICE_SAVE&qnum="+encodeURI(qnum)+"&wholeDate="+encodeURI(wholeDate)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", saveInvoiceFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
}


function saveprintStockCheck(qnum,wholeDate){
	remotos = new datosServidor;
	var saveStockCheckFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_STOCKCHECK_SAVE&qnum="+encodeURI(qnum)+"&wholeDate="+encodeURI(wholeDate)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", saveStockCheckFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
}


function markQuoteInvalid(qnum){
if(confirm('Are you sure you want to mark this track as invalid?')){
	remotos = new datosServidor;
	var markInvalidFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_MARK_INVALID&qnum="+encodeURI(qnum)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", markInvalidFile);
	
	window.location.href = unescape(window.location.pathname)+"?page=processtracker&xid="+Math.random();
	}
}


function saveprintPI(qnum,wholeDate){
	remotos = new datosServidor;
	var savePIFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PI_SAVE&qnum="+encodeURI(qnum)+"&wholeDate="+encodeURI(wholeDate)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", savePIFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
}


function viewQuote(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_QUOTATION_GENERATE_QUOTATION&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'quote_'+qnum, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


function openClientPO(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_SHOW_CPO_CLIENT_PO&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'cpo_'+qnum, "resizable=yes, toolbar=no, width=600, height=300, menubar=no, scrollbars=yes");
}


function openDesignTrack(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_SHOW_TRACK_DESIGN&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'dt_'+qnum, "resizable=yes, toolbar=no, width=600, height=300, menubar=no, scrollbars=yes");
}


function openPaymentTrack(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_SHOW_TRACK_PAYMENT&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'dt_'+qnum, "resizable=yes, toolbar=no, width=600, height=300, menubar=no, scrollbars=yes");
}


function generateDeliveryOrder(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_DELIVERY_GENERATE_DELIVERY_ORDER&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'deliorder_'+qnum, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


function generateInvoice(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_INVOICE_GENERATE_INVOICE&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'invoice_'+qnum, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


function generateStockCheckForm(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_PRODUCTION_GENERATE_STOCK_CHECK_FORM&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'pi_'+qnum, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


function generateProductionInstruction(qnum) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_PRODUCTION_GENERATE_PRODUCTION_INSTRUCTION&qnum="+encodeURI(qnum)+"&xid="+Math.random(), 'pi_'+qnum, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


function printQuote() {
	printFactory.printing.header = "";
	printFactory.printing.footer = "Toll-free: 1300 88 0235  |  Website: www.ews-store.com&bPage &p of &P";
	printFactory.printing.portrait = true;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}


function updateCPO(qnum) {
	var cponum = escape(document.getElementById('input_cponum').value);
	var cpodate = escape(document.getElementById('cpoDate').value);
	var cpomonth = escape(document.getElementById('cpoMonth').value);
	var cpoyear = escape(document.getElementById('cpoYear').value);
	var wholeDate = cpoyear + '-' + cpomonth + '-' + cpodate;
	
	remotos = new datosServidor;
	var updateCPOFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_CPO_UPDATE&qnum="+qnum+"&cponum="+cponum+"&wholeDate="+wholeDate+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", updateCPOFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
	window.close();
}


function updateDesignTrack(qnum) {
	var dsdate = escape(document.getElementById('dsDate').value);
	var dsmonth = escape(document.getElementById('dsMonth').value);
	var dsyear = escape(document.getElementById('dsYear').value);
	var wholeDsDate = dsyear + '-' + dsmonth + '-' + dsdate;
	
	var dfdate = escape(document.getElementById('dfDate').value);
	var dfmonth = escape(document.getElementById('dfMonth').value);
	var dfyear = escape(document.getElementById('dfYear').value);
	var wholeDfDate = dfyear + '-' + dfmonth + '-' + dfdate;
	
	remotos = new datosServidor;
	var updateDesignTrackFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_DESIGNTRACK_UPDATE&qnum="+qnum+"&wholeDsDate="+wholeDsDate+"&wholeDfDate="+wholeDfDate+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", updateDesignTrackFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
	window.close();
}


function updatePaymentTrack(qnum) {
	var paymode = escape(document.getElementById('input_paymode').value);
	var paydate = escape(document.getElementById('payDate').value);
	var paymonth = escape(document.getElementById('payMonth').value);
	var payyear = escape(document.getElementById('payYear').value);
	var wholeDate = payyear + '-' + paymonth + '-' + paydate;
	var paycomments = escape(document.getElementById('input_paycomments').value);
	
	remotos = new datosServidor;
	var updatePaymentTrackFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PAYMENTTRACK_UPDATE&qnum="+qnum+"&paymode="+paymode+"&wholeDate="+wholeDate+"&paycomments="+paycomments+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", updatePaymentTrackFile);
	
	var URL = unescape(window.opener.location.pathname)+"?page=processtracker&xid="+Math.random();
	window.opener.location.href = URL;
	window.close();
}


// Raw Stock Manager

function rs_editThis(category, id, name, colour, grade, variant, length, breadth, thickness, l_unit, b_unit, t_unit, qty) {
	if (isPanelOpen == 0){
		//document.getElementById('stockEditor').style.display = "";
		remotos = new datosServidor;
		var cleanupVendorPriceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_CLEANUP_VENDOR_PRICES&mid="+encodeURI(id)+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", cleanupVendorPriceFile);
		document.getElementById('se_category').value = html_entity_decode(category);
		document.getElementById('se_id').innerHTML = html_entity_decode(id);
		document.getElementById('se_hiddenid').value = html_entity_decode(id);
		document.getElementById('se_desc').innerText = html_entity_decode(name);
		document.getElementById('se_colour').innerText = html_entity_decode(colour);
		document.getElementById('se_grade').innerText = html_entity_decode(grade);
		document.getElementById('se_variant').innerText = html_entity_decode(variant);
		document.getElementById('se_length').innerText = html_entity_decode(length);
		document.getElementById('se_length_unit').innerText = html_entity_decode(l_unit);
		document.getElementById('se_breadth').innerText = html_entity_decode(breadth);
		document.getElementById('se_breadth_unit').innerText = html_entity_decode(b_unit);
		document.getElementById('se_thickness').innerText = html_entity_decode(thickness);
		document.getElementById('se_thickness_unit').innerText = html_entity_decode(t_unit);
		document.getElementById('se_qty').innerText = html_entity_decode(qty);
		document.getElementById('stockEditor').style.display = "";
		//slide_editor.start();
		isPanelOpen = 1;
		//slide_listing.start();
	} else {
		alert("You must save or cancel the current Stock Editor.");
	}
}

function resetEditor() {
	remotos = new datosServidor;
	var cleanupVendorPriceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_CLEANUP_VENDOR_PRICES&mid="+encodeURI('(NEW)')+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", cleanupVendorPriceFile);
	document.getElementById('se_id').innerHTML = "(NEW)";
	document.getElementById('se_hiddenid').value = "(NEW)";
	document.getElementById('se_category').value = "Main Raw Materials";
	document.getElementById('se_desc').innerText = "";
	document.getElementById('se_colour').innerText = "";
	document.getElementById('se_grade').innerText = "";
	document.getElementById('se_variant').innerText = "";
	document.getElementById('se_length').innerText = "";
	document.getElementById('se_length_unit').innerText = "";
	document.getElementById('se_breadth').innerText = "";
	document.getElementById('se_breadth_unit').innerText = "";
	document.getElementById('se_thickness').innerText = "";
	document.getElementById('se_thickness_unit').innerText = "";
	document.getElementById('se_qty').innerText = "";
	retrieveVendorPrices('(NEW)');
}

function addMaterial() {
	if (isPanelOpen == 0){
		resetEditor();
		slide_editor.start();
		isPanelOpen = 1;
		//slide_listing.start();
	} else {
		alert("You must save or cancel the current Stock Editor.");
	}
}

function deleteMaterial(mid) {
	if(confirm('Are you sure you want to delete this Raw Material? All data including vendor price details will be deleted. Any product that refers to this material needs manual updation. Click \'OK\' to delete now or \'Cancel\' to quit without deleting.')){
		remotos = new datosServidor;
		var deleteMaterialFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_DELETE_MATERIAL&mid="+encodeURI(mid)+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", deleteMaterialFile);
	}
}

function retrieveVendorPrices(mid) {
	remotos = new datosServidor;
	var vendorPricesFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_RETRIEVE_VENDOR_PRICES&mid="+encodeURI(mid)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("vendorPriceList", vendorPricesFile);
}

function editVendorPriceLine(rpid, vid) {
	document.getElementById('buttonholder_'+rpid).innerHTML = '<font color=red>Editing</font>';
	document.getElementById('input_vendorID').value = vid;
	document.getElementById('input_vendorPrice').value = document.getElementById('vprice_'+vid).innerHTML;
	document.getElementById('input_rpID').value = rpid;
	document.getElementById('cancelVpriceEdit').style.display = '';
	var highlightEditor = new Spry.Effect.Highlight('vpriceEditor', {duration: 2000, from:'#FFFFFF', to:'rgb(255,204,51)'});
	highlightEditor.start();
}

function addVendorPrice(mid) {
	rpid = document.getElementById('input_rpID').value;
	vid = document.getElementById('input_vendorID').value;
	vprice = document.getElementById('input_vendorPrice').value;
	remotos = new datosServidor;
	var addVendorPriceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_ADD_VENDOR_PRICE&mid="+encodeURI(mid)+"&rpid="+encodeURI(rpid)+"&vid="+encodeURI(vid)+"&vprice="+encodeURI(vprice)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", addVendorPriceFile);
}

function deleteVendorPrice(mid,rpid) {
	if(confirm('Are you sure you want to delete this Vendor and Price detail?')){
		remotos = new datosServidor;
		var deleteVendorPriceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_DELETE_VENDOR_PRICE&mid="+encodeURI(mid)+"&rpid="+encodeURI(rpid)+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", deleteVendorPriceFile);
	}
}


function generateRawPO(rpid) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_RAWSTOCK_GENERATE_PURCHASE_ORDER&rpid="+encodeURI(rpid)+"&xid="+Math.random(), 'rpo_'+rpid, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}


function savePrintRPO(rpid,mid,unitprice,rpodate) {
	rpoterm = escape(document.getElementById('termBox').innerText);
	rpodeldate = escape(document.getElementById('deliveryDateBox').innerText);
	rpoorderby = escape(document.getElementById('orderBy').innerText);
	rpoqty = escape(document.getElementById('qtyBox').innerText);
	rpodeladdress = escape(document.getElementById('deliverAddressBox').innerText);
	
	remotos = new datosServidor;
	var saveRPOFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_RAWSTOCK_SAVE_RPO&rpid="+rpid+"&mid="+mid+"&unitprice="+unitprice+"&rpodate="+rpodate+"&rpoterm="+rpoterm+"&rpodeldate="+rpodeldate+"&rpoorderby="+rpoorderby+"&rpoqty="+rpoqty+"&rpodeladdress="+rpodeladdress+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", saveRPOFile);
}


function printRPO() {
	printFactory.printing.header = "";
	printFactory.printing.footer = "Email: purchase@ews.com.my&bPage &p of &P";
	printFactory.printing.portrait = true;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}


// Production Estimator

function addProductionProduct(model,pname,aid,qty,boxvalue){
	if (pname == boxvalue){
		document.addProductionProductForm.addButton.disabled = true;
		remotos = new datosServidor;
		aPPfile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTION_ADD_PRODUCT&pid="+model+"&aid="+aid+"&qty="+qty+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", aPPfile);
		document.addProductionProductForm.submit();
	}
}

function ClearOptions(OptionList) {
	// Always clear an option list from the last entry to the first
	for (x = OptionList.length; x >= 0; x--) {
		OptionList[x] = null;
	}
}

function AddToOptionList(OptionList, OptionValue, OptionText, isSelect) {
	// Add option to the bottom of the list
	OptionList[OptionList.length] = new Option(OptionText, OptionValue, isSelect);
}

function passSelectedPProduct(selectedProduct) {
	document.addProductionProductForm.productionmodel.value = selectedProduct.info;
	document.addProductionProductForm.productionname.value = selectedProduct.value;
	remotos = new datosServidor;
	attribSelect = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTION_SELECT_ATTRIB&pid="+selectedProduct.info+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", attribSelect);
}

function remove_PProduct(model, aid, qty) {
	document.addProductionProductForm.addButton.disabled = true;
	remotos = new datosServidor;
	rPPfile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTION_REMOVE_PRODUCT&pid="+model+"&aid="+aid+"&qty="+qty+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", rPPfile);
	document.addProductionProductForm.submit();
}

function confirmProduction() {
	if(confirm("This process involves deduction of required raw materials from the Raw Stock Inventory and cannot be undone automatically. Click 'OK' to confirm or 'Cancel' to go back.")) {
		document.getElementById('prodTitlePrompt').style.display = '';
	}
}

function setProdTitle(title) {
	document.getElementById('prodTitlePrompt').style.display = 'none';
	remotos = new datosServidor;
	confirmPPfile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTION_CONFIRM_PRODUCTION&title="+title+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", confirmPPfile);
}

function generateMPC(model, aid, qty) {

	var pc_mt = document.getElementById('pc_mt').value;
	var pc_pl = document.getElementById('pc_pl').value;
	var pc_sc = document.getElementById('pc_sc').value;
	var pc_df = document.getElementById('pc_df').value;
	var pc_uc = document.getElementById('pc_uc').value;
	var pc_ap = document.getElementById('pc_ap').value;
	var pc_rd = document.getElementById('pc_rd').value;
	var pc_ic = document.getElementById('pc_ic').value;
	var pc_dc = document.getElementById('pc_dc').value;
	var pc_fob = document.getElementById('pc_fob').value;
	var pc_ct = document.getElementById('pc_ct').value;
	var pc_br3 = document.getElementById('pc_br3').value;
	var pc_br2 = document.getElementById('pc_br2').value;
	var pc_br1 = document.getElementById('pc_br1').value;
	var pc_rcp = document.getElementById('pc_rcp').value;
	var pc_gsc = document.getElementById('pc_gsc').value;
	var pc_gwp = document.getElementById('pc_gwp').value;
	var pc_gep = document.getElementById('pc_gep').value;

	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_PRODUCTION_GENERATE_MPC&pid="+model+"&aid="+aid+"&qty="+qty+"&pc_mt="+pc_mt+"&pc_pl="+pc_pl+"&pc_sc="+pc_sc+"&pc_df="+pc_df+"&pc_uc="+pc_uc+"&pc_ap="+pc_ap+"&pc_rd="+pc_rd+"&pc_ic="+pc_ic+"&pc_dc="+pc_dc+"&pc_fob="+pc_fob+"&pc_ct="+pc_ct+"&pc_br3="+pc_br3+"&pc_br2="+pc_br2+"&pc_br1="+pc_br1+"&pc_rcp="+pc_rcp+"&pc_gsc="+pc_gsc+"&pc_gwp="+pc_gwp+"&pc_gep="+pc_gep+"&xid="+Math.random(), aid+qty, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}

function generatePalletNote(prodID,prodTitle) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_PRODUCTION_GENERATE_PALLET_NOTE&prodid="+prodID+"&prodtitle="+prodTitle+"&xid="+Math.random(), prodID, "resizable=yes, toolbar=no, width=1024, height=600, menubar=no, scrollbars=yes");
}

function generateBarcode(prodID,prodTitle) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_PRODUCTION_GENERATE_BARCODE&prodid="+prodID+"&prodtitle="+prodTitle+"&xid="+Math.random(), prodID, "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}

function printMPC() {
	printFactory.printing.header = "";
	printFactory.printing.footer = "BlackBox :: Enterprise Resource Planning :: v1.2.0&bPage &p of &P";
	printFactory.printing.portrait = true;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}

function printPalletNote() {
	printFactory.printing.header = "";
	printFactory.printing.footer = "BlackBox :: Enterprise Resource Planning :: v1.2.0&bPage &p of &P";
	printFactory.printing.portrait = false;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}

function printBarcode() {
	printFactory.printing.header = "";
	printFactory.printing.footer = "";
	printFactory.printing.portrait = true;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}


// Product manager

function passSelectedRMaterial(selectedMaterial) {
	document.getElementById('input_materialid').value = selectedMaterial.materialid;
	document.getElementById('input_length').title = 'Max length: '+selectedMaterial.matlength;
	document.getElementById('input_breadth').title = 'Max breadth: '+selectedMaterial.matbreadth;
	if(selectedMaterial.matlength == '' || selectedMaterial.matlength == 0){
		document.getElementById('input_length').style.visibility = 'hidden';
	} else {
		document.getElementById('input_length').style.visibility = 'visible';
	}
	if(selectedMaterial.matbreadth == '' || selectedMaterial.matbreadth == 0){
		document.getElementById('input_breadth').style.visibility = 'hidden';
	} else {
		document.getElementById('input_breadth').style.visibility = 'visible';
	}
	//document.addProductionProductForm.productionname.value = selectedProduct.value;
	//remotos = new datosServidor;
	//attribSelect = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTION_SELECT_ATTRIB&pid="+selectedProduct.info+"&xid="+Math.random(),"");
	//Spry.Utils.setInnerHTML("messages", attribSelect);
}

function fetchProductData(pid) {
	remotos = new datosServidor;
	productDataFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTMANAGER_PRODUCT_DATA&pid="+pid+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("productDataTab", productDataFile);
}

function manageProductData(pid) {
	Spry.Utils.setInnerHTML("productDataTab", "<img src='images/processing.gif'>&nbsp;Processing data...");
	setTimeout('fetchProductData("'+pid+'")', 500);
}

function addResource(pid, aid, partname, mid, len, bre, qty) {
	remotos = new datosServidor;
	addResourceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTMANAGER_ADD_RESOURCE&pid="+pid+"&aid="+aid+"&partname="+partname+"&mid="+mid+"&len="+len+"&bre="+bre+"&qty="+qty+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", addResourceFile);
}

function deleteResource(pid, prid) {
	if(confirm('Are you sure you want to delete this resource information?')){
		remotos = new datosServidor;
		deleteResourceFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTMANAGER_DELETE_RESOURCE&pid="+pid+"&prid="+prid+"&xid="+Math.random(),"");
		Spry.Utils.setInnerHTML("messages", deleteResourceFile);
	}
}

function saveProductProperties(pid) {
	psize = escape(document.getElementById('input_product_size').value);
	pboxes = escape(document.getElementById('input_boxes').value);
	plabour = escape(document.getElementById('input_labour_cost').value);
	pprofit = escape(document.getElementById('input_trade_profit').value);
	
	if(document.getElementById('tradeCheck').checked == true) {
		istrade = '1';
	} else {
		istrade = '0';
	}

	remotos = new datosServidor;
	saveProductPropertiesFile = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCTMANAGER_SAVE_PROPERTIES&pid="+pid+"&psize="+psize+"&pboxes="+pboxes+"&plabour="+plabour+"&pprofit="+pprofit+"&istrade="+istrade+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", saveProductPropertiesFile);
}


// Delivery

function getElementHeight(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) { 
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}


// ------------------ Pitching - Telephone ----------------------

function updateWorkflow(allocationId, requestId) {
	remotos = new datosServidor;
	var workflowData = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PITCHING_TELEPHONE_WORKFLOW&allocid="+encodeURI(allocationId)+"&requestId="+encodeURI(requestId)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("workflowContainer", workflowData);
}

function changeFlag(allocationId, locationId, flag, flagText, scheduleTime) {
	remotos = new datosServidor;
	var changeFlagData = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PITCHING_CHANGE_FLAG&allocid="+encodeURI(allocationId)+"&locid="+encodeURI(locationId)+"&flag="+encodeURI(flag)+"&flagText="+encodeURI(flagText)+"&scheduleTime="+encodeURI(scheduleTime)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", changeFlagData);
}

function suggestContactChange(locationId, user, changeText) {
	remotos = new datosServidor;
	var suggestChange = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PITCHING_SUGGEST_CONTACT_CHANGE&locid="+encodeURI(locationId)+"&user="+encodeURI(user)+"&changeText="+encodeURI(changeText)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", suggestChange);
}

function postCall() {
	document.getElementById('callingArea').style.display = "none";
}


// ----------------------- Resolution Centre --------------------

function ww_showcontactdetails(contactId, targetdiv) {
	
	remotos = new datosServidor;
	var showcontactdetails = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_SHOWCONTACTDETAILS&cid="+encodeURI(contactId)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML(targetdiv, showcontactdetails);
}


function showcontactdetails(contactId, logId, targetdiv)
{ 
	boxid = targetdiv
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	{
		alert ("Browser does not support HTTP Request. Please upgrade your web browser.")
		return
	}
	var url="ajaxFetcher.php"
	url=url+"?filetoken=FILENAME_AJAX_SHOWCONTACTDETAILS&cid="+contactId
	url=url+"&logid="+logId
	url=url+"&xid="+Math.random()
	xmlHttp.onreadystatechange=c_showContactDetails_stateChanged 
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
}

function c_showContactDetails_stateChanged() 
{ 
	if (xmlHttp.readyState==1 || xmlHttp.readyState==2 || xmlHttp.readyState==3)
	{ 
		document.getElementById(boxid).innerHTML="<small>Fetching data...</small>" 
	} 

	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{ 
		document.getElementById(boxid).innerHTML=xmlHttp.responseText
	} 
}


/* ------------- APPROVAL - FOR FIELD -------------------- */
function approveForField(logid, locationid, sourceuser, purpose, comments, actionflag) {
	remotos = new datosServidor;
	var updateApproval = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_APPROVE_FOR_FIELD_VISIT&logid="+encodeURI(logid)+"&locid="+encodeURI(locationid)+"&sourceuser="+encodeURI(sourceuser)+"&purpose="+encodeURI(purpose)+"&comments="+encodeURI(comments)+"&actionflag="+encodeURI(actionflag)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", updateApproval);
}


/* ------------- PITCHING - FIELD -------------------- */
function setFieldAppointment(logid, hr, mnt, seldate, currentindex, locationid, purpose) {
	remotos = new datosServidor;
	var setSchedule = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_FIELD_SET_APPOINTMENT&logid="+encodeURI(logid)+"&hr="+encodeURI(hr)+"&mnt="+encodeURI(mnt)+"&seldate="+encodeURI(seldate)+"&currentindex="+encodeURI(currentindex)+"&locid="+encodeURI(locationid)+"&purpose="+encodeURI(purpose)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", setSchedule);
}

function updateFieldWorkflow(requestId) {
	remotos = new datosServidor;
	var fieldWorkflowData = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PITCHING_FIELD_WORKFLOW&requestId="+encodeURI(requestId)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("workflowContainer", fieldWorkflowData);
}

function changeFieldFlag(locationid, logid, flag, flagText, scheduleTime) {
	remotos = new datosServidor;
	var changeFieldFlagData = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PITCHING_FIELD_CHANGE_FLAG&locid="+encodeURI(locationid)+"&logid="+encodeURI(logid)+"&flag="+encodeURI(flag)+"&flagText="+encodeURI(flagText)+"&scheduleTime="+encodeURI(scheduleTime)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("messages", changeFieldFlagData);
}

function generateDocumentBarcode(bid, quantity) {
	window.open("ajaxFetcher.php?filetoken=FILENAME_PRINT_DOCUMENT_GENERATE_BARCODE&bid="+encodeURI(bid)+"&quantity="+quantity+"&xid="+Math.random(), "dbc", "resizable=yes, toolbar=no, width=850, height=600, menubar=no, scrollbars=yes");
}

function printDocumentBarcode() {
	printFactory.printing.header = "Barcodes for Document Reference";
	printFactory.printing.footer = "BlackBox epsilon";
	printFactory.printing.portrait = true;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}

function open_appointment_sheet(username, appDate, appMonth, appYear){
	window.open("ajaxFetcher.php?filetoken=FILENAME_APPOINTMENT_SHEET&appDate="+encodeURI(appDate)+"&appMonth="+encodeURI(appMonth)+"&appYear="+encodeURI(appYear)+"&xid="+Math.random(), 'appsheet_'+appDate+appMonth+appYear, "resizable=yes, toolbar=no, width=600, height=300, menubar=no, scrollbars=yes");
}

function printAppointmentSheet(username, fordate) {
	printFactory.printing.header = "";
	printFactory.printing.footer = "BlackBox epsilon :: Appointment Sheet :: " + username + " :: " + fordate;
	printFactory.printing.portrait = true;
	printFactory.printing.leftMargin = 0.75;
	printFactory.printing.topMargin = 0.50;
	printFactory.printing.rightMargin = 0.50;
	printFactory.printing.bottomMargin = 0.50;
	printFactory.printing.Print(true);
}

function selectDivList(elem, group, activecolor){
	if(activecolor == undefined){
		activecolor = "#0f0";
	}
	groupobject = document.getElementsByClassName(group);
	for (var i = 0; i < groupobject.length; i++){
		groupobject[i].style.background = "#fff";
	}
	elem.style.background = activecolor;
}

function updateRawDetails(rawid){
	Spry.Utils.setInnerHTML("rawDetails", "Please wait..");
	remotos = new datosServidor;
	var rawDetails = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PRODUCT_TECHNICAL_RAW_DETAILS&rawid="+encodeURI(rawid)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("rawDetails", rawDetails);
}


function show_project_room_product_details(projid, contactid, rawid){
	Spry.Utils.setInnerHTML("productDetails", "Please wait..");
	remotos = new datosServidor;
	var rawDetails = remotos.enviar("ajaxFetcher.php?filetoken=FILENAME_AJAX_PROJECT_ROOM_PRODUCT_DETAILS&pid="+encodeURI(rawid)+"&projid="+encodeURI(projid)+"&cid="+encodeURI(contactid)+"&xid="+Math.random(),"");
	Spry.Utils.setInnerHTML("productDetails", rawDetails);
}


function divScrollTo(id){
var objf=document.getElementById(id);
var objS=document.getElementById('fred').style;
objS.left=zxcPos(objf)[0]+'px';
objS.top=zxcPos(objf)[1]+'px';
}

function zxcPos(zxc){
zxcObjLeft = zxc.offsetLeft;
zxcObjTop = zxc.offsetTop;
while(zxc.offsetParent!=null){
zxcObjParent=zxc.offsetParent;
zxcObjLeft+=zxcObjParent.offsetLeft;
zxcObjTop+=zxcObjParent.offsetTop;
zxc=zxcObjParent;
}
return [zxcObjLeft,zxcObjTop];
}


function calculateDistance(mode, dest, locid, lat, lng, verify, loclog){
    var directionsService = new google.maps.DirectionsService();
    var origin = new google.maps.LatLng(3.199038, 101.575974);
    var destination = 'hello';
    if(verify == undefined || loclog == undefined){
        verify = 0;
        loclog = 0;
    }
    if(mode == 'known'){
        destination = new google.maps.LatLng(lat, lng);
        fetchDistance();
    } else {
        var geocoder = new google.maps.Geocoder();
        function geocodeNow(){
            geocoder.geocode({'address': gdest}, 
                            function(results, status){
                                if(status == google.maps.GeocoderStatus.OK){
                                    var resultLat = results[0].geometry.location.lat();
                                    var resultLng = results[0].geometry.location.lng();
                                    destination = new google.maps.LatLng(resultLat, resultLng);
                                    fetchDistance();
                                } else {
                                    var arr = gdest.split(/\s+/);
                                    arr.shift();  // same as: reverse, pop, reverse
                                    gdest = arr.join(' ');
                                    if(gdest != ''){
                                        setTimeout(geocodeNow, 100);
                                    }
                                }
                            });
        }
        var gdest = dest;
        geocodeNow();
    }
    
    function fetchDistance(){
        directionsService.route(
            {
            origin: origin,
            destination: destination,
            provideRouteAlternatives: false,
            travelMode: google.maps.DirectionsTravelMode.DRIVING,
            unitSystem: google.maps.DirectionsUnitSystem.METRIC
            }, function(result, status)
                {
                if(status == google.maps.DirectionsStatus.OK){
                    processResult(result);
                } else {
                    var storeLat = destination.lat();
                    var storeLng = destination.lng();
                    storeGeocode(storeLat, storeLng);
                } /*else {
                    var arr = destination.split(/\s+/);
                    arr.shift();  // same as: reverse, pop, reverse
                    destination = arr.join(' ');
                    if(destination != ''){
                        setTimeout(fetchDistance, 100);
                    }
                }*/
                }
        );
    }
    
    
    function processResult(directionResult){
        var metreDistance = directionResult.routes[0].legs[0].distance.value;
        var duration = directionResult.routes[0].legs[0].duration.value;
        var storeLat = destination.lat();
        var storeLng = destination.lng();
        storeDistance(storeLat, storeLng, metreDistance, duration);
    }
    
    
    function storeDistance(sLat, sLng, dist, dur){
        remotos = new datosServidor;
        remotos.enviar("/ajaxFetcher.php?filetoken=FILENAME_AJAX_PROJECT_STORE_DISTANCE&distance="+encodeURI(dist)+"&duration="+encodeURI(dur)+"&locid="+encodeURI(locid)+"&lat="+encodeURI(sLat)+"&lng="+encodeURI(sLng)+"&verify="+encodeURI(verify)+"&loclog="+encodeURI(loclog)+"&xid="+Math.random(),"");
    }
    
    
    function storeGeocode(sLat, sLng){
        remotos = new datosServidor;
        remotos.enviar("/ajaxFetcher.php?filetoken=FILENAME_AJAX_PROJECT_STORE_DISTANCE&locid="+encodeURI(locid)+"&lat="+encodeURI(sLat)+"&lng="+encodeURI(sLng)+"&verify="+encodeURI(verify)+"&loclog="+encodeURI(loclog)+"&xid="+Math.random(),"");
    }
}