var debug=false;
var debugLevel=0;
var lP=new Array();
var pHash=new Array();
var map;
var mgr;
var mgr2;
var gicons=[];
var tabs=new Array();
var searchType=url_parameters("type");
var markerz = [];
// class hacks
var textclass = "around_map_input";
var lhsclass = "lhs";
var lhsclass2 = "lhs2";
var tool_tip = new Array(2);
var tipz;
var bounds;
var hybrid_state;
var street_state;
var bar_toggle;
var prop_bounds;
var bCheck = true;
if(url_parameters('ids')) var dontuseboundary = true;
var jump_map_tip;
//min_level = 1;
//max_level = 6;
//var console = true;
var icons=new Array();
var properties=new Array();
var myDropDownOptions = new Array(); 
/*for(var k=0;k<myAmenities.length;k++)
{
    eval(myAmenities[k][0]+"= new Array();");
}*/
var propmarkers=[];
var pt;
var on_map;
var on_map_nos=new Array();
var dis=new Array();
var lyrs=new Array();
var mouseX=0;
var mouseY=0;
var firstpass=true;
var map_size=0;
var scaleFactor=1;
var myValues=new Array();
var rA=false;var tabalign=0;
var restrictedBoundaries=new Array();
var rB=restrictedBoundaries;
var roto=null;

// might not work with ie
//var ie=(window.attachEvent)?true:false;
var b=navigator.userAgent.toLowerCase();
var ie = ((b.indexOf("msie") != -1));

var bString="";
var pid="";
var roh=new Array();
var greyv=false;
var cl=0;
var ol=0;
var lhs_text="";
var od="";
var dblclickzoom=true;
isset_tip = true;

/*var minZoom=11;var maxZoom=16;*/

function String_Replace( string_to_be_replaced ) {
	
	if( string_to_be_replaced.indexOf( 'shelly' ) != -1 ) {
		// string found:
		string_to_be_replaced = string_to_be_replaced.replace( 'shelly', 'shelley' );
	}
	return string_to_be_replaced;
}

function getPlaces(obj,form) {
	var pn = $('placeName').value;
    if( pn == "" || pn.length <= 2 || pn.indexOf( "[" ) != -1 ) {
      document.getElementById('autocomplete_choices').style.display = 'none'; 
	  //$('dSelect').style.display = "block";
      return false;
    }else{
		setTimeout("Hide_Box()", 1500);
	}
    
	pn2 = String_Replace( pn );
	var url = "/" + dirOnly + "/mapping3/ajax_smartsearch.php?placeName=" + pn2;
	// var url = "/" + dirOnly + "/mapping3/ajax_smartsearch.php?placeName=" + pn;
                      
    var ajx = new Ajax.Request(url,
    {
            method: "post",
            parameters: $(form) ? $(form).serialize() : "",
            onSuccess: function(transport) {
                      
                      var data = transport.responseText;
                      eval ("data = " +  data)
                      
					  // If a checkbox whas checked, do not popup the autocomplete_choices div:

                      document.getElementById('autocomplete_choices').innerHTML = data ['place'];
					  document.getElementById('autocomplete_choices').style.display = 'block'; 
					  document.getElementById('map_filters').innerHTML = data ['filters'];
                      populate_dropdown (data ['store_name']);
            },
            onFailure: function(transport) {
                      document.getElementById('autocomplete_choices').style.display = 'block'; 
                      document.getElementById('autocomplete_choices').innerHTML = "<p>Ajax Error</p>";
            }
    });
	// hide the list box, as it's displaying over the rest
	
	
}

function Hide_Box(){
	// $('dSelect').style.display = "none";
}

function populate_dropdown (stores) {
    //alert (stores );
      if (stores) {
      
            var select= $("store_locator_dropdown");
            
            select.onchange = function () {
                selectPan (this.value);
            }
            
            clearObject (select);
            for (var p = 0; p <stores.length;p++ ) {
                  var option = document.createElement ("option");
                  option.value = " [" + stores[p][1] + ", " + stores [p][0] + ", '" + stores[p][2] + "', " + stores[p][3] + "]";
                  option.innerHTML = stores[p][2];
                  select.appendChild (option);
            }
            
      }
}

function selectPan (data) {
      eval ("data = " + data );
      
      if (data [0] && data [1] &&  data [3]) {
            doMapSearch (data [0],data [1],data [2],data [3]);
      }
}

function clearObject (obj) {
      if (obj) {
            failsafe = 0;
            while ( obj.firstChild && failsafe < 300) {
                    obj.removeChild (obj.firstChild)
                    failsafe ++;
            }
      
      }
}

function pin_to_map(id,anchor,position)
{
	var pos = new GControlPosition(anchor, position);
	pos.apply($(id));
	map.getContainer().appendChild($(id));
	$(id).style.display = "block";
}
var showall = false;
function show_all_property(){
    
       
       // alert (url);
       url = url.replace(/\&ids/,"");
       //url_parameters('ids') = '';
       MAP_IDS = "";
       FILTERS = "";
       // showall = true;
       gptr();
    
}


function get_map_tips(rd,xmltip)
{    
        var tips= rd.documentElement.getElementsByTagName("tips");
        //alert(url_parameters('searchterm'));
        tipz="";
        
        var showother = "";
        if(url_parameters("ids") && !showall)
        {
          showother="<div style=\"width: 250px; text-align: right;\"></div><span id='allshow'  onclick='show_all_property();this.style.display=\"none\"' style='color: #333333; cursor: pointer;text-decoration: underline;'><strong> Show adjacent stores</strong><span></div>";
        }
        
        if(url_parameters('searchterm') )
	
        {
		
            for(var i=0; i<tips.length;i++)
            {	
		var place = url_parameters('searchterm').replace(/\+/g," ");
		place = place.replace(/\%20/g," ");
                tool_tip[i,1]= tips[i].getAttribute('header');
                tool_tip[i,2]= tips[i].getAttribute('text');
                tool_tip[i,3]= tips[i].getAttribute('command');
                tipz = tipz+"<span class='tip_header'>TIP: </span><span id='jump_map_tip'> Showing markers for "+place+"</span> <div id='props2' style='display:inline;'>"+showother+"</div>";
            }
            
            if(isset_tip)
            {
            $('tip_body').innerHTML =  tipz;
            isset_tip = false;
            }
        }
        else
        {
          $('tip_body').innerHTML =  "<span class='tip_header'>TIP: </span><span id='jump_map_tip'>"+xmltip+"</span><div id='props2' style='display:inline;'>"+showother+"</div>";
        }
        
        
        
}

function addLoadEvent(func)
{
    var oldonload=window.onload;
    if(typeof window.onload!='function'){window.onload=func;}else{window.onload=function(){oldonload();func();}}
}

function pB(){var bminX=null;var bmaxX=null;var bminY=null;var bmaxY=null;for(var b=0;b<rB.length;b++){bminX=rB[b][1];bmaxX=rB[b][3];bminY=rB[b][2];bmaxY=rB[b][4];blevel=rB[b][0];
if(blevel<(17-cl)){var pts=new Array(new GPoint(bminX,bmaxY),new GPoint(bmaxX,bmaxY),new GPoint(bmaxX,bminY),new GPoint(bminX,bminY),new GPoint(bminX,bmaxY));map.addOverlay(new GPolyline(pts,bT[2],bT[3],bT[4]));}}}

function dZ2()
{	
	//alert ("Max : " + maxZoom + "\nMin:" + minZoom);
	args=arguments;
    if(args[1]>maxZoom){
        map.setZoom(maxZoom);
    }else if(args[1]<minZoom){
		
        map.setZoom(minZoom);
    }
	// map.setZoom(minZoom);
    cl=map.getZoom();
    map.clearOverlays();
    pB();
    properties=new Array();
    csb();
    return;
    //if(console.log)console.log("now calling Dz2");
}

function SetMapZoom() {
	map.setZoom(minZoom);
	$('garmin').style.display ='none';
}

function dZ(level){
    //min_level = 1;
    //max_level = 6;
    if(level>17-min_level-1) {
        return;
    }
    
    if(level<17-max_level-1) {
        return;
    }
        
    level++;
    cl=level;   // cl might stand for current level
    if(debug && debugLevel == 1) {
        GLog.write("CL = " + cl);
        GLog.write("Level = " + level);
    }    
    map.setZoom(level);
    map.clearOverlays();
    pB();

    for(var p=0;p<properties.length;p++)
    {
        rmal(properties[p]);
    }
    properties=new Array();
    csb();
    return;
}

function createBString(){
    for(var b=0;b<rB.length;b++) {
        var blevel=rB[b][0];
        bString+="&bminX"+b+"="+rB[b][1]+"&bmaxX"+b+"="+rB[b][3]+"&bminY"+b+"="+rB[b][4]+"&bmaxY"+b+"="+rB[b][2]+"&blevel"+b+"="+rB[b][0];
    }
    bString+="&nBound="+rB.length;
}

function oob(lng,lat,bounds){return lng<bounds.minX||lng>bounds.maxX||lat<bounds.minY||lat>bounds.maxY?true:false}

function im(){
    if(!GBrowserIsCompatible()) {
        //alert("You are not using a Google Maps compatible browser!");
        return;
    }
    createBString();
    var lng=url_parameters("lng");
    var lat=url_parameters("lat");
    var scalar=url_parameters("scale");
    propertyId=url_parameters("panelist")?url_parameters("panelist"):url_parameters("id");
    cl=17-url_parameters("scale");

    if(!lat)lat=-29.11377539511439;
    if(!lng)lng=24.78515625;
    if(!cl)cl=13;
    var affected=0;
    im_itself(lat,lng,map_width,map_height);
    if(affected>0){
        setTimeout('showHide("advanced")',1000);
    }
}

function cmb(){
    var a="true";var b="inc";
    if(map_size!=0){
        a="";b="dec";
    }
}

function setIcons(name) { 
	
	if(arguments[1]==false){
    
    }else{
        name=name.replace(/s$/,"");
    }
    
    gicons[name]=new GIcon();
    gicons[name].image="icons/"+name+".png";
    gicons[name].iconName=name;
    gicons[name].iconSize=new GSize(icon_width,icon_height);
    gicons[name].iconAnchor=new GPoint(icon_width/2,icon_height/2);
    gicons[name].infoWindowAnchor=new GPoint(icon_width,1);
}

function doIcons() {
    if(icon_width==undefined||icon_width==null){
        icon_width=30;
    }
    if(icon_height==undefined||icon_height==null){
        icon_height=22;
    }
}


function wheelZoom(a)
{
    if(a.detail)
    {
        if(a.detail<0)
        {
            map.zoomIn();
        }
        else if(a.detail>0)
        {
            map.zoomOut();
        }
    }
    else if(a.wheelDelta)
    {
        if(a.wheelDelta>0)
        {
            map.zoomIn();
        }
        else if(a.wheelDelta<0)
        {
            map.zoomOut();
        }
    }
}

// this will need to change, can not have the co ordinates hardcoded when changing the mapview

function im_itself(lat,lng,width,height){
fixer();

//END*/

    map=new GMap2($("map"));
    if(large_hybrid) {
        //map.addControl(new GMapTypeControl());
    }
    //insert tool tips
   
  var mapHeight = $("map").offsetHeight;
  var mapWidth = $("map").offsetWidth;
  //$("tool_body").style.height=  ($("map").offsetHeight-38)+"px";
  $("tool_bar").style.width=  ($("map").offsetWidth)+"px";     
  // filter options
   
  //pin_to_map("tool_bar",G_ANCHOR_TOP_LEFT, new GSize(0,0));
  pin_to_map("zoom_controle",G_ANCHOR_TOP_RIGHT, new GSize(25,2));
  map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,5)));
  
  /// status loading bar
//  var my_y = ($("map").offsetHeight/2)-($("status").offsetHeight/2);
//  var my_xx = ($("map").offsetWidth/2)-75;
//  var my_co = (($("map").offsetWidth/2)-($("status").offsetWidth/2));
//pin_to_map("status",G_ANCHOR_TOP_LEFT, new GSize(my_xx,my_y));
//pin_to_map("activated",G_ANCHOR_TOP_LEFT, new GSize(my_xx,my_y));
//pin_to_map("amenities_div",G_ANCHOR_TOP_LEFT, new GSize(51,100));
      
      var mapstats =$("map");
      var my_co = (($("map").offsetWidth/2)-(200/2))
   
    map.enableContinuousZoom();
    map.enableDoubleClickZoom();
    GEvent.addDomListener($("map"),'DOMMouseScroll',wheelZoom);
    GEvent.addDomListener($("map"),'mousewheel',wheelZoom);
    
    
     $('tool_bar').style.width =  $('map').offsetWidth-3+"px";
     map.addControl(new DragZoomControl({opacity:.6,border:"2px solid #f69932"},{buttonHTML:"<img title='Click here then drag an area on the map to zoom' src='icons/btn_zoom_on.gif'/>",buttonZoomingHTML:"<img title='Click here to disable drag-zoom' src='icons/btn_zoom.gif' alt='Click here to disable drag-zoom' />",buttonStartingStyle:{width:'24px',height:'24px'}}),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(2,2)));
    
    
    /**************This code gets the cookie if it exits********************/
    
    if(url_parameters("back") == "mappos" && getcookie("savedmappos")) {
        
        var cv = getcookie("savedmappos");
        cv = cv.parseJSON();
         //if(console.log) console.log("get cookie CV => " +url_parameters("back") + cv.cp.x + "|" + cv.cp.y + " / " + cv.zm + " / " + cv.pids);
        use_cookie=true;
        lat =cv.cp.x;
        lng = cv.cp.y;
        cl = cv.zm;
        //alert(cv.cmt);
        if(!cv.cmt)
        {
          map_type = G_NORMAL_MAP;
        }
        else
        {
          map_type = G_HYBRID_MAP;
        }
        if(cv.sha)
        {
          showall = true;
        //  if(console.log)console.log("now setting showall => "+showall);
        }
        bCheck= false;
    }
    /**END**/
    map.setCenter(new GLatLng(lng,lat),cl);
    change_map (map_type);
    
    if(show_map_ov){
        map.addControl(new GOverviewMapControl(new GSize(100,100)));
        var omap=$("map_overview");
        var mapdiv=$("map");
	if (omap) 
	{        
		omap.style.position="relative";
		omap.style.right="0px";
		omap.style.bottom="8px";
		mapdiv.appendChild(omap);
	}
    }
    doIcons();
    var top=top2=0;
    if(ie){
        width-=90;top=top2=-1*(height+39);
    }else{
        width+=90;top=-1*(height+59);top2=-1*(height+29);
    }

    top=-1*(height+39);cmb();
    if(show_zoom){
        csb();
        add_listeners();
        pB();
        lp();
    }
  
    
    /*new Effect.BlindUp('tool_body');
    document.images['tab'].src= "./icons/tab_plus.gif";
    bar_toggle =1;*/
    GEvent.addListener(map,"click",function (){
     //$('actions').style.display = "none";
      //new Effect.Fade("amenities_div");
    });
    
}

function add_listeners(){GEvent.addListener(map,"moveend",function () { 
    if (!POPUP_WINDOW ) {
        lp ();
    }
    else {
        POPUP_WINDOW = false;
    }
});
//if(smallzoom){GEvent.addListener(map,"zoomend",gptr);}}
if(smallzoom){GEvent.addListener(map,"zoomend",dZ2);}}

function movemap(d){
    var dx=0;var dy=0;
    if(d.match("right"))dx="-1";
    if(d.match("left"))dx="+1";
    if(d.match("up"))dy="+1";
    if(d.match("down"))dy="-1";map.panDirection(dx,dy);
}

function updateBoundary(){halfWidth=scaleFactor*(mapWidth/2);halfHeight=scaleFactor*(mapHeight/2);leftEdge=-1*halfWidth+map.lng;bottomEdge=halfHeight+map.lat;rightEdge=halfWidth+map.lng;topEdge=-1*halfHeight+map.lat;}

/*function alphaG(id){return"<img width=30 height=22 id='"+id+"' class=trans src='icons/"+id+".gif'>";}

function alpha(id)
{
  if(ie)
    {
    $(id).style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='icons/"+id+".png', sizingMethod='scale')";
    }
    else
    {
    $(id).src="icons/"+id+".png";
    $(id).onload="";
    }
}
*/
function clearProperties(){for(var p=0;p<properties.length;p++){}
for(var k=0;k<myAmenities.length;k++){var m=eval(myAmenities[k][0]);var l=myAmenities[k][0].substr(0,(myAmenities[k][0].length-1));for(var p=0;p<m.length;p++){}}}

function getObj(name){if($){return $(name);}else if(document.all){return document.all[name];}else if(document.layers){return document.layers[name];}else{return document.layers[name];}}

function resizeMap(large){var c=map.getCenter();var lng=c.x;var lat=c.y;
if(typeof(current_url)=="string"){c=current_url;}else{c="street_level_map.php";}
document.location=c+guv(0,0,0,0)+"&lng="+lng+"&lat="+lat+"&large="+large+"&zoom="+(17-cl)+"&id="+pid;}

function formRequest(url,func){
	//window.open(url,'debug');
    if(url_parameters("test")){
        window.open(url,'debug');
    }
   //window.open(url,'debug');
    var r=GXmlHttp.create();
    r.open("GET",url,true);
   eval("r.onreadystatechange = function () { "+func+"(r); }");r.send(null);
}

function overlaps(lat,lng,id){if(pHash[id]){return false;}
var times=cl>=11?0.9701:0.77162458338772;var cLng=(icon_width-0)/(Math.pow(2,(cl))*times);var cLat=(icon_height-0)/(Math.pow(2,(cl)));for(var p=0;p<lP.length;p++){var dLng=Math.abs(lng-lP[p]["lng"]);var dLat=Math.abs(lat-lP[p]["lat"]);
if(dLng<cLng&&dLat<cLat&&lP[p]["id"]!=id){overlap++;return true;}}
return false;}

function rp(){var bounds=map.getBounds();var keepProperties=new Array();haveProperties=new Array();var added=kept=0;overlap=removed=0;for(var p=0;p<properties.length;p++)
{if(oob(properties[p]["lng"],properties[p]["lat"],bounds)||overlaps(properties[p]["lat"],properties[p]["lng"],properties[p]["id"])||!pHash[properties[p]["id"]]||rA)
{rmal(properties[p]);removed++;}else{kept++;keepProperties[keepProperties.length]=properties[p];haveProperties[properties[p]["id"]]=true;}}
for(var p=0;p<lP.length;p++)
{if(!haveProperties[lP[p]["id"]])
{keepProperties[keepProperties.length]=lP[p];added++;}}
properties=keepProperties;}
//fedex = [];
function loadElement(rD,name,element,hash)
{
    eval(name+"=new Array()");
    var te=rD.documentElement.getElementsByTagName(element);
    for(var i=0;i<te.length;i++)
    {
        eval("el="+name+".length");
        eval(name+"[el] = new Array()");
        eval(name+"[el]['id'] = te[i].getAttribute('id')");
        eval(name+"[el]['lat'] = te[i].getAttribute('lat')");
        eval(name+"[el]['lng'] = te[i].getAttribute('lng')");
        eval(name+"[el]['type'] = te[i].getAttribute('type')");
        eval(name+"[el]['s_name'] = te[i].getAttribute('s_name')");
        //fedex.push(new GLatLng(te[i].getAttribute('lat'),te[i].getAttribute('lng')))
    }
}

function propertyframe(url)
{
    for(var i=0;i<tabs.length;i++)
    {
        changeContent(tabs[i]+"frame","none",tabs[i]+"updown",upArrow(tabs[i]));
    }
    changeContent("propertyframe","block","propertyupdown",downArrow("property"));
    $('propertyiframe').src=url;
    return;
}

function list()
{
    var b=map.getBounds();
    var sw=b.getSouthWest();
    var ne=b.getNorthEast();
    // added by graham 06 june 07
    if (url_parameters('ids')) var gv="ids=" + url_parameters('ids') + "&type=" + searchType; // no boundries
    else var gv=guv(sw.lng(),sw.lat(),ne.lng(),ne.lat());
    var url="/"+dirOnly+"/search/?"+gv+"&a=list_view&from=console";
    //alert(url);
    top.location.href=url;
}

function createMarker2(markerobj, propertyid) {
	  var url = "/" + dirOnly + "/php/info_popup.php?id=" + propertyid;
          
                      
                      var ajx = new Ajax.Request(url,
                      {
                              onSuccess: function(transport) {
                                        POPUP_WINDOW = true;
                                        var data = transport.responseText;
                                        //map.setCenter (point);
                                        //var label = new ELabel(point, data, null);
                                        //var IDS = pid.split (",");
                                        //var fid = parseInt (IDS[0]); 
                                        //ELABLES[fid] = label;
                                        //map.addOverlay( ELABLES[fid] );
                                        //map.setCenter (point);
                                        marker.openInfoWindowHtml(data);
                              },
                              onFailure: function(transport) {
                              }
                      });
}


function boundaryText(number,text,ids,bminX,bmaxY,bmaxX,bminY)
{
    var nameTag=new GIcon();
    var total=noc(ids);
    nameTag.image=tag_url+"?t="+text+": "+total+"&h="+bT[1]+"&w="+bT[0]+"&f="+bT[5]+"&b="+bT[6]+"&it="+bT[7]+"&ib="+bT[8]+"&s="+bT[9]+"&fo="+bT[10];
    nameTag.iconSize=new GSize(bT[0],bT[1]);
    nameTag.iconAnchor=new GPoint(0,0);
    
    if(typeof(bm[number])!="undefined")
        map.removeOverlay(bm[number]);bm[number]=new GMarker(new GLatLng(bminY+((bmaxY-bminY)/2),bminX+((bmaxX-bminX)/2)-(bT[0]/(Math.pow(2,(17-cl))*0.77162458338772))/2),nameTag);
        
    GEvent.addListener(bm[number],'click',function(){showlist(number)});
    if(rB[number][0]<17-cl)
        map.addOverlay(bm[number]);
}

function pms(which,use_frame,use_icon,prefix,arrayName){if(use_icon=="property")inbox=new Array();var point=null;var theid=null;prefix="";for(var i=0;i<which.length;i++){if(inBoundary(which[i]["lng"],which[i]["lat"],which[i]["id"])&&use_icon=="property"){}else if(haveProperties[which[i]["id"]]&&use_icon=="property"){}else{point=new GLatLng(parseFloat(which[i]["lat"]),parseFloat(which[i]["lng"]));
if(use_icon=="property"){var marker=new GMarker(point,icons[which[i]["type"]]);}else{var marker=new GMarker(point,icons[use_icon]);}
eval(arrayName+"[i][\"marker\"] = marker");map.addOverlay(marker);theid=which[i]["id"];
if(use_frame=="Property"&&haveProperties[which[i]["id"]]){}else{eval(arrayName+"[i][\"listener\"]=GEvent.addListener("+arrayName+"[i][\"marker\"], 'click', function() { show"+use_frame+"Frame('"+theid+"')}); ");
if(use_icon=="property"){if(numberOfCommas(which[i]["id"])>1)
eval(arrayName+"[i][\"listener2\"]=GEvent.addListener("+arrayName+"[i][\"marker\"], 'mouseover', function() { sh2('rollover','"+numberOfCommas(which[i]["id"])+" "+plural_label+"')}); ");else if(single_rollover)
eval(arrayName+"[i][\"listener2\"]=GEvent.addListener("+arrayName+"[i][\"marker\"], 'mouseover', function() { sh2('rollover',propup(\""+which[i]["id"]+"\"))}); ");else
eval(arrayName+"[i][\"listener2\"]=GEvent.addListener("+arrayName+"[i][\"marker\"], 'mouseover', function() { sh2('rollover','1 "+singular_label+"')}); ");}
if(use_icon=="office"||use_icon=="school")
eval(arrayName+"[i][\"listener2\"]=GEvent.addListener("+arrayName+"[i][\"marker\"], 'mouseover', function() { sh2('rollover',\""+which[i]["kd"]+"\")}); ");}}}
if(use_icon=="property"&&1){for(var b=0;b<rB.length;b++){boundaryText(b,rB[b][5],inbox[b],rB[b][1],rB[b][2],rB[b][3],rB[b][4]);}}}


function greyOut(msg)
{
    cap();
    if(hideGrey)
        return;
    if(greyv)
        greyOff();
        
    $('grey').innerHTML="<img src='"+icon_directory+grey_icon+"' height='"+map_height+"' width='"+map_width+"'><div style='position:relative; top: -300px; left:30px; width:300px'>"+labels["warningbox"]+"<div class='"+lhsclass+"' id=warningbox name=warningbox><font color=#333333><b>"+msg+"</b></font></div></div>";greyv=true;
}

function greyOff()
{
    if(!greyv) return;
    
    $('grey').innerHTML="";greyv=false;
}

function cap(){
    map.clearOverlays();
    for(var p=0;p<properties.length;p++) {
        rmal(properties[p]);
    }
    properties=new Array();
}
var cnt =0;
var st=0;
var HTML_POP = document.createElement("div");


var ELABLES = [];
var POPUP_WINDOW =false;
var POPUPWINDOW;

function createMarker(count, point,icon,html,pid,amn)
{       
	var extra_id;
    var marker=new GMarker(point,icon);
    markerz.push(marker);
    if(arguments[4]!=undefined) { extra_id=arguments[4]; }
    
    
        var adjust = true;
		// createMarker2(marker, pid);
		
		
                      //Create elable popupvar HTML = "<div style=\"padding: 10xpx; background: #fff;\">No HTML/div>";
                    // createMarker2(marker, pid);
			  
		if ( count == 1 ) {
			if (POPUPWINDOW) window.clearTimeout (POPUPWINDOW);
			POPUPWINDOW = window.setTimeout ( function() {
				// alert("Tester");
				var url = "/" + dirOnly + "/php/info_popup.php?id=" + pid;
                                
                      
                      var ajx = new Ajax.Request(url,
                      {
                              onSuccess: function(transport) {
                                        POPUP_WINDOW = true;
                                        var data = transport.responseText;
                                        marker.openInfoWindowHtml(data);
                              },
                              onFailure: function(transport) {
                              }
                      });
			}, 3000 );
		}

		
        GEvent.addListener(marker,"click",function(){
                  
                      //Create elable popupvar HTML = "<div style=\"padding: 10xpx; background: #fff;\">No HTML/div>";
                    // createMarker2(marker, pid);
					  var url = "/" + dirOnly + "/php/info_popup.php?id=" + pid;
                                          
                      
                      var ajx = new Ajax.Request(url,
                      {
                              onSuccess: function(transport) {
                                        POPUP_WINDOW = true;
                                        var data = transport.responseText;
                                        //map.setCenter (point);
                                        //var label = new ELabel(point, data, null);
                                        //var IDS = pid.split (",");
                                        //var fid = parseInt (IDS[0]); 
                                        //ELABLES[fid] = label;
                                        //map.addOverlay( ELABLES[fid] );
                                        //map.setCenter (point);
                                        marker.openInfoWindowHtml(data);
                              },
                              onFailure: function(transport) {
                              }
                      });
        });
        
        GEvent.addListener(marker,"mouseover",function() 
        {     
           	$( 'map' ).style.zIndex = 500;
			//alert( $( 'map' ).style.zIndex );
			var HTML = "<div id='hov_t' class='"+lhsclass+"' style='border: solid 1px darkgrey;padding: 2px 2px 2px 12px;background: #fff;color: #000; width: 210px; height:auto;position: absolute;filter:alpha(opacity=91);-moz-opacity:.91;opacity:.91;font-weight: normal; z-index: 501;'>"+html+"</div>";
			// var HTML = "<div style='z-index: 600;'><br />Tester<br />Tester<br />Tester<br />Tester<br />Tester<br />Tester</div>";
			//alert(HTML);
              mapstats =$("map");
              
              $('rollover').style.zIndex = 502;
			  $("rollover").innerHTML = HTML;
              
              $("map").mousemove = getMouseXY;
              $("rollover").style.display = "block";
              
              var overlap =(mapstats.offsetLeft+mapstats.offsetWidth)-(mouseX+210);
              var x_cor;
        
              if(overlap < 0)x_cor = ((mouseX+overlap)-15)+"px";
              else x_cor = mouseX+"px";
              
              if(pid != 0 && pid.match(',') || overlap < 0)
              {
                $("rollover").style.left =x_cor; 
                $("rollover").style.top = mouseY+"px";
              }
              else
              {
               $("rollover").style.left = x_cor; 
                $("rollover").style.top = (mouseY-30)+"px";
              }
              
        });
        GEvent.addListener(marker,"mouseout",function()
            {   
              $("rollover").style.display = "none";
            
        });
    
    return marker;
}

function sh2(name, id) { 
    sh(name, id,'visible');
} // roto = setTimeout("sh('rollover','','hidden')",1000); }

function shtime(name, id, t) { 
    sh(name, id,'visible',t);
} // roto = setTimeout("sh('rollover','','hidden')",t); }

function sh(name, id,state,t)
{
    if(debug && debugLevel == 2) {
        GLog.write("Name-One: " + name);
        GLog.write("ID-One: " + id);
        GLog.write("State-One: " + state);
    }
    if (!t) { t=800; }

    if (id=="") { state='hidden'; }
    var extra = document.body.scrollTop;
    if (!ie) { extra=0; }

    var width = id ? id.length * 8 : 0;
    var height = 15;

    if (state=="hidden")
    {
        $(name).style.left=0+"px";
        $(name).style.visibility = "hidden";
    }

    if (!id) { return; }
   
    if (id.length>30 && !id.match ("School"))
    {
        width=300;
        height=70;
    }
   
    if (id.match("Bedroom") && name=="rollover")
    {
        if (mouseY<map_down_from_top+100) { 
            mouseY+=140;
        }
        $(name).style.top=(mouseY-100) + "px";

        if (mouseX-200<lhs_panel_width) {
            $(name).style.left=(lhs_panel_width) + "px";
        } else {
            $(name).style.left=(mouseX-200) + "px";
        }
        
        if (page_width< mouseX-200) {
            $(name).style.left=0 + "px";
        }
    } else {
        $(name).style.top=(mouseY-20+extra)+"px";
        
        if (page_width<mouseX || mouseX+width+40>page_width)
        {
            $(name).style.left=(mouseX-width) + "px";
            $(name).style.top=(mouseY+13)+ "px";
        } else {
            $(name).style.left=(mouseX+10)+"px";
        }
    } //if

    if ($)
    {
        $(name).style.visibility = state;
    } else {
        if (document.lyrs)  // Netscape 4
        {
            eval ("document."+name+".visibility = '"+ state+"'");
        } else { // IE 4
            eval ("document.all."+name+".style.visibility = '"+ state +"'");
        }
    }

    if (typeof(id)!="undefined") {
        $(name).innerHTML= "<div class='"+lhsclass+"' style='border: solid 2px;padding: 2px 2px 2px 12px; width:"+width+"px; height:"+height+"px'>"+id+"</div>";
    }

    if (state=="visible")
    {
        if (roto) { clearTimeout(roto); }
        roto=setTimeout("sh('rollover','','hidden')",t);
    }
}

function numberOfCommas(st) { return st.split(",").length; }

function ddb(divid,html,icon)
{
    tdiv=document.createElement("div");
    tdiv.style.backgroundColor="#FFFFFF";
    tdiv.style.color="#FF0000";
    tdivinner=document.createTextNode(html);
    tdiv.appendChild(tdivinner);
    divid.appendChild(tdiv);
}
var EXTRAS = new Array ();

function makeSideBarStores (p,marker,cnt,side_bar_name) {
      
      var sidebar = $('side_bar_other_closest_store');
      
      var div   = document.createElement ('div');
      var image = document.createElement ('img');
      
      div.onclick = function () {
            myclick (marker);
      }
      
      div.style.cursor = "pointer";
      div.className = "number2";
      
      div.innerHTML = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr><td><img title=\"" + side_bar_name + "\" src=\"" + ICONS_DIR + "icon_" + cnt + ".png\" alt=\"\" class=\"sidebar_icons\" /></td>" +
                      "<td><div class=\"claremont\">" + side_bar_name.substring (0,20) + "...</div></td></tr></table>" + 
                      "";
      
      if (cnt <  ( max_view_in_list + 1 )  ) {
            sidebar.appendChild (div);
      }
      else {
            if ( EXTRAS.length < 5 ) EXTRAS.push (div);
      }
}


function myclick(marker) {

      GEvent.trigger(marker, "click");
}

function pp() {
    
    
	$('side_bar_other_closest_store').innerHTML = "";
    $('change_store').style.display = "block";
    $('more_icons').innerHTML = "";
    ELABLES = new Array ();
    EXTRAS = new Array ();
    if(on_map>on_map_cutoff){
        alert("Icons Exceed Amount!");
        return;
    }
    divContent('propnumbers',on_map);
/*    for(g=0;g<myFilters.length;g++){
        divContent(myFilters[g][0]+'numbers',"<div style='display:inline; width:25px; text-align: center;' id='numbers'><b>"+on_map_nos[myFilters[g][0]]+"</b></div> ");
    }
   */ 
    if(0){
        //divContent('viewinlist',"<span class='viewinlistlink'><a href='javascript:void(list())' class='viewinlistlink'><strong>"+on_map+" Properties </strong>(View all)</a></span>");
    }else{
        //divContent('viewinlist',"");
        
    }
    
    var graphic=null;
    var point=null;
    var ee={};
    map.clearOverlays();

    if(mgr!=null){
        delete mgr;
    }

    propmarkers=[];
    var markers;
    if(bCheck) prop_bounds = new GLatLngBounds();
    
    var cnt = 0;
    if (properties.length == 0) {
        $('side_bar_other_closest_store').innerHTML =  NO_STRORES_FOUND
        
    }
    
  $("stores_amount").innerHTML = properties.length;
    for(var p=0;p<properties.length;p++)
    {
        cnt ++;
        var Icon = ICONS_DIR  + "icon_" + cnt + ".png";
        gicons['shop']=new GIcon();
        gicons['shop'].image= Icon;
        gicons['shop'].iconName=name;
        //gicons['shop'].iconSize=new GSize(icon_width,icon_height);
        gicons['shop'].iconAnchor=new GPoint(icon_width/2,icon_height/2);
        gicons['shop'].infoWindowAnchor=new GPoint(icon_width,1);
        
        point=new GLatLng(properties[p]["lng"],properties[p]["lat"]);
        setIcons(properties[p]["type"],false);
        //if(gicons["shops"]==undefined){
        //   setIcons(properties[p]["type"],false);
        //}
        var html= "";
        if(properties[p]["id"].match(","))
        {
			  var names =  properties[p]["s_name"].split(",");
              var types =  properties[p]["type"].split(",");
              
              var side_bar_name = "";
			  html += "<font color=\"#999999\"><b>The following stores were found and clustered as they are in the same area:</b></font><br /><ul>";
              for (var i=0; i< names.length; i ++ ) {
                    html += "<li>";
					html += names [i]  + " " + types + "<br/>";
					html += "</li>";
                    side_bar_name += names [i] + " ";
              }
			  html += "</ul>";
			  
			  var Icon = ICONS_DIR  + "cluster.png";
        	gicons['shop']=new GIcon();
	        gicons['shop'].image= Icon;
	        gicons['shop'].iconName=name;
	        //gicons['shop'].iconSize=new GSize(icon_width,icon_height);
	        gicons['shop'].iconAnchor=new GPoint(icon_width/2,icon_height/2);
	        gicons['shop'].infoWindowAnchor=new GPoint(icon_width,1);
        }
        else
        {
          html =properties[p]["s_name"] + " "  + properties[p]["type"];
          side_bar_name = properties[p]["s_name"];
        }
        
		// Extending the boundaries:
		// alert(bCheck);
        if(bCheck) prop_bounds.extend(point);
        
       		//markers=createMarker(point,gicons[properties[p]["type"]],html,properties[p]["id"]);propmarkers.push(markers);map.addOverlay(markers);
        
		markers=createMarker(properties.length, point,gicons['shop'],html,properties[p]["id"]);propmarkers.push(markers);map.addOverlay(markers);
		
		makeSideBarStores (properties[p], markers,cnt,side_bar_name); 
  	}
  $("more_section").style.display =  (EXTRAS.length > 0) ? "block" : "none"; 
  // $("branch_options").style.display =  (properties.length > 0) ? "block" : "none"; 
  //if(console.log)console.log("Bcheck => "+bCheck);
  if(bCheck) 
  {
      //if(console.log)console.log("Properties => "+properties.length);
      if(properties.length == 1) 
      {
        bCheck = false;
        map.setZoom();

        map.setCenter(point,(maxZoom-3),map_type);
        //if(console.log)console.log("New zoom leve => "+map.getZoom());
        //alert("1 "+map.getZoom())
      }
      else
      {
         
		 
		// if(url_parameters('ids'))
		if(bCheck)
        {
        	cl = map.getBoundsZoomLevel(prop_bounds);
         	map.setCenter(new GLatLng(prop_bounds.getCenter().y,prop_bounds.getCenter().x),cl,map_type);
        }
       	 	delete prop_bounds;
        	bCheck = false;
      }
	  
	  //MAP_IDS = "";
    
  }
    /*
    for(var n=0;n<myAmenities.length;n++)
    {
        if(debug && debugLevel==7) {
            GLog.write("Amenities = [" + myAmenities[n][0] + "] "  + myAmenities[n][1]);
        }
        var m=eval(myAmenities[n][0]);
        var l=myAmenities[n][0].substr(0,(myAmenities[n][0].length-1));
        var myMarker=[];
        for(var p=0;p<m.length;p++)
        {
            var myPoint=new GLatLng(m[p]["lng"],m[p]["lat"]);
            switch(myAmenities[n][0])
            {
            //(point,icon,html,pid)
                case"offices":
                    var atitle=m[p]["k"];
                    var office_id=m[p]["id"];
                    amarkers=createMarker(myPoint,gicons["office"],atitle,office_id,true);
                break;
                
                case"schools":
                    var atitle=m[p]["k"];
                    if(atitle.match(","))atitle  = atitle.replace(/,/g,"<br/>");
                    amarkers=createMarker(myPoint,gicons["school"],atitle,m[p]["id"],true);
                break;
                
                case"hospitals":
                    var atitle=m[p]["k"];
                    if(atitle.match(","))atitle  = atitle.replace(/,/g,"<br/>");
                    amarkers=createMarker(myPoint,gicons["hospital"],atitle,m[p]["id"],true);
                break;
                
                case"policestations":
                    var atitle=m[p]["k"];
                    if(atitle.match(","))atitle  = atitle.replace(/,/g,"<br/>");
                    amarkers=createMarker(myPoint,gicons["policestation"],atitle,m[p]["id"],true);
                break;
                
                case"postoffices":
                    var atitle=m[p]["k"];
                    if(atitle.match(","))atitle  = atitle.replace(/,/g,"<br/>");
                    amarkers=createMarker(myPoint,gicons["postoffice"],atitle,m[p]["id"],true);
                break;
            }
            
            map.addOverlay(amarkers);
        }
    }
    
    for(var n=0;n<myAgentOffices.length;n++)
    {
        if(debug && debugLevel==7) {
            GLog.write("AgentOffices = [" + myAgentOffices[n][0] + "] "  + myAgentOffices[n][1]);
        }
        var m=eval(myAgentOffices[n][0]);
        var l=myAgentOffices[n][0].substr(0,(myAgentOffices[n][0].length-1));
        var myMarker=[];
        for(var p=0;p<m.length;p++)
        {
            var myPoint=new GLatLng(m[p]["lng"],m[p]["lat"]);
            switch(myAgentOffices[n][0])
            {
                case"officefncs":
                    var atitle=m[p]["k"];
                    var office_id=m[p]["id"];
                    var officon = m[p]["icon"];
                    amarkers=createMarker(myPoint,gicons[officon],"<div>"+atitle+"</div>",0,office_id);
                break;
                
                case"officepgps":
                    var atitle=m[p]["k"];
                    var office_id=m[p]["id"];
                    var officon = m[p]["icon"];
                    amarkers=createMarker(myPoint,gicons[officon],"<div>"+atitle+"</div>",0,office_id);
                break;
            }
            
            map.addOverlay(amarkers);
        }
    }
    */
    //$("status").style.display = "none";
    //divContent('status',loading+'<br/><span id="loads">Now loading map tiles...</span>');
	
	fixer2();
}

function pp1(){
    if(on_map<on_map_cutoff)
    { 
        rp();
        if(cl>=17-3 && schools.length>0 && show_schools) {
            pms(schools,"School","school","s","schools");
        }
        pms(offices,"Office","office","o","offices");

        if(cl>=17-4 && trains.length>0) {
            pms(trains,"Train","train","t","trains");
            pms(properties,"Property","property","","properties");
            greyOff();
        }else{
            greyOut("Too many properties on the map.<br />&nbsp;<br />Please <a href='javascript:void(dZ(cl))' class='BasicLink'>zoom in</a> or change the criteria to narrow your search.");
        }
    }    

    var word=plural_label;
    if(on_map==1) {
        word=singular_label;
    }    
    set_numbers();
    var b=map.getBounds();
    var sw=b.getSouthWest();
    var ne=b.getNorthEast();
    var thelabel="("+labels["listview"]+")";

    if(!labels["listview"])
        thelabel="";

    if(on_map=="0")
        thelabel="";var url="";var targ="";

    if(propertyStringType==1)
    {
        url=search_url+guv(sw.lng(),sw.lat(),ne.lng(),ne.lat())+"&a=list_view";
    }
    else if(propertyStringType==2)
    {
        var center=map.getCenter();
        var newx=center.x;
        var newy=center.y;
        url=search_url+propertyIds()+"&cx="+newx+"&cy="+newy+"&z="+(17-cl)+"&type="+searchType;targ="target='_top'";
    }
    
    if(typeof(lvt)!="undefined") {
        targ=lvt;
    }
    
    if(alternate_view_list)
    {
        //if(on_map==0)
        //slb("status",on_map+" "+word+" in selected area");else if(on_map>on_map_cutoff)
        //slb("status","<center>"+on_map+" "+word+" in selected area<br />zoom in to display icons</center>");else
        //slb("status","<center>"+on_map+" "+word+" now showing<br />click on icons to show details below</center>");
    }
    else if(!greyv)
    {
        //slb("status","<b>"+on_map+" "+word+" <a "+targ+" href='"+url+"' class='"+aroundmaplinksclass+"' onmouseover='sle (\"info\",labels[\"list_view\"],20)' onmouseout='hideInfo()'>"+thelabel+"</a></b>");
    } else {
        //slb("status","<b>"+on_map+" "+word+"</b>");
    }    
}
    
function cm(){
    var ce=map.getCenter();
    var lng=ce.x;
    var lat=ce.y;
    var newcl=17-cl;
    for(var b=0;b<rB.length;b++)
    {
        if(lng>rB[b][1]&&lng<rB[b][3]&&lat>rB[b][4]&&lat<rB[b][2])
        {
            if(rB[b][6]>0&&newcl<rB[b][6])
            {
                return true;
            }
        }
    }
    return false;
}


function lp(){
    
    if(greyv) greyOff();
    if(cm()) return;
    if(pt) clearTimeout(pt);
    //slb('status',loading);
    gptr();
   
    
}


function lp_request(request)
{
    //$("status").style.display = "block";
    //divContent('status',loading+'<br/><span id="loads">Now loading map tiles...</span>');
    if(request.readyState==4&&request.status==200){
        var rD=request.responseXML;
        if(rD.documentElement){
            var pf=rD.documentElement.getElementsByTagName("total");
            var tips=rD.documentElement.getElementsByTagName("tips");
            
            //if(pf[0].getAttribute("amenitieson") == 1)new Effect.Appear("exclamation");
            //else new Effect.Fade("exclamation");
              basic = new Array();
            for(var i=0;i<basic.length;i++) {
                on_map_nos[basic[i]]=pf[0].getAttribute(basic[i]);
            }

            on_map=(1*on_map_nos["houses"])+1*(on_map_nos["flats"]);
            cc=0;
            
            for(j=0;j<basic.length;j++) {
                cc=cc+parseInt(on_map_nos[basic[j]]);
            }
            
            on_map=cc;
            loadElement(rD,"properties","shop","properties");
            
            //alert (properties);
            
            /*for(k=0;k<myAmenities.length;k++) {
                fL=myAmenities[k][0].substr(0,3);
                loadElement(rD,myAmenities[k][0],fL,myAmenities[k][0]);
            }*/
            
            /*for(m=0;m<myAgentOffices.length;m++) {
                pfL = myAgentOffices[m][0].substr(0,3);
                loadElement(rD,myAgentOffices[m][0],pfL,myAgentOffices[m][0]);
            }*/
             
             
            
               get_map_tips(rD,tips[0].getAttribute("text"));
              
          // $('tip_body').innerHTML =  "MAP TIPS";
            
            pt=window.setTimeout(pp,100);
            divContent('loads','Now ploting icons...');
            delete request;
        }
    }
}


function url_parameters(which)
{
    var params=location.search;
    if(params.length==0)
        return"";params=params.substr(1,params.length);
    var pairs=params.split("&");
    for(var i=0;i<pairs.length;i++)
    {
        var pair_values=pairs[i].split("=");
        if(pair_values[0]==which)
        {
            return pair_values[1];
        }
    }
    return"";
}

if(!ie){
    document.captureEvents(Event.MOUSEMOVE)
}

/*
document.onmousemove=function(e){
    getMouseXY(e);
};
*/

document.onclick = getMouseXY;
document.onmousemove = getMouseXY;

function getXY(e) { 
    mouseX = (window.Event) ? e.pageX : event.clientX; 
    mouseY = (window.Event) ? e.pageY : event.clientY;     
}


function getMouseXY(e){
    if(ie){
        mouseX=event.clientX+document.body.scrollLeft;
        mouseY=event.clientY+document.body.scrollTop;
    }else{
        mouseX=e.pageX;
        mouseY=e.pageY;
    }
    
    if(debug && debugLevel == 5) {
        GLog.write("mouseX: " + mouseX);
        GLog.write("mouseY: " + mouseY);
    }
    
    if(mouseX<0) {
        mouseX=0;
    }
    if(mouseY<0){
        mouseY=0;
    }
    return true;
}

/*function getVars(){
    var vars="type="+searchType+"&x1="+leftEdge+"&x2="+rightEdge+"&y2="+topEdge+"&y1="+bottomEdge+"&z="+map.getZoom()+"&cx="+url_parameters("lng")+"&cy="+url_parameters("lat") + "&ids="+url_parameters("ids") + "&searchterm="+url_parameters("searchterm");
    
    for(var m=0;m<myOptions.length;m++)
    {
        vars+="&"+myOptions[m][0]+"="+myValues[myOptions[m][0]];
    }

    for(var m=0;m<myAmenitiesOptions.length;m++)
    {
        vars+="&"+myAmenitiesOptions[m][0]+"="+myValues[myAmenitiesOptions[m][0]];
    }

    for(var m=0;m<myDropDownOptions.length;m++)
    {
        vars+="&"+myDropDownOptions[m][0]+"="+myValues[myDropDownOptions[m][0]];
    }
    
    for(var m=0;m<myAgentOfficesOptionsOptions.length;m++)
    {
        vars+="&"+myAgentOfficesOptions[m][0]+"="+myValues[myAgentOfficesOptions[m][0]];
    }

    return vars;
}*/

function pre_populate(obj,type)
{
    if(type=="checkbox"){
        myValues[obj.name]=obj.checked;
    }else{
        myValues[obj.name]=obj.value;
    }
    gptr();
}

function guv(minX,minY,maxX,maxY){
    if(minX=="undefined"){
        return false;
    }
    var ce=map.getCenter();
    var nx=ce.x;
    var ny=ce.y;
    var ext="";
    var times=cl>=11?0.9701:0.77162458338772;
    var cLng=(icon_width-0)/(Math.pow(2,(cl))*times);
    var cLat=(icon_height-0)/(Math.pow(2,(cl)));
    minX+=cLng;
    maxX-=cLng;
    minY+=cLat;
    maxY-=cLat;
    var vars="type="+searchType+"&x1="+minX+"&x2="+maxX+"&y1="+maxY+"&y2="+minY+"&z="+map.getZoom()+"&cx="+ny+"&cy="+nx;
   /*  for(var m=0;m<myOptions.length;m++){
        vars+="&"+myOptions[m][0]+"="+myValues[myOptions[m][0]];
    }
   for(var m=0;m<myAmenitiesOptions.length;m++){
        vars+="&"+myAmenitiesOptions[m][0]+"="+myValues[myAmenitiesOptions[m][0]];
    }
    for(var m=0;m<myDropDownOptions.length;m++){
        vars+="&"+myDropDownOptions[m][0]+"="+myValues[myDropDownOptions[m][0]];
    }
    for(var m=0;m<myAgentOfficesOptions.length;m++){
        vars+="&"+myAgentOfficesOptions[m][0]+"="+myValues[myAgentOfficesOptions[m][0]];
    }*/
    
    vars+="&icon_width="+icon_width+"&icon_height="+icon_height+"&z="+(17-cl);
    return vars;
}

function guv2(minX,minY,maxX,maxY){
    dontuseboundary = false;
    if(minX=="undefined"){
        return false;
    }
    var ce=map.getCenter();
    var nx=ce.x;
    var ny=ce.y;
    var ext="";
    var times=cl>=11?0.9701:0.77162458338772;
    var cLng=(icon_width-0)/(Math.pow(2,(cl))*times);
    var cLat=(icon_height-0)/(Math.pow(2,(cl)));
    minX+=cLng;
    maxX-=cLng;
    minY+=cLat;
    maxY-=cLat;
    var vars="type="+searchType+"&z="+map.getZoom()+"&cx="+ny+"&cy="+nx;
    for(var m=0;m<myOptions.length;m++){
        vars+="&"+myOptions[m][0]+"="+myValues[myOptions[m][0]];
    }
    /*for(var m=0;m<myAmenitiesOptions.length;m++){
        vars+="&"+myAmenitiesOptions[m][0]+"="+myValues[myAmenitiesOptions[m][0]];
    }*/
    for(var m=0;m<myDropDownOptions.length;m++){
        vars+="&"+myDropDownOptions[m][0]+"="+myValues[myDropDownOptions[m][0]];
    }
    for(var m=0;m<myAgentOfficesOptions.length;m++){
        vars+="&"+myAgentOfficesOptions[m][0]+"="+myValues[myAgentOfficesOptions[m][0]];
    }
    vars+="&icon_width="+icon_width+"&icon_height="+icon_height+"&z="+(17-cl);
    return vars;
}

var FILTERS = "";
var MAP_IDS = ""
var FACILITIES = "";
function filterMap (form) {
    FILTERS = "&" +  $(form).serialize();
	gptr();
}

function doMapSearch (lt,ln,term,ids) { 
	$('autocomplete_choices').style.display ='none';
	$('garmin').style.display ='none';
    bCheck = true;
    FILTERS = "&" +  $("map_form").serialize();
    MAP_IDS = ids ? ids : "";
    
    goXY (lt,ln,"Showing markers for " + term);
    $("on_map_search").style.display = "none";

}

function doMapSearchProvince (lt,ln,term,ids) {
	$('autocomplete_choices').style.display ='none';
    bCheck = false;
    FILTERS = "&" +  $("map_form").serialize();
    MAP_IDS = ids ? ids : "";
    
    goXY (lt,ln,"Showing markers for " + term);
    $("on_map_search").style.display = "none";

}

function gptr(){

	var b=map.getBounds();
    var sw=b.getSouthWest();
    var ne=b.getNorthEast();

    MAP_IDS = MAP_IDS ;//? MAP_IDS : url_parameters('ids') ;

    if(typeof(dontuseboundary)!="undefined") {  //this means that the user is coming in from the quicksearch and therefore we need to do the ids thing
        if(dontuseboundary) { // dontuseboundary is true so this is the first instance of the xml loader
            url=properties_url+guv2(sw.lng(),sw.lat(),ne.lng(),ne.lat())+bString+"&maxprops="+on_map_cutoff+"&ids="+MAP_IDS+"&searchterm="+url_parameters('searchterm') + FILTERS + FACILITIES;
        } else {
            url=properties_url+guv(sw.lng(),sw.lat(),ne.lng(),ne.lat())+bString+"&maxprops="+on_map_cutoff+"&ids="+MAP_IDS+"&searchterm="+MAP_IDS + FILTERS + FACILITIES;
        }
    } else {
		// Search Result was not clicked.
		url=properties_url+guv(sw.lng(),sw.lat(),ne.lng(),ne.lat())+bString+"&maxprops="+on_map_cutoff+"&ids="+MAP_IDS+"&searchterm="+url_parameters('searchterm') + FILTERS + FACILITIES;
    }
    
    
    if(showall)
    {
	   url=properties_url+guv(sw.lng(),sw.lat(),ne.lng(),ne.lat())+bString+"&maxprops="+on_map_cutoff+"&searchterm="+url_parameters('searchterm') + FILTERS + FACILITIES;
        //if(console.log)console.log("ids removed => "+url);
    }
          //url=properties_url+guv(sw.lng(),sw.lat(),ne.lng(),ne.lat())+bString+"&maxprops="+on_map_cutoff+"&ids="+url_parameters('ids')+"&searchterm="+url_parameters('searchterm');
    /***********************This sets the cookie for the Back to link**********************/
    //var maptype = map.getCurrentMapType;
    var cVal = { sha: showstatus(),  cmt: getcuurrentmaptype(), cp: map.getCenter(), zm: map.getZoom(), pids: MAP_IDS };
    var cValText = cVal.toJSONString();
    //if (console.log)console.log("string => "+cValText+ " curentmap center => "+map.getCenter());
    setcookie("savedmappos", cValText,365);
    /**END**/
    //formRequest(url,"lp_request");  
    formRequest(url,"lp_request");  

}
//this is the initialize map function

function showstatus()
{ 
  return showall;
}
function getcuurrentmaptype()
{
  var bool = false;
  
  if(map.getCurrentMapType() == G_HYBRID_MAP)
  {
    bool = true;
  }
  return bool;
}
function rmal(props)
{
    for(var k=0;k<propmarkers.length;k++)
    {
        map.removeOverlay(propmarkers[k]);
        GEvent.removeListener(propmarkers[k])
    }
}
//DOUBLE CHECK THIS LOGIC
function divContent(name,content){
    //$(name).innerHTML=content;
}

function removelayer(marker){
    cap();
}

function removeMarker(marker){
    mgr.RemoveMarker(marker);
}

function changeContent(name,what,name2,content)
{
    for(var i=0;i<tabs.length;i++)
    {
        if(what=="block"){
            $(tabs[i]+"frame").style.display="none";
            $(tabs[i]+"updown").innerHTML=upArrow(tabs[i]);
        }
    }
    if(what=="block")dis="false";
    if(what=="none")dis="true";
    $(name).style.display=what;$(name2).innerHTML=content;
}

function getOptions(){var theform="<form name='optionform' id='optionform' style='padding:0;'>";var op=values=display=selected=null;for(var i=0;i<myOptions.length;i++){op=myOptions[i];
if(op[2]=="select"){myValues[op[0]]=op[5];
if(i>0)theform+="";theform+="<div class='dropdownpadding'>";theform+=op[1]+"<br /><select class='select1' name='"+op[0]+"' id='f_"+op[0]+"' onchange='pre_populate(this,\""+op[2]+"\")'>";values=op[3].split("|");displays=op[4].split("|");for(var j=0;j<values.length;j++){selected=displays[j]==op[5]?"selected":"";
if(!displays[j])displays[j]=values[j];theform+="<option "+selected+" value='"+displays[j]+"'>"+values[j]+"</option>";}
theform+="</select>";theform+="</div>";}
if(op[2]=="checkbox"){myValues[op[0]]=op[5];
if(i>0)theform+="";
if(op[5]=="true"){var checked='checked';}else{var checked='';}
theform+="<div class='filtercheckbox'>";theform+="<input "+checked+" value='"+op[3]+"' type='checkbox' name='"+op[0]+"' id='f_"+op[0]+"' onclick='pre_populate(this,\""+op[2]+"\")'><span class='text h1'>"+op[1]+"</span>";theform+="</div>";}}
theform+="</form>";return theform;}
/*
function getAmenitiesOptions()
{
    var theform="<form name='optionform1' id='optionform1'>";
    var op=values=display=selected=null;
    for(var i=0;i<myAmenitiesOptions.length;i++)
    {
        op=myAmenitiesOptions[i];
        if(op[2]=="select")
        {
            myValues[op[0]]=op[5];
            if(i>0) theform+="<br />";
            theform+=op[1]+"<select class='select1' name='"+op[0]+"' id='f_"+op[0]+"' onchange='pre_populate(this,\""+op[2]+"\")'>";values=op[3].split(",");displays=op[4].split(",");
            for(var j=0;j<values.length;j++)
            {
                selected=displays[j]==op[5]?"selected":"";
                if(!displays[j])displays[j]=values[j];
                theform+="<option "+selected+" value='"+displays[j]+"'>"+values[j]+"</option>";
            }
            theform+="</select>";
        }

        if(op[2]=="checkbox")
        {
            myValues[op[0]]=op[5];
            if(i>0)theform+="<br />";
            if(op[5]=="true")var checked='checked';
            else var checked='';
            theform+="<input "+checked+" value='"+op[3]+"' type='checkbox' name='"+op[0]+"' id='f_"+op[0]+"' onclick='pre_populate(this,\""+op[2]+"\");activated(\""+op[0]+"..\")'><span class='text h1'>"+op[1]+"</span>";
            //theform+= " image =>  " +op[i];
        }
    }
    theform+="</form>\n";
    return theform;
}

function getDropDownOptions() {
    var theform="<form name='optionform2' id='optionform2'>";
    var op=values=display=selected=null;
    for(var i=0;i<myDropDownOptions.length;i++) {
        op=myDropDownOptions[i];
        if(op[2]=="select") { 
            myValues[op[0]]=op[5];
            if(i>0)theform+="";
            theform+="<div class='dropdownpadding'>";
            theform+=op[1]+"<br /><select class='select1' name='"+op[0]+"' id='f_"+op[0]+"' onchange='pre_populate(this,\""+op[2]+"\")'>";
            values=op[3].split("|");
            displays=op[4].split("|");
            for(var j=0;j<values.length;j++){
                selected=displays[j]==op[5]?"selected":"";
                if(!displays[j]){
                    displays[j]=values[j];
                }
                theform+="<option "+selected+" value='"+displays[j]+"'>"+values[j]+"</option>";
            }
            theform+="</select>";
            theform+="</div>";
        }
        
         if(op[2]=="checkbox")
        {
            myValues[op[0]]=op[5];
            if(i>0)theform+="<br />";
            if(op[5]=="true")var checked='checked';
            else var checked='';
            theform+="<input "+checked+" value='"+op[3]+"' type='checkbox' name='"+op[0]+"' id='f_"+op[0]+"' onclick='pre_populate(this,\""+op[2]+"\")'><span class='text h1'>"+op[1]+"</span>";
        }
    }
    theform+="</form>\n";
    return theform;
}


function getAgentOfficesOptions() {
var theform="<form name='optionform3' id='optionform3'>";
    var op=values=display=selected=null;
    for(var i=0;i<myAgentOfficesOptions.length;i++) {
        op=myAgentOfficesOptions[i];
        if(op[2]=="select") { 
            myValues[op[0]]=op[5];
            if(i>0)theform+="";
            theform+="<div class='dropdownpadding'>";
            theform+=op[1]+"<br /><select class='select1' name='"+op[0]+"' id='f_"+op[0]+"' onchange='pre_populate(this,\""+op[2]+"\")'>";
            values=op[3].split("|");
            displays=op[4].split("|");
            for(var j=0;j<values.length;j++) {
                selected=displays[j]==op[5]?"selected":"";
                if(!displays[j]){
                    displays[j]=values[j];
                }
                theform+="<option "+selected+" value='"+displays[j]+"'>"+values[j]+"</option>";
            }
            theform+="</select>";
            theform+="</div>";
        }
        
         if(op[2]=="checkbox")
        {
            myValues[op[0]]=op[5];
            if(i>0)theform+="<br />";
            if(op[5]=="true")var checked='checked';
            else var checked='';
            theform+="<input "+checked+" value='"+op[3]+"' type='checkbox' name='"+op[0]+"' id='f_"+op[0]+"' onclick='pre_populate(this,\""+op[2]+"\")'><span class='text h1'>"+op[1]+"</span>";
        }
    }
    theform+="</form>\n";
    return theform;
}
*/
var scale_icon_height=15;
var scale_off_icon="scale_off.gif";
var scale_on_icon="scale_on.gif";
var scale_minus_icon="zoom_negtive.gif";
var scale_plus_icon="zoom_postive.gif";
var scale_icon_width=8;
var images_directory="icons/";
var scaleText="";

function csb(){
    
    if (!$("scalesdiv")) return false;
    
    var scaleGraphics='';
    var graphic="";
    var temp_height=scale_icon_height;
    var vspace=0;
    if(min_level > max_level)
    {
        var au = max_level;
        var ad = min_level;
        max_level = ad;
        min_level = au;
    }
    
    var md=17-max_level;
    var cnt = 1;
    for(i=17-min_level;i>=9;i--)
    {
        
        if(debug && debugLevel == 1){ 
            //GLog.write("min-level = " + min_level);
            //GLog.write("max-level = " + max_level);
            GLog.write("Map Zoom Level = " + map.getZoom().toString());
            //GLog.write("<img src='"+images_directory+graphic+"' alt='change map scale' width='"+scale_icon_width+"' border='0' height='"+temp_height+"' vspace='"+vspace+"' />");
        }
        
        graphic=(cl==i) ? scale_on_icon: scale_off_icon;
        scaleGraphics+="<a href='javascript:void(dZ(\""+(i-1)+"\"))'><img src='"+images_directory+graphic+"' alt='change map scale' title='change map scale' width='"+scale_icon_width+"' border='0' height='"+temp_height+"' vspace='"+vspace+"' style=\"display: inline;\"/>&nbsp;</a>";
        temp_height-=2;
        vspace = 0;
        //alert(cnt++);
        //vspace+=1;
    }
    var previous=cl;
    
    if(od!=md||cl!=ol)
    {
        slb("scalesdiv",scaleText+"<a href='javascript:void(dZ(\""+previous+"\"))' id='zoomin' ><img alt='zoom into map'  style=\"display: inline;\" title='zoom into map' src='"+images_directory+scale_plus_icon+"' border='0' ></a> "+scaleGraphics+"<a href='javascript:void(dZ(\""+(cl-2)+"\"))' id='zoomout'><img style=\"display: inline;\" src='"+images_directory+scale_minus_icon+"' border='0' alt='zoom out of map' title='zoom out of map' /></a>");
    }
    od=md;
    ol=cl;
}

function clearBox2(){
	if($('placeName').value.length == 0){
		// $('dSelect').style.display = "block";
	}
}

function upArrow(name)
{return"<a href='javascript:void(changeContent(\""+name+"frame\",\"block\",\""+name+"updown\",downArrow(\""+name+"\")))'><img border='0' align='absmiddle' src='icons/tab_plus.gif' ></a> &nbsp;";}

function downArrow(name)
{return"<a href='javascript:void(changeContent(\""+name+"frame\",\"none\",\""+name+"updown\",upArrow(\""+name+"\")))'><img border='0' align='absmiddle' src='icons/tab_minus.gif' ></a> &nbsp;";}

function upArrow1(name)
{return"<a href='javascript:void(changeContent(\""+name+"frame\",\"block\",\""+name+"updown\",downArrow(\""+name+"\")))'><img border='0' align='absmiddle' src='icons/tab_minus.gif' ></a> &nbsp;";}

function downArrow1(name)
{return"<a href='javascript:void(changeContent(\""+name+"frame\",\"none\",\""+name+"updown\",upArrow(\""+name+"\")))'><img border='0' align='absmiddle' src='icons/tab_plus.gif' ></a> &nbsp;";}
var dis;
function newTab(name,heading,value,visible,hideleftside)
{
	tabs[tabs.length]=name;
	
	var change='';
	
	if(visible=="block") {
		var updown="<a href='javascript:void(changeContent(\""+name+"frame\",\"none\",\""+name+"updown\",upArrow(\""+name+"\")))'><img border=0 src='icons/tab_minus.gif' ></a> &nbsp;";
		
	}
	else 
        {
		var updown="<a href='javascript:void(changeContent(\""+name+"frame\",\"block\",\""+name+"updown\",downArrow(\""+name+"\")))'><img border=0 src='icons/tab_plus.gif' ></a> &nbsp;";
		
	}
	
	var displaywhat;
        
        var change_down="changeContent(\""+name+"frame\",\"none\",\""+name+"updown\",downArrow1(\""+name+"\"));";
        var change_up="changeContent(\""+name+"frame\",\"block\",\""+name+"updown\",upArrow1(\""+name+"\"));";
	
	if (hideleftside) displaywhat='block';
	else displaywhat='none';
	//alert(displaywhat);
	document.write("<div class='header' style='display:" + displaywhat + ";'><div id='"+name+"updown' style='display:inline'>"+updown+" </div><span onclick='if(dis){"+change_down+" dis=false;}else{"+change_up+" dis=true;}' style='cursor: pointer;'>"+heading+"</span></div><div class='text h1' id="+name+"frame style='display:"+visible+"'>"); 
		
	document.write(value);
	document.write("</div>");
	
}

function getXY(e){mouseX=(window.Event)?e.pageX:event.clientX;mouseY=(window.Event)?e.pageY:event.clientY;}

function gp(marker,extra_x_offset) {
    if(typeof(extra_x_offset)=='undefined') extra_x_offset=0;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom()),br=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom()),hn=marker.getIcon().iconAnchor,width=marker.getIcon().iconSize.width,hd=marker.getIcon().iconSize.height,height=ae.clientHeight,kn=new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(br.x-point.x-hn.x+width+5+extra_x_offset,br.y-point.y-hn.y-height+hd));
    kn.apply(ae);
    ae.innerHTML=marker.tooltip;
    ae.style.display='block';
    ae.style.visibility="visible";
};


function dochange(mx, my)
{
    new Effect.SlideUp('resultspanel', { duration:2.0 });
    mx = parseFloat(mx);
    my = parseFloat(my);
    base_x = my;
    base_y = mx;
    map.panTo(new GLatLng(base_x, base_y));
}

function goXY(mx,my,maptip)
{
    jump_map_tip = maptip;
    if (jump_map_tip && $('jump_map_tip')) $('jump_map_tip').innerHTML=jump_map_tip + "&nbsp;&nbsp;<span style=\"cursor: pointer; text-decoration: underline;\" onclick=\"show_all_property();this.style.display='none'\" id=\"allshow\"><strong> <font color=\"#333333\">Show all stores in the area</font></strong><span/>";
    mx = parseFloat(mx);
    my = parseFloat(my);
    base_x = my;
    base_y = mx;
	
	
	
   	map.panTo(new GLatLng(base_x, base_y));
}

/*function generateOutput() 
{
  new Effect.BlindUp('tool_body');
  document.images['tab'].src= './icons/tab_plus.gif';
  bar_toggle =1;
}*/

function valfinder(arr,val)
{
  var len = arr.length;
  for(var i=0; i<len; i++)
  {
    d = arr[i];
    if(i != 0)
    {
      d2 = arr[i-1];
    } else {
      d2 = arr[0];
    }
    if(d==val) return d2;
  }
}

function findPosX(obj)
{
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
     curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function ProcessMouseMove(mouseX, mouseY)
{
  pixscale = (scaler*2)/parseInt(mapWidth);
  posMouseX = base_x + ((mouseX-parseInt(mapWidth/2))-findPosX(getObj("mapimg"))+10)*pixscale;
  posMouseY = base_y - ((mouseY-parseInt(mapWidth/2))-findPosY(getObj("mapimg"))+22)*pixscale;
  $('X_Update').value=posMouseX.toString();
  $('Y_Update').value=posMouseY.toString();
}
/************************GET AND SAVE COOKIE LOGIC************************/
function setcookie(n,v,d){ 
    if (document.location.href.match(/roea/)) return; 
    n = searchType + n; 
    var cS=n+"="+escape(v)+";EXPIRES="+getexpirydate(d);
    //if(console.log)console.log("cookie => "+cS);
    document.cookie=cS;
    if(!getcookie(n)){ 
        return false; 
    } else{ 
        return true; 
    } 
}
function getcookie(cN) { 
    cN = searchType + cN; 
    /*
    if (iconsasonecookie){ 
        if (cN.match("bicon") && !cN.match("bicons")){ 
            var num = cN.replace ("bicon",""); 
            var wholevalue  = getcookie ("icons");
            if (wholevalue) {  
                var wvs = wholevalue.split(":");   
                return wvs[num-1]; 
            }
        }
    } */
    var cS=""+document.cookie; 
    var i1=cS.lastIndexOf(cN); 
    if (i1==-1 || cN=="") return ""; 
    var i2=cS.indexOf(';',i1); 
    if (i2==-1) i2=cS.length; 
    return unescape(cS.substring(i1+cN.length+1,i2)); 
}
function getexpirydate( nodays){ var UTCstring; Today = new Date(); nomilli=Date.parse(Today); Today.setTime(nomilli+nodays*24*60*60*1000); UTCstring = Today.toUTCString(); return UTCstring; }
/**END**/

var type_map;

function change_map(type)
{
  if(type == G_HYBRID_MAP)
  {
      $("hyb_view").style.fontWeight = "bold";
      $("map_view").style.fontWeight = "normal";
  }
  else
  {
      $("hyb_view").style.fontWeight = "normal";
      $("map_view").style.fontWeight = "bold";
  }
  //$("actions").style.display = "none";
  //menu=false;
  map.setMapType(type);
    
}
function new_location()
{
  //$("lightBox").style.display = "block";
 // new Effect.Appear("placesFormDiv");
  //$("actions").style.display = "none";
  //$("placesFormDiv").style.zIndex = "8001";
  menu=false;
}
var help = true;

var at;
function activated(message)
{
  //alert(message);
  if(at)
  {
    window.clearTimeout(at);
  }
  //if(console.log)console.log("message => " +message);
  if(message == "policestations..")
  {
    message = "police station..";
  }
  var active = $("activated");
  active.innerHTML = "Now showing all "+message;
  active.style.zIndex = "99999";
  new Effect.Appear("activated");
  at = window.setTimeout(function(){new Effect.Fade("activated");},1200);
}
/*******************
    TABS JS
********************/
 var mt;
function hide_menu()
{
//$("actions").style.display = "none";
menu=false;
}


var menu = false;

/*******************
    TABS JS
********************/
/*function toggle_tabs()
{
//alert(bar_toggle);
    if(bar_toggle == 1) 
    {
					new Effect.BlindDown('tool_body');
                     document.images['tab'].src= "./icons/tab_minus.gif";
                    bar_toggle =0;
    } 
    else 
    {
                    new Effect.BlindUp('tool_body');
                   document.images['tab'].src= "./icons/tab_plus.gif";
                    bar_toggle =1;
    }	
}*/

addLoadEvent(im);

/******************************** JSON Code ******************************************/
/*
    json.js
    2007-04-30

    Public Domain

    This file adds these methods to JavaScript:

        array.toJSONString()
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString()
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

/*jslint evil: true */

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function () {
        var a = ['['],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

        function p(s) {

// p accumulates text fragments in an array. It inserts a comma before all
// except the first fragment.

            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;

// Otherwise, serialize the value.

            case 'string':
            case 'number':
            case 'boolean':
                p(v.toJSONString());

// Values without a JSON representation are ignored.

            }
        }

// Join all of the fragments together and return.

        a.push(']');
        return a.join('');
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Ultimately, this method will be equivalent to the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : "null";
    };


    Object.prototype.toJSONString = function () {
        var a = ['{'],  // The array holding the text fragments.
            b,          // A boolean indicating that a comma is required.
            k,          // The current key.
            v;          // The current value.

        function p(s) {

// p accumulates text fragment pairs in an array. It inserts a comma before all
// except the first fragment pair.

            if (b) {
                a.push(',');
            }
            a.push(k.toJSONString(), ':', s);
            b = true;
        }

// Iterate through all of the keys in the object, ignoring the proto chain.

        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;

                case 'string':
                case 'number':
                case 'boolean':
                    p(v.toJSONString());

// Values without a JSON representation are ignored.

                }
            }
        }

// Join all of the fragments together and return.

        a.push('}');
        return a.join('');
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (v.hasOwnProperty(i)) {
                            v[i] = walk(i, v[i]);
                        }
                    }
                }
                return filter(k, v);
            }


// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

            if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                    test(this)) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                try {
                    j = eval('(' + this + ')');
                } catch (e) {
                    throw new SyntaxError("parseJSON");
                }
            } else {
                throw new SyntaxError("parseJSON");
            }

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

            if (typeof filter === 'function') {
                j = walk('', j);
            }
            return j;
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function (a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}

var CURRENT_SHOP = 1;

function paginatePopUp (index, incr, total) {
    
    for (var i = 1; i < (total + 1); i++ ) {
            if ( document.getElementById ("store_popup_" + i) ) {
            
                    document.getElementById("store_popup_" + i).style.display = "none";
            }
    }
    
    if (index) {
            CURRENT_SHOP = index;
    }
    else {
    
          var goTo  = incr + CURRENT_SHOP;
          
          if (goTo < 1) {
              goTo = 1;  
          }
          else if ( goTo > total ) {
              goTo = total;
          }
          CURRENT_SHOP = goTo;
    }
    
    document.getElementById("store_popup_" + CURRENT_SHOP).style.display = "block";
    document.getElementById("indexer").innerHTML= CURRENT_SHOP;
    
    
}

function Filter_By_Store_Facilities(form_id) {

    $('filter_facilities').style.display = "none";
	FACILITIES = "&" +  $(form_id).serialize();
    gptr();
	
}

var tabs_types_array = new Array ('Store', 'Manager', 'Facilities');        
var div_type_variables = new Array ('table', 'div');

function Tab (activeType, storeID) {
        
        //alert(activeType);
        //Here we loop through all the stores, times, facilites or 'categories' we need to close example-the capitalised letter is an element of the array: STORE_div_589, MANAGER_div_589, FACILITIES_div_589
        for (t=0; t<tabs_types_array.length; t++) {
                
                //Here we loop through all the div, tables, or thing we need to close example-the capitalised letter is an element of the array: Store_TABLE_589, Store_DIV_589
                for (i=0; i<div_type_variables.length; i++) {
                        
                        var type = tabs_types_array[t];
                        var element = div_type_variables[i];
                        
                        //alert(type + "_" + element + "_" + storeID);
                        var currentElement = type + "_" + element + "_" + storeID; // This is the element currently build in this loop
                        
                        if (activeType == type) { // check if this is the a element we want to open
                                
                                document.getElementById(currentElement).style.display = "block";
                                //alert("block");
                                
                        } else { // it is the a element we want to close
                                
                                document.getElementById(currentElement).style.display = "none";
                                //alert("none");
                        }
                        
                }
        }

}