
/* Global variables */
    var map, done=false, refreshNeeded=true;
    var sidebarMarkers = [], sidebarItemCount = 0, sidebarIDs = [], sidebarURLs = [];
    
    function createIRmap(container,defaultView)
    {
        try
        {
            var mapitem = new GMap2(container);
            mapitem.enableDoubleClickZoom();
            mapitem.enableContinuousZoom();
            mapitem.enableScrollWheelZoom();
            mapitem.addMapType(G_PHYSICAL_MAP);
            mapitem.removeMapType(G_SATELLITE_MAP);
            mapitem.removeMapType(G_HYBRID_MAP);
            switch(defaultView)
            {
                case "Map":
                    mapitem.setMapType(G_NORMAL_MAP);
                    break;
                case "Satellite":
                    mapitem.setMapType(G_SATELLITE_MAP);
                    break;
                case "Hybrid":
                    mapitem.setMapType(G_HYBRID_MAP);
                    break;
                case "Terrain":
                    mapitem.setMapType(G_PHYSICAL_MAP);
                    break;
                default:
                    mapitem.setMapType(G_PHYSICAL_MAP);
            }
            var mapControl = new GMapTypeControl();
            mapitem.addControl(mapControl);
            mapControl = new GLargeMapControl();
            mapitem.addControl(mapControl);
            mapControl = new GScaleControl();
            mapitem.addControl(mapControl);
            return mapitem;
        }
        catch(ex)
        {
            raiseError("Error in createIRmap:"+ex.description);
        }
    }
            
/* Generic markers */
    var markers = [];
    var showChalets = false; showLifts = true;
    
    function checkZoom()
    {
        try
        {
            if (refreshNeeded && map.isLoaded())
            {
                refreshNeeded = false;
                var curZoom = map.getZoom();
                var curBounds = map.getBounds();
                getMarkersByBounds(curZoom,curBounds);
                checkVis(curZoom,curBounds);
            }
            setTimeout('checkZoom()',100);
        }
        catch(ex)
        {
            raiseError("Error in checkZoom:"+ex.description);
        }
    }
    
    function checkVis(mapZoom, mapBounds)
    {
        try
        {
            for (var m in markers)
                    markers[m].checkVisibility(mapZoom,mapBounds);
        }
        catch(ex)
        {
            raiseError("Error in checkVis:"+ex.description);
        }
    }

    function toggleMarkerFilter(filtername)
    {
        try
        {
            switch(filtername)
            {
                case 'Lifts':
                    showLifts = !showLifts;
                    break;
                case 'Chalets':
                    showChalets = !showChalets;
                    break;
            }
            refreshNeeded = true;
            checkZoom();
        }
        catch(ex)
        {
            raiseError("Error in toggleMarkerFilter:"+ex.description);
        }
    }
    
    function getMarkersByBounds(mapZoom, mapBounds)
    {
        try
        {
            var sURL = "/Markers.aspx?SW="+mapBounds.getSouthWest().lat()+","+mapBounds.getSouthWest().lng();
            sURL += "&NE="+mapBounds.getNorthEast().lat()+","+mapBounds.getNorthEast().lng();
            sURL += "&zoom="+mapZoom;
            GDownloadUrl(sURL, function (data) { eval(data);checkVis(mapZoom,mapBounds); });
        }
        catch(ex)
        {
            raiseError("Error in getMarkersByBounds:"+ex.description);
        }
    }
    
    function CreateMarker(UID,X,Y,MinZoom,Category,SubCategory,Title,IWURL,IWHTML)
    {
        try
        {
            if (!markers[UID])
                markers[UID] = new IRMarker(UID,X,Y,MinZoom,Category,SubCategory,Title,IWURL,IWHTML);
        }
        catch(ex)
        {
            raiseError("Error in CreateMarker:"+ex.description);
        }
    }
    
    function IRstdMarker()
    {
        try
        {
            var markerIcon = new GIcon();
                markerIcon.shadow = "/i/images/ir-markers/26px-marker-shadow.png";
                markerIcon.iconSize = new GSize(26,26);
                markerIcon.shadowIconSize = new GSize(40,30);
                markerIcon.iconAnchor = new GPoint(13,13);
                markerIcon.infoWindowAnchor = new GPoint(12,2);
            return markerIcon;
        }
        catch(ex)
        {
            raiseError("Error in IRstdMarker:"+ex.description);
        }
    }
    
    /* public interface:
     * checkVisibility(Zoom, Bounds)
     */
    function IRMarker(UID,X,Y,MinZoom,Category,SubCategory,Title,IWURL,IWHTML)
    {
        try
        {
            this.UID = UID;
            this.MinZoom = MinZoom;
            this.Category = Category;
            this.SubCategory = SubCategory;
            var click = (IWURL == '' && IWHTML == '' ? false : true);
            var markerIcon = IRstdMarker();
            switch(Category)
            {
                case 0:
                    markerIcon.image = "/i/images/ir-markers/chalet-marker.png"; 
                    markerIcon.shadow = "/i/images/ir-markers/chalet-marker-shadow.png";
                    markerIcon.iconSize = new GSize(26,34);
                    markerIcon.shadowIconSize = new GSize(43,38);
                    markerIcon.iconAnchor = new GPoint(12,34);
                    markerIcon.infoWindowAnchor = new GPoint(12,2);
                    break;
                case 1:
                    markerIcon = getResortIcon(-1);
                    break;
                case 2: //lifts handled by dynalifts
                    break;
                case 3: //airport
                    markerIcon.image = "/i/images/ir-markers/travel-airport.png";
                    break;
                case 4: //eurostar
                    markerIcon.image = "/i/images/ir-markers/travel-eurostar.png";
                    break;
                case 5: //train
                    markerIcon.image = "/i/images/ir-markers/travel-rail.png"; 
                    break;
                case 6: //tourist info
                    markerIcon.image = "/i/images/ir-markers/resort-tic.png";
                    break;
                case 7: //ski school
                    markerIcon.image = "/i/images/ir-markers/resort-ski-school.png";
                    break;
                case 8: //lift office
                    markerIcon.image = "/i/images/ir-markers/resort-lift-pass-office.png";
                    break;
                case 9: //restaurant
                    markerIcon.image = "/i/images/ir-markers/resort-restaurant.png";
                    break;
                case 10: //bus stop
                    markerIcon.image = "/i/images/ir-markers/resort-bus-stop.png";
                    break;
                case 11: //parking
                    markerIcon.image = "/i/images/ir-markers/resort-parking.png";
                    break;
                default:
                    markerIcon = new GIcon(G_DEFAULT_ICON);
            }
            this.gmarker = new GMarker(new GLatLng(Y,X),opts={title:Title,icon:markerIcon,clickable:click});
            if (IWURL != '')
                GEvent.addListener(this.gmarker,'click',function(){openIWbyURL(markers[UID].gmarker,IWURL);});
            else
                if (IWHTML != '')
                    GEvent.addListener(this.gmarker,'click',function(){openIWbyHTML(markers[UID].gmarker,IWHTML);});
                    
            this.visible = false;
            this.hidden = false;
            this.added = false;
            this.checkVisibility = function (curZoom, curBounds) {
                                            var newvis = (this.MinZoom <= curZoom && curBounds.containsLatLng(this.gmarker.getLatLng()) && !this.hidden);
                                            newvis = newvis && (Category==0?showChalets:true);
                                            if (newvis && !this.visible)
                                                if (this.added)
                                                    this.gmarker.show();
                                                else
                                                {
                                                    map.addOverlay(this.gmarker);
                                                    this.added = true;
                                                }
                                            else
                                                if (!newvis && this.visible)
                                                        this.gmarker.hide();
                                            this.visible = newvis;
                                        }
            this.hide = function () {this.hidden=true; this.gmarker.hide(); this.visible=false;}
        }
        catch(ex)
        {
            raiseError("Error in IRMarker:"+ex.description);
        }   
    }
    
    function openIWbyURL(marker,URL)
    {
        try
        {
            $('li.r-listing').removeClass('r-listing-selected');
            GDownloadUrl(URL, function(data){OpenWindow(marker,data);});
        }
        catch(ex)
        {
            raiseError("Error in openIWbyURL:"+ex.description);
        }
    } 

    var IWlistener;
    function OpenWindow(marker,data,maximised)
    {     
        try
        {   
            var codearray = data.split("<div class='scriptbreaker' />");
            if (codearray.length == 2)
            {        
                var contentarray = codearray[0].split("<div class='headbreaker' />");
                if (contentarray.length == 2)
                {   
                    var navhtml = "<div class='min-iw'>"+contentarray[0]+
                                    "<div class='iw-wizard'><ul>"+
                                    "<li class='iw-details-button'><a href='#' onclick='map.getInfoWindow().maximize(); return false;'>View Details</a></li>"+
                                    "<li class='iw-zoom-button'><a href='#' class='IWZoomIn' onclick='IWZoom($(this));return false;'>Zoom In</a></li>"+
                                    "</ul></div></div>";
                    map.openInfoWindowHtml(marker.getLatLng(),navhtml,{maxTitle:contentarray[0],maxContent:contentarray[1]});
                    if (IWlistener)
                        GEvent.removeListener(IWlistener);
                    IWlistener=GEvent.addListener(map.getInfoWindow(),'maximizeend',function (){setTimeout(codearray[1],100);})
                    if (maximised)
                        setTimeout('map.getInfoWindow().maximize()',250);
                }
                else
                {
                    marker.openInfoWindowHtml(codearray[0]);
                    setTimeout(codearray[1],100);
                }
            }
        }
        catch(ex)
        {
            raiseError("Error in OpenWindow:"+ex.description);
        }
    }
    
    var _lastZoom = -1;
    function IWZoom(btn)
    {
        if (btn.hasClass('IWZoomIn'))
        {
            var curZoom = map.getZoom();
            if (curZoom < 14)
            {
                _lastZoom = curZoom;
                map.setZoom(14);
            }
            else
            {
                if (curZoom < map.getCurrentMapType().getMaximumResolution())
                    map.zoomIn();
            }
            btn.removeClass('IWZoomIn').addClass('IWZoomOut').html('Zoom Out');
        }
        else
        {
            if (_lastZoom > 0)
                map.setZoom(_lastZoom);
            else
                if (map.getZoom() > 1)
                    map.zoomOut();
            btn.removeClass('IWZoomOut').addClass('IWZoomIn').html('Zoom In');
        }
    }
    
/* Suffixes for sidebar item marker images */

    function getSuffix(ID)
    {
        try
        {
            if (ID==-1)
                return "";
            else
            {
                var suffix = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];    
                return suffix[ID]; 
            }            
        }
        catch(ex)
        {
            raiseError("Error in getSuffix:"+ex.description);
        }
    }

/* Lettered icons */

    function getChaletIcon(counterID)
    {
        try
        {
            var markerIcon;
            markerIcon = new GIcon(); 
            if (counterID != -2)
            {
                markerIcon.image = "/i/images/ir-markers/chalet-marker"+getSuffix(counterID)+".png"; 
                markerIcon.shadow = "/i/images/ir-markers/chalet-marker-shadow.png";
                markerIcon.iconSize = new GSize(26,34);
                markerIcon.shadowIconSize = new GSize(43,38);
                markerIcon.iconAnchor = new GPoint(12,34);
                markerIcon.infoWindowAnchor = new GPoint(12,2);
            }
            else
            {
                markerIcon.iconSize = new GSize(1,1);
                markerIcon.shadowIconSize = new GSize(0,0);
                markerIcon.iconAnchor = new GPoint(0,0);
                markerIcon.infoWindowAnchor = new GPoint(0,0);
            }
            return markerIcon;
        }
        catch(ex)
        {
            raiseError("Error in getChaletIcon:"+ex.description);
        }
    }

    function getResortIcon(counterID)
    {
        try
        {
            var markerIcon = IRstdMarker();
            markerIcon.image = "/i/images/ir-markers/resort-marker"+getSuffix(counterID)+".png"; 
            return markerIcon;
        }
        catch(ex)
        {
            raiseError("Error in getResortIcon:"+ex.description);
        }
    }
    
/* Dyna lifts */
    var dynalifts = [];
    var dynalift, dynaliftcount = 0;
    var icoLiftBubble,icoLiftCable,icoLiftChair,icoLiftDrag,icoLiftFunicular;
    
    function createLiftIcons()
    {
        try
        {
            icoLiftBubble = IRstdMarker();
            icoLiftBubble.image = "/i/images/ir-markers/lift-bubble.png"; 
                
            icoLiftCable = IRstdMarker();
            icoLiftCable.image = "/i/images/ir-markers/lift-cable.png"; 
                
            icoLiftChair = IRstdMarker();
            icoLiftChair.image = "/i/images/ir-markers/lift-chair.png"; 
                
            icoLiftDrag = IRstdMarker();
            icoLiftDrag.image = "/i/images/ir-markers/lift-drag.png"; 
                
            icoLiftFunicular = IRstdMarker();
            icoLiftFunicular.image = "/i/images/ir-markers/lift-funicular.png"; 
        }
        catch(ex)
        {
            raiseError("Error in createLiftIcons:"+ex.description);
        }
    }
    createLiftIcons();
    
    function DynamicLift(map,minZoom,markericon,markertitle,polyline)
    {
        try
        {
            if (dynalifts[markertitle])
                return;
                
            //set props
            this.map = map;
            this.route = polyline;
            this.dynaMarker = new GMarker(polyline.getVertex(0),opts={title:markertitle,icon:markericon});
            
            this.routeSteps = [];
            this.currentStep = 0;
            this.direction = 1;
            this.speed = 0.00005;
            this.minZoom = minZoom;
            this.hidden = false;
            this.added = false;
            this.hide = function()
                        {
                            this.route.hide();
                            this.dynaMarker.hide();
                            /*
                            if (this.route.supportsHide())
                                this.route.hide();
                            else
                            {
                                this.map.removeOverlay(this.route);
                                this.added=false;
                            }
                            if (this.dynaMarker.supportsHide())
                                this.dynaMarker.hide();
                            else
                                this.map.removeOverlay(this.dynaMarker);
                                */
                            this.hidden = true;
                        }
            this.show = function()
                        {
                            this.route.show();
                            this.dynaMarker.show();
                            /*
                            if (this.added)
                            {
                                this.route.show();
                                this.dynaMarker.show();
                            }
                            else
                            {
                                this.map.addOverlay(this.route);
                                this.map.addOverlay(this.dynaMarker);
                                this.added = true;
                            }
                            */
                            this.hidden = false;
                        }
            
            //calc steps
            var currentStep = 0;
            for (var vertex = 0; vertex < polyline.getVertexCount() - 1; vertex++)
            {
                var startpoint = polyline.getVertex(vertex);
                var endpoint = polyline.getVertex(vertex+1);
                var sideo = endpoint.y - startpoint.y;
                var sidea = endpoint.x - startpoint.x;
                var diro = (sideo < 0 ? -1 : 1);
                var dira = (sidea < 0 ? -1 : 1);
                var theta = Math.abs(Math.atan(sideo / sidea));
                var length = Math.sqrt(sideo * sideo + sidea * sidea);
                var steplength = 0;
                
                while (steplength < length)
                {
                    sideo = steplength * Math.sin(theta);
                    sidea = steplength * Math.cos(theta);
                    this.routeSteps[currentStep++] = new GLatLng(startpoint.y+(sideo*diro),startpoint.x+(sidea*dira));
                    steplength+=this.speed;
                    if (steplength >= length)
                        this.routeSteps[currentStep] = endpoint;
                }
            }        
            //add overlays
            map.addOverlay(this.route);
            map.addOverlay(this.dynaMarker);
            this.added = true;
            //add to array
            dynalifts[markertitle] = this;
            dynaliftcount++;
        }
        catch(ex)
        {
            raiseError("Error in DynamicLift:"+ex.description);
        }
    }

    function animateDynamicLifts()
    {
        try
        {
            if (dynaliftcount > 0)
            {
                    for (var i in dynalifts)
                        moveMarker(dynalifts[i]);
                    setTimeout('animateDynamicLifts()',500);
            }
            else
                setTimeout('animateDynamicLifts()',1000);
        }
        catch(ex)
        {
            raiseError("Error in animateDynamicLifts:"+ex.description);
        }
    }    

    function moveMarker(dynamiclift)
    {
        try
        {
            if (dynamiclift.map.getZoom() < dynamiclift.minZoom || !showLifts)
            {
                if (!dynamiclift.hidden)
                    dynamiclift.hide();
                if (dynamiclift.currentStep > 0)
                {
                    dynamiclift.currentStep = 0;
                    if (dynamiclift.routeSteps[dynamiclift.currentStep])
                        dynamiclift.dynaMarker.setLatLng(dynamiclift.routeSteps[dynamiclift.currentStep]);
                }
            }
            else
            {
                if (dynamiclift.route.getBounds().intersects(dynamiclift.map.getBounds()))
                {
                    if (dynamiclift.hidden)
                        dynamiclift.show();
                    if (dynamiclift.routeSteps[dynamiclift.currentStep])
                    {
                        dynamiclift.dynaMarker.setLatLng(dynamiclift.routeSteps[dynamiclift.currentStep]);
                        dynamiclift.currentStep += dynamiclift.direction;
                        if (dynamiclift.currentStep >= dynamiclift.routeSteps.length || dynamiclift.currentStep < 0)
                        {
                            //dynamiclift.direction = dynamiclift.direction * -1;
                            //dynamiclift.currentStep += dynamiclift.direction * 2;
                            dynamiclift.currentStep = 0;
                            if (dynamiclift.routeSteps[dynamiclift.currentStep])
                                dynamiclift.dynaMarker.setLatLng(dynamiclift.routeSteps[dynamiclift.currentStep]);
                        }
                    }
                }
            }
        }
        catch(ex)
        {
            raiseError("Error in moveMarker:"+ex.description);
        }
    }
    
/* Sidebar routines */

    function createSidebarItem(itemID, marker, URL)
    {
        try
        {
            var alreadyexists = false;
            for(var id in sidebarMarkers)
                if (id==itemID)
                {
                    alreadyexists=true;
                    break;
                }
            sidebarMarkers[itemID] = marker;
            sidebarURLs[itemID] = URL;
            if (!alreadyexists)
            {
                sidebarIDs[sidebarItemCount++] = itemID;
                GEvent.addListener(sidebarMarkers[itemID],'click',function(){displaySBItem(itemID,false);});
                map.addOverlay(sidebarMarkers[itemID]);
            }
        }
        catch(ex)
        {
            raiseError("Error in createSidebarItem:"+ex.description);
        }
    }

    function centerMapOnSidebar()
    {
        try
        {
            var mapbounds = new GLatLngBounds();
            for(var m in sidebarMarkers)
                mapbounds.extend(sidebarMarkers[m].getLatLng());
            map.setCenter(mapbounds.getCenter());
            var maxzoom = map.getBoundsZoomLevel(mapbounds);
            if (maxzoom > 0)
                maxzoom--;
            if (sidebarItemCount == 1 & maxzoom > 12)
                maxzoom = 12;
            map.setZoom(maxzoom);
        }
        catch(ex)
        {
            raiseError("Error in centerMapOnSidebar:"+ex.description);
        }
    }

    var _lastZ = 1;
    function displaySBItem(itemID, maximised)
    {
        try
        {
            if (done)
            {
                //clear map
                map.closeInfoWindow();
                try
                {
                    if (SLenqOpen==true)
                    {
                        $('#enquiry-panel').animate({
    	    	            marginLeft: (SLenqOpen==true?"-2400px":"2400px")
                            }, 'slow' );
                        SLenqOpen = !SLenqOpen;
                    }
                }
                catch(ex) {}
                
                map.removeOverlay(sidebarMarkers[itemID]);
                map.addOverlay(sidebarMarkers[itemID]);
                gotoSidebarItem(itemID);
                if (sidebarURLs[itemID] != "")
                    GDownloadUrl(sidebarURLs[itemID], function (data) { OpenWindow(sidebarMarkers[itemID],data,maximised); });
                if ($('#listing-'+itemID).length>0)
                {
                    $('li.accom-listing').removeClass('accom-listing-selected');
                    $('#listing-'+itemID).addClass('accom-listing-selected');
                    
                    var targetOffset = $('#listing-'+itemID).offset().top - 150;
                    var currentOffset = $('#sb-resizer').scrollTop();
                    $('#sb-resizer').animate({scrollTop: targetOffset+currentOffset}, 500);
                }
                if ($('#txtWeekNo-'+itemID).length>0)
                    addRecentlyViewed(itemID+'W'+$('#txtWeekNo-'+itemID).val());
                else
                    addRecentlyViewed(itemID);
            }
        }
        catch(ex)
        {
            raiseError("Error in displaySBItem:"+ex.description);
        }
    }

    function gotoSidebarItem(itemID)
    {
        try
        {
            if (done)
            {
                map.panTo(sidebarMarkers[itemID].getLatLng());
            }
        }
        catch(ex)
        {
            raiseError("Error in gotoSidebarItem:"+ex.description);
        }
    }

    function clearSidebarItems()
    {    
        try
        {    
            map.closeInfoWindow();
            for(var m in sidebarMarkers)
            {
                GEvent.clearInstanceListeners(sidebarMarkers[m]);
                map.removeOverlay(sidebarMarkers[m]);
            }
            sidebarMarkers = [];
            sidebarIDs = [];
            sidebarURLs = [];
            sidebarItemCount = 0;
        }
        catch(ex)
        {
            raiseError("Error in clearSidebarItems:"+ex.description);
        }
    }
