/**
 * UWW Interactive Maps
 * Inspiration for this map goes out to BYU, BU, and OSU 
 * @author Joel Herron
 * @version 1.1
 */

/**
 * Define public variables
 */
var map,
	parkingOverlay,
	parkingCheck,
	buildingOverlay,
	current_search = '',
	current_search_type = '',
	current_results_page = 1,
	current_results_size = 15,
	current_results_count = 0,
	searchResults = [];

$(document).ready(startUp);
$(window).unload(GUnload);

function startUp()
{
	startLoad();
	resizeMap();
	initializeMap();
	endLoad();
}

/**
 * creates the base map
 */
function initializeMap()
{
	//create new map
	if (google.maps.BrowserIsCompatible()) {
		
		// set map to auto resize
		$(window).resize(resizeMap);
		
		//setup map and attributes
		map = new GMap2($("#map")[0]);
		mapControl = new GLargeMapControl3D();
		typeControl = new GMapTypeControl();
		sidebarControl = new PlaceholderControl();
		powered = new PowerLogo();
		legend = new LegendControl();
		map.addControl(legend);
		map.addControl(mapControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(305,7)));
		map.addControl(typeControl);
		map.addControl(sidebarControl);
		map.addControl(powered);
		map.addControl(legend);
		map.removeMapType(G_SATELLITE_MAP);
		// Scrolling is causing mushroom effect disabled till i can fix it. 
		// map.enableScrollWheelZoom();
    	// map.enableContinuousZoom();
		
		// add custom maptype
		uwwCustomMap();
		map.setMapType(campusmap);
		map.removeControl(mapControl);
		$('#map-legend').show();
		
		//center map on defined coords
		centerMap();
		
		//set the min and max Zoom levels
		var mapType = map.getMapTypes();
		// Overwrite the getMinimumResolution() and getMaximumResolution() methods
		for (var i=0; i<mapType.length; i++) {
			mapType[i].getMinimumResolution = function() {return 11;}
			mapType[i].getMaximumResolution = function() {return 17;}
		}
		
		
	}
	// setup toggle for side bar open/close
	$("#side-bar-top").click(toggleSideBar);
	
	createSideBarLinks();
	createQuickMenu();
	
	// do AJAX search
	// NOTE: search results will not stick on refresh
	$("#searchForm").submit(function(){
		var input = $("#search-input").val();
		newSearch(input,'search',1);
		return false;
	});	
		
	($("#side-bar").attr('offsetLeft') == 0) ? $("#powered").show() : $("#powered").hide();
	
	/*
	// functions to stop scroll zoom while over the side bar
	// for some reason it's failing and causing mushroom effect 
	$("#side-bar").mouseover(function(){
		try {
			map.disableScrollWheelZoom();
		}
		catch(e){}
	});
	
	$("#side-bar").mouseout(function(){
		try {
			map.enableScrollWheelZoom();		}
		catch(e){}
	});*/
	
	// check current map type
	// set display objects based on maptype
	GEvent.addListener(map, "maptypechanged", function() 
	{
		if(map.getCurrentMapType() == campusmap) {
			map.removeControl(mapControl);
			map.setZoom(17);
			$('#map-legend').show();
		} else {
			var openCheck = checkSideBar();
			if(openCheck == 1) {
				map.addControl(mapControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(305,7)));
				
			} else {
				map.addControl(mapControl);
			}
			$('#map-legend').hide();
		}
	});
	
	// event to trigger opening info windows
	GEvent.addListener(map, "click", function(overlay) {
		if (overlay && overlay.html_info)
			openMarker(overlay.id);
	});	
	
	// check the current url for items
	//checkItems();
	checkUrl();	
}

function checkUrl()
{
	var params = parseUrl();
	var s = params['search'];
	var tag = params['tag'];
	var id = params['id'];
	var custom = params['custom'];
	var page = (isNaN(params['page'])) ? 1 : params['page'];
	current_results_size = (isNaN(params['page_size'])) ? 15 : params['page_size'];
	
	resetResultSizeLinks();
	
	if (s) {
		var decodeS = s.replace("+", " ");
		$("#search-input").val(decodeS);
	} else if (tag) {
		var decodeTag = tag.replace("+", " ");
		$("#search-input").val(decodeTag);
	}
	
	if(custom) return newSearch(custom,'custom',page);
	if(id) return newSearch(id,'id',page);
	if(s) return newSearch(s,'search',page);
	if(tag) return newSearch(tag,'tags',page);
}

/**
 * sets global search vars and then passes the page on to runSearch
 * @param {Object} query
 * @param {Object} search_type
 * @param {Object} page
 */
function newSearch(query,search_type,page)
{
	if(!query){ return; }
	current_search = query;
	current_search_type = search_type;
	current_results_page = (page) ? page : 1;
	runSearch();
}

function runSearch()
{
	if(current_search_type == 'custom') searchCustom();
	if(current_search_type == 'search') searchMap();
	if(current_search_type == 'tags') searchMap();
	if(current_search_type == 'id') searchOnId();
}

function searchMap()
{
	prepSearch();
	var params = {
		query: current_search,
		page: current_results_page,
		page_size: current_results_size 
	};
	
	$.getJSON('common/php/searchLoader.php', params, function(search_results){
		processResults(search_results);
	});
}

/* Old function not needed
function searchTags()
{
	prepSearch();
	var params = {
		tag: current_search,
		page: current_results_page,
		page_size: current_results_size 
	};
	
	$.getJSON('common/php/tagSearchLoader.php', params, function(search_results){
		processResults(search_results);
	});
}*/

function searchOnId()
{
	prepSearch();
	var params = {
		id: current_search,
		page: current_results_page,
		page_size: current_results_size 
	};
	
	$.getJSON('common/php/idSearchLoader.php', params, function(search_results){
		processResults(search_results);
	});
}

function searchCustom()
{
	switch(current_search)
	{
		case 'theatrefest':
			theatreFestOverlay();
			$('#map-legend img').attr("src","/maps/common/images/custom-overlays/theatre-legend.jpg");
		break;
		default:
		
	}
}

/**
 * gets search result iterates through them and passes each result to createMarker
 * @param {Object} search_results
 */
function processResults(search_results)
{
	var markers = search_results.markers;
	var marker_count = search_results.marker_count;
	current_results_count = marker_count;
	
	for(var key in markers)
		createMarker(markers[key]);
	
	// setup sidebar 
	// setup results
	setupSearchQuery(marker_count);
	setupSearchPages(marker_count);
	
	$("#welcome").hide();
	var current_side_bar_pos = checkSideBar();
	if (current_side_bar_pos == 0) 
		toggleSideBar();
	if(marker_count < 1) {
		$("#results").hide();
		$("#no-results").show();
	} 
	else {
		$("#no-results").hide();
		$("#results").show();
	}
	
	//end loading screen
	endLoad();
}

/**
 * Creates the individual marker
 * @param {Object} data
 */
function createMarker(data) 
{
	var point = new GLatLng(data.lat, data.long);
	var icon_name = data.letter;
	var icon_type = data.type;
	var icon_acronym = data.acronym;
	var myIcon = getIcon(icon_type, icon_acronym, icon_name);
	
	var marker = new GMarker(point, myIcon);
	marker.id = data.id;
	marker.type = data.type;
	marker.html_info = data;
	marker.point = point;
	
	map.addOverlay(marker);	
	
	searchResults[marker.id] = marker;
	addMarker2SideBar(data);
}

function addMarker2SideBar(data)
{
	// build marker list item
	var item = $.create("li");
	// function to open marker on map

	var openMarkerSide = function() {
		openMarker(data.id);
		return false;
	}
	// create the link an icon for the item
	var itemLink = $.create('a').attr('href', './?id='+data.id);
	itemLink.append($.create('img').attr('src', getResultIcon(data.type, data.acronym, data.letter)));
	itemLink.click(openMarkerSide);
	item.append(itemLink);
	
	// create the item information
	var itemInfo = $.create('div').addClass('result-details');
	var a = $.create('a').attr('href', './?id='+data.id).click(openMarkerSide).text(data.name);
	itemInfo.append(a);
	itemInfo.append($.create('br'));
	itemInfo.append($.create('span').text(data.address));
	
	// add the item infomation to the li
	item.append(itemInfo);
	item.append( $.create('div').addClass('clear-both') );
	$('#results ul').append(item);
}

function openMarker(id)
{
	if(searchResults[id]) marker = searchResults[id];
	
	if(!marker) return;
	//check to see if info window exists already
	if(!marker.html) {
		try {
			marker.html = json2html(marker.html_info);
		}
		catch(e) {
			alert('Error can not open marker:'+e);
			return false;
		}
	}
	
	var div = $.create('div').html(marker.html);
	marker.openInfoWindow(div[0]);
}
