var ajaxRequest;

function ajaxFunction(){
 try{
   // Opera 8.0+, Firefox, Safari
   ajaxRequest = new XMLHttpRequest();
 }catch (e){
   // Internet Explorer Browsers
   try{
      ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
   }catch (e) {
      try{
         ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
      }catch (e){
         // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
}

function ajaxStart(func,url)
{
	ajaxFunction();
	ajaxRequest.onreadystatechange = func;
	ajaxRequest.open("GET", url, true);
   	ajaxRequest.send(null);
}


function approveBuyer(state,id)
{
	ajaxFunction();
	ajaxRequest.onreadystatechange = redisplayBuyerApprovalTable;
	var url = "ajax-approve-buyer.php?state=" + state + "&id=" + id;
	ajaxRequest.open("GET",url,true);
	ajaxRequest.send(null);
	showit();
}

function redisplayBuyerApprovalTable()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('buyer_approval_table').innerHTML = ajaxRequest.responseText;
		hideit();
	}
}






function searchsuppliers()
{
   	ajaxStart(processRequest,"/admin/search-suppliers-ajax.php?search=" + document.getElementById('search_for0').value);
}

function searchtenders(x)
{
	ajaxStart(processRequest, "/admin/search-tenders-ajax.php?search=" + document.getElementById('search_for0').value + "&start=" + x);
}

function processRequest()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('resultshereplease').innerHTML = ajaxRequest.responseText;
	}
}

// called from the map-cpv-category.php page
function codeAllocationSelectionChange()
{
	ajaxStart(updateSubCategories, "/admin/get-categories-ajax.php?cpv=" + document.getElementById('unallocated_codes').value);
}

function updateSubCategories()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('subcategories').innerHTML = ajaxRequest.responseText;	
		ajaxRequest.onreadystatechange = updateMappings;
		var url = "/admin/get-mappings-ajax.php?cpv=" + document.getElementById('unallocated_codes').value;
		ajaxRequest.open("GET", url, true);
	   	ajaxRequest.send(null);
	}
}

function updateMappings()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('mappings').innerHTML = ajaxRequest.responseText;	
	}
}

function allocateCode(code)
{
	// unallocated code refers to the cpv code
	// client code is dotgov
	ajaxStart(updateMappings,"/admin/set-mappings-ajax.php?cpv=" + document.getElementById('unallocated_codes').value + "&dotgov=" + document.getElementById('client_codes').value);
}

function deletemapping(cpv,dotgov)
{
	ajaxStart(updateMappings, "/admin/delete-mappings-ajax.php?cpv=" + cpv + "&dotgov=" + dotgov);
}

function changeSelectionType()
{
	// change from allocated to unallocated codes or vice versa
	var url;
	if (document.getElementById('rad_allocated').checked == true)
	{
		url = "/admin/cpv-codes-ajax.php?show=allocated";
	}
	else
	{
		url = "/admin/cpv-codes-ajax.php?show=unallocated";
		
	}
	ajaxStart(updateCPVlist,url);
}

function updateCPVlist()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('radioSelect').innerHTML = ajaxRequest.responseText;	
		document.getElementById('subcategories').innerHTML = "";
		document.getElementById('mappings').innerHTML = "";
	}
}

function showit()
{
	OAT.Dimmer.show('dimmer_content', {color:"#99f", popup:false});
}
function hideit()
{
	OAT.Dimmer.hide();
	document.getElementById('mainID').style.display = 'block';
}


function tickerupdate()
{
	ajaxStart(savedTickerText, "/admin/tt/ticker-update-ajax.php?content=" + document.getElementById('tickertext').value);//
}


function savedTickerText()
{
	if (ajaxRequest.readyState == 4)
	{	
		alert(ajaxRequest.responseText);	
		// now reload the page 
		window.location.href=window.location.href;
	}
}

function addTradeCode()
{
	ajaxStart(replaceTradeCodeList, "/admin/codes/trade-code-add-ajax.php?content=" + document.getElementById('inputbox').value);
}

function tradecodedeleteConfirmed()
{
	ajaxStart(replaceTradeCodeList, "/admin/codes/trade-code-delete-ajax.php?id=" + deleteID);
	// call the cancel delete function to redisplay the cotents of the page
	canceldelete();
}

var deleteID,deleteText;

function tradecodedelete(x,y)
{
	// called when a user initially clicks the delete link for an item 
	// displays the confirm or cancel option
	document.getElementById('tradecode').style.display = 'none';
	document.getElementById('addtradecode').style.display = 'none';
	document.getElementById('edittradecode').style.display = 'none';
	document.getElementById('deletetradecode').style.display = 'block';
	deleteID 	= x;
	deleteText 	= y;
	document.getElementById('spandeleteid').innerHTML = y;
}

function canceldelete()
{
	document.getElementById('tradecode').style.display = 'block';
	document.getElementById('addtradecode').style.display = 'block';
	document.getElementById('edittradecode').style.display = 'none';
	document.getElementById('deletetradecode').style.display = 'none';
}


function replaceTradeCodeList()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('tradecode').innerHTML = ajaxRequest.responseText;
		document.getElementById('inputbox').value = '';		
	}
}

function tradecodeedit(x,y)
{
	document.getElementById('tradecode').style.display = 'none';
	document.getElementById('addtradecode').style.display = 'none';
	document.getElementById('edittradecode').style.display = 'block';
	document.getElementById('deletetradecode').style.display = 'none';
	// save for later event
	deleteID 	= x;
	deleteText 	= y;
	// transfer the contents here .....
	document.getElementById('editbox').value = y;
}

function saveEditTradeCode()
{
	ajaxStart(replaceTradeCodeList,"/admin/codes/trade-code-edit-ajax.php?id=" + deleteID + "&content=" + document.getElementById('editbox').value);
	// call the cancel delete function to redisplay the cotents of the page
	canceldelete();
}

// used on the add user page 
function toggleRegion()
{
	if (document.getElementById('national').value == 1)
	{
		document.getElementById('region').disabled = true;
	}
	else
	{
		document.getElementById('region').disabled = false;
	}
}
function parent_change()
{
	if (document.getElementById('groupX').checked == true)
	{
		document.getElementById('supplier_name_select').disabled = true;
	}
	else
	{
		document.getElementById('supplier_name_select').disabled = false;
	}
}

function billing_change()
{
	if (document.getElementById('groupY').checked == true)
	{
		changeBillingAddress(true)
		copyAddress();
	}
	else
	{
		changeBillingAddress(false)
	}
}

function changeBillingAddress(x)
{
	document.getElementById('billing_address1').disabled = x;
	document.getElementById('billing_address2').disabled = x;
	document.getElementById('billing_address3').disabled = x;
	document.getElementById('billing_address4').disabled = x;
	document.getElementById('billing_address5').disabled = x;
	document.getElementById('billing_town').disabled = x;
	document.getElementById('billing_county').disabled = x;
	document.getElementById('billing_postcode').disabled = x;
}

function copyAddress()
{
	copyAddressLine('address1');
	copyAddressLine('address2');
	copyAddressLine('address3');
	copyAddressLine('address4');
	copyAddressLine('address5');
	copyAddressLine('town');
	copyAddressLine('county');
	copyAddressLine('postcode');
}
function copyAddressLine(x)
{
	document.getElementById('billing_' + x).value = document.getElementById('main_' + x).value;
}
function addressFieldChange(field)
{
	
	if (document.getElementById('groupY').checked == true)
	{
		//copy the contents
		copyAddressLine(field.replace("main_",""));
	}
}





function accesscontrolchange(x)
{
	// screen has changed
	// update the database
	ajaxStart(testtesttest,"/admin/um/access-control-ajax.php?id=" + x + "&value=" + document.getElementById('checkBox' + x).checked);
}

function testtesttest()
{
	if (ajaxRequest.readyState == 4)
	{	
		//alert(ajaxRequest.responseText);
	}
}


function displaytradesintrades()
{
	var tradeID = document.getElementById('selecttradelist').value;
	ajaxStart(update_resultsarea, "/buyers/ajax-show-suppliers.php?by=trade&id=" + tradeID);
}

function displaytradesinarea()
{
	var areaID = document.getElementById('selectarealist').value;
	ajaxStart(update_resultsarea, "/buyers/ajax-show-suppliers.php?by=area&id=" + areaID);
}

function update_resultsarea()
{
	if (ajaxRequest.readyState == 4)
	{	
		//alert(ajaxRequest.responseText);
		document.getElementById('resultsarea').innerHTML = ajaxRequest.responseText;
	}
}


function deleteemailaddress(user,record)
{
	ajaxStart(update_extraemails, "ajax-delete-email-address.php?user=" + user + "&record=" + record);
}
function add_email(user)
{
	ajaxStart( update_extraemails, "ajax-add-email-address.php?user=" + user + "&email=" + document.getElementById('new_email').value);
}

function update_extraemails()
{
	if (ajaxRequest.readyState == 4)
	{	
		//alert(ajaxRequest.responseText);
		document.getElementById('extra_emails').innerHTML = ajaxRequest.responseText;
	}
}
function add_email(user)
{
	ajaxStart(update_extraemails, "ajax-add-email-address.php?user=" + user + "&email=" + document.getElementById('new_email').value);
}

function deletetrade(user,record)
{
	ajaxStart(update_trade_categories, "ajax-delete-trade.php?user=" + user + "&record=" + record);
}

function add_trade(user)
{
	ajaxStart(update_trade_categories, "ajax-add-trade.php?user=" + user + "&trade=" + document.getElementById('trade_list_select').value);
}

function update_trade_categories()
{
	if (ajaxRequest.readyState == 4)
	{	
		//alert(ajaxRequest.responseText);
		document.getElementById('trade_categories').innerHTML = ajaxRequest.responseText;
	}
}

function natlocalchange()
{
	if (document.getElementById('natorlocal').value == 0)
	{
		document.getElementById('region').style.visibility = 'visible';
		document.getElementById('region').style.display = 'block';
	}
	else
	{
		document.getElementById('region').style.visibility = 'hidden';
		document.getElementById('region').style.display = 'none';
	}
}

function toggle(show,tochange,title,nr)
{
	nr = (nr%2)+1;
	var htmlreplace = "<a href='javascript:toggle(\"" + show + "\", \"" + tochange + "\",\"" + title + "\"," + nr + ")'><img src='/_images/arrow" + nr + ".gif' border='0' />"+ title + "</a>";
	//alert(var);
	if (nr == 1)
	{
		document.getElementById(show).style.display = 'block';
		//alert("<a href='javascript:toggle('" + show + "', '" + tochange + "','" + title + "'," + nr + ")'><img src='/_images/arrow" + nr + ".gif' border='0' />"+ title + "</a>");
		document.getElementById(tochange).innerHTML = htmlreplace;
	}
	else
	{
		//document.getElementById(show).style.display= '';
		document.getElementById(show).style.display = 'none';
		document.getElementById(tochange).innerHTML = htmlreplace;
	}
}

function display_tender()
{
if (ajaxRequest.readyState == 4)
	{	
		//alert(ajaxRequest.responseText);
		document.getElementById('mainID').style.display = 'none';
		document.getElementById('dimmer_content').innerHTML = ajaxRequest.responseText;
		document.getElementById('dimmer_content').className = 'centered2';
	}
}

function dtdnameupdate(x)
{
	var url;
	if ( document.getElementById('checkbox' + x).checked == true)
	{
		url = "ajax-display-categories.php?id=" + x + "&inuse=1";
	}
	else
	{
		url = "ajax-display-categories.php?id=" + x + "&inuse=0";
	}
	ajaxStart(null,url);
}

function tradesmansearch()
{
	ajaxStart(tradesmansearchresults, "/ajax-tradesman-search.php?postcode=" + document.getElementById('postcode').value + "&trade="  + document.getElementById('trade_list_select').value);
}

function tradesmansearchresults()
{
if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('tradesmansearchresults').innerHTML = ajaxRequest.responseText;
	}
}

function approvetestimonial(x)
{
	ajaxStart(testimonialchange, "ajax-testimonial-change.php?id=" + x + "&approve=1");
}
function rejecttestimonial(x)
{
	ajaxStart(testimonialchange,"ajax-testimonial-change.php?id=" + x + "&approve=2");
}
function pendtestimonial(x)
{
	ajaxStart(testimonialchange, "/admin/ajax-testimonial-change.php?id=" + x + "&approve=0");
}
function testimonialchange()
{
	if (ajaxRequest.readyState == 4)
	{	
		var x= ajaxRequest.responseText;
		document.getElementById('tstmnl' + x).innerHTML = '';
	}
}

function areachange(loc,sup)
{
	ajaxStart( null,"ajax-edit-locations.php?supplier=" + sup + "&location=" + loc + "&checked=" + document.getElementById(loc).checked);
}

function reportit()
{
	if (ajaxRequest.readyState == 4)
	{	
		alert(ajaxRequest.responseText);
	}
}

function approveSupplier(state,id)
{
	ajaxStart(redisplaySupplierApprovalTable, "ajax-approve-supplier.php?state=" + state + "&id=" + id);
	showit();
}

function redisplaySupplierApprovalTable()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('supplier_approval_table').innerHTML = ajaxRequest.responseText;
		hideit();
	}
}

function emailAddressCheck(str) 
{

	var at = "@"
	var dot = "."
	var lat = str.indexOf(at)
	var lstr = str.length
	var ldot = str.indexOf(dot)
	
	if (str.indexOf(at)==-1)
	{
	   alert("Invalid E-mail Address")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
	   alert("Invalid E-mail Address")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
		alert("Invalid E-mail Address")
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1)
	 {
		alert("Invalid E-mail Address")
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	 {
		alert("Invalid E-mail Address")
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1)
	 {
		alert("Invalid E-mail Address")
		return false
	 }
	
	 if (str.indexOf(" ")!=-1)
	 {
		alert("Invalid E-mail Address")
		return false
	 }

	 return true					
}

function validateData()
{
	// check the fields before allowing a post
	if (false == emailAddressCheck(document.dotgov_supplier_signup_form.email_address.value))
	{return;}
	
	if (5 > document.dotgov_supplier_signup_form.name.value.length)
	{
		alert('Please enter Company Name');
		return;
	}
	if (3 > document.dotgov_supplier_signup_form.contact.value.length)
	{
		alert('Please enter a contact name');
		return;
	}
	if (8 > document.dotgov_supplier_signup_form.phone.value.length)
	{
		alert('Please enter a full telephone number including dialing code');
		return;
	}
	if (5 > document.dotgov_supplier_signup_form.address1.value.length)
	{
		alert('Please enter address');
		return;
	}
	if (5 > document.dotgov_supplier_signup_form.postcode.value.length)
	{
		alert('Please enter a postcode');
		return;
	}	
	if (2 > document.dotgov_supplier_signup_form.town.value.length)
	{
		alert('Please enter a town');
		return;
	}	
	if (5 > document.dotgov_supplier_signup_form.county.value.length)
	{
		alert('Please enter a county');
		return;
	}	
	if (5 > document.dotgov_supplier_signup_form.password1.value.length)
	{
		alert('Please enter a longer password');
		return;
	}	
	if (document.dotgov_supplier_signup_form.password1.value != document.dotgov_supplier_signup_form.password2.value)
	{
		alert('Passwords do not match');
		return;
	}	
	
	// check the email is unique
	if (checkEmailUnique(document.dotgov_supplier_signup_form.email_address.value) )
	{
		alert('Email address must be unique');
		return;
	}
	
	document.dotgov_supplier_signup_form.submit();
}

function checkEmailUnique(email)
{
	// synchronous!
	ajaxFunction();
	var url = "ajax-test-email.php?address=" + email;
	ajaxRequest.open("GET",url,false);
	ajaxRequest.send(null);
	if( "duplicate" == ajaxRequest.responseText)
	{
		return true;
	}
	else
	{
		return false;
	}
}

function buyertender(action,id)
{
	ajaxStart(redisplayBuyerTenderTable, "/buyers/ajax-approve-tender.php?action=" + action + "&id=" + id);
	showit();
}

function redisplayBuyerTenderTable()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('buyertendertable').innerHTML = ajaxRequest.responseText;
		hideit();
	}
}

function saveproducttable()
{
	alert('in saveproducttable');
	var query = "";
	var name = "";
	for(i=0; i < document.forms[0].elements.length; i++)
	{
		name = document.forms[0].elements[i].name;
		if ( name != "undefined")
		{
			// build the query string
			if (i > 0)	{	query = query + "&"; }
			if (document.forms[0].elements[i].name.indexOf("display") > 1)
			{	
				query = query + name + "=" + document.forms[0].elements[i].checked;
			}else
			{	query = query + name + "=" + htmlEncode(document.forms[0].elements[i].value); }
		}
	}
	ajaxStart(saveproducttableresponse,"ajax-store-table.php?" + query);
}

function saveproducttableresponse()
{
	if (ajaxRequest.readyState == 4)
	{	
		ajaxStart(saveproducttableresponseresponse, "ajax-get-product-table.php");
	}
}

function saveproducttableresponseresponse()
{
	if (ajaxRequest.readyState == 4)
	{	
		document.getElementById('producttable').innerHTML = ajaxRequest.responseText;
		alert ('Saved');
	}
}

function addproducttotable()
{
	var query = "title=" + htmlEncode(document.getElementById('new_title').value);
	query = query + "&description=" + htmlEncode(document.getElementById('new_description').value);
	query = query + "&order=" + htmlEncode(document.getElementById('new_order').value);
	query = query + "&price=" + htmlEncode(document.getElementById('new_price').value);
	ajaxStart(addproducttotableresponse, "ajax-add-product-table.php?" + query);
}

function addproducttotableresponse()
{
	if (ajaxRequest.readyState == 4)
	{
		document.getElementById('new_price').value = "";
		document.getElementById('new_order').value = "";
		document.getElementById('new_description').value = "";
		document.getElementById('new_title').value = "";
		document.getElementById('producttable').innerHTML = ajaxRequest.responseText;
	}
}

function htmlEncode(s) 
{
	var str = new String(s);
	str = str.replace(/&/g, "&amp;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	str = str.replace(/"/g, "&quot;");
	return str;
} 

function salesreportA()
{
	ajaxStart(showsalesreport, "ajax-get-sales-report.php?salesperson=" + document.getElementById('salesperson').value + "&from=" + document.getElementById('from').value + "&to=" + document.getElementById('to').value);
}

function showsalesreport()
{
	if (ajaxRequest.readyState == 4)
	{
		document.getElementById('salesreport').innerHTML = ajaxRequest.responseText;
	}
}

function displaylogs()
{
	ajaxStart(displayreturnedlogs, "ajax-show-logs.php?id=" + document.getElementById('logperson').value);
}

function displayreturnedlogs()
{
	if (ajaxRequest.readyState == 4)
	{
		document.getElementById('logs').innerHTML = ajaxRequest.responseText;
	}
}

function getTradeCodeByCPVCode()
{
	ajaxStart(displayTradeCodeResults, "ajax-get-trade-codes.php?cpv=" + document.getElementById('cpvcode').value);
}

function displayTradeCodeResults()
{
	if (ajaxRequest.readyState == 4)
	{
		document.getElementById('results').innerHTML = ajaxRequest.responseText;
	}
}

function getCPVCodeByTradeCode()
{
	ajaxStart(displayTradeCodeResults, "ajax-get-cpv-codes.php?trade=" + document.getElementById('tradecode').value);
}

function deleteMappedCPVCode(cpv,dotgov)
{
	ajaxStart(displayTradeCodeResults, "ajax-delete-mapped-cpv-codes.php?cpv=" + cpv + "&trade=" + dotgov);
}

function displaySubRegions()
{
	if (ajaxRequest.readyState == 4)
	{
		document.getElementById('results').innerHTML = ajaxRequest.responseText;
	}
}

function ccsearch()
{
	ajaxStart(displayCreditCardResults, "ajax-get-credit-cards.php?number=" + document.getElementById('ccno').value);
}

function displayCreditCardResults()
{
	if (ajaxRequest.readyState == 4)
	{
		document.getElementById('results').innerHTML = ajaxRequest.responseText;
	}
}
