/*###########################################################################
Changelog:
  18.04.2005 - Initial Writing (DG)
#############################################################################*/

<!-- hide from antiquated browsers

	var row_orig_class = '';
	var oldstyle = "";
	var sel_menu_num = null;
	var menu_oldstyle = null;
	var menu_indicator_oldstyle = null;

	/* Finds an element within an array */
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}
	
	 /* Removes redundant elements from the array */
	 Array.prototype.unique=function() {
	     var a=[],i;
	     this.sort();
	     for(i=0;i<this.length;i++) {
	         if(this[i]!==this[i+1]) {
	             a[a.length]=this[i];
	         }
	     }
	     return a;
	 }		

	function chk_assetbkg_qty(input_el, maxqty) {
		var curval = (+input_el.value);
		var maxqty = (+maxqty);
		if(maxqty!="" && maxqty!=null) {
			if(curval > maxqty) {
				input_el.value = maxqty;
				alert('Booking Quantity for this asset cannot exceed '+maxqty);
			}
		}
	}

	function ucaseValue(el) {
		el.value = el.value.toUpperCase();
	}
	
	function show_fetchpremise_layer(prem_el,product_code,showdef) {
		if(prem_el.value!='') {
			var act_prod_code = document.getElementById('actual_prodcode_'+product_code).value;
			prem_el.disabled = true;
				
			// Show Progress Bar
			window.top.bottomFrame.show_progress_bar();
		
			document.getElementById('fetchGenIframe').src='req_projcode_fetch.php?srch='+prem_el.value+'&product_code='+act_prod_code+'&showdef='+showdef;
		}
	}

	function disableEnterKey(e) {
		var key;
     	if(window.event)
        	key = window.event.keyCode;     //IE
     	else
        	key = e.which;     //firefox

     	if(key == 13) return false;
     	else return true;
	}

	function trimWhiteSpace(str) { 
		str.replace(/^\s*/, '').replace(/\s*$/, ''); 	
	   	return str;
	}

	function loginBrowserCheck() {
		//var x = check_for_popup_blockers();
		//if(x) {
			// Show Popup Blocker Error Message
			//document.getElementById('popupMessage').style.display = 'block';
		//}
	}

	function check_for_popup_blockers() {
		var popUpsBlocked = false;
 		var mine = window.open('','','width=1,height=1,left=0,top=0,scrollbars=no');
 		if(!mine) popUpsBlocked = true;
 		else mine.close();	
 		return popUpsBlocked;
	}

	function reqedit_suburb_layer(state_el) {
		state_el.disabled = true;
		document.getElementById('suburb').value='';
		document.getElementById('suburb').style.display = 'none';
		document.getElementById('fetchSuburbIframe').src='req_suburb_fetch.php?state='+state_el.value
	}

	function show_ledelsub(state_el) {
		loanequip_type = 'del';
		state_el.disabled = true;
		document.getElementById('suburbs').value='';
		document.getElementById('suburbs').style.display = 'none';
	
		document.getElementById('fetchSuburbIframe').src='loanequip_suburb_fetch.php?type=del&state='+state_el.value	
	}
	
	function show_lepusub(state_el) {
		loanequip_type = 'pu';
		state_el.disabled = true;
		document.getElementById('pickup_suburb').value='';
		document.getElementById('pickup_suburb').style.display = 'none';
	
		document.getElementById('fetchSuburbIframe').src='loanequip_suburb_fetch.php?type=pu&state='+state_el.value	
	}	

	function HS_TreeLevel(divname, imgname) {
		tmpLyrObj = document.getElementById(divname);
		tmpImgObj = document.getElementById(imgname);

		if(tmpLyrObj.style.display=="none") {
			ShowDiv(divname);
			tmpImgObj.src = 'images/minus_sign.gif';
		}
		else {
			HideDiv(divname);
			tmpImgObj.src = 'images/plus_sign.gif';
		}
	}

	function reqedit_fetchsuburbs(state_el) {
		state_el.disabled = true;
		scombo = document.getElementById('suburbs');
		scombo.disabled = true;
		document.getElementById('fetchSuburbIframe').src='suburbs_'+state_el.value+'.php';
	}

	function update_tbsquote_cart(req_qty, prod_code, pkqty, incsellprice, exsellprice, ctype, brand, warehouse, costcentre) {
		window.top.bottomFrame.show_progress_bar();
		if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    		http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
             http_request.overrideMimeType('text/xml');
         }
		} else if (window.ActiveXObject) { // IE
    		http_request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		http_request.onreadystatechange = function() {
			if (http_request.readyState == 4) {
				// Make sure the status is "OK"
				if (http_request.status == 200) {
					window.top.bottomFrame.hide_progress_bar();
				}
			}
		};
		var args = new Array();
		args[0] = 'qty='+req_qty;
		args[1] = 'pcode='+prod_code;
		args[2] = 'pkqty='+pkqty;
		args[3] = 'wh='+warehouse;
		args[4] = 'cc='+costcentre;
		args[5] = 'incprice='+incsellprice;
		args[6] = 'exprice='+exsellprice;
		args[7] = 'ctype='+ctype;
		args[7] = 'brand='+brand;
		var arg_str = args.join('&');

      http_request.open('POST', 'tbs_prodsave.php?'+arg_str, true);
      http_request.send(null);
	}

	function tbs_update_details(field_name, field_value) {
		if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    		http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
             http_request.overrideMimeType('text/xml');
         }
		} else if (window.ActiveXObject) { // IE
    		http_request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		http_request.onreadystatechange = function() {
		    // do the thing
		};
      http_request.open('GET', 'tbs_autosave.php?name='+field_name+'&value='+field_value, true);
      http_request.send(null);
	}

	function req_update_details(field_name, field_value) {
		if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    		http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
             http_request.overrideMimeType('text/xml');
         }
		} else if (window.ActiveXObject) { // IE
    		http_request = new ActiveXObject("Microsoft.XMLHTTP");
		}
		http_request.onreadystatechange = function() {
		    // do the thing
		};
      http_request.open('GET', 'req_autosave.php?name='+field_name+'&value='+field_value, true);
      http_request.send(null);
	}

	function check_maxcalloff(el, maxcalloff) {
		var curval = el.value-0;
		var maxval = maxcalloff-0;
		if(maxval!='' && maxval!=0) {
			if(curval > maxval) {
				el.value = maxcalloff;
				alert('The maximum quantity of this product you\ncan order at any one time is: '+maxcalloff);
			}
		}
	}

	function reload_userman(randval) {
		if(window.opener.location.href.indexOf('?') !=-1) {
			window.opener.location.href=window.opener.location.href+'&randval='+randval;
		} else {
			window.opener.location.href=window.opener.location.href+'?randval='+randval;
		}
	}
	
	function complete_questionnaire(ques_form) {
		var department = document.getElementById('department');
		if(department.value=="") {
			alert('Please state your department...');
			department.focus();
			return false;
		}
		
		var s1q1_check = false;
		for (counter = 0; counter < ques_form.s1q1.length; counter++){
			if (ques_form.s1q1[counter].checked)
				s1q1_check = true; 
		}
		if(!s1q1_check) {
			alert('Please answer Section 1, Question 1...');
			return false;
		}
		
		var s1q2_check = false;
		for (counter = 0; counter < ques_form.s1q2.length; counter++){
			if (ques_form.s1q2[counter].checked)
				s1q2_check = true; 
		}
		if(!s1q2_check) {
			alert('Please answer Section 1, Question 2...');
			return false;
		}
		
		var s1q3_check = false;
		for (counter = 0; counter < ques_form.s1q3.length; counter++){
			if (ques_form.s1q3[counter].checked)
				s1q3_check = true; 
		}
		if(!s1q3_check) {
			alert('Please answer Section 1, Question 3...');
			return false;
		}
		
		var s1q4_check = false;
		for (counter = 0; counter < ques_form.s1q4.length; counter++){
			if (ques_form.s1q4[counter].checked)
				s1q4_check = true; 
		}
		if(!s1q4_check) {
			alert('Please answer Section 1, Question 4...');
			return false;
		}
		
		var s1q5_check = false;
		for (counter = 0; counter < ques_form.s1q5.length; counter++){
			if (ques_form.s1q5[counter].checked)
				s1q5_check = true; 
		}
		if(!s1q5_check) {
			alert('Please answer Section 1, Question 5...');
			return false;
		}
		
		var s1q6_check = false;
		for (counter = 0; counter < ques_form.s1q6.length; counter++){
			if (ques_form.s1q6[counter].checked)
				s1q6_check = true; 
		}
		if(!s1q6_check) {
			alert('Please answer Section 1, Question 6...');
			return false;
		}
		
		var s2q1_check = false;
		for (counter = 0; counter < ques_form.s2q1.length; counter++){
			if (ques_form.s2q1[counter].checked)
				s2q1_check = true; 
		}
		if(!s2q1_check) {
			alert('Please answer Section 2, Question 1...');
			return false;
		}
		
		var s2q2_check = false;
		for (counter = 0; counter < ques_form.s2q2.length; counter++){
			if (ques_form.s2q2[counter].checked)
				s2q2_check = true; 
		}
		if(!s2q2_check) {
			alert('Please answer Section 2, Question 2...');
			return false;
		}
		
		var s2q3_check = false;
		for (counter = 0; counter < ques_form.s2q3.length; counter++){
			if (ques_form.s2q3[counter].checked)
				s2q3_check = true; 
		}
		if(!s2q3_check) {
			alert('Please answer Section 2, Question 3...');
			return false;
		}
		
		var s2q4_check = false;
		for (counter = 0; counter < ques_form.s2q4.length; counter++){
			if (ques_form.s2q4[counter].checked)
				s2q4_check = true; 
		}
		if(!s2q4_check) {
			alert('Please answer Section 2, Question 4..');
			return false;
		}

		var s3q0 = document.getElementById('s3q0');
		if(s3q0.value=="") {
			alert('Please answer question 3...');
			document.ques_form.s3q0.focus();
			return false;
		}
		
		return true;
	}

	function validate_profile() {
		var fname_el = document.getElementById('firstname');
		if(fname_el.value=="") {
			alert('Your firstname is missing ...');
			fname_el.focus();
			return false;
		}

		var lname_el = document.getElementById('lastname');
		if(lname_el.value=="") {
			alert('Your lastname is missing ...');
			lname_el.focus();
			return false;
		}

		var email_el = document.getElementById('email_addr');
		if(email_el.value=="") {
			alert('Your email address is missing ...');
			email_el.focus();
			return false;
		}

		var password_el = document.getElementById('password');
		if(password_el.value=="") {
			alert('Your account password is missing ...');
			password_el.focus();
			return false;
		}

		// they have made it this far - everything must be ok!
		return true;
	}

	function show_pc_cat(divname, imgname, ctype, tc, pc, url) {
		tmpLyrObj = document.getElementById(divname);
		prodLyrObj = document.getElementById('prod'+divname);
		tmpImgObj = document.getElementById(imgname);
		if(prodLyrObj.innerHTML=="") {
			show_genmsg_layer('Please wait while we fetch all <br> the available products ...');
			window.fetchprod.location.href= url+"?ctype="+ctype+"&tipcount="+tc+"&prodcount="+pc;
		}

		if(tmpLyrObj.style.display=="none") {
			ShowDiv(divname);
			tmpImgObj.src = 'images/minus_sign.gif';
		}
		else {
			HideDiv(divname);
			tmpImgObj.src = 'images/plus_sign.gif';
		}
	}

	function clear_qadd() {
		var form_el = document.getElementById('quickaddtocart');
		var pc_el = document.getElementById('qa_stmprod');
		form_el.reset();
		pc_el.focus();
	}

	function prepare_pcsrch_count(tc, pc) {
		document.getElementById('srch_tipcount').value = tc+'';
		document.getElementById('srch_prodcount').value = pc+'';
	}

	function prepare_srch_count(tc, pc) {
		document.getElementById('srch_tipcount').value = tc+'';
		document.getElementById('srch_prodcount').value = pc+'';
	}

	function sr_showhide(linkObj, showStatus) {
	  if(showStatus==true) {
	    linkObj.innerHTML = 'Hide';
	    linkObj.onclick = function() { sr_showhide(linkObj, false); }
	    document.getElementById('search_area_contents').style.display='block';
	  } else {
	    linkObj.innerHTML = 'Show';
	    linkObj.onclick = function() { sr_showhide(linkObj, true); }
	    document.getElementById('search_area_contents').style.display='none';
	  }
	}

	function show_fetchsuburb_layer(state_el) {
		state_el.disabled = true;
		document.getElementById('suburb').value='';
		document.getElementById('suburb').style.display = 'none';
	
		// Show Progress Bar
		window.top.bottomFrame.show_progress_bar();
	
		document.getElementById('fetchSuburbIframe').src='req_suburb_fetch.php?state='+state_el.value
	}

function show_genmsg_layer(msg) {
	// Show Progress Bar
	window.top.bottomFrame.show_progress_bar();

	// Div Sizes and Positioning ...
	the_height = (document.documentElement)? document.documentElement.clientHeight:document.body.clientHeight;
	the_width = (document.documentElement)? document.documentElement.clientWidth:document.body.clientWidth;
	the_top = (document.documentElement)? document.documentElement.scrollTop:document.body.scrollTop;
	scroll_height = (document.documentElement)? document.documentElement.scrollHeight:document.body.scrollHeight;
	document.getElementById('gm_lyr').style.left = ((the_width-(the_width*0.75))/2)+"px";
	document.getElementById('gm_lyr').style.width = (the_width*0.75)+"px";
	document.getElementById('gm_lyr').style.top = (((the_height-(the_height*0.75))/2)+document.documentElement.scrollTop)+"px";
	document.getElementById('gm_lyr').style.height = (the_height*0.75)+"px";

	// Table Sizes ...
	document.getElementById('gm_bg').style.width = (the_width*0.75)+"px";
	document.getElementById('gm_bg').style.height = (the_height*0.75)+"px";

	// Alter DIV Content
	document.getElementById('gmdiv_msg').innerHTML = msg;

	// Show Layer
	document.getElementById('gm_lyr').style.visibility = "visible";
}

function show_updcart_layer() {
	// Show Progress Bar
	window.top.bottomFrame.show_progress_bar();

	// Div Sizes and Positioning ...
	the_height = (document.documentElement)? document.documentElement.clientHeight:document.body.clientHeight;
	the_width = (document.documentElement)? document.documentElement.clientWidth:document.body.clientWidth;
	the_top = (document.documentElement)? document.documentElement.scrollTop:document.body.scrollTop;
	scroll_height = (document.documentElement)? document.documentElement.scrollHeight:document.body.scrollHeight;
	document.getElementById('updcart_lyr').style.left = ((the_width-(the_width*0.75))/2)+"px";
	document.getElementById('updcart_lyr').style.width = (the_width*0.75)+"px";
	document.getElementById('updcart_lyr').style.top = (((the_height-(the_height*0.75))/2)+document.documentElement.scrollTop)+"px";
	document.getElementById('updcart_lyr').style.height = (the_height*0.75)+"px";

	// Table Sizes ...
	document.getElementById('updcart_bg').style.width = (the_width*0.75)+"px";
	document.getElementById('updcart_bg').style.height = (the_height*0.75)+"px";

	// Show Layer
	document.getElementById('updcart_lyr').style.visibility = "visible";
}

function change_price(combo, prodcode, pkqty, pcount) {
	// Only update if the price element exists!
	
	if(document.getElementById('req_price_'+prodcode)) {

		// total price 
		var tmp_totalprice = combo.options[combo.selectedIndex].getAttribute('price');
		
		// Update unit price display
		if(combo.value == 0) {
			var tmp_priceperpack = 0;
		}
		else {
			var tmp_priceperpack = tmp_totalprice/combo.value;
		}

		if(document.all)
			document.getElementById('req_price_'+prodcode).innerText = toDollarsAndCents(tmp_priceperpack);
		else document.getElementById('req_price_'+prodcode).textContent = toDollarsAndCents(tmp_priceperpack);
		
		// Update hidden element for unit price
		document.getElementById('costp_'+pcount).value = toDollarsAndCents(tmp_priceperpack);
		
		// Update total qty
		if(document.getElementById('tqty_'+pcount))
			document.getElementById('tqty_'+pcount).value = combo.value*pkqty;
		
		// Update total price
		if(document.getElementById('tcost_'+pcount)) {
			if(document.all)
				document.getElementById('tcost_'+pcount).innerText = toDollarsAndCents(tmp_totalprice);
			else document.getElementById('tcost_'+pcount).textContent = toDollarsAndCents(tmp_totalprice);
			document.getElementById('tcost_'+pcount).value = toDollarsAndCents(tmp_totalprice);	
		}	
	}
}

//added by weihan to change in stock value when bulk is in play (NOT USING IT ANYMORE)
//THIS SECTION WILLBE REMOVE PERMAMENTLY IF THERE'S NO PROBLEM PRESISTS
/*
function change_price_not_using(qty, prodcode, wh, pkqty, pcount){
		if(qty > 0) {
			post_array = new Array();
			post_array[post_array.length] = 'qty='+qty;
			post_array[post_array.length] = 'prodcode='+prodcode;
			post_array[post_array.length] = 'wh='+wh;
			uri_args = post_array.join('&');		
			
			if (window.XMLHttpRequest) { // Mozilla, Safari, ...
				http_request = new XMLHttpRequest();
				if (http_request.overrideMimeType) {
					http_request.overrideMimeType('text/xml');
				}
			} else if (window.ActiveXObject) { // IE
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
		
			http_request.onreadystatechange = function() {
				if (http_request.readyState == 4) {
					// Make sure the status is "OK"
					if (http_request.status == 200) {
						// The script Executed fine!
						handle_change_price(http_request.responseXML, qty, prodcode, pkqty, pcount);
					}
				}
			};		
		 	http_request.open('POST', 'getReqPrice.php?'+uri_args, true);
		 	http_request.send(null);	
		}
	}
	
	function handle_change_price(response, qty, prodcode, pkqty, pcount) {
		var rp_chk = response.getElementsByTagName('reqprice');
		if(rp_chk.length>0) {
			var reqprice = response.getElementsByTagName('reqprice')[0].firstChild.data;	
			document.getElementById('req_price_'+prodcode).innerHTML = reqprice;
			
			//setting the hidden 'costp_' value
			var price_val = document.getElementById('costp_'+pcount);
			price_val.value = reqprice;
			
			
			var el_hnd = document.getElementById('tqty_'+pcount);
			if(el_hnd!=false) {
				if(reqprice=='' || reqprice=="0.00") el_hnd.value = '';
				else {
					el_hnd.value = qty * pkqty;
				}
			}
			
			var totprice_el = document.getElementById('tcost_'+pcount);
			if(totprice_el!=false) {
				if(reqprice=='' || reqprice=="0.00") totprice_el.value = '';
				else {
					var grand_total = price_val.value * qty;
					totprice_el.value = toDollarsAndCents(grand_total);
				}
			}
			//return false;
		} else {
			// Something went wrong with the response - do nothing ...
			return false;			
		} 		
	}
*/

function show_err_updcart_layer(msg) {
	// Div Sizes and Positioning ...
	the_height = (document.documentElement)? document.documentElement.clientHeight:document.body.clientHeight;
	the_width = (document.documentElement)? document.documentElement.clientWidth:document.body.clientWidth;
	the_top = (document.documentElement)? document.documentElement.scrollTop:document.body.scrollTop;
	scroll_height = (document.documentElement)? document.documentElement.scrollHeight:document.body.scrollHeight;
	document.getElementById('err_updcart_lyr').style.left = ((the_width-(the_width*0.75))/2)+"px";
	document.getElementById('err_updcart_lyr').style.width = (the_width*0.75)+"px";
	document.getElementById('err_updcart_lyr').style.top = (((the_height-(the_height*0.75))/2)+document.documentElement.scrollTop)+"px";
	document.getElementById('err_updcart_lyr').style.height = (the_height*0.75)+"px";

	// Table Sizes ...
	document.getElementById('err_updcart_bg').style.width = (the_width*0.75)+"px";
	document.getElementById('err_updcart_bg').style.height = (the_height*0.75)+"px";

	// Alter DIV Content
	document.getElementById('err_updcart_msg').innerHTML = msg;

	// Show Layer
	document.getElementById('err_updcart_lyr').style.visibility = "visible";
}

function hide_genmsg_lyr() {
	document.getElementById('gm_lyr').style.visibility = "hidden";
	window.top.bottomFrame.hide_progress_bar();
}

function hide_updcart_lyr() {
	document.getElementById('updcart_lyr').style.visibility = "hidden";
	window.top.bottomFrame.hide_progress_bar();
}

function hide_err_updcart_lyr() {
	document.getElementById('err_updcart_lyr').style.visibility = "hidden";
}

function find_and_highlight(prodcode, quantity, viewimg) {
	input_array = document.getElementsByTagName('input');
	  for(i=0; i<input_array.length; i++) {
	  		if(input_array[i].id.indexOf('pc_count_conv')!=-1) {
	  			if(input_array[i].id.indexOf('['+prodcode+']')!=-1) {
	  				if(quantity==0) quantity='';
	  				if(viewimg=="Y") {
	  					document.getElementById('reqqty'+input_array[i].value).value = quantity;
						thumb_highlight_addedproduct(input_array[i].value);
	  				} else {
	  					document.getElementById('reqqty'+input_array[i].value).value = quantity;
	  					update_tqty(quantity, 'tqty_'+input_array[i].value, document.getElementById('this_pkqty_'+input_array[i].value).value, input_array[i].value);
	  					highlight_addedproduct(input_array[i].value);
	  				}
	  			}
	  		}
	  }
}

function thumb_highlight_addedproduct(prod_code) {
	var sChar=String.fromCharCode(187);
	var prod_qty = document.getElementById('reqqty'+prod_code);
	var prod_tbl = document.getElementById('prod_'+prod_code+'_tbl');
	var prod_btn = document.getElementById('prod_'+prod_code+'_btn');
	if((prod_qty.value*1)>0 && prod_qty.value!='') {
		prod_tbl.className = 'thumb_addedtocart';
		prod_btn.value = 'Edit '+sChar;
	} else {
		prod_tbl.className = '';
		prod_btn.value = 'Add '+sChar
	}
}

function highlight_addedproduct(prod_code) {
	var sChar=String.fromCharCode(187);	
	var prod_qty = document.getElementById('reqqty'+prod_code);
	var prod_tr = document.getElementById('prod_'+prod_code+'_tr');
	var prod_btn = document.getElementById('prod_'+prod_code+'_btn');
	if((prod_qty.value*1)>0) {
		prod_tr.className = 'addedtocart';
		row_orig_class = 'addedtocart';
		existRowClass = 'addedtocart';
		prod_btn.value = 'Edit '+sChar
	} else {
		prod_tr.className = '';
		row_orig_class = '';
		prod_btn.value = 'Add '+sChar
	}
}

function update_tqty(qtyval, elname, factor, pcount) {
	var el_hnd = document.getElementById(elname);
	if(el_hnd!=false) {
		if(qtyval=='') el_hnd.value = '';
		else {
			el_hnd.value = qtyval * factor;
		}
	}
	if(calc_totprice==true) {
		var totprice_el = document.getElementById('tcost_'+pcount);
		if(qtyval=='') totprice_el.value = '';
		else {
			var price_val = document.getElementById('costp_'+pcount);
			var grand_total = price_val.value * qtyval;
			totprice_el.value = toDollarsAndCents(grand_total);
		}
	}
	return true;
}

function toDollarsAndCents(n) {
	var s = "" + Math.round(n * 100) / 100
  	var i = s.indexOf('.')
  	if (i < 0) return s + ".00"
  	var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
  	if (i + 2 == s.length) t += "0"
  	return t
}

function getAbsLeft(o) {
	oLeft = o.offsetLeft
	while(o.offsetParent!=null) {
		oParent = o.offsetParent
		oLeft += oParent.offsetLeft
		o = oParent
	}
	return oLeft
}

function getAbsTop(o) {
	oTop = o.offsetTop
	while(o.offsetParent!=null) {
		oParent = o.offsetParent
		oTop += oParent.offsetTop
		o = oParent
	}
	return oTop
}

	function pos_today_marker() {
		daysinto = 24;
		today_div = document.getElementById('todays_marker');
		today_line = document.getElementById('todayline');
		lbar = document.getElementById('left_bar');
		ftr = document.getElementById('schedule_ftr');
		hdr = document.getElementById('schedule_hdr');
		stbl = document.getElementById('schedule_tbl');
		tbl_height = stbl.offsetHeight;
		hdr_height = hdr.offsetHeight;
		ftr_height = ftr.offsetHeight;
		totline_height = tbl_height - (hdr_height + ftr_height);
		toppos = getAbsTop(stbl)+hdr_height;
		today_div.style.top = toppos+'px';
		today_div.style.left = ((getAbsLeft(lbar)+(daysinto*2))+3)+'px';
		today_div.style.height = totline_height+'px';
		today_line.style.height  = totline_height+'px';
		today_div.style.visibility = 'visible';
	}

	function trimLength(textarea, maxChars) {
		if(textarea.value.length <= maxChars) return;
		textarea.value = textarea.value.substr(0, maxChars)
	}

	function canAddCharacter(textarea, maxChars) {
		if(typeof(textarea.onkeypress.arguments[0]) != 'undefined')
			var keyCode = textarea.onkeypress.arguments[0].keyCode;
		else {
			if(document.selection.createRange().text.length != 0) return true;
			var keyCode = event.keyCode;
		}
		var allowedChars = new Array(8, 37, 38, 39, 40, 46);	//Backspace, delete and arrow keys
		for(var x=0; x<allowedChars.length; x++) if(allowedChars[x] == keyCode) return true;
		if(textarea.value.length < maxChars) return true;
		return false;
	}

	function check_for_framed_login() {
		if(window.top.location.href != this.window.location.href) {
			window.top.location.href = 'login.php';
		} else if(window.opener!=null) {
			window.opener.location.href = 'login.php';
			window.close();
		}
	}

	function enqord_orderno_defmsg(custno) {
		var statmsg = document.getElementById('specord_status');
		statmsg.innerHTML = '[<a href="#" onclick="enqord_orderno_exists(document.getElementById(\'spec_orderno\').value, \''+custno+'\');return false;">Click here to verify Order Number</a>]';
		statmsg.className = '';
		validate_ordenq();
	}

	function enqord_refno_defmsg(custno) {
		var statmsg = document.getElementById('specref_status');
		statmsg.innerHTML = '[<a href="#" onclick="enqord_refno_exists(document.getElementById(\'spec_custrefno\').value, \''+custno+'\');return false;">Click here to verify Reference Number</a>]';
		statmsg.className = '';
		validate_custrefenq();
	}

	function enqord_orderno_exists(el_val, custno) {
		if(el_val!="") {
			jsrsPOST = false;
			jsrsExecute("ajax_handler.php", enqord_orderno_callback, "ordernumExists", Array(el_val,custno));
		} else {
			var statmsg = document.getElementById('specord_status');
			statmsg.innerHTML = '[<a href="#" onclick="enqord_orderno_exists(document.getElementById(\'spec_orderno\').value, \''+custno+'\');return false;">Click here to verify</a>]';
			validate_ordenq();
		}
	}

	function enqord_refno_exists(el_val, custno) {
		if(el_val!="") {
			jsrsPOST = false;
			jsrsExecute("ajax_handler.php", enqord_refno_callback, "refnumExists", Array(el_val,custno));
		} else {
			var statmsg = document.getElementById('specref_status');
			statmsg.innerHTML = '[<a href="#" onclick="enqord_refno_exists(document.getElementById(\'spec_custrefno\').value, \''+custno+'\');return false;">Click here to verify</a>]';
			validate_custrefenq();
		}
	}

	function enqord_orderno_callback(returnstring) {
		var statmsg = document.getElementById('specord_status');
		if(returnstring==1) {
			statmsg.innerHTML = '[ Valid Order Number ]';
			statmsg.className = 'valid';
		}
		else {
			statmsg.innerHTML = '[ INVALID Order Number ]';
			statmsg.className = 'invalid';
		}
		validate_ordenq();
	}

	function enqord_refno_callback(returnstring) {
		var statmsg = document.getElementById('specref_status');
		if(returnstring==1) {
			statmsg.innerHTML = '[ Valid Reference Number ]';
			statmsg.className = 'valid';
		}
		else {
			statmsg.innerHTML = '[ INVALID Reference Number ]';
			statmsg.className = 'invalid';
		}
		validate_custrefenq();
	}

	function disable_form_element(currentval, enabledval, eltitle, elfield) {
		var title_element = document.getElementById(eltitle);
		var field_element = document.getElementById(elfield);
		if(currentval!=enabledval) {
			// disable form element
			title_element.disabled = true;
			title_element.className = 'disabled_fld_title';
			field_element.disabled = true;
		} else {
			// enable form element
			title_element.disabled = false;
			title_element.className = '';
			field_element.disabled = false;
		}
	}

	function highlight_menu(trel, tdnum, mouseover) {
		var indel = document.getElementById('td_'+tdnum);
		if(mouseover=='true') {
			menu_oldstyle = trel.className;
			menu_indicator_oldstyle = indel.className;
			trel.className = 'menu_on';
			indel.className = 'menu_indicator_on';
		} else {
			trel.className = menu_oldstyle;
			indel.className = menu_indicator_oldstyle;
		}
	}

	function select_menu(elnum) {
		if(sel_menu_num!=null) {
			var trel = document.getElementById('tr_'+sel_menu_num);
			var indel = document.getElementById('td_'+sel_menu_num);
			trel.className = 'menu_off';
			indel.className = 'menu_indicator_off';
		}
		var trel = document.getElementById('tr_'+elnum);
		var indel = document.getElementById('td_'+elnum);
		trel.className = 'menu_sel';
		indel.className = 'menu_indicator_sel';
		menu_oldstyle = trel.className;
		menu_indicator_oldstyle = indel.className;
		sel_menu_num = elnum;
	}

	function highlight_taskrow(chkbox, elname) {
		var chkboxel = document.getElementById(chkbox);
		var rowel = document.getElementById(elname);
		if(chkboxel.checked==true) {
			rowel.className = 'rowselect';
			oldstyle = 'rowselect';
		} else {
			rowel.className = '';
			oldstyle = '';
		}
	}

	function validate_apprcond() {
		var order_from = document.getElementById('value_from');
		var order_to = document.getElementById('value_to');

		// make sure order_from has been
		// provided and is a valid number
		if(order_from.value=="") {
			alert('The \'Order From\' value cannot be blank!');
			order_from.focus();
			return false;
		} else if( isNaN( parseFloat(order_from.value))) {
			alert('The \'Order From\' value is Invalid!\n\nPlease ensure that the value is a valid number and does not\n include any additional characters - for e.g. dollars signs ($)');
			order_from.focus();
			return false;
		}

		// make sure order_to has been
		// provided and is a valid number
		if(order_to.value=="") {
			alert('The \'Order To\' value cannot be blank!');
			order_to.focus();
			return false;
		} else 	if( isNaN( parseFloat(order_to.value))) {
			alert('The \'Order To\' value is Invalid!\n\nPlease ensure that the value is a valid number and does not include any additional characters - for e.g. dollars signs ($)');
			order_from.focus();
			return false;
		}

		// Now lets make sure the order to is greater than order from
		//if(order_to.value<=order_from.value) {
		//	alert('The \'Order To\' value must be greater than the \'Order From\' value!');
		//	order_to.focus();
		//	return false;
		//}

		return true;
	}

	function validate_userdetails(mode) {
		// check firstname
		if(document.getElementById('firstname').value=="") {
			alert("The users firstname is missing!");
			document.getElementById('firstname').focus();
			return false;
		}

		// check lastname
		if(document.getElementById('lastname').value=="") {
			alert("The users lastname is missing!");
			document.getElementById('lastname').focus();
			return false;
		}

		// check email address
	    if (document.getElementById('email_addr').value=="") {
	      alert ('E-Mail Address should be supplied!');
	      document.getElementById('email_addr').focus();
	      return false;
	    } else {
	    	validemail = emailCheck(document.getElementById('email_addr').value);
	    	if(validemail==false) {
	    		document.getElementById('email_addr').focus();
	    		return false;
	    	}
	    }

		// check username
		if(document.getElementById('username').value=="") {
			alert("The users username is missing!");
			document.getElementById('username').focus();
			return false;
		}

		// check password (if creating)
		if(mode=="C") {
			if(document.getElementById('password').value=="") {
				alert("A Password is required so that the user may be able to login.");
				document.getElementById('password').focus();
				return false;
			} else {
				// lets check that they have provided the
				// confirmation password ...
				if(document.getElementById('confirm_password').value=="") {
					alert("Please confirm your password in the space provided");
					document.getElementById('confirm_password').focus();
					return false;
				} else {
					// Lets make sure that the password and the
					// confirmation password are exactly the same.
					if(document.getElementById('password').value!=document.getElementById('confirm_password').value) {
						alert("The supplied passwords do not match - please correct and try again.");
						document.getElementById('confirm_password').focus();
						return false;
					}
				}
			}
		}

		// check costcentre
		if(document.getElementById('all_costcentres').checked==false) {
			// lets check that they have selected at least one costcentre
			var x = document.getElementById('costcentre_combo');
			var num_sel = 0;
			for(i=0; i<x.options.length;i++) {
				if(x.options[i].selected==true)
					num_sel++;
			}
			if(num_sel==0) {
				alert("This user needs to be assigned to at least one costcentre. \n\nAlternatively, tick the 'ALL Costcentres' tickbox and apply all \ncostcentres to this user..");
				document.getElementById('all_costcentres').focus();
				return false;
			}
		}

		// nows lets verify the budget related information
		if(document.getElementById('restrict_to_budget_y').checked==true) {
			// lets test the budget period
			if(document.getElementById('cust_period').checked==true) {
				if(document.getElementById('ub_period').value=="") {
					alert("You have indicated that this user is on a custom period budget, but you \nhave not provided the number of days.");
					document.getElementById('ub_period').focus();
					return false;
				} else {
					// lets make sure it is a valid number ...
					if( isNaN( parseInt(document.getElementById('ub_period').value, 10))) {
						alert("The number of days you have provided does not seem to be a valid number!");
						document.getElementById('ub_period').focus();
						return false;
					}
				}
			}
		}

		// Now lets make sure that the max. acc is greater than the
		// highest between the print / merch. budget
		if(document.getElementById('acc_y').checked==true) {
			var a = document.getElementById('ub_print_amt');
			var b = document.getElementById('ub_merch_amt');
			var y = document.getElementById('ub_maxacc');
			if(isNaN(parseFloat(y.value))) {
		   	alert("The Maximum Accumulation amount is not a valid number!");
		   	y.focus();
		    	return false;
		  	} else {
	    		// Lets determine which of the two budget amounts is greater
	    		var highest_budget_amt = 0;
	    		if(a.value > b.value) highest_budget_amt = a.value;
	    		else if(b.value > a.value) highest_budget_amt = b.value
	    		else if(a.value = b.value) highest_budget_amt = a.value

	    		// lets compare the highest budget amt to the max acc amt
	    		highest_budget_amt = highest_budget_amt - 0;
	    		if(highest_budget_amt > y.value) {
	    			alert('The Maximum Accumulation is smaller than the budget amount of $'+highest_budget_amt);
	    			y.value = highest_budget_amt;
	    			y.focus();
	    			return false;
	    		}
			}
		}

		// If they have made it this far then everything must be ok :-D
		return true;
	}

  function emailCheck (emailStr) {
    var emailPat=/^(.+)@(.+)$/
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    var validChars="\[^\\s" + specialChars + "\]"
    var quotedUser="(\"[^\"]*\")"
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    var atom=validChars + '+'
    var word="(" + atom + "|" + quotedUser + ")"
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

    /* Begin with the coarse pattern to simply break up user@domain into
     different pieces that are easy to analyze. */
    var matchArray=emailStr.match(emailPat)
    if (matchArray==null) {
      /* Too many/few @'s or something; basically, this address doesn't
       even fit the general mould of a valid e-mail address. */
  	  alert("Email address seems incorrect - please check @ and dots (.)")
  	  return false
    }
    var user=matchArray[1]
    var domain=matchArray[2]

    // See if "user" is valid
    if (user.match(userPat)==null) {
      // user is not valid
      alert("The username in your email address doesn't seem to be valid.")
      return false
    }

    /* if the e-mail address is at an IP address (as opposed to a symbolic
     host name) make sure the IP address is valid. */
    var IPArray=domain.match(ipDomainPat)
    if (IPArray!=null) {
      // this is an IP address
  	  for (var i=1;i<=4;i++) {
  	    if (IPArray[i]>255) {
  	      alert("Destination IP address in your email address is invalid!")
  		    return false
  	    }
      }
      return true
    }

    // Domain is symbolic name
    var domainArray=domain.match(domainPat)
    if (domainArray==null) {
  	  alert("The domain name in your email address doesn't seem to be valid.")
      return false
    }

    /* domain name seems valid, but now make sure that it ends in a three-letter word (like com, edu, gov) or a two-letter word,
     representing country (uk, nl), and that there's a hostname preceding the domain or country. */

    /* Now we need to break up the domain to get a count of how many atoms it consists of. */
    var atomPat=new RegExp(atom,"g")
    var domArr=domain.match(atomPat)
    var len=domArr.length
    if (domArr[domArr.length-1].length<2 ||
      domArr[domArr.length-1].length>3) {
      // the address must end in a two letter or three letter word.
      alert("Your email address must end in a three-letter domain, or two letter country.")
      return false
    }

    // Make sure there's a host name preceding the domain.
    if (len<2) {
      var errStr="This email address is missing a hostname!"
      alert(errStr)
      return false
    }

    // If we've gotten this far, everything's valid!
    return true;
  }

function highlight_row(selrow, highlightclass) {
	row_orig_class = selrow.className;
	selrow.className = highlightclass;
}

function remove_highlight(selrow) {
	selrow.className = row_orig_class;
	row_orig_class = '';
}

	function tick_parent(obj, parent_id) {
		if(parent_id!='0' && obj.checked==true) {
			input_array = document.getElementsByTagName('input');
			for(i=0; i<input_array.length; i++) {
				if(input_array[i].value==parent_id) {
					input_array[i].checked = obj.checked;
				}
			}			
		}
		// Select / Deselect all the children with the parent value of this element
		input_array = document.getElementsByTagName('input');
		for(i=0; i<input_array.length; i++) {
			if(input_array[i].getAttribute('parent')==obj.value) {
				input_array[i].checked = obj.checked;
			}
		}				
	}

	function chkUserDel() {
  		var x = confirm('Are you entirely sure you want to delete the selected user account/s?\n\nNB: This action is permanent and cannot be undone.');
  		if(x==false) return false;
  		else {
  			window.top.bottomFrame.show_progress_bar();
			return true;
  		}
	}

function chkMenuDel() {
  var x = confirm('Are you entirely sure you want to delete the selected menu group/s?\n\nNB: This action is permanent and cannot be undone.');
  if(x==false) return false;
  else return true;
}

function checkAll(linkObj, cName, check ) {
  if(check==true) {
    linkObj.innerText = 'Deselect All';
    linkObj.onclick = function() { checkAll(linkObj, cName, false); }
  } else {
    linkObj.innerText = 'Select All';
    linkObj.onclick = function() { checkAll(linkObj, cName, true); }
  }
  for (i=0,n=document.all.length;i<n;i++)
      if (document.all[i].id.indexOf("chk_"+cName+"_") !=-1)
          document.all[i].checked = check;
  return false;
}

function checkAllCheckboxes(linkObj, cName, check) {
  if(check==1) {
    linkObj.onclick = function() { checkAllCheckboxes(linkObj, cName, 0); return false; }
  } else {
    linkObj.onclick = function() { checkAllCheckboxes(linkObj, cName, 1); return false; }
  }
  input_array = document.getElementsByTagName('input');
  for(i=0; i<input_array.length; i++) {
  		if(input_array[i].id.indexOf(cName)!=-1 && input_array[i].disabled!=true) {
  			var tmp_el = document.getElementById('tr_'+input_array[i].value);
  			if(tmp_el) {
	  			if(check==1) {
	  				tmp_el.className = 'rowselect';
	  			} else tmp_el.className = '';
	  		}
  			input_array[i].checked = check;
  		}
  }
  return false;
}

function checkAllRowCheckboxes(linkObj, cName, rowname, check) {
  if(check==1) {
    linkObj.onclick = function() { checkAllRowCheckboxes(linkObj, cName, rowname, 0); return false; }
  } else {  
    linkObj.onclick = function() { checkAllRowCheckboxes(linkObj, cName, rowname, 1); return false; }
  }
  input_array = document.getElementsByTagName('input');
  for(i=0; i<input_array.length; i++) {
  		if(input_array[i].id.indexOf(cName)!=-1 && input_array[i].disabled!=true) {
  			var tmp_el = document.getElementById(rowname+input_array[i].value);
  			if(check==1) {
  				tmp_el.setAttribute('oldcss', tmp_el.className);
  				tmp_el.className = 'rowselect';
  			} else {
  				var x = tmp_el.getAttribute('oldcss');
  				tmp_el.className = x;
  			}
  			input_array[i].checked = check;
  		}
  }
  return false;
}

function ShowDivLayer(el, el_value, vis_value) {
	ObjHandle = document.getElementById(el);
	if (el_value==vis_value) {
		ObjHandle.style.display = "block";
	} else {
		ObjHandle.style.display = "none";
	}
}

function HideDiv(divname) {
	ObjHandle = document.getElementById(divname);
	ObjHandle.style.display = "none"
}

function ShowDiv(divname) {
	ObjHandle = document.getElementById(divname);
	ObjHandle.style.display = "block"
}

function HSDiv(divname, imgname) {
	tmpLyrObj = document.getElementById(divname);
	tmpImgObj = document.getElementById(imgname);

	if(tmpLyrObj.style.display=="none") {
		ShowDiv(divname);
		tmpImgObj.src = 'images/minus_sign.gif';
	}
	else {
		HideDiv(divname);
		tmpImgObj.src = 'images/plus_sign.gif';
	}
}

function tbsquote_fetchprod(divname, imgname, numprods, grp_id, tc, pc) {
	if(numprods>0) {
		tmpProdLyr = document.getElementById('prod'+divname);
		if(tmpProdLyr.innerHTML=="") {
			show_genmsg_layer('Please wait while we fetch the<br>products for this group ...');
			window.fetchprod.location.href="tbsquote_displayonreq.php?grp_id="+grp_id+"&tipcount="+tc+"&prodcount="+pc;
		}
	}
	tmpLyrObj = document.getElementById(divname);
	tmpImgObj = document.getElementById(imgname);

	if(tmpLyrObj.style.display=="none") {
		ShowDiv(divname);
		tmpImgObj.src = 'images/minus_sign.gif';
	}
	else {
		HideDiv(divname);
		tmpImgObj.src = 'images/plus_sign.gif';
	}
}

function HSDiv_two(divname, imgname, numprods, grp_id, tc, pc) {
	if(numprods>0) {
		tmpProdLyr = document.getElementById('prod'+divname);
		if(tmpProdLyr.innerHTML=="") {
			show_genmsg_layer('Please wait while we fetch the<br>products for this group ...');
			window.fetchprod.location.href="req_displayonreq.php?grp_id="+grp_id+"&tipcount="+tc+"&prodcount="+pc;
		}
	}
	tmpLyrObj = document.getElementById(divname);
	tmpImgObj = document.getElementById(imgname);

	if(tmpLyrObj.style.display=="none") {
		ShowDiv(divname);
		tmpImgObj.src = 'images/minus_sign.gif';
	}
	else {
		HideDiv(divname);
		tmpImgObj.src = 'images/plus_sign.gif';
	}
}

function trim(inputString) {
  // Removes leading and trailing spaces from the passed string. Also removes
  // consecutive spaces and replaces it with one space. If something besides
  // a string is passed in (null, custom object, etc.) then return the input.
  if (typeof inputString != "string") return inputString;
  var retValue = inputString;
  var ch = retValue.substring(0, 1);
  while (ch == " ") {
    // Check for spaces at the beginning of the string
    retValue = retValue.substring(1, retValue.length);
    ch = retValue.substring(0, 1);
  }
  ch = retValue.substring(retValue.length-1, retValue.length);
  while (ch == " ") {
    // Check for spaces at the end of the string
    retValue = retValue.substring(0, retValue.length-1);
    ch = retValue.substring(retValue.length-1, retValue.length);
  }
  while (retValue.indexOf("  ") != -1) {
    // Note that there are two spaces in the string - look for multiple spaces within the string
    retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
  }
  return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function


// Returns true or false based on whether the specified string is found
// in the array. This is based on the PHP function of the same name.
function in_array(stringToSearch, arrayToSearch) {
	for (s = 0; s < arrayToSearch.length; s++) {
		thisEntry = arrayToSearch[s].toString();
		if (thisEntry == stringToSearch) return true;
	}
	return false;
}

function OpenCentreWin(page_name,window_name,page_height,page_width,attributes) {
  LeftPosition = (screen.availWidth) ? (screen.availWidth-page_width)/2 : 0;
  TopPosition = (screen.availHeight) ? (screen.availHeight-page_height)/2 : 0;
  settings = 'height='+page_height+',width='+page_width+',top='+TopPosition+',left='+LeftPosition;
  if(attributes!='') settings = settings +','+attributes;
  var x = window.open(page_name,window_name,settings);
}

function resetTabs(clickedtab) {
	input_array = document.getElementsByTagName('li');
	  for(i=0; i<input_array.length; i++) {
      	if(input_array[i].id!=clickedtab)
      		document.getElementById(input_array[i].id).className = '';
	  }
}
/*#########################################################################*/
// end hiding -->