$(function(){
    var isAnimating = false;
    var mapViewer = null;
    var markerGroups = [];
    var prevMarkerGroup = null;
    var currentMarkerGroup = null;
    var currentMarkerIdx = -1;
    var currentCatId = 0;
    var slideSpeed = 1000;
    var sliderOptions = {
            vertical: true,
            scroll: 6,
            initCallback: maplistcarousel_initCallback
        }
    var sliderContainerHeight = 195;
    
    function maplistcarousel_initCallback(carousel)
    {
        $("ul.subMenu li").bind('focus', function(){
            var idx = $("ul.subMenu li").index(this);
            carousel.scroll($.jcarousel.intval(idx + 1));
            return false;
        });
    };
    
     /*** Clears map and pan to world view ***/
    $("#placeCat_world > a").click(function(){
        if(!isAnimating)
        {
            isAnimating = true;
            $(this).addClass("loading");
            
            if(!mapViewer)
            {
                mapViewer = $.HeliumGMapViewerGetMap("map");
            }
            
            mapViewer.clearMap();
            mapViewer.resetMap();
            
            $("div.subMenuContainer:visible").slideUp(slideSpeed);
            $("ul.catMenu li a.selected").removeClass("selected");
            
            prevMarkerGroup = currentMarkerGroup;
            currentMarkerGroup = $(this).parent("li").attr("id");
            currentMarkerIdx = 0;
            currentCatId = 0
            
            $(this).removeClass("loading");
            $(this).addClass("selected");
            isAnimating = false;
        }
    });
    
    /*** Clears map and pan to Adelaide view ***/
    $("#placeCat_adel > a").click(function(){
        if(!isAnimating)
        {
            isAnimating = true;
            $(this).addClass("loading");
            
            if(!mapViewer)
            {
                mapViewer = $.HeliumGMapViewerGetMap("map");
            }
            
            mapViewer.clearMap();
            mapViewer.panTo(-34.9294304855664525, 138.60162734985351, 14);
            
            $("div.subMenuContainer:visible").slideUp(slideSpeed);
            $("ul.catMenu li a.selected").removeClass("selected");
            
            prevMarkerGroup = currentMarkerGroup;
            currentMarkerGroup = $(this).parent("li").attr("id");
            currentMarkerIdx = 0;
            currentCatId = 0
            
            $(this).removeClass("loading");
            $(this).addClass("selected");
            isAnimating = false;
        }
    });
    
    /*** Expands the selected category, clears map and loads all related placemarks ***/
    $("ul.catMenu li:gt(1) > a").click(function(){
        
        if(!isAnimating)
        {
            isAnimating = true;
            
            $(this).addClass("loading");
            
            if(!mapViewer)
            {
                mapViewer = $.HeliumGMapViewerGetMap("map");
            }
            
            if(currentMarkerGroup)
            {
                $("#"+currentMarkerGroup + " a").removeClass("selected");
            }   
            
            prevMarkerGroup = currentMarkerGroup;
            currentMarkerGroup = $(this).parent("li").attr("id");
            currentCatId = currentMarkerGroup.replace(/^[^_]+_/gi, "");
           
            mapViewer.clearMap();
            if(markerGroups[currentMarkerGroup])
            {
                //Grab placemarks from existing array
                mapViewer.loadPlacemarkArray(markerGroups[currentMarkerGroup]);
                   
                showLocations($(this).parent("li"), function(){
                    $("#"+currentMarkerGroup + " > a").removeClass("loading");
                    $("#"+currentMarkerGroup + "> a").addClass("selected");
                    isAnimating = false;
                });
            }
            else
            {
                //Query for placemarks via ajax
                $.get(
                    "MapRequest.aspx", 
                    {"mode":"getPlacesByCat","catId":currentCatId}, 
                    function (mapXmlDoc){
                        if(mapXmlDoc)
                        {
                            mapViewer.loadPlacemarks(mapXmlDoc);
                            markerGroups[currentMarkerGroup] = mapViewer.getPlacemarkArray();

                            loadLocations($("#"+currentMarkerGroup), function (){
                                $("#"+currentMarkerGroup + " > a").removeClass("loading");
                                $("#"+currentMarkerGroup + "> a").addClass("selected");
                                isAnimating = false;
                            });
                        }
                    },
                    "xml");
            }
        }
    });
    
    /*** Shows placemarks for the selected category. ***/
    function showLocations(container, callback)
    {
        if(prevMarkerGroup && prevMarkerGroup == currentMarkerGroup && container.find("div.subMenuContainer").height() != 0)
        {
            //slide up
            container.find("div.subMenuContainer").animate({height:0}, slideSpeed, null, function(){
                container.find("a:first").removeClass("selected");
                mapViewer.clearMap();
                callback();
            });
        }
        else
        {
            if(prevMarkerGroup && $("#"+prevMarkerGroup + " > div.subMenuContainer").height() != 0)
            {
                //slide previous up
                $("#"+prevMarkerGroup + " > div.subMenuContainer").animate({height:0}, slideSpeed, null, function(){
                    $(this).parent().find("a:first").removeClass("selected")
                    //slide current down
                    container.children("div.subMenuContainer").animate({height:sliderContainerHeight}, slideSpeed, null, function(){
                        callback();
                    });
                });
                
            }
            else
            {
                //slide current down
                container.children("div.subMenuContainer").animate({height:sliderContainerHeight}, slideSpeed, null, function(){
                    callback();
                });
            }
        }
    }
    
    /*** Builds the markup for placemarks of the selected category. ***/
    function loadLocations(container, callback)
    {
        var subMenuConatiner = $("<div class='subMenuContainer'></div>");
        var subMenu = $("<ul class='subMenu jcarousel jcarousel-skin-discadel'></ul>");
        var subMenuItem = null;
        var shortTitle = "";
        var markerArray = mapViewer.getPlacemarkArray();
        
        for(var i=0; i<markerArray.length; i++)
        {
            shortTitle = markerArray[i].Title;
            if(shortTitle.length >= 27)
            {
                shortTitle = shortTitle.substring(0,27) + "...";
            }
            subMenuItem = $("<li id='subItem_"+currentCatId+"_"+i+"'><a href='#' title='"+markerArray[i].Title+"'>"+shortTitle+"</a></li>");
            subMenu.append(subMenuItem);
            
            subMenuItem.children("a").click(function(){
                selectSubMenuItem(subMenu, this);
            });
            
            GEvent.addListener(markerArray[i], "heliumGMarkerSelected", function() {
                if(currentMarkerIdx != this.Index)
                {
                    selectSubMenuItem(subMenu, $("li:eq("+this.Index+")", subMenu).find("a"));
                    $("li:eq("+this.Index+")", subMenu).triggerHandler("focus");
                }
            });
        }
        
        subMenuConatiner.append(subMenu);
        container.append(subMenuConatiner);
        
        subMenuConatiner.height(0);
        subMenu.jcarousel(sliderOptions);
        
        mapViewer.setZoom(14);
        showLocations(container, callback);
    }
    
    /*** Selects the placemark in the menu and on the map. ***/
    function selectSubMenuItem(container, item)
    {
        var idx = $(item).parent("li").attr("id").replace(/^[a-z]+_[0-9]+_/gi, "");
        
        container.find("li > a.selected").removeClass("selected");
        $(item).addClass("selected");
        currentMarkerIdx = idx;
        mapViewer.selectPlacemark(idx);
    }
    
});