// CONFIG VARS
var maxZoom = 17; //Max zoom level to show icons at
var minZoom = 6;  //Min zoom level to show icons at
var defaultZoom = 8;
var startLat = 44.57;
var startLng = -69.61;
var listingXmlUrl = '/directory/categories';
var mapIconPath = '/layout/images/map/markers/';
var defaultMapIcon = 'blue';
var defaultShowMarkers = false;
var infoWindowBaseName = "custom_info_window_red";

var debugOn = false;

// GLOBAL VARS [DO NOT EDIT BELOW THIS LINE]
var ICONS = []; // Array of icons. Icon Name is used as they key, the value is a GIcon object.
var map = null; // Google Map object
var mgr = null;	// Marker Manager object, see markermanager.js for details
var listingsXml = null; // An XML Document
var categoryMarkers = []; // An array of arrays. Top level array is using category ID as keys. Inner arrays are not associative.
var listingMarkers = []; // An array of markers. Top level array is using listing ID as keys.

// FUNCTIONS
function setupMap() {
  if (GBrowserIsCompatible()) {	
    map = new GMap2(document.getElementById("map"));
//  map.setMapType(G_HYBRID_MAP);
//  map.setUIToDefault();
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GOverviewMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(startLat, startLng), defaultZoom);
    map.enableDoubleClickZoom();
//    map.enableScrollWheelZoom();
	map.enableContinuousZoom();
//	map.enableRotation();
    setupListingMarkers();
  }
}

function setupListingMarkers() {
	$.ajax({
		type: "GET",
		url: listingXmlUrl,
		dataType: "xml",
		success: function(xml) {
		    listingsXml = xml;
			addXmlMarkers();
		}
	});
}

// This function was split out from the setupListingMarkers function, but they go hand in hand. 
function addXmlMarkers(){
	if(mgr == null){
		var mgrOptions = { borderPadding: 10, maxZoom: maxZoom, trackMarkers: false };	  
		mgr = new MarkerManager(map, mgrOptions);
	}else{
		mgr.clearAllMarkers();
	}
	$("category",listingsXml).each(function(){
		if(debugOn){
			console.log('Adding Category Markers');
		}
		var categoryMarkers = getCategoryMarkers(this);
		if(defaultShowMarkers){
			mgr.addMarkers(categoryMarkers, minZoom, maxZoom);
		}
	});
	mgr.refresh();
	if(!defaultShowMarkers){
		for(var i in listingMarkers){
			listingMarkers[i].hide();
		}
	}
	setupMapControls();
}

// Create the map controls for hiding/showing markers for categories
function setupMapControls() {
	var controlsHtml = '<ul id="categoryToggles">';
	$('category', listingsXml).each(function(index, Element){
		var categoryId = $(this).attr('id');
		if(categoryMarkers[categoryId] != null && categoryMarkers[categoryId].length > 0){
			var iconName = defaultMapIcon;
			if($('category#'+categoryId, listingsXml).find('icon').text().length > 0){
				iconName = $('category#'+categoryId, listingsXml).find('icon').text();
			}
			controlsHtml += '<li class="categoryToggle ';
			if(defaultShowMarkers){
				controlsHtml += 'active ';
			}
			controlsHtml += iconName + '" id="categoryToggle-' + categoryId + '"><span>'+ $('category#' + categoryId + ' > name', listingsXml).text()+'</span></li>';
		}
	});
	controlsHtml += '</ul>';
	$('#map-controls').html(controlsHtml);
	for(var i in categoryMarkers){
		var categoryId = parseInt(i);
		$('#categoryToggle-' + categoryId).click(function(event){
			if($(this).hasClass('active')){
				$(this).removeClass('active');
				var categoryId = $(this).attr('id').substr(15);
				hideCategoryMarkers(categoryId);
				for(var j in categoryMarkers){
					if($('#categoryToggle-' + j).hasClass('active')){
						showCategoryMarkers(j);
					}
				}
			}else{
				$(this).addClass('active');
				var categoryId = $(this).attr('id').substr(15);
				showCategoryMarkers(categoryId);
			}			
		}).mouseover(function(){
			$(this).addClass('hover');
		}).mouseout(function(){
			$(this).removeClass('hover');
		});
	}
}

// Create and return all markers for a category. 
// This also adds references to the markers into the categoryMarkers array for later use
function getCategoryMarkers(categoryXml) {
	var batch = [];
	var categoryId = $(categoryXml).attr('id');
	if(categoryMarkers[categoryId] == null){
		categoryMarkers[categoryId] = new Array();
	}
	if(debugOn){
		console.log('Category ID: ' + categoryId);
	}
	$("listing", categoryXml).each(function(){
		if(debugOn){
			console.log('Adding Listing Marker');
		}
		var listingId = $(this).attr('id');
		var listingUrl = $(this).find('url').text() + '?lid=7';
		var listingTitle = $(this).find('name').text();
		if(debugOn){
			console.log('Listing ID: ' + listingId);
		}
		/**if(listingMarkers[listingId] == null){**/
			// Listing marker doesn't exist yet, create it
			var marker = createMarker(getListingPoint(this), listingTitle, getCategoryIcon(categoryId), listingUrl );
			listingMarkers[listingId] = marker;
			categoryMarkers[categoryId].push(marker);
			batch.push( marker );
			
		/**}else{
			// Marker already exists, add it to the category
			categoryMarkers[categoryId].push(listingMarkers[listingId]);
		}**/
	});
	return batch;
}

// Return a GLatLng object from the passed Listing XML
function getListingPoint(listingXml){
	var lat = $(listingXml).find('latitude').text();
	var lng = $(listingXml).find('longitude').text();
	if(debugOn){
		console.log('Got Listing Point');
		console.log('Lat: ' + lat);
		console.log('Lng: ' + lng);
	}
	return new GLatLng(lat, lng);
}

// Return the icon for a category. If the icon is not in the ICONS array already, it will be created and added.
function getCategoryIcon(categoryId){
	var name = defaultMapIcon;
	if($('category#'+categoryId, listingsXml).find('icon').text().length > 0){
		name = $('category#'+categoryId, listingsXml).find('icon').text();
	}
	if (!ICONS[name]) {
	    var icon = new GIcon();
	    icon.image = mapIconPath
	        + name + ".png";
	    icon.iconAnchor = new GPoint(16, 16);
	    icon.infoWindowAnchor = new GPoint(16, 0);
	    icon.iconSize = new GSize(19, 32);
	    icon.shadow = mapIconPath
//	        + name + "-shadow.png";
	    + "shadow.png";
	    icon.shadowSize = new GSize(59, 32);
	    ICONS[name] = icon;
	}
	return ICONS[name];
}

// Create a single Marker and return it
function createMarker(posn, title, icon, infoAjaxUrl) {
  var marker = new GMarker(posn, {title: title, icon: icon});
  marker = addMarkerListeners(marker, infoAjaxUrl);
  return marker;
}

// Bind events to a marker (for loading the infobox)
function addMarkerListeners(marker, infoAjaxUrl){
	GEvent.addListener(marker, 'click', function(){
		marker.openExtInfoWindow(
				map,
				infoWindowBaseName, //Info Window Class
				"<div class='ib-profile-name'><span>Loading Info...</span></div>", //Info Window Loading Content
				{beakOffset: 3, ajaxUrl: infoAjaxUrl, paddingX: 59, paddingY: 20}
		);
	});
	GEvent.addDomListener(map, 'extinfowindowupdate',function(){
		var windowContent = document.getElementById(infoWindowBaseName + "_contents");
		if($('#loadComplete', windowContent).length == 0){
			$(windowContent).append('<span id="loadComplete" style="display:none;">&nbsp;</span>');
		    var tabs = new Array();
		    for( var i = 0; i < 3; i++){
		    	if(document.getElementById("tab"+i)){
		    		tabs.push(document.getElementById("tab"+i));
		    	}
		    }
		    if( tabs.length > 0 ){
		      var tabContentsArray = new Array(tabs.length);
		      for( i=0; i < tabs.length; i++){
		    	  var tabId = tabs[i].id.substr(3);
		        tabContentsArray[i] = document.getElementById("tab"+tabId+"_content");
		        if( i > 0){
		          $('#'+tabContentsArray[i].id).hide().css('position', 'absolute');
		        }else{
		          $('#'+tabs[i].id).addClass('active');
		        }
		        tabs[i].setAttribute("name", i.toString());
		        $(tabs[i]).click(function(){
		          var tabIndex = this.getAttribute("name");
		          
		          for(tabContentIndex=0; tabContentIndex < tabs.length; tabContentIndex++){
		            if( tabContentIndex == tabIndex ){
		              $('#'+tabContentsArray[tabContentIndex].id).show().css('position', 'relative');
		              $('#'+tabs[tabContentIndex].id).addClass('active');	             
		            }else{
		              $('#'+tabContentsArray[tabContentIndex].id).hide().css('position', 'absolute');
		              $('#'+tabs[tabContentIndex].id).removeClass('active');
		            }
		          }
		          map.getExtInfoWindow().resize();
		        });
		      }
			  //Video Player
			  if(document.getElementById("tab1")){
		    	  var flashvars = {
		    			  file: $('#videoFLVUrl').val(),
		    			  image: $('#videoPreviewImage').val(),
		    			  controlbar: 'none'
		    			  };
		    	  var params = {
		    			  allowfullscreen: true
		    			  };
		    	  var attributes = {};
		    	  $(function(){
		    		  swfobject.embedSWF("/layout/js/shadowbox/libraries/mediaplayer/player.swf", "videoPlaceholder", "295", "163", "9.0.0", "/layout/js/shadowbox/libraries/mediaplayer/expressInstall.swf", flashvars, params, attributes);
		    	  });
		      }
			  //Photo Cycle
		      if(document.getElementById("tab2")){
				  $('#photosPlaceholder').cycle({ 
					    fx:     'fade', 
					    speed:  'fast', 
					    timeout: 0, 
					    next:   '#nextPhoto', 
					    prev:   '#prevPhoto',
					    pause: 1,
					    containerResize: 0,
					    before: function(curr, next, opts, forwardFlag){ 
				            $('a', next).css('marginTop', function(){
				            	var imgHeight = parseInt($('img', next).attr('height'));
				            	var top = 0;
				            	if (imgHeight > 0) {
					            	top = 166 - imgHeight;
					                top = top/2;
				            	}
				                return  top + "px";
				            });
			        	}
				  });
			      Shadowbox.setup("a.shadowbox");
		      }
		    }
		}
	});
	return marker;
};


function hideCategoryMarkers(categoryId){
	if(debugOn){
		console.log('Hiding Markers for Category ID ' + categoryId);
	}
	for( var i in categoryMarkers[categoryId]){
		if(debugOn){
			console.log('Hiding Marker ' + i);
		}
		mgr.removeMarker(categoryMarkers[categoryId][i]);
	}
}

function showCategoryMarkers(categoryId){
	if(debugOn){
		console.log('Showing Markers for Category ID ' + categoryId);
	}
	for( var i in categoryMarkers[categoryId]){
		if(debugOn){
			console.log('Showing Marker ' + i);
		}		
		mgr.removeMarker(categoryMarkers[categoryId][i]); //Remove it first to prevent shadows from stacking....
		mgr.addMarker(categoryMarkers[categoryId][i], minZoom, maxZoom);
	}
}
   
function clearMarkers() {
  mgr.clearMarkers();
}

