// MAP
 
jQuery(document).ready(
    function() {
    	
        vartti_map.init();
        vartti_map.getMap();
    }
);
    
var vartti_map = {

    map: null,
    defaultCenter: null, // Default center point of the map
    defaultZoom: null, // Default zoom level of the map
    topLeft: null, // Coordinates of the top left corner of the map
    bottomRight: null, // Coordinates of the bottom right corner of the map
    articleDataURL: null, // URL to the endpoint for getting article data via Ajax
    newsArticlesPageNumber: null,
    userArticlesPageNumber: null,
    articlePageURL: null,
    articleId: null, // Used when only one article is shown on the map
    shapes: [],
    pageType: null, // 'etusivu', 'artikkeli', 'nyttekeilla', 'haku' or 'uusijuttu' 
	
	//Search options
	searchType: null, //vartti, web, channel, category, mostread
	channel: null, //channel
	category: null, //category
	searchString: null, //LLDS free text search 
	searchPageNumber: null, //search page number
	userNewsFilter: null,

    init: function() {
        this.setMapConfigValues();
        this.setArticleConfigValues();
    },

    // Set the configured initial values for the map
    setMapConfigValues: function() {
        this.defaultCenter = new VELatLong(this.getValueForId("defaultLat"),
                                           this.getValueForId("defaultLong"));
        this.defaultZoom = this.getValueForId("defaultZoom");
    },
    
    // Set the article specific configuration
    setArticleConfigValues: function() {
        this.articleDataURL = this.getValueForId("articleDataURL");
                
        this.topLeft = new VELatLong(this.getValueForId("maxLatitude"),
                                           this.getValueForId("minLongitude"));
    	this.bottomRight = new VELatLong(this.getValueForId("minLatitude"),
                                           this.getValueForId("maxLongitude"));
                                           
        this.newsArticlesPageNumber = this.getValueForId("newsArticlesPageNumber");
        this.userArticlesPageNumber = this.getValueForId("userArticlesPageNumber");
        this.articleId = this.getValueForId("articleId");
        this.articlePageURL = this.getArticlePageURL();
        this.pageType = this.getValueForId("pageType");// 'etusivu', 'artikkeli', 'haku' or 'uusijuttu'
        this.searchType = this.getValueForId("searchType");
        this.channel = this.getValueForId("channel");
        this.category = this.getValueForId("category");
        this.searchString = this.getValueForId("searchString");
        this.searchPageNumber = this.getValueForId("searchPageNumber");
        this.userNewsFilter = this.getValueForId("userNewsFilter");
    },
    isShowableInInit: function() { //Custom method
    	if (vartti_map.pageType =='artikkeli' || vartti_map.pageType =='nyttekeilla') {
    		return false;	
    	} else {
    		return true;
    	}
    },
    // Puts the map with articles on the page.
    getMap: function() {
        
        if (!vartti_map.map) {
        	if (vartti_map.isShowableInInit()) {
        		jQuery(".newMapTopWrapper").show();	
        		jQuery("#varttiMap").show();
        		vartti_map.initMap();
        	}
        }
        
        this.addArticlesOnMap();
        
        //this.updateMapInfo();
    },
    
    initMap: function() {
	    vartti_map.map = new VEMap('varttiMap');
	    vartti_map.map.SetDashboardSize(VEDashboardSize.Tiny);
	    
	    vartti_map.map.LoadMap(vartti_map.defaultCenter, // Center point
	                           vartti_map.defaultZoom, // Zoom level
	                           VEMapStyle.Road); // Map style
	   
       
	    // Use kilometers instead of miles
	    vartti_map.map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
	    
	    vartti_map.map.AttachEvent("onmousewheel", vartti_map.eventMouseWheel);
	    //vartti_map.map.AttachEvent("onendpan", vartti_map.updateMapInfo);
	    //vartti_map.map.AttachEvent("onendzoom", vartti_map.updateMapInfo);
    },
    
    // Fetches the articles' data from the server by Ajax and places the articles
    // on the map.
    addArticlesOnMap: function () {
        if (this.pageType) { // Get the information for a single article
            jQuery.getJSON(
                this.articleDataURL, // URL of the server-side resource
                {pageType: this.pageType,
                articleId: this.articleId,
                searchType: this.searchType, 
		        channel: this.channel,
		        category: this.category, 
		        searchString: this.searchString, 
		        searchPageNumber: this.searchPageNumber,
                newsPgNo: this.newsArticlesPageNumber,
        		userPgNo: this.userArticlesPageNumber,
        		userNewsFilter: this.userNewsFilter},
                
                function(data) { // Callback function
				    if (data.articles/* && data.articles.length>0*/) {
				    	
				    	articlesWithinBounds = 0;
				    	
				    	if (data.articles.length>0) {
        					var articleLayer = null;
							
							if (!vartti_map.isShowableInInit()) { //Show Map only if not
					        	var showMap = false;
	        					jQuery.each(data.articles, function(index, article) {
	        						if (vartti_map.isWithinBounds(article.lat, article.lon)) {
		        						showMap = true;	
	        						}
	        					}); 
								if (!showMap) {
									return;
								}
							
				        		jQuery("#varttiMapHeader").show();	
				        		jQuery("#varttiMap").show();
				        		vartti_map.initMap();
				        		articleLayer = vartti_map.getArticleLayer(data.articles);
				        	} else {
				        		articleLayer = vartti_map.getArticleLayer(data.articles);
				        	}
				        	
							if (articleLayer.GetShapeCount()>0) {
								vartti_map.map.AddShapeLayer(articleLayer);
							}
							articlesWithinBounds = articleLayer.GetShapeCount(); 
						}
						
						if (articlesWithinBounds == 1) {
							currZoomLevel = data.articles[0].zoom;
							currZoomLevel = currZoomLevel+'';
							if (currZoomLevel && currZoomLevel != "") {
								vartti_map.adjustLocationAndZoomLevel(currZoomLevel);
							} else {
								vartti_map.adjustLocationAndZoomLevel(vartti_map.defaultZoom);
							}
						}else if (articlesWithinBounds > 1) {
							vartti_map.adjustLocationAndZoomLevel(null);
						} else {
							vartti_map.adjustLocationAndZoomLevel(vartti_map.defaultZoom);
						}
					}
                }
            );
        }
    }, 
    isWithinBounds: function (lat,long) {
    		return (vartti_map.topLeft.Latitude>lat) && (vartti_map.bottomRight.Latitude<lat) && (vartti_map.topLeft.Longitude < long) && (vartti_map.bottomRight.Longitude > long);
    },
    getArticleLayer: function(articles) {
        var articleLayer = new VEShapeLayer();
        
        jQuery.each(articles, function(index, article) {
            
            if (article.lat && article.lat !== "" && article.lon && article.lon !== "" && vartti_map.isWithinBounds(article.lat, article.lon)) {
	        
	            var articleLocation = new VELatLong(article.lat, article.lon);
	            
	            var articlePin = new VEShape(VEShapeType.Pushpin, articleLocation);
	            
	            //articlePin.SetTitle(vartti_map.getInfoBoxHeader(article));
	            articlePin.SetDescription(vartti_map.getArticleContents(article));
	            
	            articlePin.SetCustomIcon(vartti_map.getIconFor(article.iconurl));
	
	            articleLayer.AddShape(articlePin);
	            vartti_map.shapes[article.id] = articlePin;
            }
        });

        return articleLayer;
    },
            
    // Sets the center point and zoom level so that all articles fit on the map.
    adjustLocationAndZoomLevel: function(zoomlevel) {
        var shapeRectangles = [];
        for (var i = 1; i < vartti_map.map.GetShapeLayerCount(); i++) {
            shapeRectangles.push(vartti_map.map.GetShapeLayerByIndex(i).GetBoundingRectangle());
        }
        
        vartti_map.map.SetMapView(shapeRectangles);
        if (zoomlevel) {
        	vartti_map.map.SetZoomLevel(zoomlevel);
        }
    },

    // Returns the image URL for the given category.
    getIconFor: function(imageUrl) {
        return "<img src='"+imageUrl+"'/>";
    },
    
    // Returns the base URL for the article page
    getArticlePageURL: function() {
        return vartti_url_utils.getContext() + this.getValueForId("articlePageURL");
    },
    
    getLinkForArticle: function(articleId, text) {
        return vartti_url_utils.getLinkFor(this.articlePageURL + articleId, text);
    },
    getArticleContents: function(article) {
    
    	output = "<div class='varttiInfoBoxHeader'><span style='margin-right:5px;'><strong>"+article.categoryname+"</strong></span>";    	
    	output+="<span class='date'>"+article.publishdate+"</span></div>"; 	
    	output+="<div class='varttiInfoBoxContent' onclick=\"window.location.href='"+article.articlelink+"'\">";
    		
    	if (article.imageurl.length>0) {
    		output+="<img src='"+article.imageurl+"'/>";
    	}
    	
    	output+="<h3 class='title'>"+article.title+"</h3>"; 
    	output+=article.caption + "&nbsp;";
        output+="<a href='"+article.articlelink+"'>Lue lis&auml;&auml;</a></div>";
        return output;
    },
    
    getInfoBoxHeader: function(article) {
        return "<div class='infoBoxCategory'>" + article.category + "</div> <br />" +
               "<div class='infoBoxTime'>" + article.publishdate + "</div> <br />" +
               vartti_map.getLinkForArticle(article.id, article.title);
    },
    
    // Can be used for debugging purposes. Updates information about map to
    // "varttiMapInfo" div.
    updateMapInfo: function() {
       var VELatLongRectangle = vartti_map.map.GetMapView();
       topLeft = VELatLongRectangle.TopLeftLatLong;
       bottomRight = VELatLongRectangle.BottomRightLatLong;
       
       var topLeftStr = topLeft.Longitude + ', ' + topLeft.Latitude;
       zoomLevel = vartti_map.map.GetZoomLevel();
       jQuery("#varttiMapInfo").html("<div class='mapCenter'>Map center: " + vartti_map.map.GetCenter() + "</div>")
                               .append("<div class='mapTopLeft'>Top left: " + topLeft + "</div>")
                               .append("<div class='mapBottomRight'>2Bottom right: " + bottomRight + "</div>")
                               .append("<div class='mapZoomLevel'>Zoom Level: " + zoomLevel + "</div>");
    },
    
    // Return true to disable the default behavior. Return false to enable the default
    // behavior. By default mouse wheel zooms the map.
    eventMouseWheel: function() {
        return true;
    },
    
    // Returns the value attribute of an element with the given id.
    getValueForId: function(id) {
        return jQuery("#" + id).attr("value");
    },
    
    // 
    activateInfoBoxForId: function(id) {
        vartti_map.map.ShowInfoBox(vartti_map.shapes[id]);
    },
    
    // Hides a visible info box. There can be only one visible info box at a time, so
    // there's no need to give an id.
    deactivateInfoBox: function() {
        vartti_map.map.HideInfoBox();
    }
}

var vartti_url_utils = {

    // Returns the base URL for the page.
    getContext: function() {
        return location.protocol + // e.g. http:
               "//" +
               location.host; // e.g. www.vartti.fi
    },
    
    getLinkFor: function(href, text) {
        return "<a href='" + href + "'>" + text + "</a>";
    }
}
