var openExtra = "none";
var changes = 0;
var sortValue = "";
var selectedContact = "";
var readOnly = false;
var selectedContactId = 0;
var dialed = false;
var openTime = 0;
var curarea = "";
var curuser = "";
var safeuser = "";
var curaccount = "";
var curcompany = "";
var curpostcode = "";
var	dialingMode = "";
var dialingScheme = "";
var dialingIPDial = "";
var dialingIPHangup = "";
var recordCalls = "";
var dateFormat = "";
var fieldUpdates = new Array();
var updateInProgress = false;
var updateAttempts = 0;
var totalAccounts = 0;

window.onscroll = function () {
	//alert(document.documentElement.scrollTop);
    if (document.getElementById('sizablePopUp') && $('#sizablePopUp').css("display") == "none") {
		$('#sizablePopUp').css("top", document.documentElement.scrollTop + 150);
	}
	if (document.getElementById('sizablePopUpB') && $('#sizablePopUpB').css("display") == "none") {
		$('#sizablePopUpB').css("top", document.documentElement.scrollTop + 150);
	}
	if (document.getElementById('ajaxbusy')) {
		$('#ajaxbusy').css("top", document.documentElement.scrollTop);
	}
}

function disableItem(obj, self) {
	document.getElementById(obj).disabled=true;
}

function enableItem(obj, self) {
	document.getElementById(obj).disabled=false;
}

function submitForm(obj, self) {
	document.getElementById(obj).submit();
}

function showItem(obj, self) {
	document.getElementById(obj).style.visibility='visible';
}

function doLogin() {
	disableItem('continue');
	$('#loginForm').fadeTo("normal", 0.2);
	showItem('loader');
	$('#loader').fadeTo("normal", 1);
	submitForm('form1');
}

function returnLogin(e) {
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	if (KeyID == 13) { doLogin(); } else { return false;}
}

function fieldVal ( eid ) {
	if (document.getElementById(eid)) {
		return document.getElementById(eid).value;
	} else {
		return 'IDNOTFOUND';
	}
}

function checkVal ( eid ) {
	if (document.getElementById(eid)) {
		if (document.getElementById(eid).checked) {
			return "T";
		} else {
			return "F";
		}
	} else {
		return "F";
	}
}

function uenc( text ) {
	return encodeURIComponent( text );
}

function normalCursor() {
	document.body.style.cursor = '';
}

function busyCursor() {
	document.body.style.cursor = 'wait';
}

function closeAccount() {
	answer = 0;
	if (changes > 0) {
		answer = confirm("There are unsaved changes to this account\nClick OK to close the account losing changes");
	} 
	if (answer != 0 || changes == 0) {
		if (timestamp != '') {
			navTo('index.php?mode=calendar&timestamp='+timestamp);
		} else {
			navTo('index.php?mode=accountlist&action=back');
		}
	}
	
}

//used for when an account is clicked on the tree 
function treeAccount(account, project) {
	answer = 0;
	if (changes > 0) {
		answer = confirm("You are leaving the current account, but there are unsaved changes\nClick OK to close the account losing changes");
	} 
	if (answer != 0 || changes == 0) {
		navTo('index.php?mode=accountDetail&account=' + account + '&project=' + project);		
	}
}

function npAccount( dir ) {
	$('#sizablePopUp').hide();
	dialed = false;
	
	$('#phoneIcon').show();
	$('#phoneIcon2').hide();
	
	
	answer = 0;
	if (changes > 0) {
		answer = confirm("There are unsaved changes to this account\nClick OK to move onto the next or previous account losing changes");
	} 
	if (answer != 0 || changes == 0) {
	
		if (document.getElementById('scriptPanel')) {
			$('#sizablePopUpB').hide();
		}
	
		if (document.getElementById('sizablePopUpTitleB').innerHTML.substring(0,10) == 'Callguides') {
			var callguideOpen = 'T';
		} else {
			var callguideOpen = 'F';
		}
	
		if (timestamp != '') {
			navTo('index.php?mode=calendar&timestamp='+timestamp);
		} else {
			changes = 0;
			busyCursor();
			knownDivs = null;
			knownDivs = Array();
			if (dir == "n") {
				document.getElementById('statusBar').innerHTML = 'Loading next account...';
				$('#accountDetails').load('index.php?mode=ajax&action=accountDetails&process=n&callguide='+callguideOpen+'&time='+ new  Date().getTime(),{},normalCursor);
			} else {
				document.getElementById('statusBar').innerHTML = 'Loading previous account...';
				$('#accountDetails').load('index.php?mode=ajax&action=accountDetails&process=p&callguide='+callguideOpen+'&time='+ new  Date().getTime(),{},normalCursor);
			}
		}
	}
	

}

function navTo( url ) {
	if (document.getElementById('ajaxbusy')) {
		$('#ajaxbusy').show();
	}
	window.location.href=url;
}

function openAccount( url ) {
	$('#ajaxbusy').show();
	changes = 0;
	busyCursor();
	window.location.href=url;
	$('#pageSelector').hide();
	$('#loader').fadeIn('normal');
	
}

function toggleFilter() {
	busyCursor();
	if (openExtra != "" && openExtra != "filter") {
		$('#extra').hide();
	}
	if(document.getElementById('extra').style.display=='' || document.getElementById('extra').style.display=='none') {
		$('#extra').load('index.php?mode=ajax&action=filter&time='+ new  Date().getTime(),{},function() { $('#extra').slideDown("normal");	document.body.style.cursor = '';
 });
		openExtra = "filter";
	} else {
	
		
		if(document.getElementById('sizablePopUpB').style.display !='none' && document.getElementById('sizablePopUpB').style.display !='') {
			$('#sizablePopUpB').fadeOut('normal');
		}
		
		$('#extra').slideUp("normal");
		openExtra = "";
		document.body.style.cursor = '';
	}
	
}

function toggleSearch() {
	busyCursor();
	if (openExtra != "" && openExtra != "search") {
		$('#extra').hide();
	}
	if(document.getElementById('extra').style.display=='' || document.getElementById('extra').style.display=='none') {
		$('#extra').load('index.php?mode=ajax&action=alSearch&time='+ new  Date().getTime(),{},function() { $('#extra').slideDown("normal"); document.body.style.cursor = '';});
		openExtra = "search";
	} else {
		$('#extra').slideUp("normal");
		openExtra = "";
		document.body.style.cursor = '';
	}

}

function toggleAssign() {
	busyCursor();
	if (openExtra != "" && openExtra != "assign") {
		$('#extra').hide();
	}
	if(document.getElementById('extra').style.display=='' || document.getElementById('extra').style.display=='none') {
		$('#extra').load('index.php?mode=ajax&action=assign&time='+ new  Date().getTime(),{},function() { $('#extra').slideDown("normal");	document.body.style.cursor = '';
 });
		openExtra = "assign";
	} else {
		$('#extra').slideUp("normal");
		openExtra = "";
		document.body.style.cursor = '';
	}
	
}

function loadingEffect( id ) {
	document.getElementById(id).innerHTML = '<img src="images/ajaxLoader.gif" alt="loading..."/ style="margin: 25px;">';
}

function toggleAreas() {
	busyCursor();
	$('#sizablePopUp').hide();
	$('#sizablePopUp').width(300);
	$('#sizablePopUp').height(250);
	$('#sizablePopUpContent').load('index.php?mode=ajax&action=areaPopUp&time='+ new  Date().getTime(),{},function() { $('#sizablePopUp').fadeIn("normal"); document.body.style.cursor = '';});

}

function showAssignInfo( ) {
	busyCursor();
	$('#sizablePopUp').hide();
	$('#sizablePopUpContent').load('index.php?mode=ajax&action=showAssignInfo&time='+ new  Date().getTime(),{},function() { $('#sizablePopUp').fadeIn("normal"); normalCursor();});

}

function updateStatus( ) {
	
	
	if (multiple == 'T') {
		field = 'RCMPROJ-CUSTOMERSTATUS';
		value = $('#RCMPROJ-LASTRESP/option:selected').attr('change');
	} else {
		field = 'TELRCM-CUSTOMERSTATUS';
		value = $('#TELRCM-LASTRESP/option:selected').attr('change');
	}
	
	
	if (value == null) {
		value = $('#response/option:selected').attr('change');
	}
	
	if (document.getElementById(field) && value != null) {
		document.getElementById(field).value = value;
		updateField(field,fieldVal(field));
		//setTimeout($.getScript('index.php?mode=ajax&action=updateField&field='+field+'&value='+uenc(fieldVal(field))+'&time='+ new  Date().getTime()),1000);
		updateOwner();
	} 
	
}

function updateOwner() {
	if (multiple == 'T') {
		field = 'RCMPROJ-OWNER';
		value = $('#RCMPROJ-CUSTOMERSTATUS/option:selected').attr('change');
	} else {
		field = 'TELRCM-OWNER';
		value = $('#TELRCM-CUSTOMERSTATUS/option:selected').attr('change');
	}
	
	if (document.getElementById(field) && value != null) {
		document.getElementById(field).value = value;
		updateField(field,fieldVal(field));
		//setTimeout($.getScript('index.php?mode=ajax&action=updateField&field='+field+'&value='+uenc(fieldVal(field))+'&time='+ new  Date().getTime()),1250);
	} 

}

function drop2text( id, e ) {
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	if (KeyID == 13) { 
		tb = document.getElementById(id + 'TB');
		dd = document.getElementById(id);	
		tb.style.display='inline';
		dd.style.display='none';
		tb.focus();
	}
}
function text2drop( id ) {
	tb = document.getElementById(id + 'TB');
	dd = document.getElementById(id);
	tb.style.display='none';
	dd.style.display='inline';
	dd.options[dd.length] = new Option(tb.value, tb.value);
	dd.value=tb.value;
}

function selectContact( id ) {

	if (document.getElementById('CONT-CONTACT-'+id)) {
		selectedContact = document.getElementById('CONT-CONTACT-'+id).value;
	} else {
		if (document.getElementById('CONT-TITLE-'+id)) {
			selectedContact = document.getElementById('CONT-TITLE-'+id).value;
		}
		
		if (document.getElementById('CONT-FIRSTNAME-'+id)) {
			selectedContact = $.trim(selectedContact) + ' ' + document.getElementById('CONT-FIRSTNAME-'+id).value;
		}
		
		if (document.getElementById('CONT-INITIALS-'+id)) {
			selectedContact = $.trim(selectedContact) + ' ' + document.getElementById('CONT-INITIALS-'+id).value;
		}
		
		selectedContact = $.trim(selectedContact) + ' ' + document.getElementById('CONT-SURNAME-'+id).value;
	}

	
	$('#statusBar').load('index.php?mode=ajax&action=selectContact&id='+id+'&time='+ new  Date().getTime());
	document.getElementById('selectedContact'+id).checked = true;
	selectedContactId = id;

}

function readNextdate( field ) {

	dateText = document.getElementById(field).value;
	if (document.getElementById(field + '-TH')) {
		dateText = dateText + " " + document.getElementById(field + '-TH').value;
		dateText = dateText + ":" + document.getElementById(field + '-TM').value;
		if (document.getElementById(field + '-ME')) {
			dateText = dateText + " " + document.getElementById(field + '-ME').value;
		}
	}
	
	return dateText;

}

function getTimeDrops( prefix ) {

	dateText = document.getElementById(prefix + '_Hour').value;
	dateText = dateText + ":" + document.getElementById(prefix + '_Min').value;
	if (document.getElementById(prefix + '_Meridian')) {
		dateText = dateText + " " + document.getElementById(prefix + '_Meridian').value;
	}
	
	
	return dateText;

}

function readAddnCheckBoxes( id ) {

	data = "";
	x = 0;
	while (document.getElementById(id + '-' + x)) {
		if (document.getElementById(id + '-' + x).checked) {
			data += document.getElementById(id + '-' + x).value + '*X*';
		}
		x++;
	}
	if (document.getElementById(id + '-other') && document.getElementById(id + '-other').value != '') {
		data += document.getElementById(id + '-other').value + '*X*';
	}
	
	return data;
	
}

function toggleDeleteContact( id ) {
	
	if ($('#contactRow'+id).css('opacity') == 1) {
		$.getScript('index.php?mode=ajax&action=updateField&field=CONT-DELETE-' + id + '&value=T&time='+ new  Date().getTime());
		$('#contactRow'+id).fadeTo('normal',0.2);
	} else {
		$.getScript('index.php?mode=ajax&action=updateField&field=CONT-DELETE-' + id + '&value=F&time='+ new  Date().getTime());
		$('#contactRow'+id).fadeTo('normal',1);
	}
}

function addContact() {
	if ($('#CONT-CONTACT-N').val() != '' && $('#CONT-CONTACT-N').val() != '[add contact]') {
		document.getElementById('statusBar').innerHTML = 'Reloading contacts...';
		$('#panelContactContent').load('index.php?mode=ajax&action=contactPanel&new='+uenc($('#CONT-CONTACT-N').val())+'&width='+$('#panelContactContent').width()+'&height='+$('#panelContactContent').height()+'&time='+ new  Date().getTime(),{},function() { document.getElementById('statusBar').innerHTML = 'Reloaded contacts'; });
	} else {
		$('#CONT-CONTACT-N').val('[add contact]');
	}
	
}

function clearNewContact() {
	if ($('#CONT-CONTACT-N').val() == '' || $('#CONT-CONTACT-N').val() == '[add contact]') {
		$('#CONT-CONTACT-N').val('');
	}
}

function showCalTip(id) {
	
	$('#'+id).css("left",getAbsoluteLeft('a'+id));
	$('#'+id).css("top",getAbsoluteTop('a'+id) + 24);
	$('#'+id).css("display","block");
	$('#'+id).show();
}

function hideCalTip(id) {
	$('#'+id).hide();
	//$('#'+id).css("display","none");
}

function showPopup(id,id2,dir) {
	if (dir == "r") {
		$('#'+id).css("left",getAbsoluteLeft(id2));
		$('#'+id).css("top",getAbsoluteTop(id2) + 24);
	} else {
		$('#'+id).css("left",getAbsoluteLeft(id2) - parseInt($('#'+id).css("width")));
		$('#'+id).css("top",getAbsoluteTop(id2) + 24);
	}
	$('#'+id).css("display","block");
	$('#'+id).fadeIn('normal');
}

function navCalendar(dir) {
	
	if (view == "monthly") {
		if (dir == "f") {
			timestamp = timestamp + 2678400;
		} else {
			timestamp = timestamp - 2678400;
		}
	} else {
		if (dir == "f") {
			timestamp = timestamp + 604800;
		} else {
			timestamp = timestamp - 604800;
		}
	}
	busyCursor();
	$('#calendarPanel').load('index.php?mode=ajax&action=calendar&timestamp='+timestamp+'&view='+view+'&time='+ new  Date().getTime(),{},normalCursor());
}


//borrowed from jtip
function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	return oLeft
}
function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	return oTop
}

function toggleCalFilter() {
	busyCursor();
	if (openExtra != "" && openExtra != "filter") {
		$('#calFilter').hide();
	}
	if(document.getElementById('calFilter').style.display=='' || document.getElementById('calFilter').style.display=='none') {
		$('#calFilter').load('index.php?mode=ajax&action=calFilter&time='+ new  Date().getTime(),{},function() { $('#calFilter').slideDown("normal");	document.body.style.cursor = '';
 });
		openExtra = "filter";
	} else {
		$('#calFilter').slideUp("normal");
		openExtra = "";
		document.body.style.cursor = '';
	}
}

function applyAssign() {
	if(checkVal('selectedAccounts')=='T' || checkVal('numberOfAccounts')=='T' || checkVal('allAccounts')=='T') {
		if(checkVal('chOwner')=='T' || checkVal('chStatus')=='T' || checkVal('chField')=='T' || checkVal('chRenumber')=='T' || checkVal('chCopy')=='T' || checkVal('chMove')=='T' || checkVal('chDelete')=='T' || checkVal('chEmail')=='T') {
			
			var passedConfirm = false;
			if(checkVal('allAccounts')=='T') {
				passedConfirm = confirm(totalAccounts + ' accounts will be effected');
			} else {
				passedConfirm = true;
			}
			
			if(passedConfirm) {
			
				$('#assign').fadeTo('normal',0.4);
				if (checkVal('selectedAccounts') == "T") {
				$( "input.alcb" ).each(	
					function( intIndex ){
						document.getElementById('selected').value = document.getElementById('selected').value + document.getElementById('selectedAccount'+intIndex).value + '=' + checkVal('selectedAccount'+intIndex) + ',';
					}
				);
				}
				
				disableItem('apply');
				submitForm('assignForm');		
			
			}
			
		} else {
			alert('An action must be selected');		
		}
	} else {
		alert('A selection method must be selected');
	}

}

function applyDedupe() {
	if ($('#updateOwner').val() == "" && $('#updateStatus').val() == "") {
		alert('Select either a owner or status to change');
	} else {
		var selectedAccounts = "";
		$( "input.ddcb" ).each(	
			function( intIndex ){
				if (document.getElementById('selectedAccount'+intIndex).checked) {
					selectedAccounts = selectedAccounts + document.getElementById('selectedAccount'+intIndex).value + ',';
				}
			}
		);
		if(selectedAccounts == "") {
			alert('Select accounts to update');
		} else {
			$('#sizablePopUpContentB').load('index.php?mode=ajax&action=dedupe&process=update&owner='+uenc(fieldVal('updateOwner'))+'&status='+uenc(fieldVal('updateStatus'))+'&selectedAccounts='+uenc(selectedAccounts)+'&time='+ new  Date().getTime());
		}
	}


}

function popUp(URL,w,h,s) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars="+s+",location=0,statusbar=0,menubar=0,resizable=1,width="+w+",height="+h+"');");
}

function addEmailAddress(id,address) {
	if (document.getElementById(id).value == '') {
		document.getElementById(id).value = address;
	} else {
		document.getElementById(id).value = document.getElementById(id).value +';' + address;
	}
}

function checkEmailForm() {

	if(document.getElementById('emailTo').value == '' || document.getElementById('emailFrom').value  == '') {
		alert('You must enter a To and From address');
	} else {
		disableItem('sendEmail');
		disableItem('logEmail');
		disableItem('cancelEmail');
		submitForm('emailForm');
	}

}

function checkUserForm() {

	if ($('#username').val() == '') {
		alert('You must enter a username');
	} else if ($('#logintype').val() == 'i' && parseInt($('#level_no').val()) > 8) {
		alert('Restricted users cannot have an authority level greater than 8');
	} else {
		submitForm('userForm');
	}

}

function checkDocForm() {

	if ($('#docName').val() == '') {
		alert('You must enter a name');
	} else {
		submitForm('docForm');
	}

}

function duplicateUser( from ) {
	var name = prompt("Enter new username", "");
	navTo('index.php?mode=setup&action=users&process=dupe&name=' + uenc(name) + '&from=' + uenc(from));
}

function confirmAction( text ) {
	
	var agree=confirm( text );
	if (agree) {
		return true;
	} else {
		return false;
	}
}

function checkForReturn(e) {
	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	if (KeyID == 13) { return true; } else { return false;}
}

function toggleRandomPassword() {
	if (checkVal('randomPassword') == 'T') {
		document.getElementById('password').type = 'text';
		$('#password').val(randomPassword(10));
	} else {
		document.getElementById('password').type = 'password';
	}
}

function randomPassword(length)
{
  chars = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
  pass = "";
  for(x=0;x<length;x++)
  {
    i = Math.floor(Math.random() * 56);
    pass += chars.charAt(i);
  }
  return pass;
}

function selectVal( eid ) {
  var value = "";
  var selObj = document.getElementById(eid);
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].selected) {
      if (count != 0) value += '*x*';
	  value += selObj.options[i].value;
      count++;
    }
  }
  return value;
}

function reportWriterAddRow() {

	var x = 1;
	doLoop = true;
	while(x <= 9 && doLoop) {
		if ($('#row' + x).css("display") == 'none') {
			doLoop = false;
		} else {
			x++;
		}
	}
	if (doLoop) {
		alert('Maximum of 10 rows allowd');
	} else {
		$('#row'+x).css("display",'');
		if (x == 9) {
			$('#rowControl').fadeOut();
		}
	}

}

function mappingClick() {
	
	if (tmsField != '' && fileField != '') {
	
		var def = $('#mapFile').val();
		$('#mapFields').load('index.php?mode=ajax&action=import&process=viewDef&tmsField='+uenc(tmsField)+'&fileField='+(fileField)+'&file='+uenc(importFile)+'&def='+uenc(def)+'&time='+ new  Date().getTime());
		tmsField = '';
		fileField = '';
		
		document.getElementById('tmsFields').selectedIndex = -1;
		document.getElementById('fileFields').selectedIndex = -1;
	}
	
}

function checkImportLength() {

	if ( ($('#startingNumber').val().length + $('#prefix').val().length) > 10) {
		alert('Warning: Your starting account number + prefix is greater than 10 charactors. This is only supported if you have manually altered the database structure. If in doubt do not use more than 10 charactors.');
	}

}

function getInputs( divId ) {

	var inputs = [];
	
	$(':input','#'+divId).each(function() {
		if (this.type == "checkbox" || this.type == "radio") {
			if (this.checked == true) {	
				inputs.push(this.name + '=' + uenc(this.value));
			}
		} else {
			inputs.push(this.name + '=' + uenc(this.value));
		}
	});
	
	return inputs.join('&');

}

function getScriptData() {

	var inputs = [];
	
	$(':input','#scriptFields').each(function() {
		if (this.type == "checkbox" || this.type == "radio") {
			if (this.checked == true) {	
				inputs.push(this.name + '=' + uenc(this.value));
			}
		} else {
			inputs.push(this.name + '=' + uenc(this.value));
		}
	});
	$(':input','#scriptAnswer').each(function() {
		if (this.type == "checkbox" || this.type == "radio") {
			if (this.checked == true) {	
				inputs.push(this.name + '=' + uenc(this.value));
			}
		} else {
			inputs.push(this.name + '=' + uenc(this.value));
		}
	});
	
	return inputs.join('&');

}

function scriptNext() {

	$('#scriptPanel').load('index.php?mode=ajax&action=script&script='+uenc(scriptName)+'&'+getScriptData()+'&dir=next&time='+ new  Date().getTime());
	
}

function scriptCalendar( timestamp, fid, qid, aid ) {

	navTo('index.php?mode=ajax&action=scriptCalendar&process=view&aid='+aid+'&fid='+fid+'&timestamp=' + timestamp+'&qid='+qid+'&'+getScriptData());

}


function scriptPrev() {
	$('#scriptPanel').load('index.php?mode=ajax&action=script&script='+uenc(scriptName)+'&dir=prev&qid='+fieldVal('currentQuestion')+'&time='+ new  Date().getTime());
}

function scriptUpdate(table, field, value) {
		if (table == "CONT") {
			if (document.getElementById(table + '-' + field + '-' + selectedContactId)) {
				document.getElementById(table + '-' + field + '-' + selectedContactId).value = value;
			}
		} else {
			if (document.getElementById(table + '-' + field)) {
				document.getElementById(table + '-' + field).value = value;
			}
		}
	
	
}

//used for when an account is clicked on the tree 
function alarmAccount(account, project, serialDate) {
	answer = 0;
	if (changes > 0) {
		answer = confirm("You are leaving the current account, but there are unsaved changes\nClick OK to close the account losing changes");
	} 
	if (answer != 0 || changes == 0) {
		navTo('index.php?mode=accountDetail&account=' + account + '&project=' + project + '&alarm=' + serialDate);		
	}
}

function dialNumber( number ) {
		
	if (dialed == false) {

		if (dialingMode == "agent" || dialingMode == "ip") {
			$('#phoneIcon').hide();
			$('#phoneIcon2').show();
		}
		
		if (dialingMode == 'url') {
		
			document.getElementById('dialerFrame').src= dialingScheme+'://'+number;
		
		} else if (dialingMode == 'ip') {
		
			t = dialingIPDial;
			t = replaceAll(t,'*telephone',number);
			t = replaceAll(t,'*contact',uenc(selectedContact));
			t = replaceAll(t,'*ref',curaccount + '_' + curarea + '_' + openTime);
			document.getElementById('dialerFrame').src = t;
			dialed = true;
		
		} else if (dialingMode == 'agent') {
		
			var content = ' <MODE>iTMS Agent</MODE><DIAL>' + number + '</DIAL><RECORD>' + recordCalls+'</RECORD><FILENAME>' + safeuser + '_' + curaccount + '_' + curarea + '_' + openTime + '.ogg</FILENAME>';
			document.getElementById('agent').innerHTML = content;
			//setTimeout(function() {document.getElementById('agent').innerHTML='';},1000);
			dialed = true;
		
		}
		
		updateField('SPECIAL-CALLSTART', Math.round(new  Date().getTime() / 1000));
		setTimeout( function () { updateField('SPECIAL-TELEPHONE', number) },1000);
		document.getElementById('statusBar').innerHTML = 'Dialed: ' + number;
		document.getElementById('agent').innerHTML = content;
		
	} else {
	
		if (dialingMode == 'ip') {
			
			t = dialingIPHangup;
			t = replaceAll(t,'*telephone',number);
			t = replaceAll(t,'*contact',selectedContact);
			document.getElementById('dialerFrame').src = t;
			
		} else if (dialingMode == 'agent') {
		
			var content = ' <MODE> iTMS Agent</MODE><HANGUP>TRUE</HANGUP>';
			document.getElementById('agent').innerHTML = content;
			//setTimeout(function() {document.getElementById('agent').innerHTML='';},1000);
		
		}
	
		updateField('SPECIAL-CALLEND', Math.round(new  Date().getTime() / 1000));
		document.getElementById('statusBar').innerHTML = 'Hanged Up';
		$('#phoneIcon').show();
		$('#phoneIcon2').hide();
		dialed = false;
	
	}

}

function replaceAll( str, from, to ) {
	var idx = str.indexOf( from );

	while ( idx > -1 ) {
		str = str.replace( from, to );
		idx = str.indexOf( from );
	}
	return str;
}

function queryAddField() {

	var querySQL = $('#querySQL').val();
	var queryTo = $('#queryTo').val();
	var queryFrom = $('#queryFrom').val();
	var queryField = $('#queryField').val();
	var queryMultiple = checkVal('queryMultiple');
	var queryUpdate = true;
	
	if (querySQL.length > 0) {
		querySQL += ' AND ';
	}
	
	if (queryTo == "") {
		if (queryMultiple == 'F') {
			queryFrom = replaceAll(queryFrom, '*','%');
			querySQL += queryField + ' LIKE \'' + queryFrom + '\'';
		} else {
			var queryMV = queryFrom.split(',');
			if (queryMV.length > 0) {
				querySQL += queryField + ' IN (';
				for(a = 0; a < queryMV.length; a++) {
					if (a != 0) {
						querySQL += ',';
					}
					querySQL += '\'' + queryMV[a] + '\'';
				}
				querySQL += ')';
			} else {
				alert('Multiple values not found, use a comma to seperate multiple values');
				queryUpdate = false;
			}
		}
	} else {
		querySQL += queryField + ' BETWEEN \'' + queryFrom +'\' AND \'' + queryTo + '\'';
	}

	if (queryUpdate == true) {
		$('#querySQL').val(querySQL);
		$('#queryFrom').val('');
		$('#queryTo').val('');
		document.getElementById('queryMultiple').checked = false;
	}

}

function queryBrowseValues() {
	$('#view1').hide();
	$('#view2').show();
	$('#view2').load('index.php?mode=ajax&action=query&process=browse&field='+uenc(fieldVal('queryField'))+'&time='+ new  Date().getTime());
}

function querySelectValues() {

	var queryFrom = '';
	for(var i = 0; i < document.getElementById('queryValues').options.length; i++) {
		if (document.getElementById('queryValues').options[i].selected) {
			if (queryFrom != '') {
				queryFrom += ',';
			}
			queryFrom += document.getElementById('queryValues').options[i].value;
		}
	}
	$('#queryFrom').val(queryFrom);
	document.getElementById('queryMultiple').checked = true;
	$('#view2').hide();
	$('#view1').show();
	
}

function exportUpdateSort() {

	theSelFrom = document.getElementById('exportFields');
	var selLength = theSelFrom.length;
	var selectedText = new Array();
	var selectedValues = new Array();
	var selectedCount = 0;
	var i;
	exportClearSort();
	
	for(i=0; i<selLength; i++)
	{
		if(theSelFrom.options[i].selected)
		{
			selectedText[selectedCount] = theSelFrom.options[i].text;
			selectedValues[selectedCount] = theSelFrom.options[i].value;
			selectedCount++;
		}
	}
	for(i=0; i<=(selectedCount-1); i++)
	{
		exportAddSort(selectedText[i], selectedValues[i]);
		//alert('adding: ' + selectedText[i]);
	}
}

function exportClearSort() {
	
	theSel = document.getElementById('exportSort');
	var selLength = theSel.length;
	
	var a;
	for(a = 0; a < selLength; a++) {
		theSel.options[0] = null;
	}
	
}

function exportAddSort( theText, theValue) {
	theSel = document.getElementById('exportSort');
	var newOpt = new Option(theText, theValue);
	var selLength = theSel.length;
	theSel.options[selLength] = newOpt;
}

function exportDownload() {

	var selVal = '';
	var sortVal = $('#exportSort').val();
	var sortAsc = checkVal('exportAsc');
	var selFormat = $('#exportFormat').val();
	
	for(var i = 0; i < document.getElementById('exportFields').options.length; i++) {
		if (document.getElementById('exportFields').options[i].selected) {
			if (selVal != '') {
				selVal += ',';
			}
			selVal += document.getElementById('exportFields').options[i].value;
		}
	}
	
	var url = 'index.php?mode=export&fields='+uenc(selVal)+'&sort='+uenc(sortVal)+'&asc='+uenc(sortAsc)+'&format='+uenc(selFormat);
	window.location.href=url;
	$('#sizablePopUpB').fadeOut('normal');

}

function addUserDate( field ) {

	var d= new Date();
	field.value = field.value + "\n" + '[ ' + d.formatDate(dateFormat) + ' ' + curuser + ' ] ';

}

function deleteScriptSelection( scriptName ) {
	if (treePos == '') {
		alert('Select a question or answer to delete');
	} else if (confirm('Are you sure you want to delete the selection question or answer?')) {
		$('#scriptTree').load('index.php?mode=ajax&action=setupScripts&process=scriptTree&code='+uenc(scriptName)+'&delete='+treePos+'&time='+ new  Date().getTime());
		treePos = '';
	}
}

function saveScriptQuestion() {
	if ($('#questionNumber').val() == '') {
		alert('Question number is missing');
	} else if ($('#questionText').val() == '') {
		alert('Question text is missing');
	} else {
		submitForm('questionForm');
	}

}

function saveScriptAnswer() {
	if ($('#answerNumber').val() == '') {
		alert('Answer number is missing');
	} else if ($('#answerText').val() == '') {
		alert('Answer text is missing');
	} else {
		submitForm('answerForm');
	}

}

function removeNonNumeric( strString ) {

	var strValidCharacters = "1234567890";
	var strReturn = "";
	var strBuffer = "";
	var intIndex = 0;
	for( intIndex = 0; intIndex < strString.length; intIndex++ ) {
          strBuffer = strString.substr( intIndex, 1 );
          if( strValidCharacters.indexOf( strBuffer ) > -1 ) {
               strReturn += strBuffer;
          }
	}
	return strReturn;
	
}

function updateField( field, value ) {

	var t = new Array();
	var l = fieldUpdates.length;
	
	t[0] = field;
	t[1] = value;
	t[2] = 0;
	
	fieldUpdates[l] = t;
	
	//console.log('Adding new field to pending updates, ID: ' + l);
	
	if (updateInProgress == false) {
		doUpdates();
	} else {
	//	console.log('Update already in progress');
	}

}

function pendingUpdateCount() {
	var pendingCount = 0;
	for (i=0;i<fieldUpdates.length;i++) {
		if (fieldUpdates[i][2] == 0) {
			pendingCount++;
		}
	}
	//console.log('Pending updates: ' + pendingCount);
	return pendingCount;

}

function updatePending() {

	//console.log('updatePending() called');

	uid = getNextUpdateId();
	var loc = fieldUpdates[uid];
	if (loc[2] == 0) {
		updateInProgress = true;
		//sometimes this gets locked as true :(
		setTimeout( function() {
			updateInProgress = false;
		},1500);
		setTimeout( function() {
			
			
			var requestURL = 'index.php?mode=ajax&action=updateField&time='+ new  Date().getTime();
			var requestData = 'field='+uenc(loc[0])+'&value='+uenc(loc[1]);
			//console.log(requestURL);
			//console.log('Saving field: '+loc[0]);
			$.ajax({
				type: "POST",
				url: requestURL,
				dataType: "script",
				data: requestData,
				cache: false,
				timeout: 2000,
				success: function(msg) { 
										fieldUpdates[uid][2] = 1; 
									//	console.log('field '+loc[0]+' saved, value: ' + loc[1]); 
									//	console.log(msg);
										if(pendingUpdateCount() > 0) {
											updatePending();
										} else {
											//clearInterval(updateIntId);
											updateInProgress = false;
											updateAttempts = 0;
										}
									},
				error: function() { 	
										updateAttempts++;
									//	console.log('save error, field: ' + loc[0] + ' value: ' + loc[1]); 
										if (updateAttempts > 10) {
											alert('Error saving Field. Check Internet Connectivity. Field has not been updated at this point in time.');
											updateAttempts = 0;
											updateInProgress = false;
										} else {
											updatePending(); 
										}
										
								}
			});
		}, 250);
	} 
	
}

function doUpdates() {
	//console.log('doUpdates() called');
	if(pendingUpdateCount() > 0) {
		if (updateInProgress == false) {
			updatePending();
		}
	} 
}

function getNextUpdateId() {
	var id = 0;
	for (i=0;i<fieldUpdates.length;i++) {
		if (fieldUpdates[i][2] == 0) {
			id = i;
			break;
		}
	}
	//console.log('Next pending update ID: ' + id);
	return id;
}

function echoFieldUpdates() {
	for (i=0;i<fieldUpdates.length;i++) {
		alert(fieldUpdates[i][0] + ', ' + fieldUpdates[i][1] + ', ' + fieldUpdates[i][2]);
	}
}

function wrapupLogCall( returnString ) {

	$('#ajaxwait').show();	
	if (updateInProgress == false) {
		if(checkMan()) {
			$('#sizablePopUp').fadeOut('normal');
			document.getElementById('statusBar').innerHTML = 'Saving account...';
			$('#statusBar').load('index.php?mode=ajax&action=accountSave&return='+returnString+'&time='+ new  Date().getTime()); 
		}
		$('#ajaxwait').hide();
	} else {
		setTimeout ( function() { wrapupLogCall( returnString ); }, 250);
	}
	
}

function wrapupSaveOnly( returnString ) {
	
	$('#ajaxwait').show();	
	if (updateInProgress == false) {
		if(checkMan()) {
			$('#sizablePopUp').fadeOut('normal');
			document.getElementById('statusBar').innerHTML = 'Saving account...';
			$('#statusBar').load('index.php?mode=ajax&action=accountSave&log=false&return='+returnString+'&time='+ new  Date().getTime());
		}
		$('#ajaxwait').hide();
	} else {
		setTimeout ( function() { wrapupSaveOnly( returnString ); }, 250);
	}

}

function saveAccount( returnString ) {

	$('#ajaxwait').show();	
	if (updateInProgress == false) {
		if(checkMan()) {
			document.getElementById('statusBar').innerHTML = 'Saving account...';
			$('#statusBar').load('index.php?mode=ajax&action=accountSave&log=false&return='+returnString+'&time='+ new  Date().getTime());
		}
		$('#ajaxwait').hide();
	} else {
		setTimeout ( function() { saveAccount( returnString ); }, 250);
	}

}

function openWWW( fieldId ) {
	var wwwUrl = $('#'+fieldId).val();
	if (wwwUrl.substr(0,7) != 'http://') {
		wwwUrl = 'http://' + wwwUrl;
	}
	popUp(wwwUrl,640,480,1)
}


function postcodeSearch() {
	busyCursor();
	$('#sizablePopUpB').hide();
	$('#sizablePopUpContentB').load('index.php?mode=ajax&action=postcodeSearch&postcode='+uenc(fieldVal('TELRCM-POSTCODE'))+'&time='+ new  Date().getTime(),{},function() { $('#sizablePopUpB').fadeIn('normal'); normalCursor();});
}

function populateAddress( address1, address2, address3, address4) {
	
	if(document.getElementById('TELRCM-ADDRESS1') && address1 != '') {
		document.getElementById('TELRCM-ADDRESS1').value = address1;
		updateField('TELRCM-ADDRESS1',address1);
	}
	if(document.getElementById('TELRCM-ADDRESS2') && address2 != '') {
		document.getElementById('TELRCM-ADDRESS2').value = address2;
		updateField('TELRCM-ADDRESS2',address2);
	}
	if(document.getElementById('TELRCM-ADDRESS3') && address3 != '') {
		document.getElementById('TELRCM-ADDRESS3').value = address3;
		updateField('TELRCM-ADDRESS3',address3);
	}
	if(document.getElementById('TELRCM-ADDRESS4') && address4 != '') {
		document.getElementById('TELRCM-ADDRESS4').value = address4;
		updateField('TELRCM-ADDRESS4',address4);
	}
	$('#sizablePopUpB').fadeOut('fast');
	
}

function copyAreaSettings() {
	if ($('#source').val() == '') {
		alert('Select a source area to copy from');
	} else {
		if ($('#destination').val() == '') {
			alert('Select a destination to copy to');
		} else {
			if ($('#source').val() == $('#destination').val()) {
				alert('Source and Destination areas cannot be the same!');
			} else {
				if(confirm('Destination area settings will be overwritten with source area, continue?')) {
					$('#sizablePopUpContentB').load('index.php?mode=ajax&action=copyAreaSettings&process=copy&'+getInputs('sizablePopUpContentB')+'&time='+ new  Date().getTime());
				}
			}
		}
	}

}