﻿
Type.registerNamespace("SoulSolutions.Demo");
var OnCategories = [];
SoulSolutions.Demo.Map = function(service, mapArgs) {
    /// <summary>
    ///   The VE Map.
    ///   Supports load on demand
    /// </summary>
    /// <param name="service">The webservice to call for the map data.</param>
    /// <param name="mapArgs">The map initalisation data.</param>

    this._service = service;
    this._mapArgs = mapArgs;
    
    this._map = null;
    this._pinID = 0;
    this._zoomlevel = 0;
    this._layer = null;
    
    //popup specific
    this._PopupPrefix = "POPUP";
    this._currentpin = null;
    this._currentindex = 0;   
    
    this.GetPinDataDelegate = null;
    this.PinHoverDelegate = null;
    
    this._init();
}

SoulSolutions.Demo.Map.prototype = {

    _init: function() {
        /// <summary>
        ///   Initialises the Map.
        /// </summary>       
        
        //setup map
        this._map = new VEMap(this._mapArgs.DivID);    
        this._map.LoadMap(this._mapArgs.Center,this._mapArgs.Zoomlevel,this._mapArgs.Style,this._mapArgs.Fixed,this._mapArgs.Mode); 
        this._map.SetScaleBarDistanceUnit(this._mapArgs.Scale);
        
        this._layer = new VEShapeLayer();         
        this._map.AddShapeLayer(this._layer);
        //this._map.AddTileLayer;
        //setup the function to get new data whenever the map changes
        this.GetPinDataDelegate = Function.createDelegate(this, this._GetPinData);
        this._map.AttachEvent("onchangeview", this.GetPinDataDelegate);
        
        //turn off the standard popup and attach our custom handler
        this.PinHoverDelegate = Function.createDelegate(this, this._PinActivate);
        this._map.AttachEvent("onmouseover", this.PinHoverDelegate);
        this._map.AttachEvent("onclick", this.PinHoverDelegate);
        
        //Setup additional storage for shapes
        VEShape.prototype.Bounds = "";  
       // OnCategories.push(1);
      //   OnCategories.push(8);
       //  OnCategories.push(9);
        //get the data for the default view
        //this._GetPinData();
       
    },  

    _GetPinData: function() {  
        /// <summary>
        ///   Get the latest map data from the webservice.
        /// </summary>
            
        //encode the current map bounds
        var points = new Array();
        var zoom;
        
        if (this._map.GetMapStyle() == VEMapStyle.Birdseye) {    
            //set zoomlevel      
            zoom = 19;
            var be = this._map.GetBirdseyeScene();
            var rect = be.GetBoundingRectangle();
            points.push(rect.TopLeftLatLong);
            points.push(rect.BottomRightLatLong);

        }else {
            var view = this._map.GetMapView();
            points.push(view.TopLeftLatLong);
            points.push(view.BottomRightLatLong);
            
            //get zoomlevel
            zoom = this._map.GetZoomLevel();

        }
        var bounds = Utility.createEncodings(points);
        if (this._zoomlevel != zoom) {
            //clear existing pins
            this._layer.DeleteAllShapes();
            this._zoomlevel = zoom;
        }
      if(OnCategories.length > 0)
      {
            var theOnCats;
            for(i = 0; i < OnCategories.length; i++)
            {
                if(i == 0)
                {
                    theOnCats = OnCategories[i];
                }
                else
                {
                    theOnCats += "|" + OnCategories[i]; 
                }
            }
            
            this._service.GetClusteredMapDataByCategoryList(bounds, zoom, theOnCats, Function.createDelegate(this, this._OnMapDataSucceeded), Utility.OnFailed);
        }
        else
        {
            this._layer.DeleteAllShapes();
        }
    },

    _OnMapDataSucceeded: function(results) {
        /// <summary>
        ///   Receive data for map.
        /// </summary>  
        /// <param name="result">The webservice result object - Optomised CSV string</param>  
            
        //decode pins
        var result=results.split(",")
        var locs = Utility.decodeLine(result[0]);
        var newShapes = new Array();
       // alert(locs.length);
       var aCat;
        
        //clear existing pins
        this._layer.DeleteAllShapes();
               
        //add new pins
        var needBump = 0;
        
        for(x = 0; x < locs.length; x++) {
            var loc = locs[x];
            
            var isMulti = false;
            var bounds;
            if(needBump > 0)
            {
                bounds = result[x+1+needBump];
                needBump += 1;
            }
            else
            {
                bounds = result[x+1];
               // alert(result[x+2]);
                needBump += 1;
            }
            
            
            if(result[x+needBump+1] == "multi")
            {
            
           // alert("P");
                isMulti = true;
               // bounds = result[x+2];
                //x+=1;
               // needBump = 2;
            }
            else
            {
               aCat = result[x+needBump+1].substring(6,result[x+needBump+1].length);
            }
            
            var newShape = new VEShape(VEShapeType.Pushpin, loc); 
            newShape.Bounds = bounds;         
            //set custom png pin, IE6 will require a PNG fix.
            if(Sys.Browser.agent==Sys.Browser.InternetExplorer&&Sys.Browser.version==6){
            
                if(isMulti == true)
                {
                        newShape.SetCustomIcon("<div class='myPushpinIE6Multi'></div>");
                    
                }
                else
                {
                        var pinIconHTML = '<div style=\'position:relative;top:-20px;\'><img src=\'images/'+aCat+'.png\'></div>';
                        newShape.SetCustomIcon(pinIconHTML);
                    //newShape.SetCustomIcon("<div class='myPushpinIE6'></div>");
                }
            }else {  
         //   alert(isMulti);
                if(isMulti == true)
                {
                    newShape.SetCustomIcon("<div class='myPushpinMulti'></div>");
                }
                else
                {
                 var pinIconHTML = '<div style=\'position:relative;top:-20px;\'><img src=\'images/'+aCat+'.png\'></div>';
                        newShape.SetCustomIcon(pinIconHTML);
                //newShape.SetCustomIcon("<div class='myPushpin'></div>");
                    }
            }
            
            newShapes.push(newShape);
   
        }       
        this._layer.AddShape(newShapes);           
    },
    
    _PinActivate: function(e) {
        /// <summary>
        ///   Receives any mouse of event from VE
        /// </summary>  
        /// <param name="e">The MapEvent object</param>         
        if (e.elementID)
        {
            var popupShape = this._map.GetShapeByID(e.elementID)
            if (popupShape)
            {
                //set current pin
                this._currentpin = popupShape;
                this._currentindex = 0;
                
                //get the content for the pin.
                this._getAJAXContent();
                this._currentpin.SetDescription("<div id='" + this._PopupPrefix + this._currentpin.GetID() + "'>Loading...</div>");
                this._currentpin.SetTitle("");
            }
        }
    },   
    
    _getAJAXContent: function() {
        /// <summary>
        ///   Request content for popup.
        /// </summary>  
        
        //call the web service
        if(OnCategories.length > 0)
      {
            var theOnCats;
            for(i = 0; i < OnCategories.length; i++)
            {
                if(i == 0)
                {
                    theOnCats = OnCategories[i];
                }
                else
                {
                    theOnCats += "|" + OnCategories[i]; 
                }
            }
            
            this._service.GetPushPinByCategoryList(this._currentpin.Bounds, this._currentindex,theOnCats, Function.createDelegate(this, this._OnContentSucceeded), Utility.OnFailed, this._currentpin.GetID());
        }
        
    }, 
    
    _OnContentSucceeded: function(result, ID) { 
        /// <summary>
        ///   Receive content for popup.
        /// </summary>  
        /// <param name="result">The webservice result object - JSON PinData</param>  
        /// <param name="ID">The popup ID associated with this call</param>  
            
        //verify this is the data for the current popup.
        if (ID==this._currentpin.GetID()) {
            if (this._map.GetMapMode() == VEMapMode.Mode3D) {
                //3D mode fails to be able to retrieve the div we placed earlier so resort to setting the title and description only
                this._currentpin.SetTitle(result.Title);
                this._currentpin.SetDescription(result.Details);
            }else {
                //create the content element
                var el = document.createElement("div");
                
                if (result.TotalRecords > 1) 
                {
                
                    //prev / next functionlaity
                    //el.innerHTML = (this._currentindex + 1) + " of " + result.TotalRecords + " Projects<br />" + result.Title + " - " + result.Details;
                    var countStuff = document.createElement("div");
                    countStuff.innerHTML = (this._currentindex + 1) + " of " + result.TotalRecords + " Projects ";
                    el.appendChild(countStuff);
                    var prevButton = document.createElement("div");
                    prevButton.innerHTML = "Previous";
                    el.appendChild(prevButton);
                    Sys.UI.DomElement.addCssClass(prevButton, "ActionButton");
                    if (this._currentindex > 0) 
                    {  
                        $addHandler(prevButton,"click",Function.createDelegate(this, this._PreviousRecord));      
                    }
                    else 
                    {
                        Sys.UI.DomElement.addCssClass(prevButton, "ButtonDisabled");
                    }
                    var nextButton = document.createElement("div");
                    nextButton.innerHTML = "Next";
                    el.appendChild(nextButton);  
                    Sys.UI.DomElement.addCssClass(nextButton, "ActionButton");
                    if (this._currentindex < (result.TotalRecords-1)) 
                    {  
                        $addHandler(nextButton,"click",Function.createDelegate(this, this._NextRecord));                         
                    }
                    else 
                    {
                        Sys.UI.DomElement.addCssClass(nextButton, "ButtonDisabled");
                    }
                    var br = document.createElement("br");
                    el.appendChild(br);
                    var hr = document.createElement("br");
                    el.appendChild(hr);
                    var detailStuff = document.createElement("div");
                    detailStuff.innerHTML = result.Title + " " + result.Details;
                    el.appendChild(detailStuff);
                }    
                else{
                el.innerHTML = (this._currentindex + 1) + " of " + result.TotalRecords + " Projects<br />" + result.Title + "  " + result.Details;
                }
                //clear loading and attach the content
                $get(this._PopupPrefix + ID).innerHTML = "";
                // $get(this._PopupPrefix + ID).style.width = "600px";
                $get(this._PopupPrefix + ID).appendChild(el);
                
//                if (result.TotalRecords > 1) {
//                    //prev / next functionlaity
//                    var prevButton = document.createElement("div");
//                    prevButton.innerHTML = "Previous";
//                    el.appendChild(prevButton);
//                    Sys.UI.DomElement.addCssClass(prevButton, "ActionButton");
//                    if (this._currentindex > 0) {  
//                        $addHandler(prevButton,"click",Function.createDelegate(this, this._PreviousRecord));      
//                    }else {
//                        Sys.UI.DomElement.addCssClass(prevButton, "ButtonDisabled");
//                    }
//                    var nextButton = document.createElement("div");
//                    nextButton.innerHTML = "Next";
//                    el.appendChild(nextButton);  
//                    Sys.UI.DomElement.addCssClass(nextButton, "ActionButton");
//                    if (this._currentindex < (result.TotalRecords-1)) {  
//                        $addHandler(nextButton,"click",Function.createDelegate(this, this._NextRecord));                         
//                    }else {
//                        Sys.UI.DomElement.addCssClass(nextButton, "ButtonDisabled");
//                    }
//                }              
            }
        }
    },    
    
    _PreviousRecord: function() {
        /// <summary>
        ///   Request the previous record.
        /// </summary>  
        this._currentindex--;
        $get(this._PopupPrefix + this._currentpin.GetID()).innerHTML = "Loading...";
        this._getAJAXContent();
    },
    
    _NextRecord: function() {
        /// <summary>
        ///   Request the next record.
        /// </summary>      
        this._currentindex++;
        $get(this._PopupPrefix + this._currentpin.GetID()).innerHTML = "Loading...";
        this._getAJAXContent();
    },             

    Dispose: function() {
        /// <summary>
        ///   cleans up all objects. Detaches all events.
        /// </summary>
        if (this._map != null) {
            this._map.DetachEvent("onchangeview", this.GetPinDataDelegate);
            this._map.DetachEvent("onmouseover", this.PinHoverDelegate);
            this._map.DetachEvent("onclick", this.PinHoverDelegate);                
            this._map.Dispose();
        }    
        this._service = null;
        this._mapArgs = null;
        
        this._map = null;
        this._pinID = null;
        this._zoomlevel = null;
        this._layer = null;
        
        //popup specific
        this._PopupPrefix = null;
        this._currentpin = null;
        this._currentindex = null;   

        this.GetPinDataDelegate = null;
        this.PinHoverDelegate = null;   
    }    
}

SoulSolutions.Demo.Map.registerClass('SoulSolutions.Demo.Map', null, Sys.IDisposable);

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


