/**
 * Name:         PGE.Map Object
 * Description: Javascript Object handling the creation of the pge advanced Overlay Google Map.
 * Dependencies: JQuery, JQuery,JSON
 *                     Create a div to serve as placeholder for your map. e.g.: <div id="map"></div>
 *                     Google map include file e.g.: <script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='+PGE.googlekey + '"><\/script>
 *
 * @ Array - array of object
 * @ Integer - Id of the div container for the map
 * @ Integer - Google map zoom level
 * @ Array - Google map center coordinates (lat,long)
 * @ Legend html (optional)
  **/
 
if (typeof PGE=="undefined"||!PGE){var PGE={};}

PGE.Map=function(obj,mapid,zoom,center,legend){
	this.init(obj,mapid,zoom,center,legend)
};

PGE.Map.prototype={
	init: function(obj,mapid,zoom,center,legend) {

		this.obj    = obj;
		this.mapid  = mapid;
		this.zoom   = zoom;
		this.center = center;
		if ( legend ) {	this.legend = legend; }
		this.marker_path = '/includes/images/map';
		this.json_data;
		this.json_path = '/includes/json';
		this.modalID = this.mapid + '_modal';
		this.selectedMarker = -1;
		this.gSmallMarkers = [];
		this.gBigMarkers = [];
		this.bounds = new GLatLngBounds();

		if(!mapid||!document.getElementById(mapid)){return false}
		if(typeof obj!=="object"){return false}

		/***** SMALL MARKERS *****/
		this.pgeSmallIcon = new GIcon(G_DEFAULT_ICON);
		this.pgeSmallIcon.iconSize = new GSize(51, 51);
		this.pgeSmallIcon.shadow = this.marker_path + "/shadow.png";
		this.pgeSmallIcon.shadowSize = new GSize(73.0, 48.0);
		this.pgeSmallIcon.imageMap = [15,17, 15,79, 79,79, 79,17];
	    this.pgeSmallIcon.iconAnchor = new GPoint(0, 51);//new GPoint(38, 35);
	    this.pgeSmallIcon.infoWindowAnchor = new GPoint(30,20);

		/***** BIG MARKERS *****/
		this.pgeBigIcon = new GIcon(G_DEFAULT_ICON);
		this.pgeBigIcon.iconSize = new GSize(79, 79);
		this.pgeBigIcon.shadow = this.marker_path + "/shadow.png";
		this.pgeBigIcon.shadowSize = new GSize(73.0, 48.0);
		this.pgeBigIcon.imageMap = [15,17, 15,79, 79,79, 79,17];
	    this.pgeBigIcon.iconAnchor = new GPoint(0, 83);//new GPoint(37, 65);
	    this.pgeBigIcon.infoWindowAnchor = new GPoint(30,20);

		// Create Google map and set its features
		// @ map id
		// @ map type
		// @ lat
		// @ long
		// @ zoom
		// @ array containing markers lat long
		this.setGoogleMap(	this.mapid,
							[G_NORMAL_MAP],
							this.center[0],
							this.center[1],
							this.zoom,
							this.obj,
							true );

		// Create Panel inside map
		this.createMapPanel();

	},

	setGoogleMap: function(mapid,mapType,lat,long,zoom,markers,bigMarkers){
		// Create google map object
		var map = new GMap2(document.getElementById(mapid),{mapTypes:mapType});

		// Manually center the map if the json file contained the array
		map.setCenter(new GLatLng(lat,long),zoom);

		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());

		// Loop through all areas array elements and create their markers
		for (var i=0; i<markers.length; i++){
			var point = new GLatLng(markers[i].lat,markers[i].long);

			this.bounds.extend(point);

			// this will create both marker sizes
			this.createMarker(point,i,markers,map,bigMarkers);
		}

		return map;
	},

	createMapPanel: function(){
		// PANEL
		var mapPanel = document.createElement('div');
		mapPanel.className = 'map_panel';

		// PANEL HEADER
		var mapPanelHeader = document.createElement('div');
		mapPanelHeader.className = 'head';
		$(mapPanel).append(mapPanelHeader);

		// PANEL HEADER H2
		var mapPanelHeaderH2 = document.createElement('h2');
		h2Txt = document.createTextNode("Recreational Areas");
		$(mapPanelHeaderH2).append(h2Txt);
		$(mapPanelHeader).append(mapPanelHeaderH2);

		// PANEL HEADER HIDE
		var mapPanelHeaderHide = document.createElement('a');
		mapPanelHeaderHide.setAttribute('href','javascript:void(0)');
		hideTxt = document.createTextNode("Hide <<");
		$(mapPanelHeaderHide).append(hideTxt);
		$(mapPanelHeader).append(mapPanelHeaderHide);
		
		// PANEL BODY
		var mapPanelBody = document.createElement('div');
		mapPanelBody.className = 'body';
		$(mapPanel).append(mapPanelBody);

		// PANEL BODY LIST
		var self = this;
		var ul = document.createElement('ul');

		$.each(self.obj, function (i,e){
			var li = document.createElement('li');
			var a  = document.createElement('a');
			a.setAttribute('href','javascript:void(0)');

		    $(a).mouseover(function(){
				self.gSmallMarkers[i].hide();

				self.gBigMarkers[i].show();
				$(this).parent("li").css("background-color","green");
		    }).mouseout(function(){
				self.gSmallMarkers[i].show();

				self.gBigMarkers[i].hide();
				$(this).parent("li").css("background-color","transparent");
		    }).click(function(){
				var html = self.getBubbleHtml(self.obj[i],i);
				self.gSmallMarkers[i].openInfoWindowHtml(html);
			});

			var liTxt = document.createTextNode(self.obj[i].label);
			var x = i + 1;
			var num = "<span class='lbl'>" + x + "</span>  ";
			$(a).append(num);
			$(a).append(liTxt);
			$(li).append(a);
			$(ul).append(li);
		});

		$(mapPanelBody).append(ul);

		$("#"+this.mapid).prepend(mapPanel);

		// HIDE / SHOW EFFECT
		$(mapPanelHeaderHide).click(function() {
			var txt = ( $(this).text().indexOf('<') != -1 ) ? 'Show >>' : 'Hide <<';
			$(this).text(txt);
			//$(mapPanelBody).animate({opacity: 'toggle'}, 'slow');
			if ( $(this).text().indexOf('<') != -1 ) {
        $(mapPanelBody).fadeIn('slow', function(){
          $("#map .map_panel .body").removeAttr("style");
        });
			}
			else {
        $(mapPanelBody).fadeOut('slow');
			}
		});

	},

	createMarker: function(point,index,markers,map,bigMarkers){
		var self = this;

		// Create a lettered icon for this point using our icon class
		var pgeSmallIcon = new GIcon(this.pgeSmallIcon);

		// Marker representing current position
		if ( markers[index].icon ){
			pgeSmallIcon.image = this.marker_path + "/" + markers[index].icon + "_sm.png";
		}
		else {
			pgeSmallIcon.image = this.marker_path + "/marker" + (index+1) + "_sm.png";
		}

		// Set up our GMarkerOptions object
		smallMarkerOptions = { icon:pgeSmallIcon };

		var smallMarker = new GMarker(point, smallMarkerOptions);

		smallMarker.pgeObject = this;

		var html = this.getBubbleHtml(markers[index],index);

		this.gSmallMarkers.push(smallMarker);

		GEvent.addListener(smallMarker, "click", function() {
			smallMarker.openInfoWindowHtml(html);
		});

		map.addOverlay(smallMarker);
  
		if ( bigMarkers ) {
			var pgeBigIcon   = new GIcon(this.pgeBigIcon);

			if ( markers[index].icon ){
				pgeBigIcon.image = this.marker_path + "/" + markers[index].icon + "_lg.png";
			}
			else {
				pgeBigIcon.image   = this.marker_path + "/marker" + (index+1) + "_lg.png";
			}

			bigMarkerOptions   = { icon:pgeBigIcon };
			var bigMarker   = new GMarker(point, bigMarkerOptions);
			bigMarker.pgeObject   = this;
			this.gBigMarkers.push(bigMarker);

			GEvent.addListener(bigMarker, "click", function() {
				bigMarker.openInfoWindowHtml(html);
			});
			GEvent.addListener(smallMarker, "mouseover", function() {
				self.swapMarkers(index);
			});
			GEvent.addListener(smallMarker, "mouseout", function() {
				self.swapMarkers(index);
			});
			GEvent.addListener(bigMarker, "mouseover", function() {
				self.swapMarkers(index);
			});
			GEvent.addListener(bigMarker, "mouseout", function() {
				self.swapMarkers(index);
			});

			map.addOverlay(bigMarker);
			this.gBigMarkers[index].hide();
		}
	},

	swapMarkers: function(index){
		// Make sure there is only one poped marker at a time
		if ( this.selectedMarker != -1 ){
			this.gBigMarkers[this.selectedMarker].hide();
			this.gSmallMarkers[this.selectedMarker].show();
		}

		// Swap current selection
		this.gSmallMarkers[index].hide();
		this.gBigMarkers[index].show();
		
		this.selectedMarker = index;
	},

	getBubbleHtml: function(marker,index){
		var html = '';
		html += '<div style="white-space:wrap; width: 300px;">';
		html += '<span class="bb_lbl">' + marker.label + '</span>';
		html += '<div style="font-size: 11px;">';
		html += marker.desc;

		// Only show this link if its the original window (overlay will no contans an id)
		if ( marker.id ){
			html += '<br /><a onClick="PGE.recreationalAreas.initModal(\'' + index + '\')" href="javascript:void(0)">More details</a>';
		}

		html += '</div></div>';

		return html;
	},

	initModal: function(index){
		if (!index) { return false; }
		var file = this.json_path+"/"+this.obj[index].id+".js";
   
		// Get modal WIDTH
		var width = ($(window).width() * 0.95 );

		$("#" + this.modalID).width(width);
		$("#" + this.modalID+"_google").width(width);

		// Get modal height
		var height = ($(window).height() * 0.90);
		$("#" + this.modalID).height(height);
		$("#" + this.modalID+"_google").height(height-44);

		var left = ($(window).width() * 0.05) / 2;
		
		$("#" + this.modalID).jqmShow();

		// Display Modal window with "Loading..." message
		var loadingLeft = width/2-50;
		var loadingTop  = height/2-50;
		$("#" + this.modalID+"_google").html("<div class=\"loading\" style=\"left:" + loadingLeft + "px;top:" + loadingTop + "px;\"></div>");
    
	    var x = "document.documentElement.offsetWidth: "+document.documentElement.offsetWidth+"\n"+"document.documentElement.offsetHeight: "+document.documentElement.offsetHeight+"\n"+"document.documentElement.scrollTop: "+document.documentElement.scrollTop+"\n"+"document.body.scrollTop: "+document.body.scrollTop+"\n"+"document.body.clientHeight: "+document.body.clientHeight;
	    
	    // Set the modal window to center
	    if (window.innerHeight) { //@hack for browsers other than ie6
	      $("#" + this.modalID).css("left",($(window).width()-width)/2 + "px");
	      $("#" + this.modalID).css("top",($(window).height()-height)/2 + "px");
	    } else { //@hack for ie6
	      $("#" + this.modalID).css("left",(document.documentElement.offsetWidth-width)/2 + "px");
	    }
    
		// Header text
		$("#" + this.modalID + " .head h1").text(this.obj[index].label);

		// Closure
		var self = this;

		// Get JSON object and trigger createModal method when loaded
	    $.getJSON(file, null, function( data ) {
			self.json_data = data;
			self.createModal();
		});

	},

	createModal: function(){
		// Create google map on modal overlay
		this.bounds = new GLatLngBounds();

		var map = this.setGoogleMap(this.mapid + '_modal_google',
									[G_NORMAL_MAP,G_PHYSICAL_MAP],
									this.json_data.area[0].lat,
									this.json_data.area[0].long,
									12,
									this.json_data.area,
									false);

		// Set Center and zoom automatically
		if ( this.json_data.position.lat == "" || this.json_data.position.lat == undefined ){
			if (this.bounds.isEmpty() == false) {
				map.setZoom(map.getBoundsZoomLevel(this.bounds));
				map.setCenter(this.bounds.getCenter());
			}
		}

		// LEGEND
		if ( this.json_data.legend || this.legend ){
			this.createLegend();
		}
	},

  createLegend: function(){
	// Legend PANEL
	var legendPanel = document.createElement('div');
	legendPanel.className = 'legend';
	
	// Legend PANEL BODY
	var legendPanelBody = document.createElement('div');
	legendPanelBody.className = 'body';
	$(legendPanel).append(legendPanelBody);
	

	// Look up and use json legend property first if available, otherwise use the default legend set by the constructor.
	if ( this.json_data.legend && this.json_data.legend != '' ){
		$(legendPanelBody).append(this.json_data.legend);
	} else {
		$(legendPanelBody).append(this.legend);
	}
	
	// Legend PANEL HEADER
	var legendPanelHeader = document.createElement('div');
	legendPanelHeader.className = 'head';
	$(legendPanel).append(legendPanelHeader);
	
	// Legend PANEL HEADER H2
	var legendPanelHeaderH2 = document.createElement('h2');
	h2Txt = document.createTextNode("Legend");
	$(legendPanelHeaderH2).append(h2Txt);
	$(legendPanelHeader).append(legendPanelHeaderH2);
	
	// PANEL HEADER HIDE
	var legendPanelHeaderHide = document.createElement('a');
	legendPanelHeaderHide.setAttribute('href','javascript:void(0)');
	hideTxt = document.createTextNode("Hide <<");
	$(legendPanelHeaderHide).append(hideTxt);
	$(legendPanelHeader).append(legendPanelHeaderHide);

	// HIDE / SHOW EFFECT
	$(legendPanelHeaderHide).click(function() {
		var txt = ( $(this).text().indexOf('<') != -1 ) ? 'Show >>' : 'Hide <<';
		$(this).text(txt);
		//$(legendPanelBody).animate({opacity: 'toggle'}, 'slow');
		if ( $(this).text().indexOf('<') != -1 ) {
        $(legendPanelBody).fadeIn('slow', function(){
          $("#map_modal_google .legend .body").removeAttr("style");
        });
			}
			else {
        $(legendPanelBody).fadeOut('slow');
			}
	});

	$("#"+this.mapid + '_modal_google').prepend(legendPanel);
  }
};






