/* USE THIS FUNCTION FOR ALL ElementByID calls, 
as it is cross browser compatible! */
function returnObjById(id)
{
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}



function copyValue(source1, target1) {
	target1.value = source1.value+target1.value;
}

function replaceValue(source, target)
{
	target.value = source.value;
}

function changeValue(source, target) {
	target.value = source;
}

function addToValue(source, target, newline) {
	if (newline = true && target.value != '')
		target.value = target.value+'\r\n';
	target.value = target.value+source;
}

function removeDoubleSpacing(source) {
	var newvalue = source.value;
	//alert(newvalue);
	//source.value = newvalue.replace(/dog/g, "cat");
	newvalue = newvalue.replace(/\n \n /g, "\n");
	newvalue = newvalue.replace(/\n \n/g, "\n");
	newvalue = newvalue.replace(/\n\n/g, "\n");
	source.value = newvalue;
	//alert('done');
}

function copyOrganisationValues () {
	replaceValue(returnObjById('customer_Organisation'), returnObjById('customer_BillingOrganisation'));
	replaceValue(returnObjById('customer_Phone'), returnObjById('customer_BillingPhone'));
	replaceValue(returnObjById('customer_Address1'), returnObjById('customer_BillingAddress1'));
	replaceValue(returnObjById('customer_Address2'), returnObjById('customer_BillingAddress2'));
	replaceValue(returnObjById('customer_City'), returnObjById('customer_BillingCity'));
	replaceValue(returnObjById('customer_Postcode'), returnObjById('customer_BillingPostcode'));
}

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

function MM_jumpMenu(targ,selObj,restore){ //v3.0
eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0;
}

function MM_openBrWindow(theURL,winName,features,titlebar) { //v2.0
window.open(theURL,winName,features,titlebar);
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; 
  document.MM_sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){
    document.MM_sr[j++]=x; 
    if(!x.oSrc) x.oSrc=x.src; 
    x.src=a[i+2];
  }
}

function textCounter(field, maxlimit) {
	// if too long...trim it!
	if (field.value.length > maxlimit)
	{
		field.value = field.value.substring(0, maxlimit);
	}
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function addfavourite() 
{
	if (document.all)
	{
		window.external.AddFavorite(location.href,document.title)
	}
	else
	{
		window.sidebar.addPanel(document.title,location.href,'');
		//alert("To add this web page to your bookmarks, click 'OK' then press Ctrl+D");
	}
}

// blocking function

var supported = (document.getElementById || document.all);
if (supported) {
	// set all to be initally false (ie. not shown / none)
	var max = 7;
	var shown = new Array();
	for (var i=1;i<=max;i++) {
		shown[i+1] = false;
	}
}

function blocking(i) {
	if (!supported)	{
		alert('Sorry, this link does not work in your browser.');
		return;
	}
	// reverse current state
	shown[i] = (shown[i]) ? false : true;
	// set css display value
	current = (shown[i]) ? 'block' : 'none';
	// set 
	currentimg = (shown[i]) ? 'on' : 'off';
	if (document.getElementById) {
		document.getElementById('comment_'+i).style.display = current;
	}
	else if (document.all) {
		document.all['comment_'+i].style.display = current;
	}
	//             name=       newgfx
	//MM_swapImage('Image1','','boxes_01.gif',1)
	MM_swapImage('comment_img_'+i,'','/asset/image/icon/expand_'+currentimg+'.gif',1);
}

function blocking_manual(i, change) {
	// change is either block or none. block means to turn on, none means hide.
	if (!supported)	{
		alert('Sorry, this link does not work in your browser.');
		return;
	}
	// change boolean state
	shown[i] = (change=="block") ? true : false;
	// set css display value
	if (document.getElementById) {
		document.getElementById('comment_'+i).style.display = change;
	}
	else if (document.all) {
		document.all['comment_'+i].style.display = change;
	}
	//             name=       newgfx
	//MM_swapImage('Image1','','boxes_01.gif',1)
	//MM_swapImage('comment_img_'+i,'','/asset/image/icon/expand_'+currentimg+'.gif',1);
}

function showSTLAdminMenu() 
{
	elem = returnObjById('admin_quick_links');
	//var changeto = 'block';
	//changeto = (elem.style.display == 'block') ? 'none' : 'block';
	//elem.style.display = changeto;

	//alert(elem.style.display);

	var load_the_data = false;
	if (elem.style.display != 'block')
		load_the_data = true;

	if (load_the_data)
		$jq("#admin_quick_links").html("<img src='/asset/image/misc/loading.gif' border='0' alt='loading' title='loading' width='150' height='150' align='middle' />");
	
	$jq("#admin_quick_links").toggle('blind', {} , 300);
	
	if (load_the_data)
	{
		$jq.post("/include/ajax/misc/admin/quickmenu.php"
			, {}
			, function(response) {
				// update status element
				if (response == 'failed')
					alert("Failed to update this field.");
				else 
					$jq("#admin_quick_links").html(response);
				//saveButtonToggle('enable');
			}
		);
	}

	return false;
}

function location_warning(locationID) {
	if (locationID == 7 || locationID == 5)
	{
		// ensure div shown
		blocking_manual(77777, 'block');
	}
	else
	{
		// ensure div is hidden
		blocking_manual(77777, 'none');
	}
}

function change_payment_method_box(change) {
	//document.form1.box_online.className='border_grey';
	//online.className='pay_method_grey';
	phone.className='pay_method_grey';
	invoice.className='pay_method_grey';
	change.className='pay_method_green';
}
function change_payment_method_box_online(change) {
	//document.form1.box_online.className='border_grey';
	online.className='pay_method_grey_no_pointer';
	phone.className='pay_method_grey_no_pointer';
	invoice.className='pay_method_grey_no_pointer';
	vouchers.className='pay_method_grey_no_pointer';
	change.className='pay_method_blue';
}
function elearning_quiz_answer_class(td, cb) {
	// td is table data cell; cb is checkbox
	//document.form1.box_online.className='border_grey';
	//alert(cb.checked);
	if (cb.checked)
		td.className='background_blue_subtle';
	else
		td.className='no_css_assigned';
}

function FormatNumber(num, decimalNum, bolLeadingZero, bolParens)
/* IN - num:            the number to be formatted
	   decimalNum:     the number of decimals after the digit
	   bolLeadingZero: true / false to use leading zero
	   bolParens:      true / false to use parenthesis for - num

  RETVAL - formatted number
*/
{
   var tmpNum = num;

   // Return the right number of decimal places
   tmpNum *= Math.pow(10,decimalNum);
   tmpNum = Math.floor(tmpNum);
   tmpNum /= Math.pow(10,decimalNum);

   var tmpStr = new String(tmpNum);

   // See if we need to hack off a leading zero or not
   if (!bolLeadingZero && num < 1 && num > -1 && num !=0)
	   if (num > 0)
		   tmpStr = tmpStr.substring(1,tmpStr.length);
	   else
		   // Take out the minus sign out (start at 2)
		   tmpStr = "-" + tmpStr.substring(2,tmpStr.length);                        


   // See if we need to put parenthesis around the number
   if (bolParens && num < 0)
	   tmpStr = "(" + tmpStr.substring(1,tmpStr.length) + ")";


   return tmpStr;
}

// pass in a number. if it's less than 10, string will be returned with leading '0' in front
function addLeadingZero(num) {
	if (num > 0 && num < 10)
		return '0'+num;
	else
		return num;
}
// pass in a date and a field to update, adds one day on
// format in and out always yyyy-mm-dd
function incrementDay(thedate) {
	var myDate=new Date();
	var datearray;
	if (thedate == '')
	{
		return '';
	}
	datearray = thedate.split("-");
	myDate.setFullYear(datearray[0],datearray[1],datearray[2]);
	myDate.setDate(myDate.getDate()+1);
	return myDate.getFullYear() + '-' + addLeadingZero(myDate.getMonth()) + '-' + addLeadingZero(myDate.getDate());
}

// authors : david wilcock and richard hallows, 2003 - 2004
// function emailDecode : anti-spam function
function emailDecode(inString) {
	outString = inString.split(" dot ").join(".");
	outString = outString.split(" at ").join("@");
	document.location = "mailto: " + outString;
}

// another e-mail decode function, different method, but similar
function mask(end,middle,start,subject){
var one ='mai';
var two='lto:';
var three='?Subject=';
//start,middle,end,subject;
var putogether= one+two+start+middle+end+three+subject;
document.location.href=eval('"'+putogether+'"');
window.status=putogether;
}

// Add row to table (rescheduling editor)
// original from http://www.mredkj.com/tutorials/tableaddrow.html
// Last updated 2007-11-10
// Updated by Rich Talbot
function addRowToTableResch(rate)
{
  var tablename = rate + '_table';
  var tbl = document.getElementById(tablename);
  // last row (minus 2 because the last 2 rows should always be Tail lowest and Tail ontheday 
  // (the last 2 rows are special)
  var lastRow = tbl.rows.length-2;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  row.className = 'tr_' + (iteration % 2) +'_list';
  
  // first cell
  var cellzero = row.insertCell(0);
  cellzero.className = 'tr_td';
  var reschedule_min = document.createElement('input');
  reschedule_min.type = 'text';
  reschedule_min.name = 'new[' + rate + '][' + iteration + '][min]';
  reschedule_min.size = 1;
  cellzero.appendChild(reschedule_min);

  var reschedule_to = document.createTextNode(' to ');
  cellzero.appendChild(reschedule_to);

  var reschedule_max = document.createElement('input');
  reschedule_max.type = 'text';
  reschedule_max.name = 'new[' + rate + '][' + iteration + '][max]';
  reschedule_max.size = 1;
  cellzero.appendChild(reschedule_max);
 
  // middle cell
  var cellone = row.insertCell(1);
  cellone.className = 'tr_td';
  var reschedule_reschedule = document.createElement('input');
  reschedule_reschedule.type = 'text';
  reschedule_reschedule.name = 'new[' + rate + '][' + iteration + '][reschedule]';
  reschedule_reschedule.size = 2;
  cellone.appendChild(reschedule_reschedule);
  var reschedule_percentage1 = document.createTextNode('%');
  cellone.appendChild(reschedule_percentage1);
  
  // last cell
  var celltwo = row.insertCell(2);
  celltwo.className = 'tr_td';
  var reschedule_cancellation = document.createElement('input');
  reschedule_cancellation.type = 'text';
  reschedule_cancellation.name = 'new[' + rate + '][' + iteration + '][cancellation]';
  reschedule_cancellation.size = 3;
  celltwo.appendChild(reschedule_cancellation);
  var reschedule_percentage2 = document.createTextNode('%');
  celltwo.appendChild(reschedule_percentage2);  
}
function removeRowFromTableResch(rate)
{
  var tablename = rate + '_table';
  var tbl = document.getElementById(tablename);
  var lastRow = tbl.rows.length;
  // must always be 4 rows in the table
  if (lastRow > 4) tbl.deleteRow(lastRow - 3);
}



// opens up a div smoothly on the page
// (from isoHunt)
var smooth_timer;
function smoothHeight(id, curH, targetH, stepH, mode) {
  diff = targetH - curH;
  if (diff != 0) {
    newH = (diff > 0) ? curH + stepH : curH - stepH;
    ((document.getElementById) ? document.getElementById(id) : eval("document.all['" + id + "']")).style.height = newH + "px";
    if (smooth_timer) window.clearTimeout(smooth_timer);
    smooth_timer = window.setTimeout( "smoothHeight('" + id + "'," + newH + "," + targetH + "," + stepH + ",'" + mode + "')", 16 );
  }
  else if (mode != "o") ((document.getElementById) ? document.getElementById(mode) : eval("document.all['" + mode + "']")).style.display="none";
}
function servOC(i, href) {
  var trObj = (document.getElementById) ? document.getElementById('ihtr' + i) : eval("document.all['ihtr" + i + "']");
  var ifObj = (document.getElementById) ? document.getElementById('ihif' + i) : eval("document.all['ihif" + i + "']");
  if (trObj != null) {
    if (trObj.style.display=="none") {
      ifObj.style.height = "0px";
      trObj.style.display="";
	  //if (!ifObj.src)  // do this if only want to load page into frame if nothing there
	  // otherwise load it in every time
      ifObj.src = href;
      smoothHeight('ihif' + i, 0, 210, 42, 'o');
    }
    else {
      smoothHeight('ihif' + i, 210, 0, 42, 'ihtr' + i);
	  //trObj.style.display = "none";
    }
  }
}

function in_array(needle, haystack, strict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
 
    var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}

function intval( mixed_var, base ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: stensi
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: intval('Kevin van Zonneveld');
    // *     returns 1: 0
    // *     example 2: intval(4.2);
    // *     returns 2: 4
    // *     example 3: intval(42, 8);
    // *     returns 3: 42
    // *     example 4: intval('09');
    // *     returns 4: 9
 
    var tmp;
 
    if( typeof( mixed_var ) == 'string' ){
        tmp = parseInt(mixed_var*1);
        if(isNaN(tmp) || !isFinite(tmp)){
            return 0;
        } else{
            return tmp.toString(base || 10);
        }
    } else if( typeof( mixed_var ) == 'number' && isFinite(mixed_var) ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}

function floatval(mixed_var) {
    // +   original by: Michael White (http://crestidg.com)
    // %        note 1: The native parseFloat() method of JavaScript returns NaN when it encounters a string before an int or float value.
    // *     example 1: floatval('150.03_page-section');
    // *     returns 1: 150.03
    // *     example 2: floatval('page: 3');
    // *     returns 2: 0
    // *     example 2: floatval('-50 + 8');
    // *     returns 2: -50
 
    return (parseFloat(mixed_var) || 0);
}

function hideQuoteMessage() {
	if ($jq.ajax({url: "/include/ajax/misc/hide-quote-message.php",
		success: function(response) {
			if (response == 'cleared')
				$jq(returnObjById('return_to_quote')).hide("slow");
				$jq('#placeholder_return_to_quote_uk_one').html("<a href=\"/training-provider.php\" title=\"uk's number 1 for microsoft office training\"><img src=\"/asset/image/header_footer/uk_number_1_ms_office_trans.png\" border=\"0\" alt=\"The UK's Number 1 for Microsoft Office Training\" /></a>");
		}
	}))
		return true;
}

function addLogItem(the_form_id) {
	//alert('The form id: ' + the_form_id);
	var what_to_return = false;
	$jq("#" + the_form_id + "_loading").show();
	$jq.ajax({type: "POST"
			, async: false
			, url: "/include/ajax/misc/admin-addlogitem.php"
			, data: $jq("#" + the_form_id).serialize()
			, success: function(response) {
				$jq("#" + the_form_id + "_loading").hide();
				if (response == 'failed')
				{
					alert("Failed to add the message.");
				}
				else
				{
					//alert("Added message okay.");
					//alert(response);
					$jq("#" + the_form_id + "_table tbody:first").prepend(response);
					$jq("#" + the_form_id + "_textarea").val("");
					$jq("#" + the_form_id + "_textarea").effect("highlight", 150);
				}
				//alert('returning false, as ajax query was successful');
				what_to_return = false;
			}
			, error: function(response) {
				//alert ('ajax failed, returning true so form submits');
				what_to_return = true;
			}
		 });
	return what_to_return;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

// similar to print_r
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}


function toggleYesNo(the_id, current_status, the_field, the_table) {
	//alert('The id: ' + the_id + "-  The status: " + current_status + "- The Field: " + the_field);
	toggleYesNoLoading(the_id, the_field);
	$jq.post("/include/ajax/misc/admin-view-toggle-yesno.php"
		, {the_table: the_table
			, the_field: the_field
			, the_id: the_id
			, current_status: current_status
		}
		, function(response) {
			// update status element
			if (response == 'failed')
				alert("Failed to update this field.");
			else 
				$jq("#changeYesNo_" + the_field + "_" + the_id).html(response);
			//saveButtonToggle('enable');
		}
	);
	return false;
}

function toggleYesNoLoading(the_id, the_field) {
	$jq("#changeYesNo_" + the_field + "_" + the_id).html("<img src='/asset/image/misc/loading2.gif' border='0' alt='loading' title='loading' width='15' height='15' align='middle' />");
}


/*
// Add row to table
// from http://www.mredkj.com/tutorials/tableaddrow.html
// Last updated 2006-02-21
function addRowToTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);
  
  // left cell
  var cellLeft = row.insertCell(0);
  var textNode = document.createTextNode(iteration);
  cellLeft.appendChild(textNode);
  
  // right cell
  var cellRight = row.insertCell(1);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'txtRow' + iteration;
  el.id = 'txtRow' + iteration;
  el.size = 40;
  
  el.onkeypress = keyPressTest;
  cellRight.appendChild(el);
  
  // select cell
  var cellRightSel = row.insertCell(2);
  var sel = document.createElement('select');
  sel.name = 'selRow' + iteration;
  sel.options[0] = new Option('text zero', 'value0');
  sel.options[1] = new Option('text one', 'value1');
  cellRightSel.appendChild(sel);
}
function removeRowFromTable()
{
  var tbl = document.getElementById('tblSample');
  var lastRow = tbl.rows.length;
  if (lastRow > 2) tbl.deleteRow(lastRow - 1);
}
*/

// other include files
// this causes errors in IE - if turning back on, ensure it doesn't cause errors any more!
//include ("/asset/script/behaviour.js");
//include ("/asset/script/ajaxstarrater.js");


