/**
 * This Class is to be used within the MySelection Framework.
 *
 * @author Reece Schaefer (reece@thenextspark.com)
 * @version 0.2
 * @return {Object} Mootools Object
 */

var msMaps = new Class ({
	options:{
		onUpdate: Class.empty,
		custom: null,
		mapOverview: false,
		mapHelpers: null,
		mapTypeControl: true,
		mapControl: true,
		mapTiles: '',
		toolTip: false
	},
	initialize: function(el, mapCenter, options, data) {
		this.setOptions(options);

		if(this.options.mapHelpers) {
			this.helper = new Element('script', {'src':this.options.mapHelpers, 'type': 'text/javascript'}).injectInside(document.head);
		}

		this.map = new GMap2($(el));

                $(document.body).setProperty('onunload', 'GUnload()');

       	if(this.options.mapControl) 	this.map.addControl(new GLargeMapControl());
       	//if(this.options.mapOverview) 	this.map.addControl(new GOverviewMapControl());
		if(this.options.mapControl) 	this.map.enableDoubleClickZoom();
		this.map.enableScrollWheelZoom();
       	

		if(this.options.custom) {
			this.stageDetails 	= this.options.custom[0].details;
			this.customArea 	= this.options.custom[0].area;
			this.customZoom 	= this.options.custom[0].zoom;
			this.customCords 	= this.options.custom[0].posi;

			var zoomLevel = [100, 0];

			this.customZoom.each(function(level, i) {
				zoomLevel[1] = Math.max(level, zoomLevel[1]);
				zoomLevel[0] = Math.min(level, zoomLevel[0]);
			});
			var copyright = new GCopyright(1,new GLatLngBounds(new GLatLng(this.customArea[0][0], this.customArea[0][1]), new GLatLng(this.customArea[1][0], this.customArea[1][1])), 0, this.stageDetails.stage);
			var copyrightCollection = new GCopyrightCollection(this.stageDetails.estate + ' - ');
			copyrightCollection.addCopyright(copyright);
		
			var tilelayers = [new GTileLayer(copyrightCollection , zoomLevel[0], zoomLevel[1])];
			tilelayers[0].getTileUrl = this.CustomGetTileUrl.bind(this);
		
			var custommap = new GMapType(tilelayers, new GMercatorProjection(22), this.stageDetails.stage, {errorMessage:"No chart data available"});

			this.map.setCenter(new GLatLng(mapCenter[0], mapCenter[1]), zoomLevel[0], custommap); 
			this.map.addMapType(custommap);
      	} else {
			this.map.setCenter(new GLatLng(mapCenter[0], mapCenter[1]), 15);
		}
		this.dataSet = (data) ? data : null ;		
		if(this.dataSet) this.createMarker(this.dataSet);

	},
	CustomGetTileUrl: function(a,b) {
		if(this.customZoom.indexOf(b) != -1) arrPos = this.customZoom.indexOf(b);

		zLevel = this.customZoom[arrPos];
		xPos = this.customCords[arrPos][0];
		yPos = this.customCords[arrPos][1];
		ext  = this.customCords[arrPos][2];

        if (b==zLevel && (a.x >= xPos[0] && a.x <= xPos[1]) && (a.y >= yPos[0] && a.y <= yPos[1])) {
		   	return this.options.mapTiles+zLevel+'/' + zLevel + '_' + (a.x) + '_' + (a.y) + '.' + ext;      
		} else {
		   	return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
		}

	},
	createMarker: function(objects) {

		if(this.markers) this.removeMarkers();        

		this.markers = null;

		if(objects.length) {
			for(var i=0; i<objects.length; i++) {
				this.map.addOverlay(this.marker(objects[i], i));
			}
		} else {
			this.map.addOverlay(this.marker(objects, 0));
		}
	},
    marker: function(obj, index) {
        if(this.markers == null)  this.markers = [ ];

        var iconStyle = this.markerStyle(iconData[obj['status'].toLowerCase()]);

        var options    = { icon:iconStyle };
		var marker = new GMarker(new GLatLng(obj['posn'][0], obj['posn'][1]), options);
       	this.markers.push(marker);
        // marker_index = this.markers.length-1;

       	marker.clickActions = this.showDetail;
		marker.data = obj;

		
		if (this.options.toolTip) {

			if(Land.details.length) { var objHolder = Land.details[index]; }
			else 					{ var objHolder = Land.details; }

			var label = '<strong>' + objHolder.LOT_strName + '</strong> - ' + objHolder.LOT_mPrice;
			var toolTip = new Element('div').setHTML(label).addClass('toolTip');

		    GEvent.addListener(marker, "click", function() {
		      	marker.clickActions(this, index);
		    });
    
		    GEvent.addListener(marker, "mouseover", function() {
				this.showToolTip(marker, toolTip);
		        marker.setImage(options.icon.hover);
		    }.bind(this));
    
			GEvent.addListener(marker, "mouseout", function() {
		        marker.setImage(options.icon.image);
				toolTip.remove();
		    }.bind(this));
		};

        marker.id = 'marker_'+index;
    
        return marker;
    },
	showDetail: function(marker,index) {
		if(window.changeDetail) changeDetail(marker, index);
	},
	markerStyle: function(iconDetails) {
	    var icon        = new GIcon();
            var iconDir     = config.baseURI + "siteAssets/maps/icons/";

            var iconAnchor       = iconDetails.iconAnchor       || [8,25];
            var infoWindowAnchor = iconDetails.infoWindowAnchor || [16,1];
            var transparent      = iconDetails.transparent      || null;
            var imageMap         = iconDetails.imageMap         || null;

	    icon.image      = iconDir + iconDetails['icon'] + '.png';
	    icon.shadow     = iconDir + iconDetails['shadow'] + '.png';
	    icon.hover      = iconDir + iconDetails['hover'] + '.png';
	    icon.iconSize   = new GSize(iconDetails['height'], iconDetails['width']);
	    icon.shadowSize = icon.iconSize;
	    icon.iconAnchor = new GPoint(iconAnchor[0], iconAnchor[1]);	
            icon.infoWindowAnchor = new GPoint(infoWindowAnchor[0], infoWindowAnchor[1]);

            if (transparent) icon.transparent = iconDir + transparent + ".png";
            if (imageMap) icon.imageMap = imageMap;

	    return icon;
	},
	showToolTip: function (marker, tooltip, label) {
		
		var theMap = this.map;
		
		theMap.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
		tooltip.style.visibility = 'hidden';
		
		var point = theMap.getCurrentMapType().getProjection().fromLatLngToPixel(theMap.fromDivPixelToLatLng(new GPoint(0, 0), true), theMap.getZoom());
		var offset = theMap.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),theMap.getZoom());
		var anchor = marker.getIcon().iconAnchor;
		var width = marker.getIcon().iconSize.width;
		var height = tooltip.clientHeight;
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize((offset.x - point.x - anchor.x + width)-53, (offset.y - point.y - anchor.y - height)));
		pos.apply(tooltip);
		tooltip.style.visibility = 'visible';
	},
	removeMarkers: function(map) {
		this.map.clearOverlays();
	},
	moveMap: function(moveTo, zoom) {
		if(zoom) this.map.setZoom(zoom);
		this.map.panTo(new GLatLng(moveTo[0], moveTo[1]));
	},
	getOption: function(element) {
		return this.options[element];
	}
	
});
msMaps.implement(new Events);
msMaps.implement(new Options);