/*******************GLOBAL VARIABLES*******************/

/*
Description:	disables the context menu
Author:			E Van Veen
Created:		1 June 2006
DISABLED DURING DEVELOPMENT
*/
/*
var message="Function Disabled!";
function clickIE()
{
	if (document.all)
	{
		alert(message);
		return false;
	}
}
function clickNS(e)
{
	if (document.layers||(document.getElementById&&!document.all))
	{
		if (e.which==2||e.which==3)
		{
			alert(message);
			return false;
		}
	}
}
if (document.layers)
{
	document.captureEvents(Event.MOUSEDOWN);
	document.onmousedown=clickNS;
}
else
{
	document.onmouseup=clickNS;
	document.oncontextmenu=clickIE;
}
document.oncontextmenu=new Function("return false")*/

function purgeEventHandlers(domObject) {   
	var attribs = domObject.attributes;
	var i;
	
	// clear all of the functions from the DOM Object
	if (attribs){
		var attribCount = attribs.length;
		if (attribCount > 0){
	    	for (var i = 0; i < attribCount; i += 1) {
	    		var n = attribs[i].name;
	    		if (typeof domObject[n] === 'function') {
	    			domObject[n] = null;
	    		}
	    	}
		}
	}
	
	// recurse the child DOM Objects
	var childNodes = domObject.childNodes;
	if (childNodes){
		var childCount = childNodes.length;
		if (childCount > 0){
	    	for (var i = 0; i < childCount; i += 1) {
	    		purgeEventHandlers(domObject.childNodes[i]);
	    	}
		}
	}
}

function setElementInnerHTML(element, html) {
	purgeEventHandlers(element);
	element.innerHTML = html;
}

function showCurrencyConverter(amount){
	currency_window=window.open('http://www.xe.com/pca/input.php?FromSelect=AUD&ToSelect=NZD&Amount=' + amount, 'currency_exchange', 'toolbar=0,location=0,status=0,scrollbars=0,menubar=0,directories=0,resizable=1,width=620,height=200');
	currency_window.focus();
}

function isIE() {
  if( typeof( window.innerWidth ) == 'number' ) {
	/*Non-IE*/
    iebrowser = false;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    /*IE 6+ in 'standards compliant mode'*/
	  iebrowser = true;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    /*IE 4 compatible*/
	  iebrowser = true;
  }
  return iebrowser;
}

/**********************AJAX STUFF**********************/
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 populateDiv(the_div, the_script, do_return) {
	var the_script_elements = the_script.split("?");
	if (the_script_elements[1] == undefined || the_script_elements[1] == 'undefined') {
		the_script_elements[1] = '';
	}
	populateDivPost(the_div, the_script_elements[0], the_script_elements[1], do_return);
}

/* 
function populateDiv(the_div, the_script, do_return) {
	if (do_return) {
		setElementInnerHTML(document.getElementById(the_div), '<img src="wait26trans.gif" />');
	} else {
		document.getElementById(the_div).style.display = 'none';
	}
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!");
		return;
	}
	xmlHttp.open("GET", the_script, false);
	if (do_return) {
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				setElementInnerHTML(document.getElementById(the_div), xmlHttp.responseText);
			}
		}
	}
	xmlHttp.send(null);
//	while(xmlHttp.readyState != 4){}
	if (do_return) {
		setElementInnerHTML(document.getElementById(the_div), xmlHttp.responseText);
	}
}
*/

function populateDivParent(the_div, the_script, do_return) {
	if (do_return) {
		setElementInnerHTML(parent.document.getElementById(the_div), '<img src="wait26trans.gif" />');
	} else {
		parent.document.getElementById(the_div).style.display = 'none';
	}
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!");
		return;
	}
	xmlHttp.open("GET", the_script, false);
	if (do_return) {
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				setElementInnerHTML(parent.document.getElementById(the_div), xmlHttp.responseText);
			}
		}
	}
	xmlHttp.send(null);
//	while(xmlHttp.readyState != 4){}
	if (do_return) {
		setElementInnerHTML(parent.document.getElementById(the_div), xmlHttp.responseText);
	}
}

function populateDivPost(the_div, the_script, the_params, do_return) {
	if (do_return) {
		setElementInnerHTML(document.getElementById(the_div), '<img src="wait26trans.gif" />');
	} else {
		document.getElementById(the_div).style.display = 'none';
	}
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert("Your browser does not support AJAX!");
		return;
	}
	//var url = the_script;
	xmlHttp.open("POST", the_script, false);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", the_params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	if (do_return) {
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				setElementInnerHTML(document.getElementById(the_div), xmlHttp.responseText);
			}
		}
	}
	xmlHttp.send(the_params);
//	while(xmlHttp.readyState != 4){}
	if (do_return) {
		setElementInnerHTML(document.getElementById(the_div), xmlHttp.responseText);
	}
}

/*******************GENERAL FUNCTIONS*******************/

function formIsDirty(test_form)
{
	if (document.forms[test_form] != undefined) {
	   for (var i = 0; i < document.forms[test_form].elements.length; i++) {
	       var the_element = document.forms[test_form].elements[i];
	       var type = the_element.type;
	       if (type == "checkbox" || type == "radio") {
	       if (the_element.checked != the_element.defaultChecked) {
	           return true;
	       }
	   }
	   else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") {
	           if (the_element.value != the_element.defaultValue) {
	               return true;
	           }
	       }
	   }
	}
   return false;
}



function closeAllPopboxes() {
	document.getElementById('popup_dialog').style.display = 'none';
	document.getElementById('popup_dialog_2').style.display = 'none';
	document.getElementById('popup_dialog_3').style.display = 'none';
	document.getElementById('popup_dialog_anzsic').style.display = 'none';
}


function showPostcodeDialog(level, thefrm, sub, thestate, thecode, the_prefix) {
	if (level == 1) {
		pd = 'popup_dialog_2';
	} else if (level == 2) {
		pd = 'popup_dialog_3';
	} else if (level == 3) {
		pd = 'popup_dialog_anzsic';
	} else {
		pd = 'popup_dialog';
	}
	if (sub == '' && thecode == '') {
		alert('Please enter at least the first few letters of a City/Suburb, or enter a postcode');
	} else {
		document.getElementById(pd).style.display = 'block';
		theurlstring = 'php_scripts/aust_post_search.php?sub=' + sub + '&state=' + thestate + '&pcode=' + thecode + '&thefrm=' + thefrm + '&pd=' + pd + '&the_prefix=' + the_prefix + '&level=' + level;
		theuristring = encodeURI(theurlstring);
		populateDiv(pd, theuristring, true);
		searchPostcodes(thefrm, pd, the_prefix);
	}
}

function searchPostcodes(thefrm, pd, the_prefix) {
	sub = document.frm_aust_post_search.psuburb.value;
	thestate = document.frm_aust_post_search.pstate[document.frm_aust_post_search.pstate.options.selectedIndex].value;
	thecode = document.frm_aust_post_search.pcode.value;
	if (sub == '' && thecode == '') {
		alert('Please enter at least the first few letters of a City/Suburb, or enter a postcode');
	} else {
		document.getElementById('pcode_results').style.display = 'block';
		theurlstring = 'php_scripts/aust_post_search_results.php?sub=' + sub + '&state=' + thestate + '&pcode=' + thecode + '&thefrm=' + thefrm + '&pd=' + pd + '&the_prefix=' + the_prefix;
		theuristring = encodeURI(theurlstring);
		populateDiv('pcode_results',theuristring, true);
	}
}

function postbackAddressDetails(thefrm, pd, sub, thestate, thecode, the_prefix) {
	re = /`/;
	suburb = the_prefix + '_suburb';
	postcode = the_prefix + '_postcode';
	document.getElementById(pd).style.display = 'none';
	document.forms[thefrm].elements[suburb].value=sub.replace(re, "'");
	document.forms[thefrm].elements[postcode].value=thecode;
	for (i=0; i < document.forms[thefrm].elements[the_prefix + '_state'].options.length; i++) {
		if (document.forms[thefrm].elements[the_prefix + '_state'][i].value == thestate) {
			document.forms[thefrm].elements[the_prefix + '_state'][i].selected = true;
		}
	}
}

function timeValid(hrs,mins,meridian) {
	var timemsg = '';
	var timebad = 0;
	if (hrs == '' || isNaN(hrs) || hrs > 12 || hrs < 1) {
		timemsg = "Enter time in 12 hr format only.\nYou entered (" + hrs + ":" + mins + " " + meridian + ").";
		return timemsg;
	} else if (mins == '' || isNaN(mins) || mins > 59 || mins < 0) {
		timemsg = "Incorrect number of minutes - must be between 0 and 59.\nYou entered (" + hrs + ":" + mins + " " + meridian + ").";
		return timemsg;
	}
	return timemsg;
}

function dateCursor(theDay, theMonth, theYear) {
	var datemsg = '';
	var day_bad = 0;
	//alert(d + '-' + m + '-' + y);
	if ((theYear < 1000) || (theYear > 9999)) {
		datemsg="Enter only 4-digit years."
				+ "\n" + "You entered (Day=" + theDay + ", Month=" + theMonth
				+ ", Year=" + theYear + ")";
		return datemsg;
	}
	if ((theMonth > 12) || (theMonth < 1)) {
		datemsg="Incorrect Month. Dates MUST be entered in the following format: dd mm yyyy."
				+ "\n"
				+ "You entered (Day="
				+ theDay
				+ ", Month="
				+ theMonth
				+ ", Year=" + theYear + ")";
		return datemsg;
	} else {
		if (theMonth == 2 && ((theYear / 4) == parseInt(theYear / 4))) {
			if (theDay <= 0 || theDay > 29)
				day_bad = 1;
		}
		if (theMonth == 2 && ((theYear / 4) != parseInt(theYear / 4))) {
			if (theDay <= 0 || theDay > 28)
				day_bad = 1;
		}
		if (theMonth == 4 || theMonth == 6 || theMonth == 9 || theMonth == 11) {
			if (theDay <= 0 || theDay > 30)
				day_bad = 1;
		}
		if (theMonth == 1 || theMonth == 3 || theMonth == 5 || theMonth == 7
				|| theMonth == 8 || theMonth == 10 || theMonth == 12) {
			if (theDay <= 0 || theDay > 31)
				day_bad = 1;
		}
		if (day_bad == 1) {
			datemsg="This date does not exist." + "\n" + "You entered (Day="
					+ theDay + ", Month=" + theMonth + ", Year=" + theYear
					+ ")";
			return datemsg;
		}
	}
	return datemsg;
}

function showGenericDialog(popup_form, level) {
	if (level == 1) {
		pd = 'popup_dialog_2';
	} else if (level == 2) {
		pd = 'popup_dialog_3';
	} else if (level == 3) {
		pd = 'popup_dialog_4';
	} else {
		pd = 'popup_dialog';
	}
	if(document.getElementById(pd+'_parent')){document.getElementById(pd+'_parent').style.display = 'block'}
	document.getElementById(pd).style.display = 'block';
	populateDiv(pd, popup_form, true);
}

function showGenericDialogParent(popup_form, level) {
	if (level == 1) {
		pd = 'popup_dialog_2';
	} else if (level == 2) {
		pd = 'popup_dialog_3';
	} else if (level == 3) {
		pd = 'popup_dialog_4';
	} else {
		pd = 'popup_dialog';
	}
	if(parent.document.getElementById(pd+'_parent')){parent.document.getElementById(pd+'_parent').style.display = 'block'}
	parent.document.getElementById(pd).style.display = 'block';
	populateDivParent(pd, popup_form, true);
}

function showGenericDialogPost(popup_form, form_params, level) {
	if (level == 1) {
		pd = 'popup_dialog_2';
	} else if (level == 2) {
		pd = 'popup_dialog_3';
	} else if (level == 3) {
		pd = 'popup_dialog_4';
	} else {
		pd = 'popup_dialog';
	}
	if(document.getElementById(pd+'_parent')){document.getElementById(pd+'_parent').style.display = 'block'}
	document.getElementById(pd).style.display = 'block';
	populateDivPost(pd, popup_form, form_params, true);
}

function saveActions(msg, level) {
	if (level == 1) {
		id = 'popup_dialog_2';
	} else if (level == 2) {
		id = 'popup_dialog_3';
	} else if (level == 3) {
		id = 'popup_dialog_4';
	} else if (level == 'return_msg') {
		id = 'return_msg';
	} else {
		id = 'popup_dialog';
	}
	document.getElementById(id).style.display = 'none';
	if(document.getElementById(id+'_parent')){document.getElementById(id+'_parent').style.display = 'none'}
}

function validateAddEditNote(the_action, ref_type, ref_id, display_type, display_div, wsp, btn, div_to_close, noteid) {
	//validate data
	var note_text = document.frm_note_entry.note_text.value;
	if (note_text == '') {
		alert('You must enter some text.');
		return;
	}
	//initiate save or update based on the_action (may be either 'add' or 'edit')
	var form_params;
	form_params = 'note_text=' + note_text;
	form_params += '&ref_type=' + ref_type;
	form_params += '&ref_id=' + ref_id;
	form_params += '&noteid=' + noteid;
	form_params += '&the_action=' + the_action;
	populateDivPost('return_msg', 'php_scripts/add_edit_note_sql.php', form_params, true);
	saveActions('cancel',div_to_close);
	//set display based on display_type (may be either 'in_form' or 'wksp_block')
	var theurlstring = 'php_scripts/display_notes.php?ref_id=' + ref_id + '&ref_type=' + ref_type + '&display_type=' + display_type + '&display_div=' + display_div;
	var theuristring = encodeURI(theurlstring);
	if (display_type == 'in_form') {
		populateDiv(display_div,theuristring,true);
	} else if (display_type == 'wksp_block') {
		expandContractWspBlocks(display_div, theuristring, wsp, btn);
	}
}

function closeSystemMsg() {
	setTimeout('setElementInnerHTML(document.getElementById("return_msg"), "");',2000);
}

function getSelectState(the_div, thecountry, top_opt, show_selected) {
	theurlstring = 'php_scripts/get_states_list.php?thecountry=' + thecountry + '&top_opt=' + top_opt + '&show_selected=' + show_selected;
	theuristring = encodeURI(theurlstring);
	populateDiv(the_div,theuristring, true);
}

function getSelectRegion(the_div, thecountry, top_opt, thestate) {
	theurlstring = 'php_scripts/get_regions_list.php?thecountry=' + thecountry + '&thestate=' + thestate + '&top_opt=' + top_opt;
	theuristring = encodeURI(theurlstring);
	populateDiv(the_div,theuristring, true);
}

function getNonSelectStateRegion(state_div, region_div, thecountry, top_opt) {
	getSelectState(state_div, thecountry, top_opt, 0);
	getSelectRegion(region_div, 'na', top_opt, 'na');
}

function setNumFormat(numvalue, the_form, the_element, is_dollars) {
	if (numvalue != '') {
		var stripped_value = numvalue.replace(/\D/gi,"");
		formatted_array = new Array();
		var count=0;
		for (i=stripped_value.length; i > 0; i=i-3){
			formatted_array[count] = stripped_value.substring(i,i-3);
			count++;
		}
		count=0;
		for (j=0; j<formatted_array.length; j++) {
			if (count==0){
				fnum = formatted_array[j];
			} else {
				fnum = formatted_array[j] + "," + fnum;
			}
			count++;
		}
		if (is_dollars) {
			fnum = "$" + fnum;
		}
		//var fnum_timeout = setTimeout(function() { document.forms[the_form].elements[the_element].value = fnum; }, 3000);
		document.forms[the_form].elements[the_element].value = fnum;
	}
}

function setPhoneFaxFormat(numvalue, the_form, the_element) {
	if (numvalue != '') {
		var stripped_value = numvalue.replace(/\D/gi,"");
		document.forms[the_form].elements[the_element].value = stripped_value;
	}
}

function countChars(allowable_len, e_title, txt, f_name, e_name) {
	if (txt.length > allowable_len) {
		alert("You have exceeded the maximum number of characters allowed for the '" + e_title + "' field (Allowed: " + allowable_len + "; Entered: " + txt.length + ").\nYour text will be cropped to " + allowable_len + " characters.");
		document.forms[f_name].elements[e_name].value = txt.substr(0, allowable_len);
	}
}

function emailAddressContentValidation(the_email) {
	re = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (re.test(the_email)) {
		return true;
	} else {
		return false;
	}
}

function testEmail(the_form, the_element) {
	var address = document.forms[the_form].elements[the_element].value;
	theurlstring = 'php_scripts/test_email.php?theemail=' + address;
	theuristring = encodeURI(theurlstring);
	populateDiv('return_msg',theuristring, true);
}

function testURL() {
	alert("this will test a url when it is complete");
}

function autoSuggest(the_value, the_form, the_element, the_script, id_field, title_field, table_name) {
	the_div = the_element + '_autosuggest';
	if (the_value.length > 2) {
		theurlstring = the_script + '?mask=' + the_value + '&id_field=' + id_field + '&title_field=' + title_field + '&table_name=' + table_name + '&the_form=' + the_form + '&the_element=' + the_element;
		theuristring = encodeURI(theurlstring);
		document.getElementById(the_div).style.display = 'block';
		populateDiv(the_div,theuristring,true);
		asTimer(the_div,3500);
	} else {
		document.getElementById(the_div).style.display = 'none';
	}
}

function autoSuggestMulti(the_value, the_form, the_element, the_script, id_field, title_field, display_field, table_name) {
	the_div = the_element + '_autosuggest';
	if (the_value.length > 2) {
		theurlstring = the_script + '?mask=' + the_value + '&id_field=' + id_field + '&title_field=' + title_field + '&display_field=' + display_field + '&table_name=' + table_name + '&the_form=' + the_form + '&the_element=' + the_element;
		theuristring = encodeURI(theurlstring);
		document.getElementById(the_div).style.display = 'block';
		populateDiv(the_div,theuristring,true);
		asTimer(the_div,3500);
	} else {
		document.getElementById(the_div).style.display = 'none';
	}
}

function autoSuggestContract(the_div) {
	setElementInnerHTML(document.getElementById(the_div), '');
	setElementDisplay(the_div,'none');
}

function autoSuggestLoadFields(the_id, the_value, the_form, the_element) {
	the_hidden_field = the_element + '_hidden';
	the_div = the_element + '_autosuggest';
	autoSuggestContract(the_div);
	document.forms[the_form].elements[the_hidden_field].value = the_id;
	document.forms[the_form].elements[the_element].value = the_value;
	closeCalloutMsg();
}

function autoSuggestCity(the_value, the_form, the_element, the_country) {
	the_div = the_element + '_autosuggest';
	if (the_value.length > 2) {
		theurlstring = the_script + '?mask=' + encodeURIComponent(the_value) + '&the_form=' + the_form + '&the_element=' + the_element + '&the_country=' + the_country;
		document.getElementById(the_div).style.display = 'block';
		populateDiv(the_div,theurlstring,true);
		//asTimer(the_div,3500);
	} else {
		document.getElementById(the_div).style.display = 'none';
	}
}

function autoSuggestLoadLocationFieldsAU(postcode, city, state, the_form, the_prefix) {
	the_div = the_prefix + '_autosuggest';
	autoSuggestContract(the_div);
	document.forms[the_form].elements[the_prefix+'_suburb'].value = decodeURI(city);
	document.forms[the_form].elements[the_prefix+'_postcode'].value = decodeURI(postcode);
	opt_len = document.forms[the_form].elements[the_prefix+'_state'].options.length;
	for (i=0; i < opt_len; i++) {
		if (document.forms[the_form].elements[the_prefix+'_state'][i].value == state) {
			document.forms[the_form].elements[the_prefix+'_state'][i].selected = true;
		}
	}
}

function asTimer(the_div,the_msecs) {
	autosuggest_timer = setTimeout("document.getElementById(the_div).style.display = 'none'",the_msecs);
}

function autoSuggestCalloutBox(the_div, item_id, id_column_name, table_name) {
	clearTimeout(autosuggest_timer);
	document.getElementById(the_div).className='autosuggest_over';
	theurlstring = 'php_scripts/autosuggest_callout_sql.php?item_id=' + item_id + '&id_column_name=' + id_column_name + '&table_name=' + table_name;
	theuristring = encodeURI(theurlstring);
	//alert(theuristring);
	populateDiv('popup_dialog_L400',theuristring,true);
}

function closeCalloutMsg() {
	setElementInnerHTML(document.getElementById("popup_dialog_L400"), "");
}

function unlinkItem(item_type,item_id,ref_type,ref_id,return_div,file_name,wsp,btn) {
	theurlstring = 'php_scripts/unlink_item_sql.php?item_type=' + item_type + '&item_id=' + item_id + '&ref_type=' + ref_type + '&ref_id=' + ref_id;
	theuristring = encodeURI(theurlstring);
	populateDiv('return_msg',theuristring,true);
	if (item_type == 'mydiary') {
		var toggle_script = 'php_scripts/my_diary_entries.php?qstate=' + ref_type;
		toggleDiaryView('my_diary_list',toggle_script,ref_type)
		toggleDiaryView('my_diary_list',toggle_script,ref_type)
	} else {
		if (item_type == 'question') {
			file_name += '&ref_type=' + ref_type + '&display_type=wksp_block&display_div=' + return_div + '&wsp=' + wsp + '&btn=' + btn;
		} else {
			file_name += '?ref_type=' + ref_type + '&display_type=wksp_block&display_div=' + return_div + '&wsp=' + wsp + '&btn=' + btn;
		}
		expandContractWspBlocks(return_div,file_name,wsp,btn);
	}
}

function displaySelectedLocationDetails(the_div,locationid) {
	theurlstring = 'php_scripts/get_selected_location_sql.php?locationid=' + locationid + '&the_div=' + the_div;
	theuristring = encodeURI(theurlstring);
	document.getElementById(the_div).style.display='block';
	populateDiv(the_div,theuristring,true);
}

function getStatesForSelectedCountry(the_div,country_code,element_name,set_region,set_selected,selected_code,incl_deleted,is_mandatory) {
	theurlstring = '/php_scripts/reset_state_list.php?country_code=' + country_code + '&element_name=' + element_name + '&set_region=' + set_region;
	theurlstring += '&set_selected=' + set_selected + '&selected_code=' + selected_code + '&incl_deleted=' + incl_deleted + '&is_mandatory=' + is_mandatory;
	theuristring = encodeURI(theurlstring);
	populateDiv(the_div,theuristring,true);
	apicon = element_name + '_apicon';
	if (document.getElementById(apicon)) {
		if (country_code != "AU") {
			document.getElementById(apicon).src = 'images/spacer.gif';
		} else {
			document.getElementById(apicon).src = 'images/aust_post.png';
		}
	}
}

function addNewLocation(ref_type,ref_id,the_div,form_name,allow_add_new,show_selected,is_mandatory,level) {
	theurlstring = 'php_scripts/location_add_new_form.php?ref_type=' + ref_type + '&ref_id=' + ref_id + '&the_div=' + the_div;
	theurlstring += '&form_name=' + form_name + '&allow_add_new=' + allow_add_new + '&show_selected=' + show_selected + '&is_mandatory=' + is_mandatory;
	theuristring = encodeURI(theurlstring);
	showGenericDialog(theuristring,level);
}

function addNewLocationToNewCompany(level,companyid) {
	//validate that there is a company name that is unique 
	//if unique company name, add new company here and return companyid to allow addition and linking of location
	if (document.frm_add_supplier.company_name.value == '') {
		alert("Please enter a unique company name.");
		return;
	}
	//refresh new company form div, then call addNewLocation() 
	var form_params;
	form_params = 'company_name=' + document.frm_add_supplier.company_name.value;
	form_params += 'trading_as=' + document.frm_add_supplier.trading_as.value;
	form_params += 'products_services=' + document.frm_add_supplier.products_services.value;
	form_params += 'facilities=' + document.frm_add_supplier.facilities.value;
	//populateDivPost('return_msg','php_scripts/supplier_add_link_new_sql.php',form_params,true);
	
	//display Add New Location form
	
}

function validatePhoneFax(pi,pa,pn,fi,fa,fn) {
	var fail_msg = '';
	if (pn != '' && pa == '') {
		fail_msg += "Please enter an area code in the Phone area field. You entered:\nCountry Code: " + pi + "\nArea Code: " + pa + "\nNumber: " + pn + "\n";
	}
	if (fn != '' && fa == '') { 
		fail_msg += "Please enter an area code in the Fax area field. You entered:\nCountry Code: " + fi + "\nArea Code: " + fa + "\nNumber: " + fn + "\n";
	}
	return fail_msg;
}


//get the popup div's id using 'this' as the argument
//eg: thisDiv(this);
function thisDiv(node) {
	var the_id = 'popup_dialog';
	var parent = node;
	while(parent.id.indexOf(the_id) < 0) {
		parent = parent.parentNode;
	}
	if (parent.id == 'popup_dialog') {
		pd = 0;
	} else if (parent.id == 'popup_dialog_2') {
		pd = 1;
	} else if (parent.id == 'popup_dialog_3') {
		pd = 2;
	} else if (parent.id == 'popup_dialog_4') {
		pd = 3;
	} else {
		pd = -1;
	}
	return pd;
}

function showTextAreaData(the_form,the_ta,action,limit,current_div) {
	//alert(the_form + " : " + the_ta + " : " + action + " : " + limit + " : " + current_div);
	the_text = document.forms[the_form].elements[the_ta].value;
	level = current_div + 1;
	var form_params = 'text=' + the_text + '&action=' + action + '&the_form=' + the_form + '&the_ta=' + the_ta + '&limit=' + limit;
	showGenericDialogPost('php_scripts/view_textarea.php', form_params, level);
}

function replaceTextAreaData(the_form,the_ta,the_value,div_to_close) {
	document.forms[the_form].elements[the_ta].value = the_value;
	saveActions('cancel',div_to_close);
}

function showEditCompanyDetails(companyid,test_form) {
	//alert(document.forms[test_form].elements.length);
	if (test_form && formIsDirty(test_form)) {
		if (confirm('You have unsaved fields in the current form.\nDo you want to continue without saving?\n(If you click OK you will lose any unsaved changes.)')) {
			oktogo = true;
		} else {
			oktogo = false;
		}
	} else {
		oktogo = true;
	}
	if (oktogo) {
		clearCompanyData();
		populateDiv('companies_form','php_scripts/company_add_edit_form.php?companyid=' + companyid,true);
		theurlstring = 'php_scripts/display_pclinks.php?ref_id=' + companyid + '&ref_type=company&display_type=wksp_block&display_div=company_pclinks_data&wsp=companies_workspace&btn=0';
		theuristring = encodeURI(theurlstring);
		expandContractWspBlocks('company_pclinks_data',theuristring,'companies_workspace',0)
	} else {
		return;
	}
}

function isABN(s){
	if (s != ''){
		var m, as, i, sum = 0, is_abn;
		m = [10,1,3,5,7,9,11,13,15,17,19];
		s = s.replace(/\D/gi,"");
		if (s.length != 11) {
			is_abn = false;
		} else {
			as = s.split('');
			as[0] = String(parseInt(as[0]) - 1);
			for (i=0;i<as.length;i++) sum += parseInt(as[i]) * m[i];
			is_abn = (sum % 89 == 0);
		}
		if(is_abn) {
			return true;
		} else {
			alert(s + " is not a valid ABN.");
			return false;
		}
	}
	alert("Please enter a valid ABN.");
	return false;
}

function isABNNotMandatory(s){
	if (s != ''){
		var m, as, i, sum = 0, is_abn;
		m = [10,1,3,5,7,9,11,13,15,17,19];
		s = s.replace(/\D/gi,"");
		if (s.length != 11) {
			is_abn = false;
		} else {
			as = s.split('');
			as[0] = String(parseInt(as[0]) - 1);
			for (i=0;i<as.length;i++) sum += parseInt(as[i]) * m[i];
			is_abn = (sum % 89 == 0);
		}
		if(is_abn) {
			return true;
		} else {
			alert(s + " is not a valid ABN.");
			return false;
		}
	} else {
		return true;
	}
}

function saveCompany(the_action,companyid){
	company_name = document.company_add_edit_frm.company_name.value;
	abn = document.company_add_edit_frm.abn.value;
	abn = abn.replace(/\D/gi,"");
	if (company_name == '') {
		alert("Please enter a company name.");
		return;
	}
	if (abn != '' && !isABN(abn)) {
		return;
	}
	if (the_action == "insert") {
		theurlstring = 'php_scripts/company_add_edit_form.php?action=' + the_action + '&company_name=' + company_name + '&abn=' + abn;
		theuristring = encodeURI(theurlstring);
		populateDiv('companies_form',theuristring,true);
	} else if (the_action == "update") {
		var theday = document.company_add_edit_frm.update_date_d.value;
		var themonth = document.company_add_edit_frm.update_date_m.value;
		var theyear = document.company_add_edit_frm.update_date_y.value;
		if(theday != '' && theday != 'dd' && themonth != '' && themonth != 'mm' && theyear != '' && theyear != 'yyyy') {
			var datevalid = dateCursor(theday,themonth,theyear);
			if (datevalid != '') {
				alert('Update Date:\n' + datevalid);
				return;
			} else {
				var thisdate = theyear + '-' + themonth + '-' + theday;
			}
		}
		if(document.company_add_edit_frm.exporter.checked){exporter = 1;}else{exporter = 0;}
		if(document.company_add_edit_frm.active_status.checked){active_status = 1;}else{active_status = 0;}
		var form_params = 'companyid=' + companyid;
		form_params += '&action=' + the_action;
		form_params += '&company_name=' + company_name;
		form_params += '&exporter=' + exporter;
		form_params += '&active_status=' + active_status;
		form_params += '&abn=' + abn;
		form_params += '&update_date=' + thisdate;
		form_params += '&description=' + document.company_add_edit_frm.description.value;
		form_params += '&trading_as=' + document.company_add_edit_frm.trading_as.value;
		form_params += '&products_services=' + document.company_add_edit_frm.products_services.value;
		form_params += '&facilities=' + document.company_add_edit_frm.facilities.value;
		form_params += '&employees=' + document.company_add_edit_frm.employees.value.replace(/\D/gi,"");
		form_params += '&indigenous_employees=' + document.company_add_edit_frm.indigenous_employees.value.replace(/\D/gi,"");
		form_params += '&turnover=' + document.company_add_edit_frm.turnover.value.replace(/\D/gi,"");
		form_params += '&library_ref=' + document.company_add_edit_frm.library_ref.value;
		form_params += '&activity_code=' + document.company_add_edit_frm.qld_acty_code[document.company_add_edit_frm.qld_acty_code.options.selectedIndex].value;
		form_params += '&industry_code=' + document.company_add_edit_frm.qld_ind_code[document.company_add_edit_frm.qld_ind_code.options.selectedIndex].value;
		//alert(form_params);
		populateDivPost('companies_form','php_scripts/company_add_edit_form.php',form_params,true);
	}
}

function closeCompMsg() {
	document.getElementById("comp_error_msg").style.display="none";
}

function togglePcMsgValue(link_type,ref_type,ref_name,value) {
	if (link_type == 'p') {
		the_warning = '<strong>' + value + ' will become the PARENT of ' + ref_name + '.</strong>';
	} else if (link_type == 'c') {
		the_warning = '<strong>' + value + ' will become a CHILD of ' + ref_name + '.</strong>';
	}
	setElementInnerHTML(document.getElementById('pc_confirm'), the_warning);
}


function setParentChildLink(ref_type,ref_id,ref_name,selected_name,selected_id,div_to_close,display_type,display_div,wsp,btn) {
	if(!selected_id || selected_id == ''){
		alert("Please click a " + ref_type + " in the auto-suggest list.");
		return;
	}
	if (document.pc_autosuggest_frm.pc[0].checked) {
		parent_id = selected_id;
		parent_name = selected_name;
		child_id = ref_id;
		child_name = ref_name;
		pctype = 'parent';
	} else if (document.pc_autosuggest_frm.pc[1].checked) {
		parent_id = ref_id;
		parent_name = ref_name;
		child_id = selected_id;
		child_name = selected_name;
		pctype = 'child';
	} else {
		alert("Please click a link type (parent or child).");
		return;
	}
	theurlstring = 'php_scripts/parent_child_insert_link_sql.php?pctype=' + pctype + '&parent_id=' + parent_id + '&child_id=' + child_id + '&ref_type=' + ref_type + '&parent_name=' + parent_name + '&child_name=' + child_name;
	theuristring = encodeURI(theurlstring);
	populateDiv('return_msg',theuristring,true);
	saveActions('cancel',div_to_close);
	theurlstring = 'php_scripts/display_pclinks.php?ref_id=' + ref_id + '&ref_type=' + ref_type + '&display_type=' + display_type + '&display_div=' + display_div + '&wsp=' + wsp + '&btn=' + btn;
	theuristring = encodeURI(theurlstring);
	expandContractWspBlocks(display_div,theuristring,wsp,btn);
}

function showEditContactDetails(contactid) {
	//alert('start');
	clearContactData();
	//alert('cleared');
	populateDiv('contacts_form','php_scripts/contact_add_edit_form.php?contactid=' + contactid,true);
	//expandContractWspBlocks('contact_companies_data','php_scripts/contact_companies.php','contacts_workspace',0)
}

function linkContactToCompanyLocation(locationid,contactid) {
	theurlstring = 'php_scripts/contact_link_to_company_location_sql.php?locationid=' + locationid + '&contactid=' + contactid;
	theuristring = encodeURI(theurlstring);
	populateDiv('return_msg',theuristring,true);
	setMainTask(ccontacts.wsp,ccontacts.btn,ccontacts.sbtn,ccontacts.ebtn,ccontacts.default_script);
	showEditContactDetails(contactid);
}

function unlinkContactLocation(locationid,contactid) {
	theurlstring = 'php_scripts/contact_location_unlink_sql.php?locationid=' + locationid + '&contactid=' + contactid;
	theuristring = encodeURI(theurlstring);
	populateDiv('return_msg',theuristring,true);
	setMainTask(ccontacts.wsp,ccontacts.btn,ccontacts.sbtn,ccontacts.ebtn,ccontacts.default_script);
	showEditContactDetails(contactid);
}

function createCompanyWizard(step) {
	if(step == 1) {
		var cv = document.wizard_frm_1.cverify.value;
		var amv = document.wizard_frm_1.abnmarkervalue.value;
		if (cv != amv) {
			alert('The text you entered did not match the image text.');
			return;
		}
		if (document.wizard_frm_1.login_available.value == '0') {
			alert("Please enter your valid email address.  This will allow you to log in later.");
			return;
		} else if (document.wizard_frm_1.login_available.value == '2') {
			alert("The email address you entered is already in use.\n\nIf you have forgotten your password, try using the [Forgot Password] link on the login form.");
			return;
		} else if (document.wizard_frm_1.login_available.value == '1') {
			var contact_email = document.wizard_frm_1.contact_email.value;
		} else {
			alert('Error checking password validity!');
			return;
		}
		country_code = document.wizard_frm_1.abn_country[document.wizard_frm_1.abn_country.options.selectedIndex].value;
		if (document.wizard_frm_1.abn_country.options.selectedIndex == 0) {
			abn = document.wizard_frm_1.abn.value;
			if (isABN(abn)) {
				the_abn = abn.replace(/\D/gi,"");
				file_name = 'check_company_matches.php?country_code=' + country_code + '&ButtonABNLookup=1&TextBoxABN=' + the_abn + '&contact_email=' + contact_email;
				fheight = 750;
			} else {
				return;
			}
		} else {
			if (typeof document.wizard_frm_1.company_name == 'undefined' || document.wizard_frm_1.company_name.value == '') {
				alert('Please your company name.');
				return;
			} else {
				company_name = document.wizard_frm_1.company_name.value;
				file_name = 'check_company_matches.php?country_code=' + country_code + '&ButtonABNLookup=0&TextBoxABN=&company_name=' + encodeURIComponent(company_name) + '&contact_email=' + encodeURIComponent(contact_email);
				//file_name = file_name;
				fheight = 750;
			}
		}
		document.getElementById('continue_btn').value = 'Please wait...';
		setTimeout('showWizardForm(file_name,fheight)',500);
	} else if (step == 2) {
		abn = encodeURIComponent(document.hidden_details.the_abn.value);
		company_name = encodeURIComponent(document.hidden_details.company_name.value);
		trading_as = encodeURIComponent(document.hidden_details.trading_as.value);
		state = encodeURIComponent(document.hidden_details.state.value);
		postcode = encodeURIComponent(document.hidden_details.postcode.value);
		country_code = encodeURIComponent(document.hidden_details.country_code.value);
		contact_email = encodeURIComponent(document.hidden_details.contact_email.value);
		file_name = 'company_create_wizard_2.php?country_code=' + country_code + '&abn=' + abn + '&company_name=' + company_name + '&trading_as=' + trading_as + '&state=' + state + '&postcode=' + postcode + '&contact_email=' + contact_email;
		//file_name = file_name;
		//showGenericDialog(file_name,0);
		showWizardForm(file_name,810);
	} else if (step == 3) {
		created = validateCreateCompany('company_location_add_frm','street','postal');
		if (created != false) {
			file_name = 'company_create_wizard_6.php';
			//showWizardForm(file_name,600);
			createAndSubmitDynamicForm(file_name, created);
			parent.scroll(0,0);
		}
	}
}

function setSelectListMandatory(select_list_id, span_id, is_mandatory) {
	if (is_mandatory) {
		document.getElementById(select_list_id).className = "formfield_list_mandatory";
		document.getElementById(span_id).style.color = "red";
	} else {	
		document.getElementById(select_list_id).className = "formfield_gray";
		document.getElementById(span_id).style.color = "black";
		for (i=0; i < document.getElementById(select_list_id).length; i++) {
			document.getElementById(select_list_id).options[i].selected = false;
		}
	}
}

function validateLoginID(contact_email,form_name,element_name,contactid,display_forgot_link) {
	if (document.forms[form_name].elements[element_name].value == '' || !emailAddressContentValidation(document.forms[form_name].elements[element_name].value)) {
		var contact_email = 'invalid';
	} else {
		var contact_email = document.forms[form_name].elements[element_name].value;
	}
	theurlstring = 'validate_login_email_sql.php?contact_email=' + contact_email + '&contactid=' + contactid + '&display_forgot_link=' + display_forgot_link;
	theuristring = encodeURI(theurlstring);
	populateDiv('show_email_test_result',theuristring,true);
}

function showCompanyContactOptions(companyid,popup_level) {
	showGenericDialogParent('company_contact_options.php?companyid='+companyid,popup_level);
}

function updateCompany(form_name,s_prefix,p_prefix) {
	abn = document.forms[form_name].new_abn.value;
	if (isABNNotMandatory(abn)) {
		the_abn = abn.replace(/\D/gi,"");
	} else {
		return;
	}
	params = validateCreateCompany(form_name,s_prefix,p_prefix);
	if (params != false) {
		file_name = 'company_update.php';
		//location.href=file_name;
		createAndSubmitDynamicForm(file_name, params);
		parent.scroll(0,0);
	}
}

function validateCreateCompany(form_name,s_prefix,p_prefix) {
	//validate user
	var form_params = '';
	if (document.forms[form_name].company_name.value == '') {
		alert("Please enter a company name.");
		return false;
	}
	if (document.forms[form_name].contact_password) {
		if (document.forms[form_name].contact_surname.value == '' && document.forms[form_name].contact_first_name.value == '') {
			alert("Please enter your name.");
			return false;
		}
		if (document.forms[form_name].contact_password.value.length < 6 || document.forms[form_name].check_password.value.length < 6) {
			alert("Please enter a password of at least 6 characters\nin both password fields.");
			return false;
		}
		if (document.forms[form_name].contact_password.value != document.forms[form_name].check_password.value) {
			alert("The passwords you entered do not match.");
			return false;
		}
		form_params += '&contact_password=' + SHA256(document.forms[form_name].contact_password.value);
		form_params += '&contact_surname=' + escape(document.forms[form_name].contact_surname.value);
		form_params += '&contact_first_name=' + escape(document.forms[form_name].contact_first_name.value);
		form_params += '&contact_email=' + escape(document.forms[form_name].contact_email.value);
		form_params += '&contact_position=' + escape(document.forms[form_name].contact_position.value);
		form_params += '&contact_title=' + escape(document.forms[form_name].contact_title.value);
		var cph_i = document.forms[form_name].elements['contact_phone_intl'].value.replace(/\D/gi,"");
		var cph_a =  document.forms[form_name].elements['contact_phone_area'].value.replace(/\D/gi,"");
		var cph_n =  document.forms[form_name].elements['contact_phone_number'].value.replace(/\D/gi,"");
		var cph_is_valid = validatePhoneFax(cph_i,cph_a,cph_n,'','','');
		if (cph_is_valid != '') {
			alert(cph_is_valid);
			return false;
		}
		if(cph_n == ''){cph_n = '';cph_i = '';cph_a = '';}
		form_params += '&cph_ccode=' + cph_i;
		form_params += '&cph_acode=' + cph_a;
		form_params += '&cph_number=' + cph_n;
	}
	//validate address
	if (document.forms[form_name].elements[s_prefix + '_country'][document.forms[form_name].elements[s_prefix + '_country'].options.selectedIndex].value == 'AU' && (document.forms[form_name].elements[s_prefix + '_suburb'].value == '' || document.forms[form_name].elements[s_prefix + '_postcode'].value == '' || (document.forms[form_name].elements[s_prefix + '_address_1'].value == '' && document.forms[form_name].elements[s_prefix + '_address_2'].value == ''))) {
		alert("Please enter a street address, including postcode for Australian addresses.");
		return false;
	} else if (document.forms[form_name].elements[s_prefix + '_country'][document.forms[form_name].elements[s_prefix + '_country'].options.selectedIndex].value != 'AU' && (document.forms[form_name].elements[s_prefix + '_suburb'].value == '' || (document.forms[form_name].elements[s_prefix + '_address_1'].value == '' && document.forms[form_name].elements[s_prefix + '_address_2'].value == ''))) {
		alert("Please complete the required fields for the street address.");
		return false;
	}
	if (document.forms[form_name].summary.value == '') {
		alert("Please enter a one-sentence summary of your company's scope of activities.");
		return false;
	}
	if (document.forms[form_name].products_services.value == '') {
		alert("Please enter a list of the products and/or services your company provides.");
		return false;
	}
	var ph_i = document.forms[form_name].elements['phone_intl'].value.replace(/\D/gi,"");
	var ph_a =  document.forms[form_name].elements['phone_area'].value.replace(/\D/gi,"");
	var ph_n =  document.forms[form_name].elements['phone_number'].value.replace(/\D/gi,"");
	var fax_i =  document.forms[form_name].elements['fax_intl'].value.replace(/\D/gi,"");
	var fax_a =  document.forms[form_name].elements['fax_area'].value.replace(/\D/gi,"");
	var fax_n =  document.forms[form_name].elements['fax_number'].value.replace(/\D/gi,"");
	var ph_is_valid = validatePhoneFax(ph_i,ph_a,ph_n,fax_i,fax_a,fax_n);
	if (ph_is_valid != '') {
		alert(ph_is_valid);
		return false;
	}
	if(ph_n == ''){ph_n = '';ph_i = '';ph_a = '';}
	if(fax_n == ''){fax_n = '';fax_i = '';fax_a = '';}
	var pc = document.forms[form_name].elements[p_prefix + '_country'][document.forms[form_name].elements[p_prefix + '_country'].options.selectedIndex].value;
	var ps = document.forms[form_name].elements[p_prefix + '_state'][document.forms[form_name].elements[p_prefix + '_state'].options.selectedIndex].value;
	if (document.forms[form_name].elements[p_prefix + '_address_1'].value == '' && document.forms[form_name].elements[p_prefix + '_address_2'].value == '') {
		pc = '';
		ps = '';
	}
	
	form_params += '&company_name=' + escape(document.forms[form_name].company_name.value);
	form_params += '&trading_as=' + escape(document.forms[form_name].trading_as.value);
	form_params += '&locationid=' + document.forms[form_name].locationid.value;
	form_params += '&address_street_1=' + escape(document.forms[form_name].elements[s_prefix + '_address_1'].value);
	form_params += '&address_street_2=' + escape(document.forms[form_name].elements[s_prefix + '_address_2'].value);
	form_params += '&address_street_city=' + escape(document.forms[form_name].elements[s_prefix + '_suburb'].value);
	form_params += '&address_street_postcode=' + document.forms[form_name].elements[s_prefix + '_postcode'].value;
	form_params += '&address_street_country=' + document.forms[form_name].elements[s_prefix + '_country'][document.forms[form_name].elements[s_prefix + '_country'].options.selectedIndex].value;
	form_params += '&address_street_state=' + document.forms[form_name].elements[s_prefix + '_state'][document.forms[form_name].elements[s_prefix + '_state'].options.selectedIndex].value;
	form_params += '&address_postal_1=' + escape(document.forms[form_name].elements[p_prefix + '_address_1'].value);
	form_params += '&address_postal_2=' + escape(document.forms[form_name].elements[p_prefix + '_address_2'].value);
	form_params += '&address_postal_city=' + escape(document.forms[form_name].elements[p_prefix + '_suburb'].value);
	form_params += '&address_postal_postcode=' + document.forms[form_name].elements[p_prefix + '_postcode'].value;
	form_params += '&address_postal_country=' + pc;
	form_params += '&address_postal_state=' + ps;
	form_params += '&ph_ccode=' + ph_i;
	form_params += '&ph_acode=' + ph_a;
	form_params += '&ph_number=' + ph_n;
	form_params += '&fax_ccode=' + fax_i;
	form_params += '&fax_acode=' + fax_a;
	form_params += '&fax_number=' + fax_n;
	form_params += '&company_email=' + escape(document.forms[form_name].company_email.value);
	form_params += '&url=' + escape(document.forms[form_name].url.value);
	form_params += '&new_abn=' + document.forms[form_name].new_abn.value;
	//showGenericDialogPost('company_create_wizard_3.php',form_params,0);

	form_params += '&summary=' + encodeURIComponent(document.forms[form_name].summary.value);
	form_params += '&description=' + encodeURIComponent(document.forms[form_name].description.value);
	form_params += '&products_services=' + encodeURIComponent(document.forms[form_name].products_services.value);
	form_params += '&facilities=' + encodeURIComponent(document.forms[form_name].facilities.value);
	
	if (
		!document.forms[form_name].ACT.checked && 
		!document.forms[form_name].NSW.checked && 
		!document.forms[form_name].NT.checked && 
		!document.forms[form_name].QLD.checked && 
		!document.forms[form_name].SA.checked && 
		!document.forms[form_name].TAS.checked && 
		!document.forms[form_name].VIC.checked && 
		!document.forms[form_name].WA.checked && 
		!document.forms[form_name].NorthIS.checked && 
		!document.forms[form_name].SouthIS.checked && 
		!document.forms[form_name].Asia.checked && 
		!document.forms[form_name].SouthAmerica.checked && 
		!document.forms[form_name].Europe.checked && 
		!document.forms[form_name].NorthAmerica.checked && 
		!document.forms[form_name].MiddleEast.checked && 
		!document.forms[form_name].Africa.checked
		) {
		alert('Please select the region(s) to which you provide services.');
		return false;
	}
	var state_services = '';
	var country_services = '';
	var s_comma = '';
	var c_comma = '';
	if(document.forms[form_name].ACT.checked){state_services += s_comma + 'ACT'; s_comma = ', ';}
	if(document.forms[form_name].NSW.checked){state_services += s_comma + 'NSW'; s_comma = ', ';}
	if(document.forms[form_name].NT.checked){state_services += s_comma + 'NT'; s_comma = ', ';}
	if(document.forms[form_name].QLD.checked){state_services += s_comma + 'QLD'; s_comma = ', ';}
	if(document.forms[form_name].SA.checked){state_services += s_comma + 'SA'; s_comma = ', ';}
	if(document.forms[form_name].TAS.checked){state_services += s_comma + 'TAS'; s_comma = ', ';}
	if(document.forms[form_name].VIC.checked){state_services += s_comma + 'VIC'; s_comma = ', ';}
	if(document.forms[form_name].WA.checked){state_services += s_comma + 'WA'; s_comma = ', ';}
	if(document.forms[form_name].NorthIS.checked){state_services += s_comma + 'NorthIS'; s_comma = ', ';}
	if(document.forms[form_name].SouthIS.checked){state_services += s_comma + 'SouthIS';}
	if(document.forms[form_name].Asia.checked){country_services += c_comma + 'Asia'; c_comma = ', ';}
	if(document.forms[form_name].SouthAmerica.checked){country_services += c_comma + 'South America'; c_comma = ', ';}
	if(document.forms[form_name].Europe.checked){country_services += c_comma + 'Europe'; c_comma = ', ';}
	if(document.forms[form_name].NorthAmerica.checked){country_services += c_comma + 'North America'; c_comma = ', ';}
	if(document.forms[form_name].MiddleEast.checked){country_services += c_comma + 'Middle East'; c_comma = ', ';}
	if(document.forms[form_name].Africa.checked){country_services += c_comma + 'Africa';}

	if(document.forms[form_name].importer.checked){importer = 1;}else{importer = 0;}
	if(document.forms[form_name].exporter.checked){exporter = 1;}else{exporter = 0;}
	if(document.forms[form_name].local_manufacturer.checked){local_manufacturer = 1;}else{local_manufacturer = 0;}
	if(document.forms[form_name].foreign_manufacturer.checked){foreign_manufacturer = 1;}else{foreign_manufacturer = 0;}
	if(document.forms[form_name].service_provider.checked){service_provider = 1;}else{service_provider = 0;}
	if(document.forms[form_name].retailer.checked){retailer = 1;}else{retailer = 0;}
	if(document.forms[form_name].wholesaler.checked){wholesaler = 1;}else{wholesaler = 0;}
	if(document.forms[form_name].govt_work.checked){govt_work = 1;}else{govt_work = 0;}
	if(document.forms[form_name].federal_ohs_accredited.checked){federal_ohs_accredited = 1;}else{federal_ohs_accredited = 0;}
	if(document.forms[form_name].nt_cal_accredited.checked){nt_cal_accredited = 1;}else{nt_cal_accredited = 0;}
	if(document.forms[form_name].indigenous_owned.checked){indigenous_owned = 1;}else{indigenous_owned = 0;}
	if(document.forms[form_name].works_in_remote_locations.checked){works_in_remote_locations = 1;}else{works_in_remote_locations = 0;}

	if(document.forms[form_name].receive_notification.checked){receive_notification = 1;}else{receive_notification = 0;}
	
	if (document.forms[form_name].company_directories) {
		var code =  document.forms[form_name].company_directories;
		var company_directories = '';
		comma_prefix = '';
		for (i=0; i < code.length; i++) {
			if (code.options[i].selected) {
				company_directories += comma_prefix + code.options[i].value;
				comma_prefix = ' ';
			}
		}
		form_params += '&company_directories=' + company_directories;
	} else {
		form_params += '&company_directories=';
	}

	if (document.forms[form_name].imports_from) {
		var code =  document.forms[form_name].imports_from;
		var imports_from = '';
		comma_prefix = '';
		for (i=0; i < code.length; i++) {
			if (code.options[i].selected) {
				imports_from += comma_prefix + code.options[i].value;
				comma_prefix = ' ';
			}
		}
		form_params += '&imports_from=' + imports_from;
	} else {
		form_params += '&imports_from=';
	}

	if (document.forms[form_name].exports_to) {
		var code =  document.forms[form_name].exports_to;
		var exports_to = '';
		comma_prefix = '';
		for (i=0; i < code.length; i++) {
			if (code.options[i].selected) {
				exports_to += comma_prefix + code.options[i].value;
				comma_prefix = ' ';
			}
		}
		form_params += '&exports_to=' + exports_to;
	} else {
		form_params += '&exports_to=';
	}
	
	form_params += '&receive_notification=' + receive_notification;
	form_params += '&state_services=' + state_services;
	form_params += '&country_services=' + country_services;
	form_params += '&importer=' + importer;
	form_params += '&exporter=' + exporter;
	form_params += '&local_manufacturer=' + local_manufacturer;
	form_params += '&foreign_manufacturer=' + foreign_manufacturer;
	form_params += '&service_provider=' + service_provider;
	form_params += '&retailer=' + retailer;
	form_params += '&wholesaler=' + wholesaler;
	form_params += '&govt_work=' + govt_work;
	form_params += '&federal_ohs_accredited=' + federal_ohs_accredited;
	form_params += '&nt_cal_accredited=' + nt_cal_accredited;
	form_params += '&indigenous_owned=' + indigenous_owned;
	form_params += '&works_in_remote_locations=' + works_in_remote_locations;
	
	if (importer && imports_from == '') {
		alert("You must specify the countries that this company imports from.");
		return false;
	} else if (exporter && exports_to == '') {
		alert("You must specify the countries that this company exports to.");
		return false;
	} else {
		var msg = "";
		
		if (!importer && imports_from != '') {
			msg += "You have 'Imports From' countries selected but this company is not an importer.\n"
			msg += "If you continue you will delete all 'Imports From' countries.\n\n"
		}
		if (!exporter && exports_to != '') {
			msg += "You have 'Exports To' countries selected but this company is not an exporter.\n"
			msg += "If you continue you will delete all 'Exports To' countries.\n\n"
		}
		if (msg != "") {
			if (!confirm(msg + 'Do you want to continue saving?\n(If you click OK you will lose any selected countries.)')) {
				return false;
			}
		}
	}
	
	if (document.forms[form_name].nato_code) {
		var code =  document.forms[form_name].nato_code;
		var nato_code = '';
		comma_prefix = '';
		for (i=0; i < code.length; i++) {
			if (code.options[i].selected) {
				nato_code += comma_prefix + code.options[i].value;
				comma_prefix = ' ';
			}
		}
		form_params += '&nato_code=' + nato_code;
	} else {
		form_params += '&nato_code=';
	}
	if (document.forms[form_name].anzsic_code) {
		var code =  document.forms[form_name].anzsic_code;
		var anzsic_code = '';
		comma_prefix = '';
		for (i=0; i < code.length; i++) {
			if (code.options[i].selected) {
				anzsic_code += comma_prefix + code.options[i].value;
				comma_prefix = ' ';
			}
		}
		form_params += '&anzsic_code=' + anzsic_code;
	} else {
		form_params += '&anzsic_code=';
	}
	form_params += '&employees=' + document.forms[form_name].employees.value.replace(/\D/gi,"");
	form_params += '&indigenous_employees=' + document.forms[form_name].indigenous_employees.value.replace(/\D/gi,"");
	form_params += '&turnover=' + document.forms[form_name].turnover.value.replace(/\D/gi,"");
	form_params += '&duns=' + encodeURIComponent(document.forms[form_name].duns.value);
	form_params += '&unspsc=' + encodeURIComponent(document.forms[form_name].unspsc.value);
	form_params += '&incorporated_year=' + encodeURIComponent(document.forms[form_name].incorporated_year.value);
	form_params += '&associations=' + encodeURIComponent(document.forms[form_name].associations.value);
	form_params += '&qa_accreditation=' + encodeURIComponent(document.forms[form_name].qa_accreditation.value);
	form_params += '&major_clients=' + encodeURIComponent(document.forms[form_name].major_clients.value);
	form_params += '&major_projects=' + encodeURIComponent(document.forms[form_name].major_projects.value);
	form_params += '&business_types=' + encodeURIComponent(document.forms[form_name].business_types.value);

	return form_params;
}

function escapeQStringChars(s) {
	if (s != '') {
		s = s.replace(/[&]/g,"%26");
		s = s.replace(/[=]/g,"%3D");
	}
	return s;
}

function removeUnwantedChars(s) {
	if (s != '') {
		s = s.replace(/[&]/g,"and");
		s = s.replace(/[=]/g,"");
	}
	return s;
}

function setABNCountry(the_index) {
	if(the_index == 0) {
		//is Australia
		document.getElementById('abn_label').style.display = 'block';
		document.getElementById('abn_field').style.display = 'block';
		document.getElementById('company_name_label').style.display = 'none';
		document.getElementById('company_name_field').style.display = 'none';
	} else if(the_index == 2) {
		//is the divider
		document.getElementById('abn_country')[0].selected = true;
		document.getElementById('abn_label').style.display = 'block';
		document.getElementById('abn_field').style.display = 'block';
		document.getElementById('company_name_label').style.display = 'none';
		document.getElementById('company_name_field').style.display = 'none';
	} else {
		//another country
		document.getElementById('abn_label').style.display = 'none';
		document.getElementById('abn_field').style.display = 'none';
		document.getElementById('company_name_label').style.display = 'block';
		document.getElementById('company_name_field').style.display = 'block';
	}
}

function continueAnyway(companyid) {
	if (companyid == -1) {
		/*some matches, but elected to continue*/
		document.getElementById('good_msg').style.display = 'block';
		document.getElementById('match_msg').style.display = 'none';
		document.getElementById('scope_table').style.display = 'block';
		document.getElementById('warning_buttons').style.display = 'none';
	} else if (companyid == 0) {
		/*no matches*/
		alert('save function not built yet');
	} else {
		/*parent link requested*/
		document.getElementById('good_msg').style.display = 'block';
		document.getElementById('match_msg').style.display = 'none';
		document.getElementById('scope_table').style.display = 'block';
		document.getElementById('warning_buttons').style.display = 'none';
		document.company_scope_add_frm.link.value = companyid;
	}
}

function setANZSICTicks(level,lookup_code,top_level_code,mid_level_code) {
	var tick_id = 'anzsic_' + lookup_code;
	var img_src = document.getElementById(tick_id).src;
	var images = document.getElementsByTagName('img');
	if (level == 1) {
		if(img_src.indexOf('remove_grey.png') >= 0) {
			document.getElementById(tick_id).src = 'accept.png';
			/*set all sub elements to accept*/
			for (var i=0; i<images.length; i++) {
				var prefix_id = images[i].id.substr(0,9);
				if (images[i].id.length > 9 && prefix_id == 'anzsic_'+lookup_code) {
					images[i].src = 'accept.png';
				}
			}
		} else if(img_src.indexOf('accept.png') >= 0 || img_src.indexOf('accept_light.png') >= 0) {
			document.getElementById(tick_id).src = 'remove_grey.png';
			/*set all sub elements to remove_grey*/
			for (var i=0; i<images.length; i++) {
				var prefix_id = images[i].id.substr(0,9);
				if (images[i].id.length > 9 && prefix_id == 'anzsic_'+lookup_code) {
					images[i].src = 'remove_grey.png';
				}
			}
		}
	} else if (level == 2) {
		if(img_src.indexOf('remove_grey.png') >= 0) {
			document.getElementById(tick_id).src = 'accept.png';
			/*set all sub elements to accept*/
			for (var i=0; i<images.length; i++) {
				var prefix_id = images[i].id.substr(0,10);
				if (images[i].id.length > 10 && prefix_id == 'anzsic_'+lookup_code) {
					images[i].src = 'accept.png';
				}
			}
			/*set top level element to accept_light*/
			document.getElementById('anzsic_'+top_level_code).src = 'accept_light.png';
		} else if(img_src.indexOf('accept.png') >= 0 || img_src.indexOf('accept_light.png') >= 0) {
			document.getElementById(tick_id).src = 'remove_grey.png';
			/*set all sub elements to remove_grey*/
			for (var i=0; i<images.length; i++) {
				var prefix_id = images[i].id.substr(0,10);
				if (images[i].id.length > 10 && prefix_id == 'anzsic_'+lookup_code) {
					images[i].src = 'remove_grey.png';
				}
			}
			/*set top level element to accept_light*/
			document.getElementById('anzsic_'+top_level_code).src = 'accept_light.png';
		}
	} else if (level == 3) {
		if(img_src.indexOf('remove_grey.png') >= 0) {
			document.getElementById(tick_id).src = 'accept.png';
			/*set mid and top level elements to accept_grey*/
			document.getElementById('anzsic_'+mid_level_code).src = 'accept_light.png';
			document.getElementById('anzsic_'+top_level_code).src = 'accept_light.png';
		} else if(img_src.indexOf('accept.png') >= 0) {
			document.getElementById(tick_id).src = 'remove_grey.png';
			/*set mid and top level elements to accept_grey*/
			document.getElementById('anzsic_'+mid_level_code).src = 'accept_light.png';
			document.getElementById('anzsic_'+top_level_code).src = 'accept_light.png';
		}
	}
}

function expandContractANZSICLevels(lookup_code,top_level_code) {
	var img_src = document.getElementById('ec_'+lookup_code).src;
	if (img_src.indexOf('plus.png') >= 0) {
		document.getElementById('top_level_'+top_level_code).style.display = 'block';
		document.getElementById('ec_'+lookup_code).src = 'minus.png';
	} else if (img_src.indexOf('minus.png') >= 0) {
		document.getElementById('top_level_'+top_level_code).style.display = 'none';
		document.getElementById('ec_'+lookup_code).src = 'plus.png';
	}
}

function expandContractAllANZSICLevels() {
	var img_src = document.getElementById('ec').src;
	var images = document.getElementsByTagName('img');
	for (var i=0; i<images.length; i++) {
		var prefix_id = images[i].id.substr(0,3);
		var lookup_code = images[i].id.substr(3,images[i].id.length-1);
		if (images[i].id.length > 3 && prefix_id == 'ec_') {
			if (img_src.indexOf('plus.png') >= 0) {
				document.getElementById('top_level_'+lookup_code).style.display = 'block';
				images[i].src = 'minus.png';
			} else {
				document.getElementById('top_level_'+lookup_code).style.display = 'none';
				images[i].src = 'plus.png';
			}
		}
	}
	if (img_src.indexOf('plus.png') >= 0) {
		document.getElementById('ec').src = 'minus.png';
	} else {
		document.getElementById('ec').src = 'plus.png';
	}
}

function setRegionTicks(is_checked,main,level) {
	if (is_checked && level == 1) {
		/*is a top level tick*/
		if (main == 'A') {
			/*set all Australia sub levels to checked */
			document.company_location_add_frm.ACT.checked = true;
			document.company_location_add_frm.NSW.checked = true;
			document.company_location_add_frm.NT.checked = true;
			document.company_location_add_frm.QLD.checked = true;
			document.company_location_add_frm.SA.checked = true;
			document.company_location_add_frm.TAS.checked = true;
			document.company_location_add_frm.VIC.checked = true;
			document.company_location_add_frm.WA.checked = true;
		} else if (main == 'N') {
			/*set all NZ sub levels to checked */
			document.company_location_add_frm.NorthIS.checked = true;
			document.company_location_add_frm.SouthIS.checked = true;
		} else if (main == 'G') {
			/*set all Global sub levels to checked */
			document.company_location_add_frm.Asia.checked = true;
			document.company_location_add_frm.SouthAmerica.checked = true;
			document.company_location_add_frm.Europe.checked = true;
			document.company_location_add_frm.NorthAmerica.checked = true;
			document.company_location_add_frm.MiddleEast.checked = true;
			document.company_location_add_frm.Africa.checked = true;
		}
	} else if (!is_checked && level == 1) {
		/*is a top level untick*/
		if (main == 'A') {
			/*set all Australia sub levels to unchecked*/
			document.company_location_add_frm.ACT.checked = false;
			document.company_location_add_frm.NSW.checked = false;
			document.company_location_add_frm.NT.checked = false;
			document.company_location_add_frm.QLD.checked = false;
			document.company_location_add_frm.SA.checked = false;
			document.company_location_add_frm.TAS.checked = false;
			document.company_location_add_frm.VIC.checked = false;
			document.company_location_add_frm.WA.checked = false;
		} else if (main == 'N') {
			/*set all NZ sub levels to unchecked*/
			document.company_location_add_frm.NorthIS.checked = false;
			document.company_location_add_frm.SouthIS.checked = false;
		} else if (main == 'G') {
			/*set all Global sub levels to unchecked*/
			document.company_location_add_frm.Asia.checked = false;
			document.company_location_add_frm.SouthAmerica.checked = false;
			document.company_location_add_frm.Europe.checked = false;
			document.company_location_add_frm.NorthAmerica.checked = false;
			document.company_location_add_frm.MiddleEast.checked = false;
			document.company_location_add_frm.Africa.checked = false;
		}
	} else if (!is_checked && level == 0) {
		/*is a lower level untick*/
		if (main == 'A') {
			/*set Australia to unchecked*/
			document.company_location_add_frm.A.checked = false;
		} else if (main == 'N') {
			/*set NZ to unchecked*/
			document.company_location_add_frm.N.checked = false;
		} else if (main == 'G') {
			/*set Global to unchecked*/
			document.company_location_add_frm.G.checked = false;
		}
	}
}

function expandContractWP() {
	var img_src = document.getElementById('ec_wp').src;
	if (img_src.indexOf('plus_light.png') >= 0) {
		document.getElementById('project_workpackages').style.display = 'block';
		document.getElementById('ec_wp').src = '../images/minus_light.png';
	} else if (img_src.indexOf('minus_light.png') >= 0) {
		document.getElementById('project_workpackages').style.display = 'none';
		document.getElementById('ec_wp').src = '../images/plus_light.png';
	}
}

function expandContractWPFull() {
	var img_src = document.getElementById('ec_wp').src;
	if (img_src.indexOf('plus.png') >= 0) {
		document.getElementById('project_workpackages').style.display = 'block';
		document.getElementById('ec_wp').src = '../images/minus.png';
	} else if (img_src.indexOf('minus.png') >= 0) {
		document.getElementById('project_workpackages').style.display = 'none';
		document.getElementById('ec_wp').src = '../images/plus.png';
	}
}

function expandContractEditDivs(the_section) {
	var img_src = document.getElementById('img_'+the_section).src;
	/*contract all divs and set all images to plus*/
	document.getElementById('edit_contact').style.display = 'none';
	document.getElementById('img_edit_contact').src = 'plus.png';
	document.getElementById('add_contact').style.display = 'none';
	document.getElementById('img_add_contact').src = 'plus.png';
	document.getElementById('edit_scope').style.display = 'none';
	document.getElementById('img_edit_scope').src = 'plus.png';
	document.getElementById('edit_anzsic').style.display = 'none';
	document.getElementById('img_edit_anzsic').src = 'plus.png';
	document.getElementById('edit_stats').style.display = 'none';
	document.getElementById('img_edit_stats').src = 'plus.png';
	document.getElementById('edit_password').style.display = 'none';
	document.getElementById('img_edit_password').src = 'plus.png';
	document.getElementById('remove_company').style.display = 'none';
	document.getElementById('img_remove_company').src = 'plus.png';
	document.getElementById('edit_eoi').style.display = 'none';
	document.getElementById('img_edit_eoi').src = 'plus.png';
	if (img_src.indexOf('plus.png') >= 0) {
		/*is contracted, needs to expand*/
		document.getElementById(the_section).style.display = 'block';
		document.getElementById('img_'+the_section).src = 'minus.png';
	} else if (img_src.indexOf('minus.png') >= 0) {
		/*is expanded, needs to contract*/
		document.getElementById(the_section).style.display = 'none';
		document.getElementById('img_'+the_section).src = 'plus.png';
	}
}

function contactLogin(the_script,the_div,projectid) {
	//alert('login');
	var lid = encodeURIComponent(document.getElementById('contact_email').value);
	var tp = SHA256(document.getElementById('contact_pwd').value);
	theurlstring = 'login_sql.php?lid=' + lid + '&tp=' + tp + '&the_script=' + the_script + '&the_div=' + the_div + '&projectid=' + projectid;
	//populateDiv('return_msg',theurlstring,true);
	saveActions('cancel', the_div);
	showGenericDialog(theurlstring,0)
}

function displayListPopup(list_type) {
	//tba
}

function registerEOIButton(projectid,companyid,contactid) {
	if (companyid != '' &&  companyid > 0) {
		scroll(0,0);
		showGenericDialog('register_eoi.php?projectid=' + projectid + '&companyid=' + companyid + '&contactid=' + contactid,0);
	} else {
		showGenericDialog('login_form.php?projectid=' + projectid + '&script=register_eoi&div=1',1);
	}
}

function showLogout() {
	populateDiv('logout','logout_link.php',true);
	showEdit();
}

function showEdit() {
	populateDiv('edit_company','edit_link.php',true);
}

function continueNonEOI(contactid,div_to_close) {
	companyid = document.wizard_frm_1.company[document.wizard_frm_1.company.options.selectedIndex].value;
	location.href='company_edit_form_full.php?contactid=' + contactid + '&companyid=' + companyid;
	saveActions('cancel',div_to_close);
}

function setLoginForm(div) {
	if (typeof div != 'undefined' && div != '') {
		showGenericDialog('login_form.php?script=company_edit_form_full&div='+div,div);
	} else {
		showGenericDialog('login_form.php?script=edit_company&div='+div,1);
	}
}

function getProjects(source,view_type) {
	if (source == 'default') {
		location.href='project_listing.php?view_type='+view_type;
	} else {
		getProjectListing('display_project_listing.php?view_type='+view_type,view_type);
	}
}

function getProjectListing(the_script,view_type) {
	theuristring = encodeURI(the_script);
	populateDiv('project_main',theuristring,true);
//	if (view_type && isNaN(view_type)) {
//		populateDiv('select_area','display_area.php?view_type='+view_type,true);
//		populateDiv('select_directory','display_directories.php?view_type=all',true);
//	} else if (view_type) {
//		populateDiv('select_area','display_area.php?view_type=all',true);
//		populateDiv('select_directory','display_directories.php?view_type='+view_type,true);
//	}
}

function displayOfficeDetails(officeid) {
	if (typeof officeid != 'undefined' && officeid != ''){
		document.getElementById('icn_office_details').style.display = 'block';
		theurlstring = 'display_icn_office.php?officeid=' + officeid;
		theuristring = encodeURI(theurlstring);
		populateDiv('icn_office_details',theuristring,true);
	} else {
		setElementInnerHTML(document.getElementById('icn_office_details'), '');
		document.getElementById('icn_office_details').style.display = 'none';
	}
}

function registerEOI(projectid) {
	//get form values
	var qlist = document.register_eoi_frm.questionid_list.value;
	if (qlist != '') {
		qlist_array = qlist.split(",");
		for (var i = 0; i < qlist_array.length; i++) {
			qlist_array[i] = [qlist_array[i],"~"];
		}
	}
	var wplist = document.register_eoi_frm.wpid_list.value;
	if (wplist != '') {
		wplist_array = wplist.split(",");
		for (var i = 0; i < wplist_array.length; i++) {
			wplist_array[i] = [wplist_array[i],"0","0"," "];
		}
	}
	for (var i = 0; i < document.register_eoi_frm.elements.length; i++) {
	    var the_element = document.register_eoi_frm.elements[i];
	    var type = the_element.type;
		var is_question = (the_element.name.indexOf("Q",0) == 0);
		var is_workpackage = (the_element.name.indexOf("W",0) == 0);
		var dash_1 =  the_element.name.indexOf("-",0);
		var dash_2 = the_element.name.indexOf("-",dash_1+1);
		if (dash_2 == -1) {
			dash_2 = the_element.name.length;
		}
	    if (type == "checkbox" || type == "radio") {
	       if (the_element.checked) {
	    	   if (is_question) {
	    		   the_qid = the_element.name.substring(1,dash_1);
	    		   qtype = the_element.name.substring(dash_1+1,dash_2);
	    			for (var j = 0; j < qlist_array.length; j++) {
	    				if (qlist_array[j][0] == the_qid) {
	    					qlist_array[j][1] += the_element.value + "~";
	    				}
	    			}
	    	   } else if (is_workpackage) {
	    		   /*work package processing*/
	    		   the_wpid = the_element.name.substring(1,dash_1);
	    		   wptype = the_element.name.substring(dash_1+1,the_element.name.length);
	    			for (var j = 0; j < wplist_array.length; j++) {
	    				if (wplist_array[j][0] == the_wpid) {
	    					switch (wptype) {
	    						case "t1":
	    							wplist_array[j][1] = "1";
	    							break;
	    						case "t2":
	    							wplist_array[j][2] = "1";
	    							break;
	    					}
	    				}
	    			}
	    	   }
	       }
	    } else if (type == "textarea") {
	        if (the_element.value != the_element.defaultValue) {
	        	/*textarea processing*/
	    	    if (is_question) {
	    		    the_qid = the_element.name.substring(1,dash_1);
	    		    qtype = the_element.name.substring(dash_1+1,dash_2);
	    			for (var j = 0; j < qlist_array.length; j++) {
	    				if (qlist_array[j][0] == the_qid) {
	    					qlist_array[j][1] += the_element.value + "~";
	    				}
	    			}
	    	    } else if (is_workpackage) {
	    		    /*work package processing*/ 
		    		the_wpid = the_element.name.substring(1,dash_1);
		    		wptype = the_element.name.substring(dash_1+1,the_element.name.length);
		    		for (var j = 0; j < wplist_array.length; j++) {
		    			if (wplist_array[j][0] == the_wpid) {
		    				if (wptype == 'comments' && the_element.value != 'comments' && the_element.value != '') {
		    						wplist_array[j][3] = the_element.value;
		    				}
		    			}
		    		}
	    	    }
	        }
	    }
	}
	var form_params = "projectid=" + projectid;
	if (typeof qlist_array != 'undefined') {
		for (var i = 0; i < qlist_array.length; i++) {
			if (qlist_array[i][1] != '~') {
				answer = qlist_array[i][0] + "::" + encodeURIComponent(qlist_array[i][1].slice(1,qlist_array[i][1].length-1));
				form_params += "&Q" + qlist_array[i][0] + '=' + answer;
			}
		}
	}
	var unticked_wp = 0;
	for (var i = 0; i < wplist_array.length; i++) {
		if (wplist_array[i][1] == "1" || wplist_array[i][2] == "1") {
			answer = wplist_array[i][0] + "::" + wplist_array[i][1] + "~" + wplist_array[i][2] + "~" + encodeURIComponent(wplist_array[i][3]);
			form_params += "&W" + wplist_array[i][0] + '=' + answer;
		} else {
			unticked_wp++;
		}
	}
	if (unticked_wp == wplist_array.length) {
		alert('Please tick a Tier 1 and/or Tier 2 checkbox for at least one work package.');
		return;
	}
	/*run sql script*/
	showGenericDialogPost('registration_insert_sql.php', form_params);
	scroll(0,0);
}

function getSuppliers(view_type,criteria) {
	if (view_type == 'region') {
		location.href='supplier_listing.php?view_type=' + view_type + '&criteria=' + criteria;
	} else if (view_type == 'keyword') {
		criteria = document.getElementById('supplier_keywords').value;
		//alert(criteria);
		if (criteria != '' && criteria != 'Search keywords') {
			/* test and strip string */
			criteria = stripSearchString(criteria);
			count = 0;
			posn_point = criteria.indexOf('~',0);
			while (posn_point != -1) {
				count++
				posn_point = criteria.indexOf('~',posn_point+1);
			}
			if (count%2 > 0) {
				alert('There must not be an odd number of double quotes in the search keywords.');
				return;
			}
		} else {
			alert('Please enter some search keywords.');
			return;
		}
		qstring = '?view_type=' + view_type + '&criteria=' + criteria;
		theuristring = encodeURI(qstring);
		//alert(theuristring);
		location.href='supplier_listing.php'+theuristring;
	}
}

function validateGetSuppliers() {
	var region = document.supplier_search_frm.region.options.selectedIndex;
	var criteria = document.supplier_search_frm.keywords.value;
	criteria = stripSearchString(criteria);
	//if (region == 0 || (criteria.length < 3 || criteria == '...keywords (eg, ball bearings)' || criteria == '...keywords')) {
	if (criteria.length < 3 || criteria == '...keywords (eg, ball bearings)' || criteria == '...keywords') {
		alert('Please enter a search keyword (at least 3 characters).\nOnly letters, numbers and spaces are allowed.');
		return false;
	} else {
		/* test and strip string */
		count = 0;
		posn_point = criteria.indexOf('~',0);
		while (posn_point != -1) {
			count++
			posn_point = criteria.indexOf('~',posn_point+1);
		}
		if (count%2 > 0) {
			alert('There must not be an odd number of double quotes in the search keywords.');
			return false;
		}
		document.supplier_search_frm.keywords.value = criteria;
		return true;
	}
}

function getSupplierListing(the_script) {
		theuristring = encodeURI(the_script);
		populateDiv('supplier_main',theuristring,true);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function stripSearchString(the_string) {
	var stripped_string = the_string;
	
	// remove all backslashes
	stripped_string = stripped_string.replace(/\\/g,"");
	
	// remove all forward slashes
	stripped_string = stripped_string.replace(/\//g,"");
	
	// remove all asterisks
	stripped_string = stripped_string.replace(/\*/g,"");

	// remove all characters except a-z A-Z 0-9 _ " ' - space
	stripped_string = stripped_string.replace(/[^a-zA-Z0-9_"'\-\s&]/gi,"");

	// replace " with #
	stripped_string = stripped_string.replace(/"/g,"#");

	// retrieve all quoted values
	quoted_strings = stripped_string.match(/[#][a-zA-Z0-9_'\-\s&]+[#]/gi);
	stripped_string = stripped_string.replace(/([#].*[#])?/gi,"");
	
	// retrieve all words with apostrophes
	apostrophe_strings = stripped_string.match(/[a-zA-Z]+'[a-zA-Z]/gi);
	stripped_string = stripped_string.replace(/[a-zA-Z]+'[a-zA-Z]/gi,"");
	
	// retrieve all words with ampersands
	ampersand_strings = stripped_string.match(/\b[a-zA-Z]+&[a-zA-Z]+\b/gi);
	stripped_string = stripped_string.replace(/\b[a-zA-Z]+&[a-zA-Z]+\b/gi,"");

	// remove and, not, nor, of, the, or, to, as, with
	// 		  if, for, is, in, by, an, but, at, all, it
	stripped_string = stripped_string.replace(/\band\b/gi,"");
	stripped_string = stripped_string.replace(/\bnot\b/gi,"");
	stripped_string = stripped_string.replace(/\bnor\b/gi,"");
	stripped_string = stripped_string.replace(/\bof\b/gi,"");
	stripped_string = stripped_string.replace(/\bthe\b/gi,"");
	stripped_string = stripped_string.replace(/\bor\b/gi,"");
	stripped_string = stripped_string.replace(/\bto\b/gi,"");
	stripped_string = stripped_string.replace(/\bas\b/gi,"");
	stripped_string = stripped_string.replace(/\bwith\b/gi,"");
	stripped_string = stripped_string.replace(/\bif\b/gi,"");
	stripped_string = stripped_string.replace(/\bfor\b/gi,"");
	stripped_string = stripped_string.replace(/\bis\b/gi,"");
	stripped_string = stripped_string.replace(/\bin\b/gi,"");
	stripped_string = stripped_string.replace(/\bby\b/gi,"");
	stripped_string = stripped_string.replace(/\ban\b/gi,"");
	stripped_string = stripped_string.replace(/\bbut\b/gi,"");
	stripped_string = stripped_string.replace(/\bat\b/gi,"");
	stripped_string = stripped_string.replace(/\ball\b/gi,"");
	stripped_string = stripped_string.replace(/\bit\b/gi,"");
	
	// remove all single characters
	stripped_string = stripped_string.replace(/\b[a-zA-Z]\b/gi," ");
	// remove all empty single quotes
	stripped_string = stripped_string.replace(/'\s*'/gi,"");
	
	// re-add the quoted strings
	if (quoted_strings != null) {
		stripped_string += quoted_strings + " ";
	}
	// re-add all words with apostrophes
	if (apostrophe_strings != null) {
		stripped_string += apostrophe_strings + " ";
	}
	// re-add all words with ampersands
	if (ampersand_strings != null) {
		stripped_string += ampersand_strings;
	}
	// remove commas
	stripped_string = stripped_string.replace(/,/g," ");
	
	dbl = /  /;
	while (dbl.test(stripped_string)) {
		stripped_string = stripped_string.replace(/  /gi," ");
	}
	stripped_string = trim(stripped_string);
	return stripped_string;
}


function showEditForm(file_to_display,fheight) {
	document.getElementById('edit_iframe').src=file_to_display;
	document.getElementById('edit_iframe').height=fheight;
}

function showWizardForm(file_to_display,fheight) {
	//parent.document.getElementById('wizard_iframe').height=fheight;
	location.href=file_to_display;
}

function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}

/*
Description:	Opens a form div when clicked
				Sets hidden values based on arguments passed to the function
Author:			E Van Veen
Date Created:	22 June 2006
*/
function positionSupplierDetails()
{
	var scrollY = getScrollY();
	var xdist = 50;
	var ydist = 200;
    if (document.layers)
	{
		//document.getElementById('popup_dialog_4_parent').style.posLeft = xdist+'%';
		document.getElementById('popup_dialog_4_parent').style.posTop = scrollY + ydist;
    }
    else if (document.all)
	{
		//document.getElementById('popup_dialog_4_parent').style.posLeft = xdist+'%';
		document.getElementById('popup_dialog_4_parent').style.posTop = scrollY + ydist;
    }
}


function createAndSubmitDynamicForm(url, params)
{
	//alert(params);
	var form = document.createElement('form');
	form.setAttribute('name','dynamic_form');
	form.setAttribute('id','dynamic_form');
	form.setAttribute('method','POST');
	form.setAttribute('action',url);
	
	var split_params = params.split('&');
	//alert(split_params.length);
	for (var i = 0; i < split_params.length; i++)
	{
		var the_element = split_params[i].split('=');
		//alert(the_element[0]);
		if (the_element[0] != ''){
			// add a new hidden input field
			var el = document.createElement('input');
			el.type = 'hidden';
			el.name = the_element[0];
			el.id = the_element[0];
			el.value = decodeURIComponent(the_element[1]);
			form.appendChild(el);
		}
	}
	document.body.appendChild(form);
	//alert(form.id);
	//document.dynamic_form.submit();
	//document.getElementById(form_id).action = url;
	document.getElementById(form.id).submit();
}

function validateSaveChangePWD(p0,p1,p2) {
	if (p0 == '') {
		alert('You must enter your current password.');
		return;
	}
	if (p1 != p2) {
		alert('The new passwords you entered do not match.');
		return;
	}
	if (p1.length < 6) {
		alert('Your new password must be at least 6 characters long (max 20).');
		return;
	}
	cp = SHA256(p0);
	np = SHA256(p1);
	location.href = 'change_contact_password_sql.php?cp=' + cp + '&np=' + np;
}

function forgotPassword(username) {
	if (username == '') {
		alert('Please provide your email address in the Email field, then click Forgot Password.');
		return;
	} else {
		if (confirm('This will delete your current password and update your profile with a new password.\nYou will receive an email containing your new password.\nUse this new password to login and then change the password as required.\nDo you wish to continue?')) {
			var gen_pwd = generatePassword();
			var new_pwd = hash = SHA256(gen_pwd);
			location.href = 'forgot_password.php?username=' + username + '&new_pwd=' + new_pwd + '&gen_pwd=' + gen_pwd;			
		} else {
			return;
		}
	}
}

function generatePassword() {
    var length=8;
    var sPassword = "";
    var noPunction = true;
    var randomLength = false;
    for (i=0; i < length; i++) {
    	numI = getRandomNum();
        if (noPunction) { while (checkPunc(numI)) { numI = getRandomNum(); } }
        sPassword = sPassword + String.fromCharCode(numI);
    }
    return sPassword;
}

function getRandomNum() {
    // between 0 - 1
    var rndNum = Math.random()
    // rndNum from 0 - 1000    
    rndNum = parseInt(rndNum * 1000);
    // rndNum from 33 - 127        
    rndNum = (rndNum % 94) + 33;
    return rndNum;
}

function checkPunc(num) {
    if ((num >=33) && (num <=47)) { return true; }
    if ((num >=58) && (num <=64)) { return true; }    
    if ((num >=91) && (num <=96)) { return true; }
    if ((num >=123) && (num <=126)) { return true; }
    return false;
}

function autoSuggestSuburb(form_name,suburb_element,state_element,country_element,postcode_element,select_url) {
	document.getElementById(suburb_element + '_autosuggest').className='autosuggest_over';
	theurlstring = select_url;
	form_params = 'form_name=' + encodeURIComponent(form_name);
	form_params += '&suburb_element=' + encodeURIComponent(suburb_element);
	form_params += '&state_element=' + encodeURIComponent(state_element);
	form_params += '&country_element=' + encodeURIComponent(country_element);
	form_params += '&postcode_element=' + encodeURIComponent(postcode_element);
	form_params += '&suburb_value=' + document.forms[form_name].elements[suburb_element].value;
	form_params += '&country_value=' + document.forms[form_name].elements[country_element].options[document.forms[form_name].elements[country_element].options.selectedIndex].value;
	populateDivPost(suburb_element + '_autosuggest',theurlstring,form_params,true);
	document.getElementById(suburb_element + '_autosuggest').style.display = 'block';
}

function autoSuggestLoadSuburb(locality,form_name,suburb_element,state_element,postcode_element) { 
	if (locality != undefined && locality != '') {
		locality_details = locality.replace("\'","'").split(' | ');
		document.forms[form_name].elements[suburb_element].value = locality_details[0];
		
		opt_len = document.forms[form_name].elements[state_element].options.length;
		var the_index = 0;
		for (i=0; i < opt_len; i++) {
			if (document.forms[form_name].elements[state_element][i].value == locality_details[1]) {
				document.forms[form_name].elements[state_element][i].selected = true;
				break;
			}
		}

		document.forms[form_name].elements[postcode_element].value = locality_details[2];
		setElementInnerHTML(document.getElementById(suburb_element + '_autosuggest'), '');
		setElementDisplay(suburb_element + '_autosuggest','none');
	}
}

function validatePhoneFaxMobile(pi,pa,pn,fi,fa,fn,mi,ma,mn) {
	var fail_msg = '';
	if (pn != '' && pa == '') {
		fail_msg += "Please enter an area code in the Phone area field. You entered:\nCountry Code: " + pi + "\nArea Code: " + pa + "\nNumber: " + pn + "\n";
	}
	if (fn != '' && fa == '') { 
		fail_msg += "Please enter an area code in the Fax area field. You entered:\nCountry Code: " + fi + "\nArea Code: " + fa + "\nNumber: " + fn + "\n";
	}
	if (mn != '' && ma == '') { 
		fail_msg += "Please enter an area code in the Mobile area field. You entered:\nCountry Code: " + mi + "\nArea Code: " + ma + "\nNumber: " + mn + "\n(The area code for all Australian mobile numbers is 04.)\n";
	}
	return fail_msg;
}

function validatePhoneFax(pi,pa,pn,fi,fa,fn) {
	var fail_msg = '';
	if (pn != '' && pa == '') {
		fail_msg += "Please enter an area code in the Phone area field. You entered:\nCountry Code: " + pi + "\nArea Code: " + pa + "\nNumber: " + pn + "\n";
	}
	if (fn != '' && fa == '') { 
		fail_msg += "Please enter an area code in the Fax area field. You entered:\nCountry Code: " + fi + "\nArea Code: " + fa + "\nNumber: " + fn + "\n";
	}
	return fail_msg;
}

function validateContact(form_name) {
	var ok_to_go = true;
	if (document.forms[form_name].surname.value == '' || document.forms[form_name].first_name.value == '') {
		alert("Please enter a first name and surname.");
		ok_to_go = false;
	}
	if (document.forms[form_name].phone_number.value == '' || document.forms[form_name].phone_area.value == '') {
		alert("Please enter a contact telephone number and area code.");
		ok_to_go = false;
	}
	if (document.forms[form_name].email.value == '') {
		alert("Please enter an email address - this is required to log in.");
		ok_to_go = false;
	}
	re_strip = /\D/gi;
	re_test = /\D/;
	
	ph_i = document.forms[form_name].elements['phone_intl'].value.replace(re_strip,"");
	ph_a =  document.forms[form_name].elements['phone_area'].value.replace(re_strip,"");
	ph_n =  document.forms[form_name].elements['phone_number'].value.replace(re_strip,"");
	fax_i =  document.forms[form_name].elements['fax_intl'].value.replace(re_strip,"");
	fax_a =  document.forms[form_name].elements['fax_area'].value.replace(re_strip,"");
	fax_n =  document.forms[form_name].elements['fax_number'].value.replace(re_strip,"");
	m_i =  document.forms[form_name].elements['mobile_intl'].value.replace(re_strip,"");
	m_a =  document.forms[form_name].elements['mobile_area'].value.replace(re_strip,"");
	m_n =  document.forms[form_name].elements['mobile_number'].value.replace(re_strip,"");
	phfax_is_valid = validatePhoneFaxMobile(ph_i,ph_a,ph_n,fax_i,fax_a,fax_n);
	if (phfax_is_valid != '') {
		alert(phfax_is_valid);
		ok_to_go = false;
	}
	if (ok_to_go) {
		if(ph_n == ''){ph_n = '';ph_i = '';ph_a = '';}
		if(fax_n == ''){fax_n = '';fax_i = '';fax_a = '';}
		if(m_n == ''){m_n = '';m_i = '';m_a = '';}
		the_email = document.forms[form_name].elements['email'].value;
		if (the_email != '' && !emailAddressContentValidation(the_email)) {
			if (confirm("Warning: The email address appears to be invalid.\nClick OK to save anyway.\nor\nClick Cancel to change the email address before saving.")){
				ok_to_go = true;
			} else {
				ok_to_go = false;
			}
		}
		if (ok_to_go) {
			if ((ph_n == '') && (fax_n == '') && (m_n == '') && (the_email == '')) {
				alert ("You must enter at least one contact method for this person.\nPlease enter at least one of:\n\n\tContact Telephone,\n\tContact Fax,\n\tContact Mobile, or\n\tContact Email");
				ok_to_go = false;
			}
		}
	}
	return ok_to_go;
}

function validateSaveLinkContact(contactid,companyid) {
	form_name = 'frm_add_contact';
	if (document.forms[form_name].login_available.value == '0') {
		alert("Please enter your valid email address.  This will allow you to log in later.");
		return;
	} else if (document.forms[form_name].login_available.value == '2') {
		alert("The email address you entered is already in use.");
		return;
	}
	if (validateContact('frm_add_contact')) {
		form_params =  'email=' + the_email;
		form_params += '&first_name=' + encodeURIComponent(document.forms[form_name].first_name.value);
		form_params += '&surname=' + encodeURIComponent(document.forms[form_name].surname.value);
		form_params += '&title=' + encodeURIComponent(document.forms[form_name].title.value);
		form_params += '&position=' + encodeURIComponent(document.forms[form_name].position.value);
		form_params += '&ph_ccode=' + ph_i;
		form_params += '&ph_acode=' + ph_a;
		form_params += '&ph_number=' + ph_n;
		form_params += '&fax_ccode=' + fax_i;
		form_params += '&fax_acode=' + fax_a;
		form_params += '&fax_number=' + fax_n;
		form_params += '&m_ccode=' + m_i;
		form_params += '&m_acode=' + m_a;
		form_params += '&m_number=' + m_n;
		form_params += '&contactid=' + contactid;
		/* get address check box values from */
		var all_comma_prefix = '';
		var link_comma_prefix = '';
		var all_location_ids = '';
		var link_location_ids = '';
		for (var i = 0; i < document.forms[form_name].elements.length; i++) {
		    var the_element = document.forms[form_name].elements[i];
		    var type = the_element.type;
		    if (type == "checkbox" && the_element.name.substr(0, 4) == "loc_") {
		    	all_location_ids += all_comma_prefix + the_element.value;
		    	all_comma_prefix = ',';
		    	if (the_element.checked) {
			    	link_location_ids += link_comma_prefix + the_element.value;
			    	link_comma_prefix = ',';
			    }
		    }
		}
		form_params += '&all_location_ids=' + all_location_ids;
		form_params += '&link_location_ids=' + link_location_ids;
		if (document.forms[form_name].editor && document.forms[form_name].editor.checked) {
			form_params += '&editor=1';
		} else if (document.forms[form_name].editor && !document.forms[form_name].editor.checked) {
			form_params += '&editor=0';
		} else {
			form_params += '&editor=1';
		}
		location.href='contact_insert_update_sql.php?' + form_params;
	}
}
























