// change: Dec 2008 - commented out console.log as have removed 
// firebug.js as it is implicated in IE6/7 issues...
function set_test_cookie() {
	var cookie_date = new Date ( );  // current date & time
	cookie_date.setTime ( cookie_date.getTime() + 3600 );
	document.cookie = "datamarket_cookie=test;"; // domain=datamarket.co.nz; path=/
}

var submenu;
var currmenu;
var allow;
var minimumpurchase = 125; 

function $(id) {return document.getElementById(id)}



function init() {
	var menus = YAHOO.util.Dom.getElementsByClassName('menu','a','nav');
	var submenus = $('nav').getElementsByTagName('ul');
	var submenuItems = $('nav').getElementsByTagName('li')
	for (i=0; i<menus.length; i++) {
		YAHOO.util.Event.on(menus[i],"mouseover",focusMenu);
		YAHOO.util.Event.on(menus[i],"mouseout",blurMenu);
	}
	for (i=0; i<submenus.length; i++) {
		var count = (i+1).toString();
		$('submenu'+count).style.left = i*141+1+'px';
		YAHOO.util.Event.on(menus[i],"mouseup",showSubMenu);
	}
	for (i=0; i<submenuItems.length; i++) {
		YAHOO.util.Event.on(submenus[i],"mousedown",allowClick);
		YAHOO.util.Event.on(submenus[i],"mouseup",allowClick);
	}
	YAHOO.util.Event.on(document.body,"mousedown",hideSubMenu);
	//document.getElementById('categories').onmousedown=function(e){
	//	console.log(e);
	//}
}

YAHOO.util.Event.onDOMReady(init);



	
function focusMenu() {
	if(!submenu) {
		var menuFocus = new YAHOO.util.ColorAnim(this,{backgroundColor:{to:'#71aedd'}},.2,YAHOO.util.Easing.easeOut);
		menuFocus.animate();
	}
}
function blurMenu() {
	if(!submenu) {
		var menuBlur = new YAHOO.util.ColorAnim(this,{backgroundColor:{to:'#1c2a54'}},.2,YAHOO.util.Easing.easeOut);
		menuBlur.animate();
	}
}
function showSubMenu() {
	this.style.backgroundColor = '#71aedd';
	if ($('sub'+this.id) != null) {
		$('sub'+this.id).style.display = 'block';
		currmenu=$('sub'+this.id);
		submenu=true;
	}
}
function hideSubMenu() {
	if(submenu&&!allow) {
		currmenu.style.display = 'none';
		submenu=false;
		var menu = currmenu.id.substring(3,8);
		var menuBlur = new YAHOO.util.ColorAnim(menu,{backgroundColor:{to:'#1c2a54'}},.2,YAHOO.util.Easing.easeOut);
		menuBlur.animate();
	}
}
function allowClick() {
	allow ? allow=false : allow=true;
}
function highlightMenu() {
	this.parentNode.parentNode.style.backgroundColor = '#71aedd';
}








/*************************************************************************************

Advanced search Location controls

**************************************************************************************/

function moreLocation() {
	document.getElementById('locationDetailOpen').className = 'opendetail';
	document.getElementById('locationDetailClosed').className = 'hide';
	document.getElementById('locationMoreDetailButton').className = 'hide';
	document.getElementById('locationLessDetailButton').className = 'moredetail';
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?location_detail=show',
	{
		'success': null,//
		'failure': null
	});
	
	return false;
}

function lessLocation() {
	document.getElementById('locationDetailOpen').className = 'hide';
	document.getElementById('locationDetailClosed').className = 'closeddetail';
	document.getElementById('locationMoreDetailButton').className = 'moredetail';
	document.getElementById('locationLessDetailButton').className = 'hide';
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?location_detail=hide',
	{
		'success': null,//
		'failure': null
	});
	return false;

}


var toggle ='';//causes a display bug if manual refresh in fireforx
function togglemore(obj, divid) {
		if(toggle != obj.id){
			document.getElementById(obj.id).innerHTML = 'less...';
			document.getElementById(divid).className = 'show';
			toggle = obj.id;
		}else if(toggle == obj.id){
			document.getElementById(obj.id).innerHTML = 'more...';
			document.getElementById(divid).className = 'hide';
			toggle = '';
		}
	return false;	
}



/*************************************************************************************

Advanced Search Category controls

**************************************************************************************/


var businessSet = false;
var sicSet = false;
var anzsicSet = false;

function show_business_category(){
	var string;
	string = "<span id='tab1' class='highlight' >Business Categories</span>"
			+"<a id='tab2' href='#' onclick='return show_sic_category();'>SIC</a>"
			+"<a id='tab3' href='#' onclick='return show_anzsic_category();'>ANZSIC</a>";
	settabs = document.getElementById('tabs');
	settabs.innerHTML = string;
	document.getElementById('business_category').className = 'show';
	document.getElementById('sic_category').className = 'hide';
	document.getElementById('anzsic_category').className = 'hide';
	init('business_category');
	return false;
}

function show_sic_category(){
	var string;
	string = "<a id='tab1' href='#' onclick='return show_business_category();'>Business Categories</a>"
			+"<span id='tab2' class='highlight' >SIC</span>"
			+"<a id='tab3' href='#' onclick='return show_anzsic_category();'>ANZSIC</a>";
	settabs = document.getElementById('tabs');
	settabs.innerHTML = string;
	document.getElementById('business_category').className = 'hide';
	document.getElementById('sic_category').className = 'show';
	document.getElementById('anzsic_category').className = 'hide';
	init('sic_category');
	return false;
}

function show_anzsic_category(){
	var string;
	string = "<a id='tab1' href='#' onclick='return show_business_category();'>Business Categories</a>"
			+"<a id='tab2' href='#' onclick='return show_sic_category();'>SIC</a>"
			+"<span id='tab3' class='highlight' >ANZSIC</span>";
	settabs = document.getElementById('tabs');
	settabs.innerHTML = string;
	document.getElementById('business_category').className = 'hide';
	document.getElementById('sic_category').className = 'hide';
	document.getElementById('anzsic_category').className = 'show';
	init('anzsic_category');
	return false;
}


/*****************	
function updateDownloadStatus() {
	var fullName = document.getElementById('full_name').value;
	var username = fullName.toLowerCase().replace(/ /g, '.').replace(/[^a-z\.]/g, '');
	if (document.getElementById('autoname').checked) {
		document.getElementById('username').value = username;
	}
	if (document.getElementById('autoemail').checked && username) {
		document.getElementById('email').value = username +'@datamarket.co.nz';
	}
}
****************/


/*************************************************************************************

Advanced Search Deep Item controls

**************************************************************************************/


//setInterval('updateUsername()', 100);
var deepcount =1000;//safety margin

var items_used = new Array();

function addSelectedItem(obj){
	
	if(obj.value == '') return false;
	if(items_used[obj.value]) return false;//because ie7 can no longer disable options, we have to check usage!
	items_used[obj.value] = obj.value;
	
	loader = document.getElementById('loading');
	loader.innerHTML = '...Loading...';
	
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?item_id='+escape(obj.value)+'&deepcount='+escape(deepcount),
		{
			'success': getAddSelectedItem,//
			'failure': null,
			'argument': { obj:obj} 
		});
	obj.selectedIndex = 0;

}
	
function getAddSelectedItem(response)	{
	var string1;
	var string2;
	// check console exists (it is a firebug thing)
	//console.log(response.responseText);

	var responseObject = eval(response.responseText);	// unsafe
	var type = responseObject['type'];
	var label = responseObject['label'];
	var id = responseObject['id'];
	var string = responseObject['string'];	

	var deepsearch = document.getElementById('deepsearchcontainer');
	var newdeep = document.createElement('div');
	deepsearch.appendChild(newdeep);
	newdeep.innerHTML = string;
	newdeep.setAttribute('id','deep'+deepcount);
	// YAHOO.util.Dom.addClass(newdeep,'deepitem');
	newdeep.setAttribute('class','deepitem');
	newdeep.setAttribute('className','deepitem');
	deepspan = document.getElementById('inputs_'+deepcount);
	if(type == 'boolean'){
		deepspan.setAttribute('class','hide');
		deepspan.setAttribute('className','hide');
	}else{//restore full 
		deepspan.setAttribute('class','show');
		deepspan.setAttribute('className','show');
	}
	deepcount++;
	loader = document.getElementById('loading');
	loader.innerHTML = '';
	option = document.getElementById('itemoption_'+id);
	option.setAttribute('disabled','disabled');
	option.setAttribute('class','grey');
	option.setAttribute('className','grey');

	return false;
	
}



function display_input(obj,input_id){
	var option = obj.value;
	var input = document.getElementById('value_'+input_id).parentNode;
	if(option == 'full'){
		input.setAttribute('class','hide');
		input.setAttribute('className','hide');
	}else{
		input.setAttribute('class','show');
		input.setAttribute('className','show');		
	}
	
}	

function removeItemParentNode(id, obj){
	option = document.getElementById('itemoption_'+id);
	option.removeAttribute('disabled');
	option.removeAttribute('class');
	option.removeAttribute('className');
	obj.parentNode.parentNode.removeChild(obj.parentNode);
	items_used[id] = '';
	return false;
}

function removeParentNode(obj){
	obj.parentNode.parentNode.removeChild(obj.parentNode);
	return false;
}

function removeTableRow(obj){
	obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
	return false;
}

function removeResultRow(obj,listingid, searchid){
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?currentsearch_id='+escape(searchid)+'&listing_id='+escape(listingid)+'&status=remove',
		{
			'success': removeRow,//
			'failure': null,
			'argument': { obj:obj} 
		});
	return false;
}

function restoreResultRow(obj,listingid, searchid){
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?currentsearch_id='+escape(searchid)+'&listing_id='+escape(listingid)+'&status=restore',
		{
			'success': removeRow,//
			'failure': null,
			'argument': { obj:obj} 
		});
	return false;
}

function removeRow(response){//this approach ensures the item does not disappear until ajax has run
	var obj = response.argument.obj;
	obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
	return false;
}


function selectResultRow(obj,searchid){
	listingid = obj.id;
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?currentsearch_id='+escape(searchid)+'&listing_id='+escape(listingid)+'&status=select',
		{
			'success': null,//
			'failure': null
		});

}

function selectRow(response){//this approach ensures the item does not disappear until ajax has run
	var obj = response.argument.obj;
	var status = response.argument.status;
	input = document.getElementById(obj.id);
	if(status == 'clear'){
		input.setAttribute("checked", false);
	}else if (status == 'select'){
		input.setAttribute("checked", true);
	}
	return false;
}


	
/*************************************************************************************

Advanced Search Postcode controls

**************************************************************************************/

	
function populatePostcodes(area_id){

	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?postcodearea='+escape(area_id),
		{
			'success': getPostcodes,//
			'failure': null
		});

}

function getPostcodes(response)	{
	responseObject = eval(response.responseText);	// unsafe
	document.getElementById('postcodeselect').innerHTML = responseObject.codes;

}




/*************************************************************************************

Download page logic

**************************************************************************************/

function changeformat(obj) {
	if(obj.id === 'custom'){
		document.getElementById('customcontrols').className = 'show';
		document.getElementById('defaultformat').className = 'hide';
		document.getElementById('customformat').className = 'show';
	}else{
		document.getElementById('customcontrols').className = 'hide';
		document.getElementById('defaultformat').className = 'show';
		document.getElementById('customformat').className = 'hide';
	}
	return false;	
}

function calculatePayment(){
if(!document.getElementById('payment_value')) return false;
if(document.getElementById('payment_value').value == '') return false;
if(isNaN(parseFloat(document.getElementById('payment_value').value))){
	document.getElementById('gst-total').innerHTML = '0.00';
}else{
	document.getElementById('gst-total').innerHTML = r2(parseFloat(document.getElementById('payment_value').value * 1.125));
}
}


function recalculate_download(){
	//sanity checking on input values
	if(document.getElementById('quantity_part').checked){
		var maxval = 1;
		if(isNaN(parseFloat(document.getElementById('max').value))){
			maxval = parseFloat(document.getElementById('maxval').value)	;
		}else if(parseFloat(document.getElementById('max').value) > parseFloat(document.getElementById('maxval').value)){
			maxval = parseFloat(document.getElementById('maxval').value)	;																		
		}else if(parseFloat(document.getElementById('max').value) < 1){
			maxval = 1;
		}else{
			maxval = parseFloat(document.getElementById('max').value);
		}
		var minval = 1
		if(isNaN(parseFloat(document.getElementById('min').value))){
			minval = 1;
		}else if(parseFloat(document.getElementById('min').value) > parseFloat(document.getElementById('maxval').value)){
			minval = parseFloat(document.getElementById('maxval').value)	;																		
		}else if(parseFloat(document.getElementById('min').value) < 1){
			minval = 1;
		}else{
			minval = parseFloat(document.getElementById('min').value);
		}
		
		if(minval > maxval) {
			tempmax = maxval;
			maxval = minval;
			minval = tempmax;
		}
		document.getElementById('max').value = maxval;
		document.getElementById('min').value = minval;
	
	}else{//below here might be wrong - test with middle sections of larger searches?
		document.getElementById('min').value = 1; 
		document.getElementById('max').value = document.getElementById('count').value;
		document.getElementById('offset').value = 0;
		document.getElementById('length').value = document.getElementById('count').value;
	}
	
	document.forms[0].submit();

}

function recalculate_totals(){
	var checkeditems = new Array();
	//get the currently checked checkboxes inside wrapper
	var theForm = document.forms[0];
   	var query = '&dtp_company_name='+document.getElementById('dtp_company_name').value;
	var credit = parseFloat(document.getElementById('credit').innerHTML.replace(',',''));
	var limit = parseFloat(document.getElementById('limit').innerHTML);

	var itemcount = theForm.elements.length;
	// patch for IE7 
	// it is not reading the form length (it is actually returning an object, and its value is the content of the first DOM input box... therefore the DOM is corrupt?)
	if ( ! ( itemcount > 0 ) ) {
		itemcount=32;
	}

	for(i=0; i<itemcount; i++){
		if(theForm.elements[i].type == "checkbox" && theForm.elements[i].checked && theForm.elements[i].name != 'fieldnames'){
			//alert('type='+theForm.elements[i].type+' element.name='+theForm.elements[i].name);
			checkeditems[theForm.elements[i].name] = theForm.elements[i].value;
			query  += '&'+theForm.elements[i].name+'='+theForm.elements[i].value;
		}
	}

   	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?recalculate=true&credit='+credit+'&limit='+limit+query,
	{
		'success': set_totals,//
		'failure': null
	});
}

function set_totals(response){
	responseObject = eval(response.responseText);	// unsafe
	var total = parseFloat(responseObject.total.replace(',',''));
	var count = responseObject.count;
	var average = responseObject.average;
	var error = responseObject.error;
	var errortype = responseObject.errortype;
	var message = responseObject.message;
	var credit = parseFloat(responseObject.credit);
	var limit = responseObject.limit;
	var fieldcount = responseObject.fieldcount;

	document.getElementById('records').innerHTML = count;
	document.getElementById('average').innerHTML = average;
	
	var button = document.getElementById('create');
	
	if(credit <= total){
		document.getElementById('statcredit').className = 'hide';
		document.getElementById('statcreditmessage').className = 'showinline';
		document.getElementById('statcreditmessage').innerHTML = '<span class="warning"><strong>Available credit is $'+addCommas(r2(credit))+'</strong></span>';
		
	}else{
		document.getElementById('statcredit').className = 'showinline';
		document.getElementById('statcreditmessage').className = 'hide';
	}
	
	if(errortype == 'nocredit'){//if it exceeds available credit, display error	
		document.getElementById('stattotal').className = 'hide';
		document.getElementById('statmessage').className = 'showinline';
		document.getElementById('statmessage').innerHTML = '<span class="warning"><strong>'+message+'</strong></span>';
		button.disabled = true;
	}else if(errortype == 'nodownload'){//if desired items are greater than the download limit, display error
		document.getElementById('stattotal').className = 'hide';
		document.getElementById('statmessage').className = 'showinline';
		document.getElementById('statmessage').innerHTML = '<span class="warning"><strong>'+message+'</strong></span>';	
		button.disabled = true;
	}else{
		document.getElementById('stattotal').className = 'showinline';
		document.getElementById('statmessage').className = 'hide';
		document.getElementById('total').innerHTML = addCommas(total);
		button.disabled = false;
	}
}

function r2(n) {

  var ans = n * 1000;
  ans = Math.round(ans /10) + "";
  while (ans.length < 3) {
	  ans = "0" + ans;
	}
  var len = ans.length;
  ans = ans.substring(0,len-2) + "." + ans.substring(len-2,len);
  return ans;
}

function addCommas(nStr) {
	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/*************************************************************************************

Progress Bar for CSV

**************************************************************************************/

var progressstate = 2;
function checkProgress(usageid){

	if(progressstate == 'available') return false;
	
	YAHOO.util.Connect.asyncRequest('GET','/online/ajax.php?usage_id='+escape(usageid),
		{
			'success': getProgress,//
			'failure': null
		});

}

function getProgress(response)	{
	responseObject = eval(response.responseText);	// unsafe
	progressstate = responseObject.state;
	document.getElementById('progress').innerHTML = responseObject.output;

}

function createCSV(response)	{
	responseObject = eval(response.responseText);	// unsafe
	progressstate = responseObject.state;
}


	
/*************************************************************************************

Window popups

**************************************************************************************/


function openprint(currentid,resultselect,quantity, filter,count,mini,maxi,offset,length,phone,fax,mob,suburb,categories){
						
	url = "/online/printpopup/?popup=true&searchid="+currentid+"&quantity="+quantity+"&resultselect="+resultselect+"&filter="+filter+"&count="+count+"&min="+mini+"&max="+maxi+"&offset="+offset+"&length="+length+"&phone="+phone+"&fax="+fax+"&mob="+mob+"&suburb="+suburb+"&categories="+categories;
	printWin = window.open(url, 'listprint','toolbar=yes,menubar=yes,status=yes,scrollbars=yes,location=no,resizable=yes,height=800,width=800');
	printWin.focus();

}

function openhelp(url){

	helpWin = window.open(url, 'help','toolbar=no,menubar=no,status=yes,scrollbars=yes,location=no,resizable=no,height=400,width=600');
	helpWin.focus();

}

function featureDetailInfo(response){//this approach ensures the item does not disappear until ajax has run
	var feature = response.argument.feature;
	var response = eval(response.responseText);	// unsafe
	feature.showInfoWindow('<div class="mapinfo"><p><strong>'+response.name+'</strong></p><p>'+response.address+'</p><p>Ph: '+response.phone+'</p><p><a class="smallmaplink" href="/online/detail/?listing='+response.id+'">View listing...</a></div>');
	return false;
}

/*****************************
function makechoice(chosen){
  document.searchoutput.choice.value = chosen;
  document.searchoutput.submit();
}

function makeeditchoice(chosen){ 
  document.editsearch.editchoice.value = chosen;
  document.editsearch.submit();
}
*******************************/

/*****************************************************

Timeout

****************************************************/


var seconds=7100;
var txt='Your Session will timeout shortly due to inactivity.';

function countDown() {

		if(seconds<=0) {

			alert(txt);
			return;
		}

	seconds--;

	window.setTimeout("countDown()",7100);	

	}
	
 function loader(timeout)
 {
  if(timeout>0){
  	countDown();
	}
 }
 
function resetseconds()
 {
seconds = 7100;
}



//window.onload = loader(1); now called in script	


/**
function setSelect(selectElemObj) {
    // remove existing options
    selectElemObj.options.length = 0;
    // create and assign options, one by one
    selectElemObj.options[0] = new Option("Hercule Poirot", "poirot", false, false);
    selectElemObj.options[1] = new Option("Miss Marple", "marple", false, false);

}
***/

/*****************************************************

Map

****************************************************/

//var listing = <span tal:condition="json_listing" tal:replace="structure json_listing" tal:on-error="" />;    	
<!--

function businessMap() {
		if(listing){
			var mapid = "map1";
			//var feature = oSearchResult.results[0];//set this with tal
			YAHOO.util.Dom.setStyle(mapid,'height','300px');
			YAHOO.util.Dom.setStyle(mapid,'width','590px');
			YAHOO.util.Dom.setStyle(mapid,'clear','both');
			YAHOO.util.Dom.addClass(mapid,'geomap');
			/* oBusinessMap = new GSMap(mapid, {});
			oBusinessMap.addControl(GSMap.MAP_CONTROL);
			oBusinessMap.setMapOptions({useMouseWheelZooming:false})
			var coordinate = new GSPoint(listing.x, listing.y);
			oBusinessMap.centerAndZoom(coordinate,1);
			var params = {"name" : listing.name,
				  "coordinate" : coordinate,
				  "infoHtml" : listing.html};

			var feature = new GSPointFeature(params);
			feature.addEventHandler("click", function(e) {
			 this.showInfoWindow();
			 // prevents click event propagating to map
			 GSUtil.cancelEvent(e);

			});

			oBusinessMap.addFeature(feature); */
		}
	}
