var clickHandler;
var map = null;
var lat;
var lng;
var searchresultlist;
var bounds;
var currentPage;
var numberOfPages;
var mapCompat = true;
var priorityicon;
var greyicon;
var gmarkersList = new Array();
var eventListeners = new Array();
var mapLoaded=false;
var listenerCount = 0;
var searchTypeStr="";
var searchStr = "";
var searchPostCodeStr = "";

var localGoogleSearch = null;
var postCodeLat = 0;
var postCodeLong = 0;
var maximumDistance = 0;


var firstBannerRun = true; // so the banner doesn't double show on first refresh
var zone1OrigSrc="";
var zone2OrigSrc="";
var productionName = "";

var defaultSearchText = "enter a company, category, contact or credit";


var homeDirectory = "/directories/rmp_directoryfeed.php";
//var homeDirectory = "./rmp_directoryfeed.php";



function setProductionName (pname){
		productionName = pname;
}


function trimStr(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}


function startMap (){
		map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(0, 0), 13);
		setIcons();
		mapLoaded = true;
		
		
}

function setIcons(){
	priorityicon = null;
	priorityicon = new GIcon(G_DEFAULT_ICON);
	priorityicon.image = "/directories/images/png/prioritypin.png";
	priorityicon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	priorityicon.iconSize = new GSize(20, 34);
	priorityicon.shadowSize = new GSize(37, 34);
	priorityicon.iconAnchor = new GPoint(10, 34);
	greyicon = null;
	greyicon = new GIcon(G_DEFAULT_ICON);
	greyicon.image = "/directories/images/png/pin.png";
	greyicon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	greyicon.iconSize = new GSize(20, 34);
	greyicon.shadowSize = new GSize(37, 34);
	greyicon.iconAnchor = new GPoint(10, 34);
		

}

function searchForPostcode(postcode, callbackFunction) {
	
		
	localGoogleSearch.setSearchCompleteCallback(null, 
		function() {
			
			if (localGoogleSearch.results[0])
			{					
				var resultLat = localGoogleSearch.results[0].lat;
				var resultLng = localGoogleSearch.results[0].lng;
				var point = new GLatLng(resultLat,resultLng);
				callbackFunction(point);
			}else{
				
				$.growlUI('Post Code', 'Sorry - post code not recognized.'); 		
			}
		});	
	
	
		
	localGoogleSearch.execute(postcode + ", UK");
}

function getCoOrds(point)
{	
	postCodeLat = point.lat();
 	postCodeLong = point.lng();
		
	$.cookie('postCodeLat', postCodeLat, { path: '/', expires: 360 });
	$.cookie('postCodeLong', postCodeLong, { path: '/', expires: 360 });	

	// kick off a search
	patternSearch();

}







$(document).unload(function() {
		GUnload();
		
	});	


function setPageCookie(pageNum){
	$.cookie('directory_page', pageNum, { path: '/', expires: 360 });
}


function getPageCookie(){
	
	var page = 1;
	
	page = $.cookie('directory_page');
	if ( page == null ) page = 1;
	return page;
}

function setPageCountCookie(pageCount){
	$.cookie('directory_pagecount', pageCount, { path: '/', expires: 360 });
}


function getPageCountCookie(){
	
	var pageCount = 0;
	
	pageCount = $.cookie('directory_pagecount');
	if ( pageCount == null ) pageCount = 0;
	
	return pageCount;
}


function setMaxDistanceCookie(maxdistance){
	 $.cookie('maxdistance',maxdistance, { path: '/', expires: 360 }); 
}



function getMaxDistanceCookie(){
	
	var maxDistance = 0;
	
	maxDistance = $.cookie('maxdistance');
	if ( maxDistance == null ) maxDistance = 0;
		
	return maxDistance;
}




$(document).ready(function() {
						   
						   
    if (GBrowserIsCompatible()) {		   
		mapCompat = true;  		
			
    } else { mapCompat = false; }
	
	
	localGoogleSearch = new GlocalSearch();
	
	
	 $('a#loadspinner').show();
	 searchresultlist = null;
	 
	 searchPostCodeStr = $.cookie('searchpostcode');
	 postCodeLat = $.cookie('postCodeLat');
	 postCodeLong = $.cookie('postCodeLong');
	
	 
	// get the current page cookie
	currentPage = getPageCookie();
	numberOfPages = getPageCountCookie();

    maximumDistance = getMaxDistanceCookie();
		
	// get the clipboard
	$('#clipboardlist').html($.cookie("clipboard"));	
			
	retrieveRecords(null, "refresh", currentPage, numberOfPages, maximumDistance);
	 
    
    $('a#save').click(function() {
        $('div#formular').hide('slow');
        $.post( homeDirectory,
               { type: 'upload',
                 name: $('form').find('input').get(0).value,
                 latitude: postCodeLat,
                 longitude: postCodeLong
               }, 
               processLocations );        
    });
    
    $('a#cancel').click(function() {
        $('div#formular').hide('slow');
    });
    
	
    $('a#zoom_show_all').click(function() {
        zoomShowAll();
    }); 
	
	$('a#firstbtn').click(function() {
	   $('a#loadspinner').show();	
	   searchresultlist = null;		
	   retrieveRecords (null, "refresh", 1, numberOfPages, maximumDistance);	  	   
    });
	
	$('a#prevbtn').click(function() {
		if (	currentPage > 1 ){			
			$('a#loadspinner').show();
			searchresultlist = null;			
			retrieveRecords (null, "refresh", --currentPage, numberOfPages, maximumDistance);		
		}
    })
	
	$('a#nextbtn').click(function() {		
		if ( currentPage + 1 <= numberOfPages ) {			
			$('a#loadspinner').show();	
			searchresultlist = null;		
			retrieveRecords (null, "refresh", ++currentPage, numberOfPages, maximumDistance);			
		}		
    })
	
	$('a#lastbtn').click(function() {								  
		$('a#loadspinner').show();	
		searchresultlist = null;		
		retrieveRecords (null, "refresh", numberOfPages, numberOfPages, maximumDistance);
    })
	
	$('a#firstbtn2').click(function() {
	   $('a#loadspinner').show();	
	   searchresultlist = null;		
	   retrieveRecords (null, "refresh", 1, numberOfPages, maximumDistance);	  	   
    });
	
	$('a#prevbtn2').click(function() {
		if (	currentPage > 1 ){			
			$('a#loadspinner').show();
			searchresultlist = null;			
			retrieveRecords (null, "refresh", --currentPage, numberOfPages, maximumDistance);		
		}
    })
	
	$('a#nextbtn2').click(function() {		
		if ( currentPage + 1 <= numberOfPages ) {			
			$('a#loadspinner').show();	
			searchresultlist = null;		
			retrieveRecords (null, "refresh", ++currentPage, numberOfPages, maximumDistance);			
		}		
    })
	
	$('a#lastbtn2').click(function() {								  
		$('a#loadspinner').show();	
		searchresultlist = null;		
		retrieveRecords (null, "refresh", numberOfPages, numberOfPages, maximumDistance);
    })
	
	
	$('#searchinputbox').click(function() {				
			
		var inputText = "";
	 
	 	inputText = $("#searchinputbox").attr("value");
	 	 
	 	inputText = trimStr(inputText);
		
		if ( inputText == defaultSearchText ){
			
			$("#searchinputbox").attr("value","");
				
		}
		
		
    })
		
	$("#searchinputbox").blur(function () {
        
    
	 	var searchTxt = "";
	 
	 	searchTxt = $("#searchinputbox").attr("value");
	 	 
	 	searchTxt = trimStr(searchTxt);
					
		if (searchTxt == "")
		{
			$("#searchinputbox").attr("value", defaultSearchText);
		}
		
	});
		
	
	$('#searchinputbox').bind('keypress', function(e) {
        if(e.keyCode==13){
               patternSearch();
        }
	});

	
	$('#gobtn').click(function() {				
					
		patternSearch();
    })
	
	
	$('#clearbtn').click(function() {				
					
		clearSearch();
    })
	
	
	$("#searchpostcode").blur(function () {
        
    
	 	var postCodeTxt = "";
	 
	 	postCodeTxt = $("#searchpostcode").attr("value");
	 	 
	 	searchPostCodeStr = trimStr(postCodeTxt);
					
		if (searchPostCodeStr == null || searchPostCodeStr == "")
		{
			postCodeLat = 0;
 			postCodeLong = 0;
	
			$.cookie('postCodeLat', postCodeLat, { path: '/', expires: 360 });
			$.cookie('postCodeLong', postCodeLong, { path: '/', expires: 360 });			
			$.cookie('searchpostcode', searchPostCodeStr, { path: '/', expires: 360 });		
			
		}
		else 
		{			
			searchForPostcode(searchPostCodeStr, getCoOrds);			
			$.cookie('searchpostcode', searchPostCodeStr, { path: '/', expires: 360 });				
		}
	});
	
	
	
	
	
	
	
	$("#searchproduct").change(function() 
    { 
        var cat; 			
 
        cat =  $('#searchproduct option:selected').text() 
		
       $("#searchinputbox").attr("value", cat);
	 	   
	   searchStr = cat;
	   
	   setSearchCookie(1, $("#searchproduct").val(), cat);
	  
      
    }); 
	
	
	$("#maxdistance").change(function() 
    { 
         setMaxDistanceCookie( $("#maxdistance").val());
		      
    }); 
	
	
	
	$('select#maxdistance').selectToUISlider({
		
			labels: 9, 
			
			sliderOptions: { 
							  stop: function(e,ui) {
							  
							  		if ( postCodeLat == 0 && postCodeLong == 0 ){
									
										$.growlUI('Filter By Distance', "Please enter your postcode in 'Your Location'."); 
									
									}
									else {							  		
										setMaxDistanceCookie( $("select#maxdistance").val());
										patternSearch();
										}
									}
							}
					}); 
	
	
	
});



function patternSearch()
{
	searchStr = $("#searchinputbox").attr("value");
		
		searchStr = trimStr(searchStr);
		
		if ( defaultSearchText == searchStr ) searchStr="";				
				
							
		if ( searchStr.length > 0){ 								
			$('a#loadspinner').show();	
			searchresultlist = null;			
			retrieveRecords (null, "pattern", 1, 0, maximumDistance);			
		
		} else {			
	
			retrieveRecords(null, "refresh", 1, 0, maximumDistance);
		
		}
}


function clearSearch()
{
		
	$("#searchproduct").val(0);
	
	
	// this is not setting the slider back to the all value
	$("#maxdistance").val('Any');
	
			
	//$("#maxdistance").val(0);
			
	setSearchCookie(0, 0, "");	
		
	maximumDistance = 0;
	
	 setMaxDistanceCookie(maximumDistance);
	
	retrieveRecords(null, "refresh", 1, 0, 0);
	
}






function retrieveRecords (obj, searchInvocation, page, numberOfPagesInResultset, maxDistance){
	

	var searchId = 0;
	var searchType = 0;
	
	var maxDistanceLocal = 0;
	
	
	searchStr = $("#searchinputbox").attr("value");
			
	if ( searchInvocation == "pattern")
	{		
		if (searchStr == $.cookie('searchStr') )
		{ // repeat last search
			searchInvocation ="refresh";					
		}	
	}


	 maximumDistance = getMaxDistanceCookie();
	 
	 
	
	 $("#maxdistance").val(maximumDistance);
	 
	 
	 if ( maximumDistance == "Any") {	 	
		maxDistanceLocal =  0;	 
	 } else {
		maxDistanceLocal =  maximumDistance;
	 }
	
	
	switch (searchInvocation) {
		
	case "new":
		{	
			searchTypeStr = obj.info;
			
			if ( searchTypeStr.match("category") != null )
			{
				searchType = 1;	
				searchTypeStr="category";
			}
			else if ( searchTypeStr.match("listing") != null )
			{
				searchType = 2;	
			}
			else if ( searchTypeStr.match("key credit") != null )
			{
				searchType = 3;	
			}
			else if ( searchTypeStr.match("key contact") != null )
			{
				searchType = 4;	
			}
			
			
			
			setSearchCookie(searchType, obj.id, obj.value);
			
			searchStr = obj.value;
			
			$.post(homeDirectory,
					   { page: page,
						 type:searchType,
						 id:obj.id,
						 searchtext:obj.value,
						 latitude: postCodeLat,
                 		 longitude: postCodeLong,
						 numberpages: numberOfPagesInResultset,
						 maxdistance: maxDistanceLocal
						}, 
					   processLocations );
		} 
	break;
	case "refresh":
		{	
		
			
			searchId = $.cookie('searchId');
			if ( searchId == null ) searchId = 0;
			
			searchType = $.cookie('searchType');
			if ( searchType == null ) searchType = 0;
				
			searchStr = $.cookie('searchStr');			
			if ( searchStr == null ) searchStr = "";
						
			if ( "" == searchStr ){				
				$("#searchinputbox").attr("value", defaultSearchText);
			}
			else {
				$("#searchinputbox").attr("value", searchStr);
			}
			
			
			$("#searchpostcode").attr("value", searchPostCodeStr);
					
			searchStr = trimStr(searchStr);
			if ( searchStr.length <= 0)
			{ 								
				searchTypeStr= "premium";
				searchType = "5";								
				setSearchCookie(searchType, 0, "");				
			}
			
			
			switch (searchType){
				
				case "0": searchTypeStr= "pattern match";
						break;				
				case "1":	searchTypeStr= "category";					
						
						// set the category dropdown
						$("#searchproduct").val(searchId);

						break;
				case "2":
						searchTypeStr= "listing";	
						break;		
				case "3":
						searchTypeStr= "key credit";
						break;		
				case "4" :
						searchTypeStr= "key contact";
						break;		
				case "5" :
						searchTypeStr= "premium";						
						break;				
						
			}
		
			$.post(homeDirectory,
					   { page: page,
						 type:searchType,
						 id:searchId,
						 searchtext:searchStr,
						 latitude: postCodeLat,
                 		 longitude: postCodeLong,
						 numberpages: numberOfPagesInResultset,
						 maxdistance: maxDistanceLocal
						}, 
					   processLocations );
			
		}
		break;
		
		case "pattern":
		
			searchStr = $("#searchinputbox").attr("value");
									
			searchType = 0;
			
			setSearchCookie(searchType, 0, searchStr);
		
			searchTypeStr= "pattern match";
		
			$.post(homeDirectory,
					   { page: 1,
						 type:searchType,
						 id:0,
						 searchtext:searchStr,
						 latitude: postCodeLat,
                 		 longitude: postCodeLong,
						 numberpages: numberOfPagesInResultset,
						 maxdistance: maxDistanceLocal
						}, 
					   processLocations );
			break;
	
	}
	
	if ( searchStr=="")
	document.title = 'Premium listings on ' + productionName;
	else
	document.title = searchStr + ' on ' + productionName;
	
	
	
	if ( firstBannerRun == false ){		
		
		// refresh banner
		var selectedBannerIdZone1 = null;
		var selectedBannerIdZone2 = null;
						
		if ( searchType == 1) {
		
			var sponLoop = 0;		
							
			for (sponLoop = 0; sponLoop < prodIDSponsorArray.length; sponLoop++){				
				
				if ( searchId == prodIDSponsorArray[sponLoop] && zoneIDSponsorArray[sponLoop] == 2 ){
					selectedBannerIdZone2 = bannerIDSponsorArray[sponLoop];												
				}							
				
				if ( searchId == prodIDSponsorArray[sponLoop] && zoneIDSponsorArray[sponLoop] == 1 ){
					selectedBannerIdZone1 = bannerIDSponsorArray[sponLoop];												
				}							
			}			
		}		
		
		bannerSwap(selectedBannerIdZone2, 'topBannerFrame');				
		bannerSwap(selectedBannerIdZone1, 'sideBannerFrame');		
		
	}
	
	firstBannerRun = false;
	
}



// function to swap out the top banner
function bannerSwap(id, zoneName) {
		// Get the iframe object
		obj = document.getElementById(zoneName);
		
		// Replace the iframe src with it-self, but change the cache buster value
			
		if (zoneName == 'topBannerFrame' && zone2OrigSrc=="")  	zone2OrigSrc = obj.src;
		if (zoneName == 'sideBannerFrame' && zone1OrigSrc=="")  	zone1OrigSrc = obj.src;
			
			
		if (id == null){
			// induce a random banner swap
			
			
			//obj.src = 'http://www.maketimemedia.com/openx/www/delivery/afr.php?n=a0c3a9ee&amp;zoneid=2&amp;cb='+Math.floor(Math.random()*99999999999);
			if (zoneName == 'topBannerFrame' ) obj.src = zone2OrigSrc;
			
			if (zoneName == 'sideBannerFrame' ) obj.src = zone1OrigSrc;
			
			
			
			obj.src = obj.src.replace(/cb=[a-zA-Z0-9-_]+(&.*)?/, 'cb='+Math.floor(Math.random()*99999999999)+'$1');
			
			
		} else {		
			// select specific banner	
			obj.src = 'http://www.maketimemedia.com/openx/www/delivery/afr.php?n=a0c3a9ee&what=bannerid:'+id+'&cb=71819294679';
			
		}
}
	



function setSearchCookie(searchType, id, searchStr)
{
	
	
	$.cookie('searchId', id, { path: '/', expires: 360 });
	$.cookie('searchType', searchType, { path: '/', expires: 360 });
	$.cookie('searchStr', searchStr, { path: '/', expires: 360 });
	
}

var RefreshCount = 0;



// refresh the data on tab select
function getPageData(){
	
	$('a#loadspinner').show();	
		
	searchresultlist = null;
	
	retrieveRecords (null, "refresh", currentPage, numberOfPages, maximumDistance);
						
}


function getProfilePeek(parId, id){
	
	
	 
	 $.get("/directories/rmp_profilebox.php", { pid: parId },
  function(data){
   	
	$('#peekbox_'+id).html(data);
  });

	 

}


function addToClipboard(id, name ){
	
	var html;
	var list ;
	var options = { path: '/', expires: 360 };
	
	
	list = $('#clipboardlist').html();	
	if ( list.indexOf(name)==-1){
		
		html = '<a href=\"/listing/'+id+'\">'+name+'</a><br />';	
		
		$('#clipboardlist').append(html);
			
		list = $('#clipboardlist').html();	
		
		$.cookie("clipboard", list , options);
	} else {
		$.growlUI('Clipboard', 'Contact already on clipboard'); 		
	}
}



function processLocations(content) {
	
	
	
	
	var $tabs = $('#innertabs').tabs();
	var selectedTab = $tabs.data('selected.tabs');					   
	
	eval("searchresultlist = "+content);
	
	$('p#location_list').html('');
	$('ul#resultlist').html('');
	
	
	//var index = 0;
	
	
	

	if ( mapCompat ==  true  && selectedTab == 1) { // map
		
		
		if ( mapLoaded == false){
			startMap ();   			
		}
		
		// clear down the event listeners
		var listLoop = 0;
				
		
		for (listLoop = 0; listLoop < listenerCount; listLoop++){
			
			GEvent.removeListener(eventListeners[listLoop]);				
		}
		
		listenerCount = 0;
				
		
		map.clearOverlays(); 
			
		
		gmarkersList = null;		
		eventListeners = null;
		
		gmarkersList = new Array();
		eventListeners = new Array();
		
		
	
	}
	
   
    if (  searchresultlist == null || searchresultlist[0] == null || searchresultlist.count < 1 ) {
		$('a#loadspinner').hide();
		
		if ( maximumDistance > 0 ) {
				 $('#resultstats').html('No results found for '+searchTypeStr + ' \'' + searchStr+'\' within ' + maximumDistance + ' miles');
		} else {
				$('#resultstats').html('No results found for '+searchTypeStr + ' \'' + searchStr+'\'');
		}
		return;
	}
		
	currentPage = parseInt(searchresultlist[0].page);		
	// set the current page cookie
	setPageCookie(currentPage);
		
	numberOfPages = parseInt(searchresultlist[0].totalpages);	
	// set the page count cookie
	setPageCountCookie(numberOfPages);
	
	
	
	
	
	if (searchTypeStr== "premium")
	$('#resultstats').html('Featured listings' );
	else {
	 	
		if ( maximumDistance > 0 ) {				 
				 $('#resultstats').html('Page '+currentPage+' of '+numberOfPages+' : search results for '+searchTypeStr + ' \'' + searchStr+'\' within ' + maximumDistance + ' miles')
		} else {
				$('#resultstats').html('Page '+currentPage+' of '+numberOfPages+' : search results for '+searchTypeStr + ' \'' + searchStr+'\'');
		}
		
		
	}
	
	
	var navString = "";
	var canGoFwd = 'ui-state-disabled';
	var canGoBwd = 'ui-state-disabled';
	
	if ( currentPage > 1 ){
		canGoBwd = '';		
	}
	if ( currentPage < numberOfPages ){
		canGoFwd = '';		
		
	}
	
	$("a#firstbtn").attr("class", "fg-button ui-state-default "+canGoBwd+" fg-button-icon-right ui-corner-all");
	$("a#prevbtn").attr("class", "fg-button ui-state-default "+canGoBwd+" fg-button-icon-right ui-corner-all");
	$("a#nextbtn").attr("class", "fg-button ui-state-default "+canGoFwd+" fg-button-icon-right ui-corner-all");
	$("a#lastbtn").attr("class", "fg-button ui-state-default "+canGoFwd+" fg-button-icon-right ui-corner-all");
	
	$("a#firstbtn2").attr("class", "fg-button ui-state-default "+canGoBwd+" fg-button-icon-right ui-corner-all");
	$("a#prevbtn2").attr("class", "fg-button ui-state-default "+canGoBwd+" fg-button-icon-right ui-corner-all");
	$("a#nextbtn2").attr("class", "fg-button ui-state-default "+canGoFwd+" fg-button-icon-right ui-corner-all");
	$("a#lastbtn2").attr("class", "fg-button ui-state-default "+canGoFwd+" fg-button-icon-right ui-corner-all");

/*
	searchresultlist.forEach(function(element, index, array) 
	{
	*/
		
	jQuery.each(searchresultlist, function(index, element) {
		
        var marker ;
        var disptype = '';
		
		if (element.priority == 1)
		{
			if ( selectedTab == 1) 
			{
			
				if ( element.postcode_id > 0  && mapCompat ==  true ) {
								
					marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.name, icon:priorityicon});
					//disptype ='mouseover';
					
					disptype ='click';
							
					map.addOverlay(marker);					
					
					eventListeners[listenerCount] =	GEvent.addListener(marker, disptype, function() {
						marker.openInfoWindowHtml('<div class=\"popupbody\">'+element.name+'<div class=\"popuptext\"><br/><a  href="/listing/'+element.id+'\"  style="color:#005586;font:100% Trebuchet MS, Arial, Helvetica, Sans-Serif;">click to view</a></div></div>');       
					});
					
					
								
					 link = '<a href="#" onclick="moveMapTo('+listenerCount+')">'+element.name+'</a><br />';
					
					 gmarkersList[listenerCount]=marker;
										
					listenerCount++;
								
					
					$('p#location_list').append(link);
				}
			} else {
				// list	
				
				link = '<li id=\"directoryentry_'+index+'\" class=\"directoryentry resultrow\"  >'; 
				
				if ( element.logourl != null ) {
				link += '<a class=\"image\"   href=\"/listing/'+element.id+'\">';				
				link +=  '<img src=\"'+ element.logourl +'\"  height=\"'+element.logoheight+'\"/>';				
				link += '</a>';
				}				
						
				if ( element.logourl != null ) {		
				
				if ( element.logoheight < 150 ) {
					link += '<div style=\"height:150px\">';	
				} else {
					link += '<div style=\"height:'+element.logoheight+'px\">';
				}
				}					
						
				
				link += '<p id=\"directoryentry_'+index+'_snapshot\" class=\"snapshot\">';
				link += '<a href=\"/listing/'+element.id+'\">';			
				
				link += '<span class=\"prioritycompany\">'+element.name+' </span>';
				
				link += '<span class=\"address\">';
				
				if (element.town != null ) link += element.town+', ';
				if (element.county != null ) link += element.county+', ';
				if (element.country != null ) link += element.country+', ';
				if (element.postcode != null ) link += element.postcode;
				
				link += '</span></p>';
				link += '</a>';
				
				if (element.distanceto != null ){
				link += '<p><span class=\"tel\">';				
				 link += 'Distance: '+element.distanceto + ' miles (approximately)';				
				link += '</span>';
				link += '</p>';
				}
				
				if (element.tel != null ){
				link += '<p><span class=\"tel\">';				
				 link += 'tel: '+element.tel;				
				link += '</span>';
				link += '</p>';
				}
				
				
				
				
				if (element.weburl != null ) {
				
				var parWeb=element.weburl;				
				var parWebURL = parWeb; 
				if (parWeb.indexOf("http://")==-1)
				{					
					parWebURL="http://"+parWeb;					
				}
				
				link += '<p><span class=\"tel\">';
				link += 'web: <a href=\"'+parWebURL+'\">'+parWeb+'</a>';				
				link += '</span>';				
				link += '</p>';
				}
				
				if ( element.logourl != null ) {					
					link += '</div>';	
				}
				
				
				
				link += '<ul id=\"directoryentry_'+index+'_tools\" class=\"directory_iconset inline\">';								
				link += '<li>';				
				link += '<a id=\"profilepeek_'+index+'\" class=\"more_prop\" title="Preview" >Profile Peek</a>';				
				link += '</li>';	
				
				link += '<li>';				
				link += '<a id=\"clipboard_'+index+'\" class=\"clipboard\" title="Add to clipboard" >Clipboard</a>';				
				link += '</li>';	
				
				link += '<li class=\"label\" style=\"opacity: 0; display: inline-block;\">label</li>';				
				link += '</ul>';
				link +='<div id=\"peekbox_'+index+'\" class="directoryentry_more"></div>';				
				link +='</li>';
				
											
					
				$('ul#resultlist').append(link);
				
				
				$('a#clipboard_'+index).click(function() { 
					
					
					addToClipboard(element.id, element.name );
									
					
				});		
				
			    $('a#profilepeek_'+index).click(function() { 
					
					$('#peekbox_'+index).toggle("slow");	
					
					getProfilePeek(element.id, index);
					
				});			  
				
				

				
				/* $('a#profilepeek_'+index).cluetip({
					  cluetipClass: 'jtip', 
					  arrows: true, 
					  dropShadow: true,
					  hoverIntent: true,
					   sticky: false,
					  mouseOutClose: true,
					  waitImage: true,
					  closePosition: 'title',
						ajaxCache: false  
					}); */
			}
		}
    });
	
	/*for ( var index in searchresultlist )
	{
		
		element = searchresultlist[index];
		
		*/
		
		/*
	
	searchresultlist.forEach(function(element, index, array) {
			*/		
			
	jQuery.each(searchresultlist, function(index, element) {		
			
        var marker ;
        var disptype = '';
		
		if (element.priority == 2)
		{
			if ( selectedTab == 1) 
			{
			
			if ( element.postcode_id > 0  && mapCompat ==  true ) {
					
					marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.name, icon:greyicon});
					disptype ='click';
					
					
					map.addOverlay(marker);
					
					eventListeners[listenerCount] =	GEvent.addListener(marker, disptype, function() {
						marker.openInfoWindowHtml('<div class=\"popupbody\">'+element.name+'<div class=\"popuptext\"><br/><a href="/listing/'+element.id+'\" style="color:#005586;font:100% Trebuchet MS, Arial, Helvetica, Sans-Serif;">click to view</a></div></div>');      
					});
					
					gmarkersList[listenerCount]=marker;
					
					link = '<a href="#" onclick="moveMapTo('+listenerCount+')">'+element.name+'</a><br />';
					
					listenerCount++;
					
					$('p#location_list').append(link);
					
				}
			} else {
				
				/*link = '<a href="./rmp_showlisting.php?id='+element.id+'\">'+element.name+'</a><br />';
				$('ul#resultlist').append(link);
				*/
				
				link = '<li id=\"directoryentry_'+index+'\" class=\"directoryentry resultrow\"  >'; 
										
				
				link += '<p id=\"directoryentry_'+index+'_snapshot\" class=\"snapshot\">';
				link += '<a href=\"/listing/'+element.id+'\">';			
				
				link += '<span class=\"company\">'+element.name+' </span>';
				
				link += '<span class=\"address\">';
				
				if (element.town != null ) link += element.town+', ';
				if (element.county != null ) link += element.county+', ';
				if (element.country != null ) link += element.country+', ';
				if (element.postcode != null ) link += element.postcode;
				
				link += '</span></p>';
				link += '</a>';
				
				if (element.distanceto != null ){
				link += '<p><span class=\"tel\">';				
				 link += 'Distance: '+element.distanceto + ' miles (approximately)';				
				link += '</span>';
				link += '</p>';
				}
				
				if (element.tel != null ){
				link += '<p><span class=\"tel\">';				
				 link += 'tel: '+element.tel;				
				link += '</span>';
				link += '</p>';
				}
				
				
				
				
				if (element.weburl != null ) {
				
				var parWeb=element.weburl;				
				
				
				link += '<p><span class=\"tel\">';
				link += 'web: '+parWeb;				
				link += '</span>';				
				link += '</p>';
				}
				
				
				
				link += '<ul id=\"directoryentry_'+index+'_tools\" class=\"directory_iconset inline\">';	
				
				link += '<li>';				
				link += '<a id=\"clipboard_'+index+'\" class=\"clipboard\" title="Add to clipboard" >Clipboard</a>';				
				link += '</li>';	
				
				link += '<li class=\"label\" style=\"opacity: 0; display: inline-block;\">label</li>';				
				link += '</ul>';
				link +='<div id=\"peekbox_'+index+'\" class="directoryentry_more"></div>';				
				
				
				link +='</li>';
				
				$('ul#resultlist').append(link);
				
				$('a#clipboard_'+index).click(function() { 
									
					addToClipboard(element.id, element.name );
					
				});		
				
			}		
			
		}
		
    }); 
	
	$('a#loadspinner').hide();
	
	
	
	zoomShowAll();
	
}

function moveMapTo(index) {
	
	GEvent.trigger(gmarkersList[index], "click");
	
    map.panTo(new GLatLng(searchresultlist[index].latitude, searchresultlist[index].longitude));
	
	
	//GEvent.trigger(gmarkersList[0], "click");
}




function openMarkerHtml(i) {
	
	//alert(gmarkersList[i]);
        GEvent.trigger(gmarkersList[i], "click");
      }



function zoomShowAll() {
	var $tabs = $('#innertabs').tabs();
	var selectedTab = $tabs.data('selected.tabs');					   
	
	if ( selectedTab == 1 && mapCompat ==  true ) {
	
    bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);
    
  /*  searchresultlist.forEach(function(element, id, array) { */
									  
	jQuery.each(searchresultlist, function(id, element) {								  
									  
									  
		if ( element.postcode_id > 0 ) {					   
        	bounds.extend(new GLatLng(searchresultlist[id].latitude, searchresultlist[id].longitude));
		}
    });
    map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
	}
} 