﻿	//Gautrain map properties
    var GautrainMap; //the GMap2 itself
    var GooPointArray=[];
    var GooMarker=[];
    var GooPoly=[];
    var GooLine=[];
    var GauPointArray=[];
    var GauMarker=[];
    var GauPoly=[];
    var GauLine=[];
    var GoogleMap ;
    var redicon;
    var centreLat=0.0;
    var centreLon=0.0;
    var initialZoom=2;
    var imageWraps=false; //SET THIS TO false TO PREVENT THE IMAGE WRAPPING AROUND
    var custommap;
	var scrollableApi;
    var gdir;
    var gdir2;
    var html=[];
    var precis=[];
    var miniMarker=[];
    var marker=[];
    var overV;
    var BusStationList=[];
    var BusStationMarker=[];
    var BusStationOverlay=[];
	var stationList;
	var routeList;
    var routeListCounter =0;
    var totalDistance =0;
    var distPercent=[];
    var distance=[];
    var InterchangeMarker=[];
    var interchangeLatLng; 
    var interchangeInfo=""; 
    var showTransport=true;
    var JourneyBounds = new GLatLngBounds();


    /** Convert numeric degrees to radians */
    if (typeof(String.prototype.toRad) === "undefined") {
      Number.prototype.toRad = function() {
        return this * Math.PI / 180;
      }
    }
    
    ///////////////////// document.ready() block
    $(document).ready(function()
    {
        PageMethods.GetStations(OnStationsSuccess, OnStationsFail, OnStationsTimeOut);
        
        //toggleSearchBar();
        
    
		$("#widgetMap").draggable({ containment: '#container', scroll: false });
		$("#widgetPtP").draggable({ containment: '#container', scroll: false });
        $('#BusRoutes .checkbox').css('background-position','0px 0px');     //reset checkboxes
        $('#TrainRoutes .checkbox').css('background-position','0px 0px');   //reset checkboxes
        
        $(".zoom").live('click',function()
        {
            if($(this).attr('zoom') == "+") { GoogleMap.setZoom(GoogleMap.getZoom()+1); }
            if($(this).attr('zoom') == "-") { GoogleMap.setZoom(GoogleMap.getZoom()-1); }
        });

        var popupTimer =0;
        $("#IntermediateStationPopup").mouseover(function()
            {
            $("#IntermediateStationPopDOWN").fadeOut();
            clearTimeout(popupTimer);
            $(this).show();
            });

        $("#IntermediateStationPopDOWN").mouseover(function()
            {
            $("#IntermediateStationPopup").fadeOut();
            clearTimeout(popupTimer);
            $(this).show();
            });

        $("#stationContent").mouseover(function()
            {
            clearTimeout(popupTimer);
            $("#IntermediateStationPopup").show();
            });

        $("#IntermediateStationPopup").mouseout(function()
        {
            clearTimeout(popupTimer);
            //put a 1sec delay on hiding the popup
            popupTimer = setTimeout('hideStationPopup()', 1000);
        });

        $("#IntermediateStationPopDOWN").mouseout(function()
        {
            clearTimeout(popupTimer);
            //put a 1sec delay on hiding the popup
            popupTimer = setTimeout('hideStationPopup()', 1000);
        });


         $("#BackJourney").live('click',function() {
            $("#EmailThanksTable").fadeOut();
            $("#emailFormHolder").fadeOut();
            $("#directionsFormHolder").fadeIn();
         });
         
         $("#p2pPrint").live('click',function() {
            setPrintable()
            printElem();
         });
         
         $("#p2pEmail").live('click',function() {
            $("#cancelEmail").fadeIn();
            $("#EmailThanksTable").fadeOut();
            $("#EmailFormTable").fadeIn();
            $("#emailFormHolder").fadeIn();
            $('#VerificationCodeTextBox').realperson({length: 4});
            $("#directionsFormHolder").fadeOut();
         });
         
         $("#cancelEmail").live('click',function() {
            $("#emailFormHolder").fadeOut();
            $("#directionsFormHolder").fadeIn();
         });
         
         $(".browse").live('click',function() {
            scrollableApi.seekTo($(this).attr("paneId"), 400);
         });
         
         $(".emailForm").focus(function() {
             if(this.value==this.defaultValue){this.value='';} else if (this.value==''){this.value=this.defaultValue;}
         });
         
         $(".emailForm").blur(function() {
             if(this.value==''){this.value=this.defaultValue;} else if (this.value==this.defaultValue){this.value='';}
         });

        
        if (GBrowserIsCompatible()) 
        {  
            //Custom Map
            var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, "");
            var copyrightCollection = new GCopyrightCollection("GMapImgCutter");
            //copyrightCollection.addCopyright(copyright);

            //create a custom picture layer
            // ===== The Mercator map, exactly like that in the "custommaptile" example =====
            var tilelayers = [new GTileLayer(new GCopyrightCollection("Gautrain: Aqua Online"),0,3)];
            tilelayers[0].getCopyright = function(a,b) { return {prefix:"Gautrain: ", copyrightTexts:["Aqua Online"]}; }

            tilelayers[0].getTileUrl = customGetTileURL;
            custommap = new GMapType(tilelayers, G_NORMAL_MAP.getProjection(), "Gautrain",{errorMessage:"No Data Available",alt:"The usual projection"});
            
            custommap.getMinimumResolution = function() {return 2;}
            custommap.getMaximumResolution = function() {return 2;}
            //Google Map
            var latlng = new GLatLng(15, 0);
            GoogleMap = new GMap2($("#map_canvas").get(0));
            GoogleMap.enableDoubleClickZoom();
            GoogleMap.addMapType(G_NORMAL_MAP);
            GoogleMap.addMapType(custommap);
            GoogleMap.setCenter(latlng, 2, custommap);
 	        GoogleMap.disableDragging();
           
            // Add a move listener to restrict the bounds range
            GEvent.addListener(GoogleMap, "move", function() { $(".underCon").hide(); if(GoogleMap.getZoom() <4){checkBounds(GoogleMap.getZoom());}});
            
            // Add a zoom listener to set the mask bounds to the map bounds
            GEvent.addListener(GoogleMap, "zoomend", function(oldZ, newZ) { toggleBusStops(oldZ, newZ); });
 				$("#message").appendTo(GoogleMap.getPane(G_MAP_FLOAT_SHADOW_PANE));
          
            //  -- show coords in the title bar
            //GEvent.addListener(GoogleMap,"mousemove",function(point){
                //mousemovepoint = point;
                //document.title = point.lat().toFixed(6) + ', ' + point.lng().toFixed(6);
                //var latLngStr6 = point.lat().toFixed(6) + ', ' + point.lng().toFixed(6);
                //gob("over").options[0].text = LnglatStr6;
                //gob("over").options[1].text = latLngStr6;
            //});
			
			
/////////////LEG 1
            gdir = new GDirections(GoogleMap);     // init gdir object without "#directions" container, so the we can manually generate/list the directions using GRoute and GStep objects
            GEvent.addListener(gdir, "error", handleErrors);
            GEvent.addListener(gdir,"load", function() { 
                if(gdir.getRoute(0).getNumSteps())
                {
                    $("#directions1 .list").html("");   //reset the list
                    $("<li />")
                    .html("<strong><u>Driving directions</u></strong>")
                    .appendTo("#directions1 .list");
                    
                    //add first and last points of the directions to the bounds list
                    bounds.extend(gdir.getRoute(0).getStep(0).getLatLng());
                    bounds.extend(gdir.getRoute(0).getStep(gdir.getRoute(0).getNumSteps()-1).getLatLng());

                    for (var i=0;i<gdir.getRoute(0).getNumSteps() ;i++ )
                    {
                        $("<li />")
                        .html(gdir.getRoute(0).getStep(i).getDescriptionHtml())
                        .appendTo("#directions1 .list");
                    }
                    if(distance[1]) { nextstep = "bus"; } else {nextstep = "train";}
                    if( distance[1] == null && distance[2] == null && distance[3] == null && distance[4] == null && distance[5] == null) {nextstep="end"}

                    customiseDirIcons(this, "begin",nextstep);
                }
            });
            
            GEvent.addListener(gdir, "addoverlay", function()
            {
                //timeout allows for the delay of the map changing type and moving
                setTimeout('showdirs();',500);
                bestFit(GoogleMap, bounds);
            });
	
          
/////////////LEG 2
            gdir2 = new GDirections(GoogleMap);     // init gdir2 object without "#directions" container, so the we can manually generate/list the directions using GRoute and GStep objects
            GEvent.addListener(gdir2, "error", handleErrors);
            GEvent.addListener(gdir2,"load", function() { 
                if(gdir2.getRoute(0).getNumSteps())
                {
                    $("#directions2 .list").html("");   //reset the list
                    $("<li />")
                    .html("<strong><u>Driving directions</u></strong>")
                    .appendTo("#directions2 .list");
                
                    //add first and last points of the directions to the bounds list
                    bounds.extend(gdir2.getRoute(0).getStep(0).getLatLng());
                    bounds.extend(gdir2.getRoute(0).getStep(gdir2.getRoute(0).getNumSteps()-1).getLatLng());
                    for (var i=0;i<gdir2.getRoute(0).getNumSteps() ;i++ )
                    {
                        $("<li />")
                        .html(gdir2.getRoute(0).getStep(i).getDescriptionHtml())
                        .appendTo("#directions2 .list");
                    }
                    customiseDirIcons(this, "car", "end");
               }
            });
            GEvent.addListener(gdir2, "addoverlay", function()
            {
                //timeout allows for the delay of the map changing type and moving
                setTimeout('showdirs();',500);
                bestFit(GoogleMap, bounds)
            });
            
            
            // icon
            redicon = new GIcon();
            redicon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
            redicon.iconSize = new GSize(12, 20);
            redicon.iconAnchor = new GPoint(6, 20);
            redicon.infoWindowAnchor = new GPoint(6, 20);
            redicon.infoShadowAnchor = new GPoint(6, 20);
            redicon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png" ;
            // icon
            stationIcon = new GIcon();
            stationIcon.iconSize = new GSize(16,16);
            stationIcon.iconAnchor = new GPoint(8, 8);
            stationIcon.infoWindowAnchor = new GPoint(8, 16);
            stationIcon.image = "/assets/images/icons/station_point.png" ;

            // icon
            trainIcon = new GIcon();
            trainIcon.iconSize = new GSize(32, 37);
            trainIcon.iconAnchor = new GPoint(16, 37);
            trainIcon.shadow = "http://google-maps-icons.googlecode.com/files/shadow.png";
            trainIcon.image = "/assets/images/icons/train.png" ;
            // icon
            busIcon = new GIcon();
            busIcon.iconSize = new GSize(32, 37);
            busIcon.iconAnchor = new GPoint(16, 37);;
            busIcon.shadow = "http://google-maps-icons.googlecode.com/files/shadow.png";
            busIcon.image = "/assets/images/icons/bus.png" ;
            // icon
            invisibleIcon = new GIcon();
            invisibleIcon.iconSize = new GSize(30, 30);
            invisibleIcon.iconAnchor = new GPoint(15,40);
            invisibleIcon.image = "/assets/images/transparentPNG.png" ;
            // icon
            invisibleIconWide = new GIcon();
            invisibleIconWide.iconSize = new GSize(155, 30);
            invisibleIconWide.iconAnchor = new GPoint(30,15);
            invisibleIconWide.image = "/assets/images/transparentPNG.png" ;
 
            loadSchematicMapMarkers() 
        }
    });
///////////////////// end document.ready() block

     function setPrintable()
     {
        $('#fromAddressPrint').html($("#fromAddress").val())
        $('#toAddressPrint').html($("#toAddress").val())
        $('#firstCarDirections').html($('#directionsList1').html())
        $('#firstBusNo').html($('#BusRoute1info').html())
        $('#firstBusStop').html($('#BusRoute1From').html())
        $('.firstGautrainStation').html($('#GautrainLeg1From').html())
        $('#firstGautrain').html($('#GautrainLeg1Line').html())
        $('.secondGautrainStation').html($('#GautrainLeg1To').html())
        $('#secondBusNo').html($('#BusRoute2info').html())
        $('#secondBusStop').html($('#BusRoute2To').html())
        $('#secondCarDirections').html($('#directionsList2').html())
     }
         
     function printElem()
     {
        //hide printed directions initially
        $(".firstBusDirections").hide();
        $(".GautrainDirections").hide();
        $(".secondBusDirections").hide();
        $(".secondCarDirections").hide();

        //show the printed directions where the visual directions are visible
        if ($('#BusRoute1').is (':visible')) $(".firstBusDirections").show();
        if ($('#GautrainLeg1').is (':visible')) $(".GautrainDirections").show();
        if ($('#BusRoute2').is (':visible')) $(".secondBusDirections").show();
        if ($('#directionsBoxLeg2').is (':visible')) $(".secondCarDirections").show();

        //$('#PrintDirections').show();
        //printElem({ overrideElementCSS: true });

        $('#PrintDirections').printElement({});
        //$('#PrintDirections').hide();
     }

     function emailDirections()
     {
         
        toName = $('#toName').val();
        toEmail = $('#toEmail').val();
        fromName = $('#fromName').val();
        fromEmail = $('#fromEmail').val();
        if(checkEmail(toEmail) && checkEmail(fromEmail))
        {
        
            if(toName == "Name" || toEmail == "Email" || fromName == "Name" || fromEmail == "Email")
            {
                jQuery.facebox("Please fill in all fields");
            }
            else
            {
                code = $('#VerificationCodeTextBox').val();
                hash = $('.realperson-hash').val();
                fromAddress = $("#fromAddress").val();
                toAddress = $("#toAddress").val();
                firstCarDirections = $('#directions1').html();
                firstBusNo = $('#BusRoute1info').html();
                firstBusStop = $('#BusRoute1From').html();
                firstGautrainStation = $('#GautrainLeg1From').html();
                firstGautrain = $('#GautrainLeg1Line').html();
                secondBusNo = $('#BusRoute1info').html();
                secondBusStop = $('#BusRoute2To').html();
                secondCarDirections = $('#directions2').html();
                secondGautrainStation = $('#GautrainLeg1To').html();
             
                 PageMethods.EmailDirections(toName, toEmail, fromName, fromEmail, fromAddress, toAddress, firstCarDirections,
                    firstBusNo, firstBusStop, firstGautrainStation, firstGautrain,
                    secondBusNo, secondBusStop, secondGautrainStation, secondCarDirections,
                    code, hash, onSendMailSuccess, onSendMailFailure, onSendMailTimeout);
             $('#VerificationCodeTextBox').realperson('change', {length: 4});
            }
         }
         else
         {
             jQuery.facebox("Please check your email addresses");
         }
     }


/////////////////////callbacks
    function onSendMailSuccess(result) 
    {
        try {console.log('success');} catch (ex) {}
        if (result != "")
        {
            //jQuery.facebox(result)
            $("#EmailThanksTable").fadeIn();
            $("#EmailFormTable").fadeOut();
            $("#cancelEmail").fadeOut();
        }
    }
    
    function onSendMailFailure(result) 
    {
        try {console.log('fail');} catch (ex) {}
        if (result != "")
        {
            jQuery.facebox(result)

        }
    }
    function onSendMailTimeout(result) 
    {
        try {console.log('timeout');} catch (ex) {}
        if (result != "")
        {
            jQuery.facebox('Network timeout occured')
        }
    }

    function OnStationsSuccess(result) 
    {
        stationList = eval(result);
        createBusStationList(stationList);
    }
    function OnStationsFail(result) 
    {
        alert("PageMethod call failed: " + result.get_message()); 
    }
    function OnStationsTimeOut(result) 
    {
        alert("PageMethod call timed out: " + result.get_message()); 
    }
////////////////////end call backs
    
    function createBusStationList(stationList)
    {
        var station;
        BusStationList=[];  //flush BusStationList array
        var b=0;
        for (var s=0; s< stationList.length; s++)
        {
            if(stationList[s].sType=="Bus")
            {
                BusStationList.push({id:stationList[s].sID,name:stationList[s].sName, description:stationList[s].sDescription, routeName:stationList[s].sRouteName, latlng:stationList[s].sLatLng})
            }
        }
    }
    
    function showBusStops()
        { toggleBusStops("show"); }
    
    function hideBusStops()
        { toggleBusStops("hide"); }
    
    function toggleBusStops(showHide)
    {
        if(showHide=="show")
        {
        
        } else if (showHide=="hide")
        {
        
        }
    }
    
    function toggleBusStops(oldZ, newZ)
    {
        if(newZ==14 && oldZ ==13)   //two levels deeper than default
        {
            if (BusStationMarker.length==0)
            {
                for (var s=0; s< BusStationList.length; s++)
                {
                    xy = BusStationList[s].latlng.split(",",2) ;	// Break previous point into x and y
                    BusStationMarker[s] = new GMarker(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])), {icon:stationIcon, draggable: false});
                    
                    BusStationMarker[s].title = BusStationList[s].description;
                    GoogleMap.addOverlay(BusStationMarker[s]);
				    
				    GEvent.addListener(BusStationMarker[s], "mouseover", function(){
						var markerOffset = GoogleMap.fromLatLngToDivPixel(this.getLatLng());
						//alert(markerOffset.y + " " + markerOffset.x +  " " + this.title);
						$("#message")
							.stop(true, true).fadeIn()
							.css({ top:markerOffset.y+10, left:markerOffset.x+10 })
					        .html("<div id='transparency'></div>" + this.title);
                        var theHeight = $("#message p").height()+20;
                        $("#message").css({ height:theHeight });
                        $("#transparency").css({ height:theHeight});
                        //$("#message").dequeue();
						$("#message").queue("fx", []);
					});
				    GEvent.addListener(BusStationMarker[s], "mouseout", function(){
						$("#message").stop(true, true).fadeOut()
					});

                    //BusStationOverlay[s].show();
                }
            } else {
                for (var s=0; s< BusStationList.length; s++)
                {
                    BusStationMarker[s].show();
                }
            }
            if($("#busRoutes").attr("vis") == "false")
                showRoutes(2);
        }
        else if(newZ==13 && oldZ ==14)   //zoom out 
        {
            for (var s=0; s< BusStationList.length; s++)
            {
            BusStationMarker[s].hide();
            //GoogleMap.removeOverlay(BusStationMarker[s]); //either hide or remove (part 1)
            }
            //BusStationMarker=[];                          //remove (part 2)
        }
    }    
    
    function checkEmail(inputvalue)
    {	
        var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
        if(pattern.test(inputvalue)){         
		    return true;
        }else{   
		    return false;
        }
    }
    
    function bestFit(map, bounds) 
    {
       map.setZoom(map.getBoundsZoomLevel(bounds));
       map.setCenter(bounds.getCenter());
    }
    
    function hideStationPopup()
    {
        $("#IntermediateStationPopup").fadeOut();
        $("#IntermediateStationPopDOWN").fadeOut();
    }
        
    function customiseDirIcons(directionObject, FirstMarkerType, SecondMarkerType)
    {
       directionObject.getPolyline().setStrokeStyle({color:"#84BCFF", weight:3,opacity:1});
       var numMarkers = directionObject.getNumGeocodes()
        for (var i = 0; i < numMarkers; i++) 
        {
            if (directionObject.getMarker(i) != null)
            {
                if(i==0)
                {
                    directionObject.getMarker(i).getIcon().image = "/assets/images/icons/"+FirstMarkerType+".png";
                }
                else if (i==numMarkers-1)
                {
                    directionObject.getMarker(i).getIcon().image = "/assets/images/icons/"+SecondMarkerType+".png";
                }
                directionObject.getMarker(i).getIcon().shadow = "http://google-maps-icons.googlecode.com/files/shadow.png";
                directionObject.getMarker(i).getIcon().iconSize = new GSize(32, 37);
                directionObject.getMarker(i).getIcon().iconAnchor = new GPoint(16, 37);
            }
        }
    } 
	
	function loadSchematicMapMarkers()
	{
        //displayUnderConstruction("20,0", "", 0)     //midrand
        displayStationPopDOWN("68,0", "Hatfield", 3)     //hatfield
        displayStationPopDOWN("58,0", "Pretoria", 2)     //pretoria
        displayStationPopDOWN("43,0", "Centurion", 1)     //centurion
        displayStationPopup("20,0", "Midrand", 0)     //midrand
        //marlboro and sandton are defined below
        displayStationPopup("-52,-51", "Rosebank", 4)  //rosebank
        displayStationPopup("-61,-68", "Park", 5)  // park
        
        displayStationPopup("-25,-18", "Marlboro", 6)
        displayStationPopup("-29,-14", "Marlboro", 8) 
        displayStationPopup("-33,-10", "Marlboro", 7)
        displayStationPopup("-38,-34", "Sandton", 9) 
        displayStationPopup("-42,-30", "Sandton", 11) 
        displayStationPopup("-46,-26", "Sandton", 10) 
        displayStationPopup("-12,32", "Rhodesfield", 12) 
        displayStationPopup("-17,58", "OR_Tambo", 13) 
	}
	
	function showdirs()
	{
	    try
	    {
	        scrollableApi.seekTo(0, 400)
            $("#StartAgainLink").fadeIn();
            $("#p2pPrint").fadeIn();
            $("#p2pEmail").fadeIn();
            $("#searchStatus").fadeOut();
            $("#FromTo").slideUp();
            $("#scroll").slideDown();
            $('#directions1').jScrollPane({showArrows:true,scrollbarWidth:15, dragMaxHeight:90});
            $('#directions2').jScrollPane({showArrows:true,scrollbarWidth:15, dragMaxHeight:90});
            $(".auto").autoEllipsis();

        }
        catch (err)
        { 
        //alert(err);
        }
	}
	
	function setMap(mapType)
	{
	    hidePopups();
        $("#BusRoutes").hide();
        _gaq.push(['_trackEvent', 'Change Map Type', 'Click', mapType.attr('id')]);
        $("#busRoutes").attr("vis","false");    //reset checkboxes
        $("#trainRoutes").attr("vis","false");  //reset checkboxes
        $('#BusRoutes .checkbox').css('background-position','0px 0px');     //reset checkboxes
        $('#TrainRoutes .checkbox').css('background-position','0px 0px');   //reset checkboxes
	    if(mapType.attr('id')=='GoogleMapView')
	    {
            if(gdir.getNumGeocodes()==0 && gdir != undefined)
            {
                removeAllMarkers();
                stationIcon.iconSize = new GSize(16,16);
                stationIcon.iconAnchor = new GPoint(8, 8);
                stationIcon.infoWindowAnchor = new GPoint(8, 16);
                stationIcon.image = "/assets/images/icons/station_point.png" ;
                stationIcon.shadow = "";
                $('#GoogleMapView .radio').css('background-position','0px -30px');
                setTimeout('showRoutes(1)',2500);
            }
            $('#zoomout').attr('src', '/assets/images/widget_map_minus.png');
            $('#zoomin').attr('src', '/assets/images/widget_map_plus.png');
            var latlng = new GLatLng(-25.982152, 28.147810);
            GoogleMap.setCenter(latlng, 10, G_NORMAL_MAP);
            $('#GautrainMapView .radio').css('background-position','0px 0px');
            $("#TrainRoutes").show();
            $("#BusRoutes").show();
            $("#mapType").val('Google');
	        GoogleMap.enableDragging();
	    }
	    else if(mapType.attr('id')=='GautrainMapView')
	    {
            removeAllMarkers();
	        resetSearch()
            $('#zoomout').attr('src', '/assets/images/widget_map_left.png');
            $('#zoomin').attr('src', '/assets/images/widget_map_right.png');
            $('#GautrainMapView .radio').css('background-position','0px -30px');
            $('#GoogleMapView .radio').css('background-position','0px 0px');
            $("#TrainRoutes").hide();
            $("#mapType").val('Gautrain');
	        GoogleMap.disableDragging();
            var latlng = new GLatLng(15, 0);
            GoogleMap.setCenter(latlng, 2, custommap)
            loadSchematicMapMarkers();
	    }
	}
	
//////////// Geocoding and directions methods below
	
    // Geocoding

    var geo = new GClientGeocoder();
    var lat = [];
    var lng = [];
    var bounds = new GLatLngBounds();
    var Accu = [];
    var iwn=0;
    var poet=[];
    var latitude=[];
    var longitude=[];
    var country=[];
    var status=[];
    status[G_GEO_SUCCESS]            = "Success";
    status[G_GEO_MISSING_ADDRESS]    = "Missing Address";
    status[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address";
    status[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address";
    status[G_GEO_BAD_KEY]            = "Bad Key";
    status[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries";
    status[G_GEO_SERVER_ERROR]       = "Server Error"
    var alertTimerId = 0;

	

	function showRoutes(routeType)
	{
	    var mapType = $("#mapType").attr("value");
        _gaq.push(['_trackEvent', 'Show Routes on ' + mapType, 'Click', routeType]);
	    
        if(routeType ==2)
        {
            if($("#busRoutes").attr("vis") == "false")
            {
                $("#busRoutes").attr("vis","true");
                $('#BusRoutes .checkbox').css('background-position','0px -30px');     //set checkboxes
                getAllRoutes(routeType, mapType, '#ff0000',8)
            }
            else
            {
                $("#busRoutes").attr("vis","false");
                $('#BusRoutes .checkbox').css('background-position','0px 0px');     //reset checkboxes
                removeBusMarkers();
                hideAllRoutes(2, mapType);  //hide routes
            }
        }    
        
        if(routeType ==1)
        {
            if($("#trainRoutes").attr("vis") == "false")
            {
                $("#trainRoutes").attr("vis","true");
                $('#TrainRoutes .checkbox').css('background-position','0px -30px');   //set checkboxes
                getAllRoutes(routeType, mapType,'#0000ff', 9)
            }
            else
            {
                $("#trainRoutes").attr("vis","false");
                $('#TrainRoutes .checkbox').css('background-position','0px 0px');   //reset checkboxes
                
                
                hideAllRoutes(1, mapType); //hide routes
            }
        }
    }

    function getAllRoutes(routeType, mapType, color , polyID)
    {
        var busroutes =        ["Randburg", "Fourways","Rivonia", "Sandton", "Rosebank", "Wendywood", "Rhodesfield", "HIGHVELD TECHNO PARK", "ROOIHUISKRAAL", "WIERDA PARK", "SOUTHDOWNS", "BROOKLYN", "LYNNWOOD", "ARCADIA", "WAVERLEY", "MENLYN", "RANDJESPARK", "NOORDWYK", "SUNNINGHILL", "PARKTOWN", "CBD OUTER", "CBD INNER", "HIGHLANDS NORTH", "MELROSE ARCH", "ILLOVO", "CRAIGHALL"];
        var stationsSLatLng =  ["-15,-153", "28,-82","8,-47", "-9,-82", "-39,-93", "-35,10", "44,49"];
        var stationsGLatLng =  [
                                "-25.891349,28.163518",    //c1 
                                "-25.873743,28.095818",     //c2
                                "-25.849337,28.13221",      //c3
                                "-25.879303,28.222376",     //c4 (5)
                                "-25.781962,28.211174",     //h1 brk
                                "-25.763721,28.293615",     //h2 lyn
                                "-25.73474,28.203069",      //h3 arc
                                "-25.700629,28.254111",     //h4 wv
                                "-25.786290,28.298422",     //h5 mn
        //"-26.186391,28.050374",     //j1 pk
                                "-26.077639,28.135115", //m
                                "-25.964218,28.150063",     //m1 rnd
                                "-25.945626,28.104831",     //m2 ndw
                                "-26.000532,28.072022",     //m3 sng
                                "-25.746559,28.137332",     //p1 out
                                "-25.730498,28.152507",     //p2 inn
                                "-26.146501,28.100818",     //rb1 hln
                                "-26.133398,28.082815",     //rb2 mel
                                "-26.125007,28.060425",     //rb3 ilo
                                "-26.120918,27.989388",     //rb4 chp
                                "-26.196501,28.050425",     //rb5 prk
                                "-26.093255,28.241",        //rf1
                                //"-26.109993,28.070025",    //s1 snd
                                "-26.079155,28.068562",     //s2 wdy
                                "-26.061737,28.069747",    //s3 riv "-26.061679,28.072022"
                                
                                "-26.105062,27.992301",    //s4 rdb 
                                "-26.020532,28.000330"    //s5 fwy
                                //"-26.117452,28.0611402"    //s6 rsb
                                ];
        PageMethods.GetAllRoutes(routeType, mapType, onSuccess=function(data)
            {
                tempRouteObj = eval(data);
                for(var r=0; r<tempRouteObj.length; r++)
                {
                    //if(routeType==2 && mapType=="Google") { thiscolor = colors[r];}
                    //if(routeType==2 && mapType=="Gautrain") { thiscolor = "#4a4538";}
                    //if(routeType==1) { thiscolor = "#3b3934"; }
                    thiscolor = "#"+tempRouteObj[r].rRouteColour;
                    drawPolyLine(tempRouteObj[r].rRouteData.split("~"), thiscolor, tempRouteObj[r].rID, routeType, true, "");
                    if(routeType==2) {labelname = tempRouteObj[r].rRouteName.split(':')[0];}
                    if(routeType==2 && mapType=="Google")//show station label for each bus route
                    {
                        xy = stationsGLatLng[r].split(",",2) ;	// Break previous point into x and y
                        displayStationMarker(xy, "bus", "station", r, tempRouteObj.length, invisibleIconWide, "/assets/images/icons/bus_"+labelname+".png", true)
                    }
                    if(routeType==2 && mapType=="Gautrain")//show station label for each bus route
                    {
                        xy = stationsSLatLng[r].split(",",2) ;	// Break previous point into x and y
                        displayStationMarker(xy, "bus", "station", r, tempRouteObj.length, invisibleIcon, "/assets/images/icons/"+busroutes[r]+"BusRoute.png", true)
                    }

                }
            }, OnStationsFail, OnStationsTimeOut );
    }

    function hideAllRoutes(routeType, mapType)
    {
        if(routeType=="2"){$(".busStationPopup").hide();}
        PageMethods.GetAllRoutes(routeType, mapType, onSuccess=function(data)
            {
                tempRouteObj = eval(data);
                for(var r=0; r<InterchangeMarker.length; r++)
                {
                    if((routeType=="1" && InterchangeMarker[r].getIcon().image == "/assets/images/icons/station_point.png") || (routeType=="2" && InterchangeMarker[r].getIcon().image == "/assets/images/transparentPNG.png"))
                    { 
                    GoogleMap.removeOverlay(InterchangeMarker[r]); 
                    InterchangeMarker[r]=null;
                    }
                }
                for(var r=0; r<tempRouteObj.length; r++)
                {
                try { 
                GoogleMap.removeOverlay(GooLine[tempRouteObj[r].rID]);  
                GooLine[tempRouteObj[r].rID] = null;
                }
                catch (err) {}
                }
            }, OnStationsFail, OnStationsTimeOut );
    }
    
    function removeBusMarkers()
    {
        $(".busStationPopup").hide();
        $('#BusRoutes .checkbox').css('background-position','0px 0px');     //reset checkboxes
        //$('#TrainRoutes .checkbox').css('background-position','0px 0px');   //reset checkboxes

        for(var r=0; r<InterchangeMarker.length; r++)
        {
            if(InterchangeMarker[r])
            {
                if(InterchangeMarker[r].getIcon().image != "/assets/images/icons/station_point.png" 
                && InterchangeMarker[r].getIcon().image != "/assets/images/transparentPNG.png"
                && InterchangeMarker[r].getIcon().image != "/assets/images/PlatformChange.png"
                && InterchangeMarker[r].getIcon().image != "/assets/images/icons/bus.png"
                && InterchangeMarker[r].getIcon().image != "/assets/images/icons/car.png"
                && InterchangeMarker[r].getIcon().image != "/assets/images/icons/train.png"
                && InterchangeMarker[r].getIcon().image != "/assets/images/icons/begin.png"
                && InterchangeMarker[r].getIcon().image != "/assets/images/icons/end.png"
                )
                { 
                GoogleMap.removeOverlay(InterchangeMarker[r]); 
                }
            }
        }
    }
    
    function removeAllMarkers()
    {
        $(".busStationPopup").hide();
        $('#BusRoutes .checkbox').css('background-position','0px 0px');     //reset checkboxes
        $('#TrainRoutes .checkbox').css('background-position','0px 0px');   //reset checkboxes

        for(var r=0; r<InterchangeMarker.length; r++)
        {
            if(InterchangeMarker[r])
            {
                if(InterchangeMarker[r].getIcon().image == "/assets/images/icons/station_point.png" 
                || InterchangeMarker[r].getIcon().image == "/assets/images/transparentPNG.png"
                || InterchangeMarker[r].getIcon().image == "/assets/images/PlatformChange.png"
                || InterchangeMarker[r].getIcon().image == "/assets/images/icons/bus.png"
                || InterchangeMarker[r].getIcon().image == "/assets/images/icons/car.png"
                || InterchangeMarker[r].getIcon().image == "/assets/images/icons/train.png"
                || InterchangeMarker[r].getIcon().image == "/assets/images/icons/begin.png"
                || InterchangeMarker[r].getIcon().image == "/assets/images/icons/end.png"
                )
                { 
                GoogleMap.removeOverlay(InterchangeMarker[r]); 
                }
            }
        }
    }
    
    function removeAllPolyLines()
    {
        for(var r=0; r<GooLine.length; r++)
        {
            try { GoogleMap.removeOverlay(GooLine[r]); GooLine[r]=null; }
            catch (err) {}
        }
        GooLine = [];
    }

    function setScrollerNavigation(id, value)
    {
	    $("#"+id).attr("paneId", value);

    }
    
    function showPopup(index, top, left, text, ptype) 
    {
        if(showTransport)
        {
            var leftPercent=0.00;
            for(var i=0; i<index;i++)
                { leftPercent=leftPercent+parseFloat(distPercent[i]); }
            
            var popupLeft = $("#scroll").width() * (leftPercent/100);
            if(ptype=="leg")
            {
                popupLeft+= (distPercent[index]/200) * ($("#scroll").width());    //divived by 200 because we want half the width of that cell as a percentage
            }
            popupLeft-=$("#popupInfo").width()/2;
            //var popupLeft = $(this).position().left + ($(this).width()/2) - $("#popupInfo").width()/2
            var popupTop = top-40;
            $("#popupInfo")
                .fadeIn(100)
                .css({ top:popupTop, left:popupLeft });
                
            $("#popupInfoContent").html(text);
        }
        if(ptype=="interchange")
            showTransport=false;
        if(ptype=="leg")
            showTransport=true;
            
    }
        
    function hidePopups()
    {
        $("#IntermediateStationPopup").fadeOut();
        $("#IntermediateStationPopDOWN").fadeOut();
        $('#stationPopupContainer').fadeOut();
    }        
            
    function IsNumeric(sText)
    {
        var ValidChars = "0123456789.";
        var IsNumber=true;
        var Char;
        for (i = 0; i < sText.length && IsNumber == true; i++) 
        { 
            Char = sText.charAt(i); 
            if (ValidChars.indexOf(Char) == -1) 
                { IsNumber = false; }
        }
       return IsNumber;
    }
    
        
	function drawPolyLine(route, color, lineID, routeType, showStationLabel, includeBusEnd)
	{
        GooPoly = [];
        var thickness;
        if (routeType==1) {thickness=7} else {thickness=3}  //1:train; 2:bus
        var stations = [];
        if(route.length <=5 ) {stations = ["sandton", "marlboro","rhodesfield", "ortambo"];}
        //if(route.length >5 ) {stations = ["park", "rosebank", "sandton", "marlboro", "midrand", "centurion", "pretoria", "hatfield"];}
        if(route.length >5 ) {stations = ["rosebank", "sandton", "marlboro", "midrand", "centurion", "pretoria", "hatfield"];}
        
        for(var n=0;n<route.length;n++)
        {
            if(route[n]!="") { lastIndex= n;}  // get the index of the last non-null item in the array
        }
        for(var n=0;n<=lastIndex;n++)
        {
            if(route[n]!="")
            {
                if(IsNumeric(route[n].substr(1,2))) //if it's a coordinate, it will start with -26
                {
                    xy = route[n].split(",",2) ;	// Break each point into x and y
                    GooPoly.push(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])));
                    bounds.extend(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])));                    
                    if(routeType==1)
                    {
                    displayStationMarker(xy, "train", "station", n+10, lastIndex+10, stationIcon, "/assets/images/icons/train_"+stations[n]+".png",showStationLabel, includeBusEnd)
                    }
                }
                else if(route[n]!=",undefined" && route[n]!="NaN,NaN" && route[n]!="")
                {   
                    //this should only happen if the array contents are interchange info, and not LatLng co-ords
                    xy = route[n-1].split(",",2) ;	// Break previous point into x and y
                    displayPoint(xy, route[n], n)
                    
                }
            }
        }
        GooLine[lineID]=new GPolyline(GooPoly,color, thickness, 1);
        lineMarker = new GMarker(GooPoly[0], {icon:redicon, draggable: false});
        GoogleMap.addOverlay(GooLine[lineID]);
	}
	
    function displayStationMarker(xy, type, text, index, lastIndex, icon, img, showStationLabel, includeBusEnd)
    {
        var xOffset = 0;
        var yOffset=0;
        var fromAddress = $("#fromAddress").val();
        var toAddress = $("#toAddress").val();

        InterchangeMarker[index] = new GMarker(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])), {icon:icon, draggable: false});
        if(!showStationLabel && type=="train")
        {
            if(index==10)
            {
                if(fromAddress.match(/Airport/gi) || fromAddress.match(/Tambo/gi))
                { iconImage = "begin"; } else {iconImage = "train"; }
            }
            else if(index == lastIndex)
            {
                if(toAddress.match(/Airport/gi) || toAddress.match(/Tambo/gi))
                {
                    iconImage = "end";
                }
                else
                {
                    if(includeBusEnd=="Bus") { iconImage = "bus"; } else {iconImage = "car";}
                }
            }
            InterchangeMarker[index].getIcon().image = "";
            InterchangeMarker[index].getIcon().image = "/assets/images/icons/"+iconImage+".png";
            InterchangeMarker[index].getIcon().shadow = "http://google-maps-icons.googlecode.com/files/shadow.png";
            InterchangeMarker[index].getIcon().iconSize = new GSize(32, 37);
            InterchangeMarker[index].getIcon().iconAnchor = new GPoint(16, 37);
            
            if(index==10 || index == lastIndex)
            {
                GoogleMap.addOverlay(InterchangeMarker[index]);
            }
        }
        else
        {
        GoogleMap.addOverlay(InterchangeMarker[index]);
        $("<div id='"+type+"station"+index+"'></div>")
            .hide()
            .addClass("stationPopup")
            .appendTo("#container");
        }
        if(type=="train" && showStationLabel)
        {
            //if(index >10 && index <13)
            //{
                InterchangeMarker[index].getIcon().iconSize = new GSize(16,16);
                InterchangeMarker[index].getIcon().iconAnchor = new GPoint(8, 8);
                InterchangeMarker[index].getIcon().infoWindowAnchor = new GPoint(8, 16);
                InterchangeMarker[index].getIcon().image = "/assets/images/icons/station_point.png" ;
                InterchangeMarker[index].getIcon().shadow = "" ;
            //}
            GEvent.addListener(InterchangeMarker[index], "mouseover", function(){
	            var markerOffset = GoogleMap.fromLatLngToContainerPixel(this.getLatLng());
	            $("#"+type+"station"+index)
		            .fadeIn()
		            .css({ top:markerOffset.y-51, left:markerOffset.x-20, backgroundImage:"url("+img+")" })
                    //.html(img);
            });
            GEvent.addListener(InterchangeMarker[index], "mouseout", function(){
	            $("#"+type+"station"+index)
		            .fadeOut()
            });
        }
        else if(type=="bus")
        {
            xOffset = 33;
            yOffset=18;
            var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[index].getLatLng());
            $("#"+type+"station"+index)
                .fadeIn()
                    .addClass("busStationPopup")
		            .css({ top:markerOffset.y-eval(yOffset), left:markerOffset.x-eval(xOffset), backgroundImage:"url("+img+")",width:"165px" })
                //.html(text);
		
        //add event listener to the map's 'move' event
		var moveEnd = GEvent.addListener(GoogleMap, "move", function(){
		    for(var i=0; i<InterchangeMarker.length;i++)
		    {
		        if(InterchangeMarker[i])
		        {
			        var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[i].getLatLng());
	                $("#"+type+"station"+i).css({ top:markerOffset.y-eval(yOffset), left:markerOffset.x-eval(xOffset) });
    		    }
		    }
		
		});
        }

        //add event listener to the map's 'move end' event
		var moveEnd = GEvent.addListener(GoogleMap, "moveend", function(){
		    for(var i=0; i<InterchangeMarker.length;i++)
		    {
		        if(InterchangeMarker[i])
		        {
			        var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[i].getLatLng());
	                $("#"+type+"station"+i).css({top:markerOffset.y-eval(yOffset), left:markerOffset.x-eval(xOffset) });
    		    }
		    }
		
		});

    }
    
    function displayPoint(xy, text, index)
    {
        InterchangeMarker[index] = new GMarker(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])), {icon:redicon, draggable: false});
            InterchangeMarker[index].getIcon().image = "";
            InterchangeMarker[index].getIcon().image = "/assets/images/icons/PlatformChange.png";
            InterchangeMarker[index].getIcon().shadow = "http://google-maps-icons.googlecode.com/files/shadow.png";
            InterchangeMarker[index].getIcon().iconSize = new GSize(32, 37);
            InterchangeMarker[index].getIcon().iconAnchor = new GPoint(16, 37);

        GoogleMap.addOverlay(InterchangeMarker[index]);
        $("<div id='interchange"+index+"'></div>")
            .hide()
            .addClass("message")
            .appendTo("#container");

        GEvent.addListener(InterchangeMarker[index], "mouseover", function(){
	        var markerOffset = GoogleMap.fromLatLngToContainerPixel(this.getLatLng());
	        $("#interchange"+index)
		        .fadeIn()
		        .css({ top:markerOffset.y, left:markerOffset.x })
                .html(text);
        });
        GEvent.addListener(InterchangeMarker[index], "mouseout", function(){
	        $("#interchange"+index)
		        .fadeOut()
        });


		var moveEnd = GEvent.addListener(GoogleMap, "moveend", function(){
		    for(var i=0; i<InterchangeMarker.length;i++)
		    {
		        if(InterchangeMarker[i])
		        {
			        var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[i].getLatLng());
	                $("#interchange"+i).css({ top:markerOffset.y, left:markerOffset.x });
    		    }
		    }
		
		});
    }


    function displayUnderConstruction(xy, text, index)
    {
        var xOffset = 0;
        var yOffset=0;
        if(text == "park")
        {
        xOffset = 203;
        yOffset=80;
        }
        xy = xy.split(",",2) ;	// Break previous point into x and y
        InterchangeMarker[index] = new GMarker(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])), {icon:invisibleIcon, draggable: false});
        GoogleMap.addOverlay(InterchangeMarker[index]);
        GEvent.addListener(InterchangeMarker[index], "mouseover", function(){
	        var markerOffset = GoogleMap.fromLatLngToContainerPixel(this.getLatLng());
	        $(".underCon")
		        .fadeIn()
		        .css({ top:markerOffset.y-eval(yOffset), left:markerOffset.x-eval(xOffset) });
        });
        GEvent.addListener(InterchangeMarker[index], "mouseout", function(){
	        $(".underCon").fadeOut()
        });


		var moveEnd = GEvent.addListener(GoogleMap, "moveend", function(){
		    for(var i=0; i<InterchangeMarker.length;i++)
		    {
		        if(InterchangeMarker[i])
		        {
			        var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[i].getLatLng());
	                $(".underCon").css({ top:markerOffset.y-eval(yOffset), left:markerOffset.x-eval(xOffset) });
    		    }
		    }
		
		});


    }

    function displayStationPopup(xy, station, index)
    {
        xy = xy.split(",",2) ;	// Break previous point into x and y
        InterchangeMarker[index] = new GMarker(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])), {icon:invisibleIcon, draggable: false});
        GoogleMap.addOverlay(InterchangeMarker[index]);
        GEvent.addListener(InterchangeMarker[index], "mouseover", function(){
	        var markerOffset = GoogleMap.fromLatLngToContainerPixel(this.getLatLng());
	       /*
	        */
	        $(".stationContentHead").html(station);
	        //set links
	        $("#stationInfo").attr('href',"javascript:LoadStationPopup('"+station+"',1)");
	        $("#transport").attr('href',"javascript:LoadStationPopup('"+station+"',2)");
	        $("#timetable").attr('href',"javascript:LoadStationPopup('"+station+"',3)");
	        $("#attractions").attr('href',"javascript:LoadStationPopup('"+station+"',4)");
	        $("#IntermediateStationPopup")
		        .fadeIn()
		        .css({ top:markerOffset.y-188, left:markerOffset.x-28 });
        });
        GEvent.addListener(InterchangeMarker[index], "mouseout", function(){
	        //$("#IntermediateStationPopup").fadeOut()
        });


		var moveEnd = GEvent.addListener(GoogleMap, "moveend", function(){
		    for(var i=0; i<InterchangeMarker.length;i++)
		    {
		        if(InterchangeMarker[i])
		        {
			        var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[i].getLatLng());
	                $("#IntermediateStationPopup").css({ top:markerOffset.y, left:markerOffset.x });
    		    }
		    }
		
		});
    }

    function displayStationPopDOWN(xy, station, index)
    {
        xy = xy.split(",",2) ;	// Break previous point into x and y
        InterchangeMarker[index] = new GMarker(new GLatLng(parseFloat(xy[0]), parseFloat(xy[1])), {icon:invisibleIcon, draggable: false});
        GoogleMap.addOverlay(InterchangeMarker[index]);
        GEvent.addListener(InterchangeMarker[index], "mouseover", function(){
	        var markerOffset = GoogleMap.fromLatLngToContainerPixel(this.getLatLng());
	       /*
	        */
	        $(".stationContentHead").html(station);
	        //set links
	        $("#stationInfoDOWN").attr('href',"javascript:LoadStationPopup('"+station+"',1)");
	        $("#transportDOWN").attr('href',"javascript:LoadStationPopup('"+station+"',2)");
	        $("#timetableDOWN").attr('href',"javascript:LoadStationPopup('"+station+"',3)");
	        $("#attractionsDOWN").attr('href',"javascript:LoadStationPopup('"+station+"',4)");
	        $("#IntermediateStationPopDOWN")
		        .fadeIn()
		        .css({ top:markerOffset.y-20, left:markerOffset.x-25 });
        });
        GEvent.addListener(InterchangeMarker[index], "mouseout", function(){
	        //$("#IntermediateStationPopup").fadeOut()
        });


		var moveEnd = GEvent.addListener(GoogleMap, "moveend", function(){
		    for(var i=0; i<InterchangeMarker.length;i++)
		    {
		        if(InterchangeMarker[i])
		        {
			        var markerOffset = GoogleMap.fromLatLngToContainerPixel(InterchangeMarker[i].getLatLng());
	                $("#IntermediateStationPopDOWN").css({ top:markerOffset.y, left:markerOffset.x });
    		    }
		    }
		
		});
    }

function LoadStationPopup(station, tab)
{
    _gaq.push(['_trackEvent', 'StationPopup', 'Open', station + ' : tab' + tab]);
    $("#IntermediateStationPopup").fadeOut()
    $("#IntermediateStationPopDOWN").fadeOut()
    //?s="+Math.random()
    $.get("/stationpopups/popup_"+station.replace("_", "")+".htm?20110622~14", function(data) 
    {
        $('#stationPopupContainer').fadeIn();      
        $('#stationPopupContainer').html(data);   
		    if(IsNumeric(tab))
		    {
	             //$(this).attr("tabnumber", tab)
                $("#pane1").fadeOut();
	            $(".item").fadeOut();
	            $("#item" + tab).fadeIn();
	            $("#pane" + tab).fadeIn();
	            try { $('#pane' + tab).jScrollPane({showArrows:true, scrollbarWidth:21, dragMaxHeight:150}); } catch (err) {}
		        $(".tab").removeClass('selected');
                $("#tab" + tab ).addClass('selected');
		        $('#AttractionContainer').fadeOut(); 		
		    }
		    else
		    {
                $("#item1").fadeIn();
                $("#tab1").addClass('selected');
		    }
	
	    $(".tab").click(function()
		    {
            _gaq.push(['_trackEvent', 'StationPopup', 'Change Tab', station + ' : tab' + $(this).attr("tabnumber")]);
	        $("#pane1").fadeOut();
		    $(".item").fadeOut();
		    $("#item" + $(this).attr("tabnumber") ).fadeIn();
		    $("#pane" + $(this).attr("tabnumber") ).fadeIn();
            try {  $('#pane' + $(this).attr("tabnumber")).jScrollPane({showArrows:true, scrollbarWidth:21, dragMaxHeight:150}); } catch (err) {}
		    $(".tab").removeClass('selected');
		    $(this).addClass('selected');
		    $('#AttractionContainer').fadeOut(); 		
		})
		
        $('#stationselect').sexyCombo({
            emptyText: "Change Station",
            autoFill: false,
            skin: "custom", 
            changeCallback : function()
            {
                if($("[name='b__sexyComboHidden']").val()!="Change Station")
                {
                    _gaq.push(['_trackEvent', 'StationPopup', 'Open from drop-down', $("[name='b__sexyComboHidden']").val() + ' : tab' + 1]);
                    LoadStationPopup($("[name='b__sexyComboHidden']").val(),1)
                }
            }

        });
	
    });

}



    function hideDropDown()
    {
    $("#matches").fadeOut();
    $("#transparency").fadeOut();
    $("#matchesContaner").fadeOut();
    }    
    
    function handleErrors()
    {
     if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
       alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
     else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
       alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
     
     else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
       alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
       
     else if (gdir.getStatus().code == G_GEO_BAD_KEY)
       alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

     else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
       alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
      
     else alert("An unknown error occurred.");
    }



      // If the map position is out of range, move it back
      function checkBounds(zoom) {
          var allowedBounds;
          //alert(zoom);
          //GLatLngBounds(new GLatLng(BOTTOM,LEFT), new GLatLng(TOP,RIGHT));
          switch(zoom)
          {
              case 2:
                  allowedBounds = new GLatLngBounds(new GLatLng(-20,-12), new GLatLng(32,13));
                  break;
              case 3:
                  allowedBounds = new GLatLngBounds(new GLatLng(-60,-82), new GLatLng(52,88));
                  break;
              case 4:
                  allowedBounds = new GLatLngBounds(new GLatLng(-20,-12), new GLatLng(32,13));
                  break;
          }
        // Perform the check and return if OK
        if (allowedBounds.contains(GoogleMap.getCenter())) {
          return;
        }
        // It`s not OK, so find the nearest allowed point and move there
        var C = GoogleMap.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        //alert ("Restricting "+Y+" "+X);
        GoogleMap.setCenter(new GLatLng(Y,X));
        //label.hide();
     }

function getAttraction(pageName)
{
    _gaq.push(['_trackEvent', 'KeyAttraction', 'Open', pageName]);

    $.get(pageName, function(data) {
      $('#AttractionContainer').fadeIn();       // optional - just to transition between the list and contents
      $('#AttractionContainer').html(data);     //’data’ holds the contents of 'ajax/test.html'. This is then put into a div with the class ‘.result’ 
    });
}


function GetSynchronousJSONResponse(url, postData) {
    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
        // to be ensure non-cached version of response
    url = url + "?rnd=" + Math.random(); 
    
    xmlhttp.open("POST", url, false);//false means synchronous
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(postData);
    var responseText = xmlhttp.responseText;
    return responseText;
}
