// config stuff...
var hi_lite_col='#DDDDDD';
var lo_lite_col='';
var pref_on_col='#ceffd3';
var pref_off_col='#F6F6F6';
var query_array = new Array();
var searchReady=false;
var contacts=0;
var emails=0;
var phones=0;
var faxes=0;
var firsttime=1;

var max_records=0; // Not 0 as in no records, 0 as in false, silly!]

function hi_lite(ele) { gO(ele.id).style.backgroundColor=hi_lite_col; }
function un_hi_lite(ele) { gO(ele.id).style.backgroundColor=lo_lite_col; }
//function showOps(ele) { gO(ele+'_ops').style.visibility='visible'; gO(ele+'_ops').style.display='block'; gO(ele+'_text_def').style.visibility='hidden'; gO('pref_'+ele+'_on').checked='checked';  gO(ele+"_sw_div").style.backgroundColor=pref_on_col; gO(ele+"_ops").style.backgroundColor=pref_on_col;}
function showOps(ele) { gO(ele+'_ops').style.visibility='visible'; gO(ele+'_ops').style.display='block'; gO(ele+"_ops").style.backgroundColor=pref_on_col;}
//function hideOps(ele) { gO(ele+'_ops').style.visibility='hidden'; gO(ele+'_ops').style.display='none'; gO(ele+'_text_def').style.visibility='visible'; gO(ele+"_sw_div").style.backgroundColor=pref_off_col;}

function findRowMkSec(needle,a_haystack,res_div)
{
	var X = getPositionLeft(document.getElementById('mktsec_search'));
	var Y = getPositionTop(document.getElementById('mktsec_search'))+20;

	gO(res_div).style.display='none';
	gO(res_div).innerHTML='<em>no results</em>';
	showSelectBox('select_area_type');
	showSelectBox('area_county');
	if(needle.length>2)
	{
		needle = needle.toLowerCase();
		var listDef='<em>no results</em>';
// 		proto_search_area.getContent().update(listDef);
		var list='';
		var craplist=''
		var mkSecCount=0;
		var foundRes=false;
		gO(res_div).style.display='inline';
		for(i=0;i<=mksecs_arrcount;i++)
		{ 
			var str=mksecs[i];
			if (str!=null)
			{
				foundRes=true;
				str=str.toLowerCase();
				var found=str.indexOf(needle);
				if (found==0) { mkSecCount++; list+="<span class='srch_hi' id='mksekres_"+i+"' onMouseOver='hi_lite(this)' onMouseOut='un_hi_lite(this)' onClick='selectInd(\"type_of_businesses\","+i+")'>"+mksecs[i]+"</span>"; } 
				else
					{
					var found=str.match(" " + needle);
					if (found!=null) { mkSecCount++; craplist+="<span class='srch_hi' id='mksekres_"+i+"' onMouseOver='hi_lite(this)' onMouseOut='un_hi_lite(this)' onClick='selectInd(\"type_of_businesses\","+i+")'>"+mksecs[i]+"</span>"; } 
					}

			} 
		}
		list = list + craplist;
		if (mkSecCount>3) { hideSelectBox('select_area_type'); }
		if (mkSecCount>5) { hideSelectBox('area_county'); }
		if (mkSecCount==0) { list=listDef; }
		gO(res_div).innerHTML=list;
		gO(res_div).style.left = X + 'px';
		gO(res_div).style.top = Y + 'px';
	}
}


function hideSelectBox(ele)
{
	gO(ele).style.visibility='hidden';	
}

function showSelectBox(ele)
{
	gO(ele).style.visibility='visible';	
}

function findRowMkAreaTown(needle,a_haystack,res_div)
{
	var X = getPositionLeft(document.getElementById('area_search_option'));
	var Y = getPositionTop(document.getElementById('area_search_option'))+20;

	gO(res_div).style.display='none';
	var listDef='<span id=\'mk_area_sel_span_0\' class=\'srch_hi\'><em>no results</em></span>';
	gO(res_div).innerHTML=listDef;
//	proto_search_area.getContent().update(listDef);
	showSelectBox('select_area_type');
	if(needle.length>2)
	{
		needle=needle.toLowerCase();
		var list='';
		var craplist='';
		var mkTownCount=0;
		gO(res_div).style.display='inline';
		showSelectBox('search_area_towns'); 
		for(i=0;i<=mkAreaTowns_arrcount;i++)
		{ 
			var str=mkAreaTowns[i];
			if (str!=null)
			{
				str=str.toLowerCase();
				var found=str.indexOf(needle);
				if (found==0) { mkTownCount++; list+="<span id='mk_area_sel_span_"+i+"' class='srch_hi' onMouseOver='hi_lite(this)' onMouseOut='un_hi_lite(this)' onClick='selectArea(\"area_search_option\",\""+mkAreaTowns[i]+"\",\"mk_area_sel_span_"+i+"\",true)'>"+mkAreaTowns[i]+"</span>"; } 
				else
					{
					var found=str.match(" " + needle);
					if (found!=null) { mkTownCount++; craplist+="<span id='mk_area_sel_span_"+i+"' class='srch_hi' onMouseOver='hi_lite(this)' onMouseOut='un_hi_lite(this)' onClick='selectArea(\"area_search_option\",\""+mkAreaTowns[i]+"\",\"mk_area_sel_span_"+i+"\",true)'>"+mkAreaTowns[i]+"</span>"; } 
					}
			}
		}
	list = list + craplist;
	if (mkTownCount==0) { list=listDef; }
	gO(res_div).innerHTML=list;
	gO(res_div).style.left = X + 'px';
	gO(res_div).style.top = Y + 'px';
	}
}

function findRowMkAreaCounty(needle,a_haystack,res_div)
{
	var X = getPositionLeft(document.getElementById('county_search_option'));
	var Y = getPositionTop(document.getElementById('county_search_option'))+20;

	var listDef='<span id=\'mk_area_sel_span_0\' class=\'srch_hi\'><em>no results</em></span>';
	gO(res_div).innerHTML=listDef;
	gO(res_div).style.display='none';
/*	proto_search_area.getContent().update(listDef);*/
//	showSelectBox('area_county');
	if(needle.length>2)
	{
	needle=needle.toLowerCase();
	var list='';
	var craplist = '';
	var mkAreaCount=0;
	gO(res_div).style.display='inline';
//	hideSelectBox('area_county');
	showSelectBox('search_area_counties'); 
	for(i=0;i<=mkAreaCoun_arrcount;i++)
	{ 
		var str=mkAreaCoun[i];
		if (str!=null)
		{
			str=str.toLowerCase();
			var found=str.indexOf(needle);
			if (found==0) { mkAreaCount++; list+="<span id='mk_area_sel_span_"+i+"' class='srch_hi' onMouseOver='hi_lite(this)' onMouseOut='un_hi_lite(this)' onClick='selectAreaCounty(\"area_search_option\",\""+mkAreaCoun[i]+"\",\"mk_area_sel_span_"+i+"\",true)'>"+mkAreaCoun[i]+"</span>"; } 
			else
				{
				var found=str.match(needle);
				if (found!=null) { mkAreaCount++; list+="<span id='mk_area_sel_span_"+i+"' class='srch_hi' onMouseOver='hi_lite(this)' onMouseOut='un_hi_lite(this)' onClick='selectAreaCounty(\"area_search_option\",\""+mkAreaCoun[i]+"\",\"mk_area_sel_span_"+i+"\",true)'>"+mkAreaCoun[i]+"</span>"; } 
				}
		}
	}
	list = list + craplist;
	if (mkAreaCount==0) { list=listDef; }
	gO(res_div).innerHTML=list;
	gO(res_div).style.left = X + 'px';
	gO(res_div).style.top = Y + 'px';
	}
}

function gO(ele) { return document.getElementById(ele); }

function selectInd(sel_id,id)
{
	gO(sel_id).value=id;
	gO("mksec_hid").value=mksecs[id];
	gO("search_res").style.display='none';
	gO("serviceType").value=gO(sel_id).options[gO(sel_id).selectedIndex].text;
	showSelectBox('select_area_type');
	showSelectBox('area_county');
	buildQuery();
}

function selectArea(sel_id,id)
{
	//gO(sel_id).innerHTML=(conc)?gO(sel_id).innerHTML+value:value;
	gO('coLocation').value=mkAreaTowns[id];
	gO("search_area_towns").innerHTML='';
	gO("area_hid").value=mkAreaTowns[id];
	hideSelectBox('search_area_towns'); 
	buildQuery();
}

function selectAreaCounty(sel_id,id)
{

	gO('area_county').value=id;
	gO("area_hid").value=mkAreaCoun[id];
	gO('companyName').value=gO('area_county').options[gO('area_county').selectedIndex].text;
	gO("search_area_counties").innerHTML='';
	showSelectBox('area_county');
	hideSelectBox('search_area_counties'); 
	buildQuery();
}

function selectAreaType()
{
	arType=gO("select_area_type").value;
	switch(arType)
	{
		case 'the UK (Whole)':
		gO("area_search_option").style.display='none';
		gO("search_area_county_div").style.display='none';
		gO("search_area_town_div").style.display='none';
		gO("search_area_counties").style.display='none';		
		gO("search_area_towns").style.display='none';	
		gO('area_hid').value='the UK (Whole)';
		gO('area_search_option').value='';
		gO('area_county').selectedIndex=0;

		buildQuery();	
		break;
		case 'county':
		gO("area_search_option").style.display='none';
		gO("search_area_county_div").style.display='inline';
		gO("search_area_town_div").style.display='none';
		gO("search_area_counties").style.display='none';		
		gO("search_area_towns").style.display='none';	
		gO('area_search_option').value='';
		buildQuery();
		break;
		case 'town':
		gO("area_search_option").style.display='inline';
		gO("search_area_county_div").style.display='none';
		gO("search_area_town_div").style.display='inline';
		gO("search_area_counties").style.display='none';		
		gO("search_area_towns").style.display='none';	
		gO('area_county').selectedIndex=0;
		buildQuery();
		break;
	}
}

function initPage()
{
	gO("select_area_type").value= (window.TownOrCounty?window.TownOrCounty:'the UK (Whole)');
	selectAreaType();
	gO("area_search_option").value=location;
	gO('mksec_hid').value='';
	//gO("pref_prefs_off").checked='checked';
	//gO("pref_size_off").checked='checked';
	//gO("pref_esta_off").checked='checked';
	//gO("pref_turn_off").checked='checked';

	if (!window.TownOrCounty)
		{
		gO('area_hid').value='the UK (Whole)';
		gO("area_county").value='0';
		}

	if (!window.business)
		gO("type_of_businesses").value="0";


	if (!window.TownOrCounty && !window.business)
		gO("search_desc").innerHTML='<em>please fill out all the search criteria above.</em>';
}

function setPrefsServs(sense)
{
	gO("op_tps").checked=sense;
	gO("op_ctps").checked=sense;
	gO("op_fps").checked=sense;
}

function buildQuery()
{
	var mksec_q=(gO("mksec_hid").value)?gO("mksec_hid").value:'';;
	var mkarea_q=(gO("area_hid").value)?gO("area_hid").value:'';
	
	// prefs
	var not_tps=(gO("op_tps").checked==true)?'TPS':'';
	var not_ctps=(gO("op_ctps").checked==true)?(not_tps)?' or CTPS':'CTPS':'';
	var not_fps=(gO("op_fps").checked==true)?((not_tps||not_ctps)&&(!not_fps))?' or FPS':'FPS':'';
	//var search_ops_prefs=((gO("pref_prefs_on").checked==true)&&(not_tps||not_ctps||not_fps))?' that are <u>not</u> in the '+not_tps+not_ctps+not_fps:'';
	
	// workforce size
	//var search_work_size=(gO("pref_size_on").checked==true&&gO("emp_size").value.length>0)?', with a workforce size '+gO("emp_size_ord").value+' than '+gO("emp_size").value+' employees':'';
	
	// established
	//var search_esta=(gO("pref_esta_on").checked==true&&gO("bus_est_years").value.length>0)?', which have been established for '+gO("bus_est_ord").value+' than '+gO("bus_est_years").value+' years':'';
	
	// turnover
	//var search_turn=(gO("pref_turn_on").checked==true&&gO("bus_turnover_pounds").value.length>0)?' and have an annual turnover '+gO("bus_turnover_ord").value+' than &pound;'+gO("bus_turnover_pounds").value:'';

	// not enough criteria
	if (mksec_q==''||mkarea_q=='') 
	{ 
		query='<em>please fill out all the search criteria above.</em>';
		searchReady=false; 
	} else // we've got enough data...
	{
		query=mksec_q+" in "+mkarea_q; //+search_ops_prefs+search_work_size+search_esta+search_turn+'.';
		
		query_array['mksec']=gO('type_of_businesses').value;
		query_array['mkarea']=mkarea_q;
		if(gO("op_tps").checked==true) { query_array['not_tps']='true'; } else { query_array['not_tps']=null; }
		if(gO("op_ctps").checked==true) { query_array['not_ctps']='true'; } else { query_array['not_ctps']=null; }  
		if(gO("op_fps").checked==true) { query_array['not_fps']='true'; } else { query_array['not_fps']=null; }

		query_array['bands_all'] = (gO('bandsall') == null || gO('bandsall').checked?1:0);
		if (query_array['bands_all'] == 0)
			{
			query_array['bands'] = new Array();
			query_array['bandsa'] = gO('bandsa').checked?1:0;
			query_array['bandsb'] = gO('bandsb').checked?1:0;
			query_array['bandsc'] = gO('bandsc').checked?1:0;
			query_array['bandsd'] = gO('bandsd').checked?1:0;
			query_array['bandse'] = gO('bandse').checked?1:0;
			query_array['bandsf'] = gO('bandsf').checked?1:0;
			query_array['bandsg'] = gO('bandsg').checked?1:0;
			query_array['bandsh'] = gO('bandsh').checked?1:0;
			query_array['bandsi'] = gO('bandsi').checked?1:0;
			}

	//	if(search_work_size.length>0&&gO("pref_size_on").checked==true) { query_array['work_size']=gO("emp_size_ord").value+'|'+gO("emp_size").value; } else { query_array['work_size']=null; }
	//	if(search_esta.length>0&&gO("pref_esta_on").checked==true) { query_array['comp_esta']=gO("bus_est_ord").value+'|'+gO("bus_est_years").value; } else { query_array['comp_esta']=null; }
	//	if(search_turn.length>0&&gO("pref_turn_on").checked==true) { query_array['comp_turn']=gO("bus_turnover_ord").value+'|'+gO("bus_turnover_pounds").value; } else { query_array['comp_turn']=null; }
		
		searchReady=true;
	}
	if(gO("search_desc"))
		{
		gO("search_desc").innerHTML=query;
		gO('count_results').innerHTML = '';
		}
	gO('search_res').style.display="none";
	gO('search_area_counties').style.display="none";
	gO('search_area_towns').style.display="none";
}

function performCountSearch()
{
	if(searchReady==true)
	{
		max_records = '';
		// set searching graphic
		setSearchGr();
		//hide the extra info div
		document.getElementById('extra_info').style.display = "none";

		// assemble call
		url='_includes/process.php';
		query_array['action']='countSearch';
		query_array['list_desc']=gO("search_desc").innerHTML;
		//alert(query_array['list_desc']);
		apilite_get(url,query_array,"searchReturned",'',"searchFailed",'');
	}
}

function searchReturned(response)
{
	// unset searching graphic
	unsetSearchGr();
	//alert("SUCCESS: "+response);
	items=response.split("\n");
	firsttime=1;
 	if (response!=0) 
		{
		countText="<div margin-top:8px;' style='border-top:1px dashed #999999;'>\n"
		+ "<div style='float:right; margin-top:10px;'><a href='javascript:get_cust_type()' onmouseover='MM_swapImage(\"apply\",\"\",\"_includes/images/butt_apply_on.gif\",1)' onmouseout='MM_swapImgRestore()'>"
		+ "<img src='_includes/images/butt_apply_off.gif' id='apply' border=0></a></div>"
		+ "<div style='float:right; margin-top:10px;'>Promo Code: <input type='text' size='10' id='promo' onChange='get_cust_type(this.value);'>&nbsp;</div>"
		+ "<p><strong>5. Filter your results</strong><br>\n"
		+ "We have found "+items[0]+" records that match your search.</p>\n"
		+ "<div id='processing_search' style='display:none'><strong><em>...Processing</em></strong></div>"
		+ "<div style='float:right'>&pound;<span id='address_div'></span></div>"
		+ "<div><input name='address' id='address' type=checkbox value=1 checked disabled>\n"
		+ "Include Business Name &amp; Address* (<span style='color:green;'><span id='num_addresses'></span> Addresses at <span id='ppr'>" + price_per_record + "</span>p</span>).</div>\n"
		+ "<div style='float:right;'>&pound;<span id='contact_div'></span></div>"
		+ "<div><input name='name' id='name' type=checkbox value=1 onclick=\"toggle_options('Name',this.checked);\">"
		+ "Include Contact Name (<span style='color:green;'><span id='num_contacts'></span> names at <span id='pc'>" + price_contact + "</span>p</span>).</div>\n"
		+ "<div style='float:right'>&pound;<span id='email_div'></span></div>"
		+ "<div><input name='email' id='email' type=checkbox value=1 onclick=\"toggle_options('Email',this.checked);\">"
		+ "Include Email Addresses (<span style='color:green;'><span id='num_emails'></span> email addresses at <span id='pe'>" + price_email + "</span>p</span>).</div>\n"
		+ "<div style='float:right;'>&pound;<span id='phone_div'></span></div>"
		+ "<div><input type=checkbox name='phone' id='phone' value=1 onclick=\"toggle_options('Phone',this.checked);\">"
		+ "Include Telephone Numbers (<span style='color:green;'><span id='num_phones'></span> telephone numbers at <span id='pp'>" + price_phone + "</span>p</span>).</div>\n"
		+ "<div style='float:right;'>&pound;<span id='fax_div'></span></div>"
		+ "<div><input name='fax' id='fax' type=checkbox value=1 onclick=\"toggle_options('Fax',this.checked);\">"
		+ "Include Fax Numbers (<span style='color:green;'><span id='num_faxes'></span> fax numbers at <span id='pf'>" + price_fax + "</span>p</span>).</div>\n"
		+ "<div>*DataSquid will supply company turnover, employee numbers and trading history data (where known) at no extra cost.</div></span>\n"
		+ "<br><div style='float:right; text-align:right;'>List Size: <span id='num_records' style='font-weight:bold;'></span>; Cost: <b>&pound;<span id='get_price'></span></b></div>\n"
		+ "<div><input type='radio' id='prune0' name='prune' value='' checked='1' onClick='Prune()'> include selected information <b>when available</b><br>"
		+ "<input type='radio' id='prune1' name='prune' value='1' onClick='Prune()'> include <b>only</b> records with <b>all</b> selected information</div>\n"
		+ "<div style='float:right'><span id='buy_link' style='text-align:center'>"
		+ "<a href='javascript:addToCart()' onmouseover='MM_swapImage(\"addcart\",\"\",\"_includes/images/butt_addcart_on.gif\",1)' onmouseout='MM_swapImgRestore()'>"
		+ "<img src='_includes/images/butt_addcart_off.gif' id='addcart' border=0></a></span><br><br></div>\n"
		+ "<br>I want no more than <input id='limit' value='" + items[0] + "' size=3 onChange='changelimit(this.value);'> records.<br>"
		+ "<br><input type='radio' name='multipleuse' id='multipleuse0' value='0' checked onClick='ToggleUses();'> Single use\n"
		+ "<input type='radio' name='multipleuse' id='multipleuse1' value='1' onClick='ToggleUses();'> Multiple use (within 12 months)</div>\n"
		+ "";

		gO('list_id').value=items[1];
		gO('list_size').value=items[0]; 
		gO('count_results').innerHTML = countText;
		gO('count_results').style.color="black";
		Prune();
		}
	else 
		{
		countText="Sorry - your search returned no results - please change your search criteria."; 
		gO('search_gr').style.display="none";
		gO('count_results').innerHTML = countText;
		gO('count_results').style.color="black";
		gO('count_results').style.display="block";

		} 
}

function changelimit(number)
	{
	max_records = (isNaN(number)?0:number);
	Prune();
	}


function ToggleUses ()
	{
	if (document.getElementById("multipleuse0").checked)
		{
		// We have selected single use
		price_per_record = price_s_per_record;
		price_contact = price_s_contact;
		price_email = price_s_email;
		price_phone = price_s_phone;
		price_fax = price_s_fax;
		}
	else
		{
		// We have selected multiple use
		price_per_record = price_m_per_record;
		price_contact = price_m_contact;
		price_email = price_m_email;
		price_phone = price_m_phone;
		price_fax = price_m_fax;
		}
	Prune();
	}

function searchFailed(response,id)
{
	// unset searching graphic
	unsetSearchGr();
	if (response != '')
		{
		gO('count_results').innerHTML= "Sorry, no results were found, please try expanding your search criteria."
		}
	else
		{
		gO('count_results').innerHTML= "Sorry, we are currently experiencing heavy traffic. Please try again in a few seconds.";
		}
	gO('search_gr').style.display="none";
	gO('count_results').style.color="black";
	gO('count_results').style.display="block";

}

function setSearchGr()
{
	gO('search_gr').style.display='block';
}

function unsetSearchGr()
{
// 	gO('search_gr').style.display='none';
}

function removeFromCart()
{
	url='_inlcudes/process.php';
	query_array['action']='removeCartItem';
	query_array['list_id']=gO('list_id').value; // will need to be checked server side as well
	query_array['list_size']=gO('list_size').value; //gO('list_cost').value; // will need to be chexcked server side as well
	query_array['list_desc']=gO("search_desc").innerHTML;
	apilite_get(url,query_array,"cartItemRemoved",'',"cartItemFail",'');
}

function cartItemRemoved(response)
{
	// display confirmation
	//alert('Item Added: '+response);
//	gO('buy_link').innerHTML=' <font color=green>added</font>';
	gO('buy_link').innerHTML="<a href='javascript:addToCart()' onmouseover='MM_swapImage(\"addcart\",\"\",\"images/butt_addcart_on.gif\",1)' onmouseout='MM_swapImgRestore()'><img src='images/butt_addcart_off.gif' id='addcart' border=0></a>"

	setItemOptions();
	gO('gotocheckout').style.visibility="hidden";
}

function addToCart()
{
	url='_includes/process.php';
	query_array['action']='addCartItem';
	query_array['list_id']=gO('list_id').value; // will need to be checked server side as well
	query_array['list_size']=gO('list_size').value; //gO('list_cost').value; // will need to be chexcked server side as well
	query_array['list_desc']=gO("search_desc").innerHTML;
	apilite_get(url,query_array,"cartItemAdded",'',"cartItemFail",'');
}

function cartItemAdded(response)
{
	// display confirmation
	//alert('Item Added: '+response);
	gO('buy_link').innerHTML=' <font color=green>added</font>';
	gO('name').disabled = true;
	gO('email').disabled = true;
	gO('phone').disabled = true;
	gO('fax').disabled = true;
	gO('prune0').disabled = true;
	gO('prune1').disabled = true;
	gO('limit').disabled = true;
	gO('multipleuse0').disabled = true;
	gO('multipleuse1').disabled = true;
	gO('count_results').style.color="gray";
	

//	gO('buy_link').innerHTML="<a href='javascript:removeFromCart()' onmouseover='MM_swapImage(\"removecart\",\"\",\"images/butt_removecart_on.gif\",1)' onmouseout='MM_swapImgRestore()'><img src='images/butt_removecart_off.gif' id='removecart' border=0></a>"

	setItemOptions();
	gO('gotocheckout').style.visibility="visible";
}

function cartItemFail(response)
{
	// alert the problem
	alert(response);
}


function removeCartItem(list_id)
{
	url='_inlcudes/process.php';
	query_array['action']='removeCartItem';
	query_array['list_id']=gO('list_id').value; // will need to be checked server side as well
	//alert(query_array);
	apilite_get(url,query_array,"cartItemRemoved",'',"cartRemoveFail",'');
}

//function cartItemRemoved()
//{
//	alert('Item Removed');
//}

function cartRemoveFail()
{
	alert('Remove itam failed');
}

function saveList(stage)
{
	switch (stage)
	{
		case 1:
			list_div="<span style='float:right;'>Enter your email address: <input type='text' size='30' id='save_list_email' />&nbsp;<input type='button' value='Save List' onClick='saveList(2)' /></span><span>&nbsp;</span>";
			gO('save_list_div').innerHTML=list_div;
		break;
		case 2:
			if(!validateEmail(gO('save_list_email').value))	{ alert('Please enter a valid email address'); return; }
			query_array['action']='save_list_for_later';
			query_array['email_address']=gO('save_list_email').value;
			url='_inlcudes/process.php'
			apilite_get(url,query_array,"saveListSuccess",'',"saveListFail",'');
		break;
	}
}

function saveListSuccess()
{
	alert('An email has been sent to you with a link to purchase this data set in the future');
}

function saveListFail()
{
	alert('Sorry, there has been a problem saving your data set');
}

function validateEmail(str)
{
	var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
    var regex = new RegExp(emailReg);
	return regex.test(str);
}

function ToggleVisibility(id,sense)
	{
	var visible = (sense?"visible":"hidden");
	var display = (sense?"block":"none");
	document.getElementById(id).style.visibility=visible;
	document.getElementById(id).style.display=display;
	}

function setItemOptions()
	{
	// Use a bit of AJAX to store the status of the check boxes.

	xmlHttp=GetXmlHttpObject();
	var contact = (document.getElementById('name').checked ? 1:0);
	var email =( document.getElementById('email').checked ? 1:0);
	var phone = (document.getElementById('phone').checked ? 1:0);
	var fax = (document.getElementById('fax').checked ? 1:0);
	var restrict = (document.getElementById('prune0').checked ? 0:1);
	var multiple_use = (document.getElementById('multipleuse0').checked ? 0:1);
	var url = "_includes/updatecheckboxes.php?list=" + items[1] + "&contact=" + contact + "&email=" + email + "&phone=" + phone + "&fax=" + fax + "&restrict=" + restrict + "&multiple_use=" + multiple_use + "&limit=" + max_records;
	xmlHttp.onreadystatechange=stateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	}

function toggle_options(option,sense)
	{
	if (document.getElementById('prune0').checked)
		{
		AddRemove(option,sense);
		}
	else
		{
		Prune();
		}
	}

function AddRemove(option,sense)
	{
	var cost_change;
	var direction;
	var current_price = document.getElementById('get_price').innerHTML;
	//Clicking on a button will toggle between including and ignoring some fields in the CSV. This has an impact on price.
	if (sense == true)
		{
		direction = 1;

		}
	else
		{
		direction = -1;
		}

	switch (option)
		{
		case "Name":
			var number = document.getElementById("num_contacts").innerHTML * 1;
			cost_change = number * price_contact * direction;
			var contact_price = document.getElementById("contact_div").innerHTML;
			var new_contact_price = Math.round(contact_price * 100 + cost_change);
			var formated_contact_price = (new_contact_price/100 == Math.floor(new_contact_price/100)) ? new_contact_price/100 + '.00' : ((new_contact_price / 10 == Math.floor(new_contact_price / 10)) ? new_contact_price/100 + '0' : new_contact_price/100);
			document.getElementById("contact_div").innerHTML = formated_contact_price;
			break;
		case "Email":
			var number = document.getElementById("num_emails").innerHTML * 1;
			cost_change = number * price_email * direction;
			var email_price = document.getElementById("email_div").innerHTML;
			var new_email_price = Math.round(email_price * 100 + cost_change);
			var formated_email_price = (new_email_price/100 == Math.floor(new_email_price/100)) ? new_email_price/100 + '.00' : ((new_email_price / 10 == Math.floor(new_email_price / 10)) ? new_email_price/100 + '0' : new_email_price/100);
			document.getElementById("email_div").innerHTML = formated_email_price;
			break;
		case "Phone":
			var number = document.getElementById("num_phones").innerHTML * 1;
			cost_change = number * price_phone * direction;
			var phone_price = document.getElementById("phone_div").innerHTML;
			var new_phone_price = Math.round(phone_price * 100 + cost_change);
			var formated_phone_price = (new_phone_price/100 == Math.floor(new_phone_price/100)) ? new_phone_price/100 + '.00' : ((new_phone_price / 10 == Math.floor(new_phone_price / 10)) ? new_phone_price/100 + '0' : new_phone_price/100);
			document.getElementById("phone_div").innerHTML = formated_phone_price;
			break;
		case "Fax":
			var number = document.getElementById("num_faxes").innerHTML * 1;
			cost_change = number * price_fax * direction;
			var fax_price = document.getElementById("fax_div").innerHTML;
			var new_fax_price = Math.round(fax_price * 100 + cost_change);
			var formated_fax_price = (new_fax_price/100 == Math.floor(new_fax_price/100)) ? new_fax_price/100 + '.00' : ((new_fax_price / 10 == Math.floor(new_fax_price / 10)) ? new_fax_price/100 + '0' : new_fax_price/100);
			document.getElementById("fax_div").innerHTML = formated_fax_price;
			break;
		default:
			cost_change = 0;
		}
	var new_price = (Math.round(current_price * 100 + cost_change)) / 100
	document.getElementById("get_price").innerHTML = (new_price == Math.floor(new_price)) ? new_price + '.00' : ((new_price * 10 == Math.floor(new_price * 10)) ? new_price + '0' : new_price);
	}

function Prune()
	{
	// A prune radio button has been checked, find out which and run the relavent function.
//	gO('processing_search').style.display="block";
	var name_checked = document.getElementById("name").checked;
	var email_checked = document.getElementById("email").checked;
	var phone_checked = document.getElementById("phone").checked;
	var fax_checked = document.getElementById("fax").checked;
	var multiple = !document.getElementById("multipleuse0").checked
	var url = "_includes/prune.php?list=" + items[1] + "&contact=" + name_checked + "&email=" + email_checked + "&phone=" + phone_checked + "&fax=" + fax_checked + "&limit=" + max_records + "&multiple=" + multiple;
	if (!document.getElementById("prune0").checked)
		{
		url += "&prune=1";
		}
	else
		{
		url += "&prune=0";
		}
	xmlHttp=GetXmlHttpObject();
	xmlHttp.onreadystatechange=updatelist;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	}


function updatelist()
	{
	var name_checked = document.getElementById("name").checked;
	var email_checked = document.getElementById("email").checked;
	var phone_checked = document.getElementById("phone").checked;
	var fax_checked = document.getElementById("fax").checked;

	if (xmlHttp.readyState==4)
		{
		var numbers = xmlHttp['responseText']; // a string of address, contact, email, phone, fax. Separated by commas.
		var split_numbers = numbers.split(",");

		if (firsttime == 1)
			{
			contacts = split_numbers[1];
			emails = split_numbers[2];
			phones = split_numbers[3];
			faxes = split_numbers[4];	
			firsttime = 0;
			}
	
		document.getElementById("num_addresses").innerHTML = split_numbers[0];
		document.getElementById("num_contacts").innerHTML = split_numbers[1];
		document.getElementById("num_emails").innerHTML = split_numbers[2];
		document.getElementById("num_phones").innerHTML = split_numbers[3];
		document.getElementById("num_faxes").innerHTML = split_numbers[4];
		document.getElementById("num_records").innerHTML = split_numbers[0];

		if (!document.getElementById("prune0").checked)
			{
			if (!document.getElementById("name").checked)
				{
				document.getElementById("num_contacts").innerHTML = contacts;
				}
			if (!document.getElementById("email").checked)
				{
				document.getElementById("num_emails").innerHTML = emails;
				}
			if (!document.getElementById("phone").checked)
				{
				document.getElementById("num_phones").innerHTML = phones;
				}
			if (!document.getElementById("fax").checked)
				{
				document.getElementById("num_faxes").innerHTML = faxes;
				}
			}

		document.getElementById("ppr").innerHTML = price_per_record;
		document.getElementById("pc").innerHTML = price_contact;
		document.getElementById("pe").innerHTML = price_email;
		document.getElementById("pp").innerHTML = price_phone;
		document.getElementById("pf").innerHTML = price_fax;

		var cost_address = split_numbers[0] * price_per_record / 100;
		var formatted_cost_address = (cost_address == Math.floor(cost_address)) ? cost_address + '.00' : ((cost_address * 10 == Math.floor(cost_address * 10)) ? cost_address + '0' : cost_address);
		document.getElementById("address_div").innerHTML = formatted_cost_address;
	
		var cost_contact = (name_checked?split_numbers[1] * price_contact / 100:0);
		var formatted_cost_contact = (cost_contact == Math.floor(cost_contact)) ? cost_contact + '.00' : ((cost_contact * 10 == Math.floor(cost_contact * 10)) ? cost_contact + '0' : cost_contact);
		document.getElementById("contact_div").innerHTML = formatted_cost_contact;
	
		var cost_email = (email_checked?split_numbers[2] * price_email / 100:0);
		var formatted_cost_email = (cost_email == Math.floor(cost_email)) ? cost_email + '.00' : ((cost_email * 10 == Math.floor(cost_email * 10)) ? cost_email + '0' : cost_email);
		document.getElementById("email_div").innerHTML = formatted_cost_email;
	
		var cost_phone = (phone_checked?split_numbers[3] * price_phone / 100:0);
		var formatted_cost_phone = (cost_phone == Math.floor(cost_phone)) ? cost_phone + '.00' : ((cost_phone * 10 == Math.floor(cost_phone * 10)) ? cost_phone + '0' : cost_phone);
		document.getElementById("phone_div").innerHTML = formatted_cost_phone;
	
		var cost_fax =(fax_checked?split_numbers[4] * price_fax / 100:0);
		var formatted_cost_fax = (cost_fax == Math.floor(cost_fax)) ? cost_fax + '.00' : ((cost_fax * 10 == Math.floor(cost_fax * 10)) ? cost_fax + '0' : cost_fax);
		document.getElementById("fax_div").innerHTML = formatted_cost_fax;
	
		var old_price = document.getElementById("get_price").innerHTML * 1;
		var new_price = Math.round(100 * (cost_address + cost_contact + cost_email + cost_phone + cost_fax)) / 100;

		document.getElementById("get_price").innerHTML = (new_price == Math.floor(new_price)) ? new_price + '.00' : ((new_price * 10 == Math.floor(new_price * 10)) ? new_price + '0' : new_price);

		gO('processing_search').style.display="none";
		gO('search_gr').style.display='none';
		gO('count_results').style.display="block";

		if (split_numbers[0] < document.getElementById('limit').value)
			{
			if (split_numbers[0] == 0)
				{
				var message = "No results match your criteria";
				}
			else
				{
				var message = "Only " + split_numbers[0] + " results found that match your criteria!";
				}
			alert(message);
			//document.getElementById('limit').value = split_numbers[0];
			}
		}
	}

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 stateChanged() 
	{
	if (xmlHttp.readyState==4)
		{
		}
	}