var setCookieExpiry = 7;
function filterResults()
{
	if (document.getElementById('subSubCatID').value == 0)
	{
		dirID = document.getElementById('dirID').value;
		subCatID = document.getElementById('subCatID').value;
		window.location = "localdir.php?action=localdirectory&section=results&dirID="+dirID+"&subCatID="+subCatID;

	}
	else {
		document.getElementById('filterForm').submit();
	}
	
}
function showResults()
{
	//this.form.submit();
	if (document.getElementById('subCatID').value == 0)
	{
		dirID = document.getElementById('dirID').value;
		typeID = document.getElementById('typeID').value;
		window.location = "localdir.php?action=localdirectory&section=results&dirID="+dirID+"&typeID="+typeID;
	}
	else {
		document.getElementById('showForm').submit();
	}
}
function selectSuburb()
{
	//document.selectSub.submit();
	$("#loader").show();

	var suburbs = "";
	//since the suburb has been changed, also update distance information
	if ($.cookie("distanceInfo") != null){
			distanceArr = $.cookie("distanceInfo").split(",");
				for(i=0; i<distanceArr.length;i++){
					
					if (distanceArr[i] != "")
					{
						var dest = [];
						//dest = distanceArr[i].split("=");
						destVal = distanceArr[i].split("=");
						//alert(dest[0]);
						//loc = document.getElementById('fSuburb').value;
						locationVal = document.getElementById('loc').value;
						//suburbs += dest[0]+"="+ loc+",";
						//alert(suburbs);
						destVal[0] = replaceWithSpace(destVal[0]);
						suburbs += destVal[0]+"="+locationVal+",";

					}
				}
			}
		getUpdatedDistance(suburbs);

}

/* BEGIN AJAX: DISTANCE INFO */


function ajaxCall()
{
	var httpxml;
	try
	{
	  // Firefox, Opera 8.0+, Safari
	  httpxml=new XMLHttpRequest();
	}
	catch (e)
    {
		// Internet Explorer
		  try	{
				httpxml=new ActiveXObject("Msxml2.XMLHTTP");
		  }
		  catch (e)
		  {
				try
	      		{
			  		httpxml=new ActiveXObject("Microsoft.XMLHTTP");
     			 }
    			catch (e)
	      		{
					alert("Your browser does not support AJAX!");
					return false;
	      		}
    		}
    }

	return httpxml;
}

function updateDistanceChange()
{
	if (httpxml.readyState == 4)
	{
		//update distance change information, based on new suburb information and then submit the form
		$.cookie("distanceInfo", null);
		distanceInfo = httpxml.responseText;
		if (distanceInfo != "")
		{
			distanceInfo = distanceInfo.split(",");
			var suburbList = [];

			//clear cookies

			for (i=0;i<distanceInfo.length;i++ )
			{
				suburb = distanceInfo[i].split("=");
				//suburb[0] = replaceWithSpace(suburb[0]);

				addSuburb(suburb[0], suburb[1]);
			}
		}
		form = document.getElementById('selectSub');
		form.submit();
	}
}

function getUpdatedDistance(suburbs)
{
	httpxml = ajaxCall();	

	var url="index.php";
	url=url+"?action=geopoint&suburbs="+ suburbs;
	url=url+"&sid="+Math.random();

	httpxml.onreadystatechange=updateDistanceChange;
	httpxml.open("GET",url,true);
	httpxml.send(null);
}

function getDistance()
{
	if (document.getElementById('dest').value == ''){
		alert("Please enter a suburb");
		return;
	}
	document.getElementById('addSuburb').disabled = true;
	document.getElementById('dest').disabled = true;
	destText = document.getElementById('dest').value;
	locText = document.getElementById('loc').value;

	httpxml = ajaxCall();	

	var url="index.php";
	url=url+"?action=geopoint&section=getDistance&loc="+locText+"&dest="+destText;
	url=url+"&sid="+Math.random();

	httpxml.onreadystatechange=updateDistanceInfo;
	httpxml.open("GET",url,true);
	httpxml.send(null);
}

function updateDistanceInfo()
{
	if (httpxml.readyState == 4)
	{
		if (!httpxml.responseText || httpxml.responseText > 5000)
		{
			alert("Sorry, could not find directional information for this suburb, please try another suburb.");
			document.getElementById('addSuburb').disabled = false;
			document.getElementById('dest').disabled = false;
		}
		else {
			suburb = document.getElementById('dest').value;
			distance = httpxml.responseText;

			addSuburbToDis(suburb, distance);
	
			document.getElementById('addSuburb').disabled = false;
	        document.getElementById('dest').value = '';
			document.getElementById('dest').disabled = false;

			addSuburb(suburb, httpxml.responseText);
		}
	}
}

function removeElement(index)
{
	distanceArr = $.cookie("distanceInfo").split(",");
	distanceArr.splice(index, 1);
	//update cookie info
	updateCookies(distanceArr);

}

function updateCookies(array)
{
	//$.cookie('distanceInfo', array, { expires: 2, path: "/" });
	$.cookie('distanceInfo', distanceArr);
}

function findElement(search)
{
	distanceArr = $.cookie("distanceInfo").split(",");
	for (i=0;i<distanceArr.length;i++ )
	{
		suburb = distanceArr[i].split("=");
		if (suburb[0] == search)
		{ 
			return distanceArr.indexOf(distanceArr[i]);
		}
	}
}


function replaceWithSpace(string)
{
	string = string.replace(/[_\r]+/g, " "); 
	return string;
}

function addSuburbToDis(suburb, distance){
			suburbForm = "'"+ suburb + "'";
			suburbForm = suburbForm.replace(' ', '_');

			suburbDisplay = suburb;
			suburbDisplay = replaceWithSpace(suburbDisplay);

		$('#subDistance tbody').append('<tr id='+ suburbForm + ' valign="right"><td class="roadsignSuburb"><a href="#" onClick="removeSuburb('+ suburbForm +')">'+
			'<img style="padding-right:4px;" src="images/btn_cross.jpg" width="10" height="10" border="0"/></a>'+ suburbDisplay+'</td>'+
			'<td class="roadsignDistance">'+ distance+'</td></tr>');
}

function addSuburb(suburbName, distance){

	var distanceArr = [];
	suburbName = suburbName.replace(' ', '_');

	if ($.cookie("distanceInfo") == null){
		distanceArr[0] = suburbName + "="+ distance;
	}
	else {
		distanceArr = $.cookie("distanceInfo").split(",");
		distanceArr[distanceArr.length] = suburbName + "="+ distance;
	}

	//$.cookie('distanceInfo', distanceArr, { expires: 2, path: "/" });
	$.cookie('distanceInfo', distanceArr, { expires: setCookieExpiry});
}

function removeSuburb(suburb)
{
	//remove suburb from cookie
	element = findElement(suburb);
	removeElement(element);
	$('#'+suburb).remove();
}

if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}

/* END AJAX: DISTANCE INFO */



/* MENU BUTTONS: START */

function preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

/* MENU BUTTONS: END */


function submitForm()
{  
   fForm.submit();
}

function openNewsWindow(id)
{
   win2 = window.open("newsletter/index.php?id="+id, "new_window", 'fullscreen=yes,toolbar=no,location=no,directories=no, scroll=no, status=no,menubar=no,scrollbars=no,resizable=no'); 
}

function validateVisitorForm()
{
	requiredText = "";
	if (document.getElementById('fName').value == "")
	{
		requiredText += "- Please enter your name\n"
	}
	if (document.getElementById('phoneNo').value == "")
	{
		requiredText += "- Please enter your phone number\n"
	}
	if (document.getElementById('email').value == "")
	{
		requiredText += "- Please enter your email\n"
	}
	if (document.getElementById('email').value != "")
	{
		if (echeck(document.getElementById('email').value) == false)
		{
			requiredText += "- Please enter a valid email address\n"
		}
	}
	if (document.getElementById('suburb').value == "")
	{
		requiredText += "- Please enter your suburb/postcode\n"
	}
	if (document.getElementById('classification').value == "Other")
	{
		if (document.getElementById('classificationOther').value == "")
		{
			requiredText += "- Please specify who you are\n"
		}
	}

	if (requiredText != "")
	{
		alert(requiredText);
		return false;
	}

	return true;
}
function echeck(str) {

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

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

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

 		 return true					
}

function removeComma(string)
{
	string = string.replace(/\,$/,'');
	return string;
}



function toggleButton(element, specific)
{
	if (!specific)
	{
		if (element.parents(".portlet:first").find(".btnClose").attr('src') == 'images/btn_minus.jpg')
		{
			element.parents(".portlet:first").find(".btnClose").attr('src', 'images/btn_plus.jpg');
		}
		else {
			element.parents(".portlet:first").find(".btnClose").attr('src', 'images/btn_minus.jpg');
		}
	}
}

function storeClosedOrd()
{
	var cookie = $.cookie(cookieName);
	var closeOrder = "";

	$(".btnClose").each(function (){
		closeOrder += $(this).parents(".portlet").attr('id') + "="+ $(this).attr('src')+",";
	});
		
	var closeOrder = removeComma(closeOrder);
	$.cookie(cookieName, closeOrder, { expires: setCookieExpiry} );
}

function regionToSuburbs(regionID){
	if (regionID==0)
	{
		$("#suburbArea").hide();
	}
	else {
		$("#suburbArea").show();
	}
	url="../suburbs.php?action=regionToSuburbs&regionID="+regionID;
	var selectedSuburbs = $("#selectedSuburbs");
	$("#selectedSuburbs").empty();


	$.getJSON(url, function(result) {
		selectedSuburbs.append($("<option />").val("0").text("All Suburbs"));
	    $('#selectedSuburbs option[value="0"]').attr('selected', 'selected');
		$.each(result, function() {
		    selectedSuburbs.append($("<option />").val(this.SuburbID).text(this.Suburb));
		});
	});
}
