
var _mSvgForced = true;
var _mSvgEnabled = true;
var zcounter = 20000;
 

var vicon = new GIcon();
vicon.image = "/images/marker_bg.png";
vicon.iconSize = new GSize(50, 48);
vicon.iconAnchor = new GPoint(24, 46);

var goldicon = new GIcon();
goldicon.image = "/images/marker_gold.png";
goldicon.iconSize = new GSize(50, 48);
goldicon.iconAnchor = new GPoint(24, 46);

var hicon = new GIcon();
hicon.image = "/images/marker_bg_hover.png";
hicon.iconSize = new GSize(50, 48);
hicon.iconAnchor = new GPoint(24, 46);

var picon = new GIcon();
picon.image = "/images/picon.png";
picon.iconSize = new GSize (16,16);
picon.iconAnchor = new GPoint(8,8);

var help_layer = 0;
var last_help_layer =0;

var manager ;
var live_markers = [];
var live_placemarkers = [];

var icon = new GIcon();
icon.image = "/images/dart_small.png";
icon.shadow = "/images/dart_small_shadow.png";
icon.iconSize = new GSize(27,41);
icon.shadowSize = new GSize(71, 45);
icon.iconAnchor = new GPoint(27,41);


function getAddressResults() {
		var address = new String;
		var url = new String;
		address=$('postcode').value;
		var url="/get_address.php?address=" + address;
		new Ajax(url, {
		method: 'get',
		update: $('searchMapResults'),
		evalScripts: true,
		onComplete: showAddressResults()
		}).request();
	   if (typeof polygon != 'undefined') map.removeOverlay(polygon); 
	    $('marked_region').value=0;
}

function getAddressResultsfp() {
		var address = new String;
		var url = new String;
		address=$('postcode').value;
		var url="/get_address.php?fp=true&address=" + address;
		new Ajax(url, {
		method: 'get',
		update: $('searchMapResults'),
		evalScripts: true,
		onComplete: showAddressResultsfp()
		}).request();
	   
}



function showAddressResults()
{
	if ($('searchMapResults').getHTML!="") {
		$('searchMapResults').style.display='block';
		
	} else
	{
		// go ahead and try google geocoding.
		usePointFromAddress(placeSearchMarker);
		
	}
	
	
}

function showAddressResultsfp()
{
	if ($('searchMapResults').getHTML!="") {
		$('searchMapResults').style.display='block';
		
	} else
	{
		// go ahead and try google geocoding.
		document.location='search.php?searchfor=' + $('postcode').value;
		
	}
	
	
}


function chooseAddress(newaddress)
{
	$('searchMapResults').style.display="none";
	$('postcode').value=newaddress; 
	$('searchMapResults').innerHTML="";
	usePointFromAddress(placeSearchMarker);
}
function chooseLatLng(pos_lat,pos_lng,area,randres,marked_region)
{
	
	if (area!="") {
		distancesel=$('distance');
		for(x=0;x<distancesel.length;x++)
	{
		
		if (distancesel[x].value==area) distancesel[x].selected="selected";
	}
		
	} 
	
	if (marked_region!="") $('marked_region').value=marked_region; 
		$('randomise_results').value=randres;
		
	 var smpoint = new GLatLng(pos_lat,pos_lng);
	placeSearchMarker(smpoint);
}

function chooseAddressfp(newaddress)
{
	$('searchMapResults').style.display="none";
	$('postcode').value=newaddress; 
	$('searchMapResults').innerHTML="";
	document.location='search.php?searchfor=' + newaddress;
}
function chooseLatLngfp(pos_lat,pos_lng,area,randres,marked_region)
{
	
	if (area!="") {
		distancesel=$('distance');
		for(x=0;x<distancesel.length;x++)
	{
		
		if (distancesel[x].value==area) distancesel[x].selected="selected";
	}
		
	} 
	
	if (marked_region!="") $('marked_region').value=marked_region; 
		$('randomise_results').value=randres;
		
	 var smpoint = new GLatLng(pos_lat,pos_lng);
	placeSearchMarker(smpoint);
}

function closeAddress()
{
	
	$('searchMapResults').style.display="none";
}

function usePointFromAddress(callbackFunction) {
  
  var address = new String;
  address = $('postcode').value;
  if (address!="") {
  var country = new String;
  countries=document.getElementsByName('country');
  var c_length=countries.length;
  for (var i = 0; i < c_length; i++)
  {
  	if (countries[i].checked) { country=countries[i].value; }
  }
  
  //address = address + ', ' + country;
  //alert ('Searching for ' + address);
   
  localSearch.setCenterPoint(smap); // Set the center to the search map area.
  localSearch.setSearchCompleteCallback(null, 
    function() {
      
      if (localSearch.results[0]) {    
        // find most likely.. I.e where the lat and lng are in range!
		//new GLatLng(49.5,-10), new GLatLng(59,2.6)
		var ml = 0;
		var all_results = new String;
		var results_txt = new String;
		//alert (localSearch.results.length + " Results!");
		for (x=0;x<localSearch.results.length;x++) {
			var clat=localSearch.results[x].lat;
			var clng=localSearch.results[x].lng;
			//alert (localSearch.results[x].title + ", " + localSearch.results[x].region);
			if (clat>49 && clat<59 && clng>-10 && clng<2.6) { 
				ml=x;
			all_results=all_results + "Lat = " + localSearch.results[x].lat + " Long = " + localSearch.results[x].lng + "<br />";
			//results_txt=results_txt + localSearch.results[x].title  + "<br />";
			}
			//var npoint = new GLatLng(localSearch.results[x].lat,localSearch.results[x].lng);
			//placeSearchMarker(npoint);
		}
		//$('searchMapResults').setHTML(results_txt);
		//alert(all_results); 
		if (all_results!="") {
		var resultLat = localSearch.results[ml].lat;
        var resultLng = localSearch.results[ml].lng;
        var point = new GLatLng(resultLat,resultLng);
        
		callbackFunction(point);
		 }
		 else
		 {
		 	alert("Address or Location not found!");
		 }
      }else{
        alert("Address or Location not found!");
      }
    });  
  /*if (address.match("ireland")==null) {
  	 localSearch.execute(address, "UK");
	}
	else
	{
	 localSearch.execute(address);
		
	}*/
	localSearch.execute(address);
}
 
 else
 {
 	alert("Please enter a Postcode, Town or part of an Address");
	
 }
}



function showTab(thistab) {
	
	alltabs = $('resultsTabs').getElements('div[class^=tabdata]');
	
	for (x=0;x<alltabs.length;x++)
	 {
	 	
		alltabs[x].style.display='none';
		var tabname=alltabs[x].id;
		
		$(tabname+'_button').removeClass('tab_button_active');
	 }
	 //alert(tab);
	 $(thistab).style.display='block';
	 $(thistab+'_button').addClass('tab_button_active');
}

function gennumresults() {
	// Fills the id of num_results with options based on the screen size..  abandonded..
	var va = new Number;
	var ha = new Number;
	var num_results = new Number; 
	va = Math.floor((screen.height-200)/210);
	
	ha = Math.floor((screen.width-200)/310);
	
	num_results = (va*ha);
	
	max=(num_results*10)+1;
	
	optionlist = $('num_results');
	
	for(x=num_results;x<max;x=x+num_results)
	{
		optionlist.options[optionlist.options.length]=new Option (x,x);
		if (x==num_results) optionlist.options[optionlist.options.length-1].selected="selected";
	}
	
	
}



// Where did i get this from????????????? \/ 
 
function grayOut(vis, options) {
	
	// Pass true to gray out screen, false to ungray
	// options are optional.  This is a JSON object with the following (optional) properties
	// opacity:0-100         // Lower number = less grayout higher = more of a blackout 
	// zindex: #             // HTML elements with a higher zindex appear on top of the gray out
	// bgcolor: (#xxxxxx)    // Standard RGB Hex color code
	// grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
	// Because options is JSON opacity/zindex/bgcolor are all optional and can appear
	// in any order.  Pass only the properties you need to set.
	var options = options || {}; 
	var zindex = options.zindex || 50;
	var opacity = options.opacity || 70;
	var opaque = (opacity / 100);
	var bgcolor = options.bgcolor || '#000000';
	var dark=document.getElementById('darkenScreenObject');
	if (!dark) {
		// The dark layer doesn't exist, it's never been created.  So we'll
		// create it here and apply some basic styles.
		// If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
		var tbody = document.getElementsByTagName("body")[0];
		var tnode = document.createElement('div');           // Create the layer.
		tnode.style.position='absolute';                 // Position absolutely
		tnode.style.top='0px';                           // In the top
		tnode.style.left='0px';                          // Left corner of the page
		tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
		tnode.style.display='none';                      // Start out Hidden
		tnode.id='darkenScreenObject';                   // Name it so we can find it later
		tbody.appendChild(tnode);                            // Add it to the web page
		dark=document.getElementById('darkenScreenObject');  // Get the object.
	}
	if (vis) {
		// Calculate the page width and height 
		if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
			var pageWidth = document.body.scrollWidth+'px';
			var pageHeight = (document.body.scrollHeight + 200)+'px';
		} else if( document.body.offsetWidth ) {
			var pageWidth = document.body.offsetWidth+'px';
			var pageHeight = (document.body.offsetHeight + 200)+'px';
		} else {
			var pageWidth='100%';
			var pageHeight='100%';
		}   
		//set the shader to cover the entire page and make it visible.
		dark.style.opacity=opaque;                      
		dark.style.MozOpacity=opaque;                   
		dark.style.filter='alpha(opacity='+opacity+')'; 
		dark.style.zIndex=zindex;        
		dark.style.backgroundColor=bgcolor;  
		dark.style.width= pageWidth;
		dark.style.height= pageHeight;
		dark.style.display='block';                          
	} else {
		dark.style.display='none';
	}
}

function getScrollHeight() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return scrOfY;
} 

function createMarkerClickHandler(marker, text, link) {
	return function() {
		marker.openInfoWindowHtml(
			'<h3>' + text + '</h3>' +
			'<p><a href="http://localhost/' + link + '">More Info</a></p>'
		);
		return false;
	};
}

function movezhigher(marker,b) {
		zcounter=zcounter+2;
        var newz= zcounter;
		//alert ('Z is now:' + newz);
		return newz;
      }

function createMarker(lat,lng,pic,listid,zhigher,gold) {
				
				if (typeof zhigher == 'undefined' ) zhigher = 0;
				if (typeof gold == 'undefined') gold = 0;
				if (gold==0 ) { theicon=vicon; } else { theicon=goldicon; }
				
				var point = new GLatLng(lat,lng);
				
				//if (posi.length==1) var offset = new GSize(-4,-7);
				//if (posi.length==2) var offset = new GSize(-8,-7);
				var label_txt = '<img src="/thumbimg.php?pic=pictures/' + pic + '&width=42" />';
				var offset = new GSize(-26, -40);
				
				if (zhigher==0)
				{
				var marker = new LabeledMarker(point, {icon: theicon, labelText: label_txt, labelOffset: offset, listid: listid, origpic: pic });
				}
				else
				{
				var marker = new LabeledMarker(point, {icon: theicon, labelText: label_txt, labelOffset: offset, listid: listid, origpic: pic, zhigh: zcounter, zIndexProcess:movezhigher });	
				}
				
				live_markers.push(marker);
				
				
				GEvent.addListener(marker, "click", function() {
	  			
				scroll.toElement('result_'+listid);

				highlite(listid,lat,lng);
				
				
				}); 
				
				map.addOverlay(marker);
				bounds.extend(point);
}

function createPlaceMarker(lat,lng,title,description,link,email) {
						
				var point = new GLatLng(lat,lng);
				
				var marker = new GMarker(point, { icon : picon});
				var urltxt='';
				if (link!="") urltxt='<a href="http://' + link + '" target="_blank" >Website</a>';
				var emailtxt='';
				if (email!="") emailtxt='<a href="mailto:' + email + '">Email</a>';
				marker.placeinfo = '<h1>' + title + '</h1><p>' + description + '</p>' + urltxt + '<br />' + emailtxt;
				live_placemarkers.push(marker);
								
				GEvent.addListener(marker, "click", function() {
				map.panTo(point);
				$('places_div_inner').innerHTML = this.placeinfo;
				var divleft = (getWidth() / 2) - 125;
				$('places_div').style.left = divleft+'px';
				$('places_div').style.display = 'block';
				//marker.openInfoWindowHtml(this.placeinfo);
				//alert (this.placeinfo);
				//setTimeout('hidePlaces()',15000);
				}); 
				
				map.addOverlay(marker);
				//bounds.extend(point);
}

function hidePlaces()
{
	
	$('places_div').style.display = 'none';
}

function highlite (listid,lat,lng) {
	var point = new GLatLng(lat,lng);
	
	map.panTo(point);
	//map.setCenter(point, 12);
		
	
		//var x = document.getElementsByTagName('div');
				for (var i = 0; i < live_markers.length; i++) 
				{ 
				live_markers[i].setImage("/images/marker_bg.png");
				if (live_markers[i].listid==listid) { 
					var thismarker=i;
					}
				}
				
				var old_latlng = live_markers[thismarker].latlng;
				var old_listid = live_markers[thismarker].listid;
				var old_pic = live_markers[thismarker].origpic;				
				
				live_markers[thismarker].remove();
				live_markers.splice(thismarker,1);
				
				createMarker(old_latlng.lat(),old_latlng.lng(),old_pic,old_listid,20000);
				
						for (var i = 0; i < live_markers.length; i++) 
				{ 
				live_markers[i].setImage("/images/marker_bg.png");
				if (live_markers[i].listid==listid) { 
					live_markers[i].setImage("/images/marker_bg_hover.png");
					}
				}
				
				
				
				
				var x = document.getElementsByTagName('div');
				
				
				for (var i = 0; i < x.length; i++)
				{
				removeClass(x[i],"listing_highlite");
				
				}
		
	      
				addClass(document.getElementById('result_'+listid),'listing_highlite');
				
	
}

// Replace these 3 functions with Mootools!!!
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}


function setMapsize()
{
	
	var mapwidth=getWidth();
	if (mapwidth==0) mapwidth = document.body.X; // Fix for IE6?
	var mapheight=getHeight();
	if (mapheight==0) mapheight = document.body.Y; // Fix for IE6?
	if (mapwidth>0) {
	mapwidth = mapwidth - 600;
	mapheight = mapheight - 110;
	$('resultMap').style.width=mapwidth+'px';
	$('resultMap').style.height=mapheight+'px';
	$('Results').style.height=mapheight+'px';
	$('ResultsHolder').style.height=mapheight+'px';
	$('Shortlist').style.height=mapheight+'px';
	//alert($('resultMap').style.width);
	map.checkResize();
	}
}

function setSLMapsize()
{
	
	var mapwidth=getWidth();
	if (mapwidth==0) mapwidth = document.body.X; // Fix for IE6?
	var mapheight=getHeight();
	if (mapheight==0) mapheight = document.body.Y; // Fix for IE6?
	if (mapwidth>0) {
	mapwidth = mapwidth - 360;
	//mapheight = mapheight - 110;
	$('SLresultMap').style.width=mapwidth+'px';
	 
	//alert($('resultMap').style.width);
	map.checkResize();
	}
}

function shortlistDo(id,action)
{
	url = '/shortlist_frame.php?do='+action+'&id='+id;
	//if the iframe exists use that other wise use ajax.
	if (!window.shortlist_frame) {
		url=url+"&show=false";
	var slAjax = new Ajax(url, {method: 'get'});
	slAjax.request();
	
	}
	else {
	
	window.shortlist_frame.location=url;
	}
	if (action=='add') {
		//$('shortlist_'+id).setHTML='<a id="shortlist_'+ id + '" title="Remove from Shortlist" href="javascript:shortlistDo(\''+ id +'\',\'del\');  void(0);" >Shortlist <img src="/images/delete.png" /></a>';
		document.getElementById('shortlist_'+id).outerHTML='<a id="shortlist_'+ id + '" title="Remove from Shortlist" href="javascript:shortlistDo(\''+ id +'\',\'del\');  void(0);" >Shortlist <img src="/images/delete.png" /></a>';
		
	}
	if (action=='del') {
		
		document.getElementById('shortlist_'+id).outerHTML='<a id="shortlist_'+ id + '" title="Add to Shortlist" href="javascript:shortlistDo(\''+ id +'\',\'add\');  void(0);" >Shortlist <img src="/images/add.png" /></a>';
	}
}


function openpage(page_url,boxheight)
{
if(typeof boxheight=='undefined') boxheight=280;
var width=screen.width;
var height=screen.height;
var left=Math.round((width/2)-200);
var top=Math.round((height/2)-(boxheight/2));
msgWindow=window.open(page_url,'popwindow','resizable=no,width=400,height=' + boxheight + ',top=' + top + ',left=' + left);
if (msgWindow.opener == null) msgWindow.opener = self;
}

function showSearchHelp()
{
	grayOut(true,{'opacity':'37'});
	$('help_layer').style.display='block';
	
	showHelpLayer(1);
}

function showHelpLayer(layerid)
{
	grayOut(true,{'opacity':'37'}); // This makes sure the results returner doesnt ungray.
	newlayerid=layerid+1;
	if (layerid>4) {
		
		help_layer=setTimeout('hideHelpLayer()',25000);
		
	} else
	{
		$('help_layer_'+layerid).style.display='block';
		last_help_layer=setTimeout('showHelpLayer('+newlayerid+')',700);
	}
	
}

function hideHelpLayer()
{
	grayOut(false);
		
		for (x=1;x<5;x++)
			{
				$('help_layer_'+x).style.display='none';
				
			}
		$('help_layer').style.display='none';
	
	clearTimeout(help_layer);
	clearTimeout(last_help_layer);
}


function placeSearchMarker(point,offset)
{
	
	if (typeof offset == 'undefined') offset=0; 
	searchmarker.setPoint(point);
	if (window.aMkr1) smap.removeOverlay(aMkr1);
	if ($('distance').value!=9999999) {
	  distinKM = $('distance').value * 1.609344;
		aMkr1 = new BDCCCircle(point, distinKM,site_color_d,3,0.7,true,site_color_d,new Array(0.5,0.01),""); //"Searching within " + $('distance').value + " miles");
		smap.addOverlay(aMkr1);
	}
		
	$('current_lat').value=point.lat();
	$('current_lng').value=point.lng();
	currentzoom=smap.getZoom();
	//if (currentzoom==4) smap.setZoom(6);
	smap.panTo(point);
	
	getResults(offset);
	$('randomise_results').value='0';
	//optionsSlide.slideIn();
}

function moveSearchMarker(thismarker)
{

point = new GLatLng(thismarker.getPoint().lat(),thismarker.getPoint().lng());
if ($('distance').value!=9999999) { aMkr1.setPoint(point); }

$('current_lat').value=point.lat();
	$('current_lng').value=point.lng();

	currentzoom=smap.getZoom();
	if (currentzoom==4) smap.setZoom(6);
	smap.panTo(point);
	
	getResults(0);
	//optionsSlide.slideIn();
}

function moveResMarker(thismarker)
{

point = new GLatLng(thismarker.getPoint().lat(),thismarker.getPoint().lng());

if ($('distance').value!=9999999) { aMkr1.setPoint(point); }
searchmarker.setPoint(point);

$('current_lat').value=point.lat();
	$('current_lng').value=point.lng();
	currentzoom=smap.getZoom();
	if (currentzoom==4) smap.setZoom(6);
	smap.panTo(point);
	searchmarker.setPoint(point);
	getResults();
	//optionsSlide.slideIn();
}

function checkEnter(e){ //e is event object passed from function invocation
var characterCode; //literal character code will be stored in this variable

if(e && e.which){ //if which property of event object is supported (NN4)
e = e;
characterCode = e.which; //character code is contained in NN4's which property
}
else{
e = event;
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
document.getElementById('postcode').blur;
//usePointFromAddress(placeSearchMarker); //submit the form
getAddressResults();
return false 
}
else{
return true 
}

}

function checkEnterfp(e){ //e is event object passed from function invocation
var characterCode; //literal character code will be stored in this variable

if(e && e.which){ //if which property of event object is supported (NN4)
e = e;
characterCode = e.which; //character code is contained in NN4's which property
}
else{
e = event;
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
document.getElementById('postcode').blur;
//usePointFromAddress(placeSearchMarker); //submit the form
getAddressResultsfp();
return false 
}
else{
return true 
}

}
