// Constructor
var CMGMap = function (controls_container, map_container) {

	// Map Settings... Leave alone.
	this.nIcon.shadow = 'http://citywidedev.com/map/images/icon_shadow.png';
	this.nIcon.iconSize = new GSize(18, 36);
	this.nIcon.shadowSize = new GSize(43, 50);
	this.nIcon.iconAnchor = new GPoint(9, 31);
	this.nIcon.infoWindowAnchor = new GPoint (9, 9);


	this.controlsContainer = document.getElementById(controls_container);
	this.mapContainer = document.getElementById(map_container);
	this.loadAJAX({action:'getViews'}, this.createMap);
};	


// Method & Property Assignments
CMGMap.prototype = {

	// Properties
	// ++++++++++++++++++++++++++++++++++
	
	map 				: "", // GMap Reference
	mapContainer		: "", // Map HTML Element
	controlsContainer 	: "", // Controls HTML Element
	views 				: [],
	viewOptions 		: [],
	markers				: [],
	
	nIcon				: new GIcon(G_DEFAULT_ICON, 'http://citywidedev.com/map/images/normal_icon.png'),
	
	
	// Methods
	// ++++++++++++++++++++++++++++++++++
	
	createMap : function (data, self) {
		self.views = data;
		self.map = new GMap2(self.mapContainer);
		self.map.enableContinuousZoom();
		self.map.addControl(new GLargeMapControl3D());
		self.map.addControl(new GMapTypeControl());
		
		self.createControls();
	},
	
	
	createControls : function () {
		
		var	i,ni,
			view_count=this.views.length,
			option_count,
			list = "",
			self = this;

		list += '<ul id="cmgMap-controls">';
		
		for (i=0; i<view_count; i++){
		
			list += '<li>';
			list += '<a href="view-'+i+'" class="view-title">'+this.views[i].Name+'</a>';
			
			option_count = this.views[i].opts.length;
			if (option_count){
				list += '<ul class="options">';
				for (ni=0; ni<option_count; ni++){
					if (this.views[i].opts[ni].Togglable == "1"){
						if (ni+1 == option_count){			
							list += '<li class="last"><label><input type="checkbox" class="option-toggle" value="'+i+'-'+ni+'" /> '+this.views[i].opts[ni].Name+'</label></li>';				
						}else{
							list += '<li><label><input type="checkbox" class="option-toggle" value="'+i+'-'+ni+'" /> '+this.views[i].opts[ni].Name+'</label></li>';				
						}
					}
				}				
				list += '</ul>';				
			}
			
			list += '</li>';		
		}
		
		list += '</ul>';
		//list += '<div id="loading">Loading&hellip;</div>';
		list += '<div id="item_desc"></div>';
		
		$(this.controlsContainer).html(list);	
		
		
		
		// Assign events to controls and other stuff
		$('a.view-title').click(function (){ return self.changeView(this); });
		$('input.option-toggle').change(function (){ return self.toggleOption(this); });
		if ($.browser.msie){	
			$('input.option-toggle').parent('label').click(function (){return self.toggleOption($('input', this)); });
		}
		$('.options').hide();
		$('a.view-title:first').click();
		
	},

	
	
	showView : function (view) {
		var	lat = parseFloat(view.Latitude),
			lng = parseFloat(view.Longitude),
			zoom = parseFloat(view.Zoom),
			i, optionCount = view.opts.length;
			
		this.map.setCenter(new GLatLng(lat, lng), zoom);
		
		for (i=0; i<optionCount; i++){
			
			if (view.opts[i].Togglable == "0") {
				this.loadAJAX({action:'getMarkers', id:view.opts[i].ID}, this.showMarkers, view.opts[i]);
			}
		}
		
		this.currentView = view;
	},
	
	
	
	changeView : function (tar) {		
		var start = $(tar).attr('href').indexOf('view-') + 'view-'.length,	
			viewIndex = parseFloat($(tar).attr('href').substr(start));
			
		this.map.clearOverlays();
		$('#item_desc').html('');
		$('.option-toggle').attr({'checked':false});
		$('.option-toggle').parent().removeClass('selected');
		$('#cmgMap-controls ul.options').slideUp('fast');
		$(tar).siblings('.options').slideDown('fast');
		this.showView(this.views[viewIndex]);
		return false;
	},
	
	
	toggleOption : function (tar) {
		var index_arr = $(tar).val().split('-');
			viewIndex = parseFloat(index_arr[0]),
			optionIndex = parseFloat(index_arr[1]),
			option = this.views[viewIndex].opts[optionIndex];
			
		if ($.browser.msie){
			if ($(tar).attr('checked')){
				$(tar).attr('checked', '');
			}else{
				$(tar).attr('checked', 'true');
			}
		}
			
		if ($(tar).attr('checked')){
			this.loadAJAX({action:'getMarkers', id:option.ID}, this.showMarkers, this.views[viewIndex].opts[optionIndex]);
			$(tar).parent().addClass('selected');
			$('#item_desc').html(this.views[viewIndex].opts[optionIndex].Description);
		}else{
			if (this.views[viewIndex].opts[optionIndex].markers){
				this.hideMarkers(this.views[viewIndex].opts[optionIndex].markers, this.views[viewIndex].opts[optionIndex]);
			}
			$(tar).parent().removeClass('selected');
		}
		return false;
	},
	
	
	showMarkers : function (markers, self, option) {	
		var i=0,count=markers.length,point,lat,lng,markers_arr=[];
		
		for (i=0; i<count; i++){
			if (markers[i].Type == "point"){
			
				lat = parseFloat(markers[i].Latitude);
				lng = parseFloat(markers[i].Longitude);
							
				if (markers[i].Icon) {
					var icon = new GIcon(self.nIcon, 'http://citywidedev.com/map/'+markers[i].Icon);
					if (markers[i].Name == 'TechTown'){
						icon.iconSize = new GSize(26, 46);
						icon.iconAnchor = new GPoint(13, 41);
						icon.infoWindowAnchor = new GPoint (13, 9);
						icon.imageMap = [1,11,13,0,23,11,13,46,1,11];
					}

					point = new GMarker(new GLatLng(lat, lng), {icon:icon, title:markers[i].Name});
				}else{
					point = new GMarker(new GLatLng(lat, lng), {icon:self.nIcon, title:markers[i].Name});
				}
				
				point.Data = markers[i];
				
				GEvent.addListener(point, "click", function() {
					var myHtml = "<h1>"+this.Data.Name+"</h1>";
					myHtml += "<p>"+this.Data.Description+"</p>";
					this.openInfoWindow(myHtml, {maxWidth: 300});
				});				
				
				self.map.addOverlay(point);
				markers_arr.push(point);
				
			}else if (markers[i].Type == "overlay"){
						
				var image 		= 'http://citywidedev.com/map/'+markers[i].OverlayImage,
					swBound		= new GLatLng(markers[i].SWBound.split(',')[0], markers[i].SWBound.split(',')[1]),
					neBound 	= new GLatLng(markers[i].NEBound.split(',')[0], markers[i].NEBound.split(',')[1]),
				
					boundaries 	= new GLatLngBounds(swBound, neBound);
					
				lat = parseFloat(markers[i].Latitude);
				lng = parseFloat(markers[i].Longitude);					
				
				point = new GGroundOverlay(image, boundaries);
				self.map.setCenter(new GLatLng(lat, lng));
				
				markers_arr.push(point);
				
				try { self.map.addOverlay(point); } catch(e) {}

				
			}
			
			
		}
		option.markers = markers_arr;
	},

	
	
	hideMarkers : function (markers, option) {
		var i,count=markers.length;
		for(i=0; i<count; i++){
			this.map.removeOverlay(markers[i]);
		}
		delete option.markers;
	},
	
		
	showLoading : function () {
		$(this).show();
	},
	
	
	hideLoading : function () {
		$(this).hide();
	},
	
	showErrorMessage : function (xhr, status, error) {
		
		
		
	},
	
	
	loadAJAX : function (args, callback, additionalArgs) {
	
	
		var	self = this,
			addArgs = additionalArgs || '',
			options = {
				data : args,
				dataType : 'json',
				error : this.showErrorMessage,
				success : (callback != undefined) ? function (data){ callback(data, self, addArgs)  } : "",
				type : 'GET',
				url : 'http://citywidedev.com/map/app/ajax_gateway.php'
			};
			
		$('#loading').ajaxStart(this.showLoading);
		$('#loading').ajaxStop(this.hideLoading);
			
		$.ajax(options);
	
	}
	
	
		
};

