/**
 * UW-W Maps Utilities
 * @author Joel Herron
 */

/**
 * Base Utilities
 */

function getWindowHeight() 
{
    if (window.self && self.innerHeight) 
		return self.innerHeight;
	if (document.documentElement && document.documentElement.clientHeight) 
		return document.documentElement.clientHeight;
	return 0;
}	

function getWindowWidth()
{
	if (window.self && self.innerWidth)
		return self.innerWidth;
	if (document.documentElement && document.documentElement.clientWidth) 
		return document.documentElement.clientWidth;
	return 0;
}

/**
 * Gets the current URI path
 * @param {String} url
 */
function getPath(url) 
{
	if (!url) url = location.href;
	var file = url.substring(url.indexOf('://') + 3);
	return file.substring(0, file.lastIndexOf('/'));
}

/**
 * Parses the current url and breaks it into its parts
 * @param {Object} url
 * @return {Object} params
 */
function parseUrl(url)
{
	if (!url) url = location.href;
	if (url.substring(url.length -1) == '#') url = url.substring(0, url.length -1);
	var query = unescape(url.substr(url.lastIndexOf('?')+1));
	var params_array = query.split('&');

	var params = [];
	for (var i in params_array) {
		var key = params_array[i].substring(0, params_array[i].indexOf('='));
		var value = params_array[i].substring(params_array[i].indexOf('=')+1);
		
		// if the parameter is an array
		if (key.indexOf('[]', 1) > 0 && value != 'undefined' && value) {
			key = key.replace('[]', '');
			if (!params[key]) params[key] = [];
				params[key].push(value);
		}
		else {
			if (value != 'undefined' && value)
				params[key] = value;
		}
	}
	return params;
}

/**
 * Gets the windowHeight and then reassigns the map size
 */
function resizeMap() 
{
    var offset = 2;
    for (var elem = $("#map")[0]; elem !== null; elem = elem.offsetParent) {
		offset += elem.offsetTop;
    }
    var windowHeight = getWindowHeight();
    var height = windowHeight - offset;
	var height2 = windowHeight - 130;
    if (height >= 0) {
		$("#map").css('height', height+'px');
		$("#side-bar").css('height', height+'px');
		$(".s-b-filler").css('height', height2+'px');
		
    } 
}

/**
 * Function to recenter the map based on the current screen size. 
 * Currently doesn't auto recenter, requires a refresh.
 */
function centerMap()
{
	var windowWidth = getWindowWidth();
	if (windowWidth <= 1024)
		map.setCenter(new GLatLng(42.837536, -88.745402),17);
	else if (windowWidth <= 1280)
		map.setCenter(new GLatLng(42.837575, -88.745402),17);
	else if (windowWidth <= 1440)
		map.setCenter(new GLatLng(42.837638, -88.745584),17);
	else
		map.setCenter(new GLatLng(42.838181, -88.743749),17);
}

function startLoad() 
{
	$("#map-overlay").show();
	$("#map-load").show();
}

function endLoad() 
{
	$("#map-overlay").hide();
	$("#map-load").hide();
}

jQuery.create= function(element) {
	return $(document.createElement(element));
}

/**
 * Icon Functions
 */

/**
 * builds Icons for markers
 * @param {String} type
 * @param {String} acronym
 * @param {String} alpha
 * 
 * @return {Object} icon
 */
function getIcon(type, acronym, alpha)
{
	var icon;
	
	if (alpha > 26) alpha = alpha-26;
	
	if(type == '101' || type == '102' || type == '104') {
		icon = new GIcon(G_DEFAULT_ICON,
			'common/images/icons/alpha/'+type+'/'+alpha+'.png');
		icon.shadow = "common/images/icons/shadow-square.png";
		icon.iconSize = new GSize(25.0, 28.0);
		icon.iconAnchor = new GPoint(12, 14);
		icon.infoWindowAnchor = new GPoint(12, 1);
	}
	
	if(type == '103') {
		icon = new GIcon(G_DEFAULT_ICON,
			'common/images/icons/parking/'+acronym+'.png');
		icon.shadow = "common/images/icons/shadow-square.png";
		icon.iconSize = new GSize(25.0, 28.0);
		icon.iconAnchor = new GPoint(12, 14);
		icon.infoWindowAnchor = new GPoint(12, 1);
	}
	return icon;
}

/**
 * builds Icons for search result nav
 * @param {String} type
 * @param {String} acronym
 * @param {String} alpha
 * 
 * @return {String} icon image url
 */
function getResultIcon(type, acronym, alpha)
{
	if (alpha > 26) alpha = alpha-26;
	
	if (type == '101' || type == '102' || type == '104')
		return 'common/images/icons/alpha/'+type+'/'+alpha+'.png';
	if(type == '103')
		return 'common/images/icons/parking/'+acronym+'.png';
	
	return 'common/images/icons/alpha/purple/'+alpha+'.png';
}

/**
 * Side bar toggle functions
 */

/**
 * Check to see if the side bar is open or not
 * @return {Integer} isOpen
 */
function checkSideBar()
{
	var isOpen = 0;
	if ($("#side-bar").attr('offsetLeft') < 0) {
		return isOpen;
	} else {
		isOpen = 1;
		return isOpen;
	}
}

/**
 * Function to toggle the side bar open and close
 */
function toggleSideBar()
{
	($("#side-bar").attr('offsetLeft') < 0) ? openSideBar() : closeSideBar();
	return false;
}

/**
 * function opens the side bar
 * because of the absolute positioning we need to reposition the map controller
 * and the powered by Big G icon for legal reasons
 */
function openSideBar()
{
	map.removeControl(mapControl);
	
	$("#side-bar").show().animate({
		left:"0px"
	}, 200, "linear",function(){
		if (map.getCurrentMapType() != campusmap) {
			map.addControl(mapControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(305, 7)));
		}
		map.addControl(sidebarControl);
		map.addControl(powered);
	});
	$("#side-bar-top").show().animate({left:"0px"}, 200,"linear").css('background-image','url(common/images/icons/arrows/arrow-left.png)');
}

/**
 * function closes the side bar
 * because of the absolute positioning we need to reposition the map controller
 * and reset powered by Big G icon
 */
function closeSideBar()
{
	if (map.getCurrentMapType() != campusmap) {
		map.removeControl(mapControl);
		map.addControl(mapControl);
	}
	map.removeControl(sidebarControl);
	map.removeControl(powered);
	$("#side-bar").animate({left:"-300px"}, 200,"linear");
	$("#side-bar-top").css('background-image','url(common/images/icons/arrows/arrow-right.png)').animate({left:"-278px"}, 200,"linear");
}

/**
 * creates an placeholder GControl behind 
 * the sideBar to allow infowindows to slide into view
 * @return {Object} container
 */
function PlaceholderControl(){}
PlaceholderControl.prototype = new GControl();
PlaceholderControl.prototype.initialize = function(_map) 
{
	var container = document.createElement("div");
	var placeHolder = document.createElement("div");
	placeHolder.className = "s-b-filler";
	placeHolder.appendChild(document.createTextNode("this is a place holder block"));
	placeHolder.style.width = "297px";
	container.appendChild(placeHolder);
	
	_map.getContainer().appendChild(container);
	return container;
} 

PlaceholderControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(0,0));
}

/**
 * Google logo made into a GControl()
 * @return {Object} logo
 */
function PowerLogo(){}
PowerLogo.prototype = new GControl();
PowerLogo.prototype.initialize = function(map)
{
	var logo = document.createElement("img");
	map.getContainer().appendChild(logo);
	logo.src = "http://maps.google.com/intl/fi_ALL/mapfiles/poweredby.png";
	return logo;
}

PowerLogo.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(305,7));
}

function LegendControl(){}
LegendControl.prototype = new GControl();
LegendControl.prototype.initialize = function(map)
{
	var container = document.createElement("div");
	container.setAttribute("id","map-legend");
	var img = document.createElement("img");
	img.src = "common/images/map-legend.png";
	container.appendChild(img);
	container.style.border = "1px solid #000";
	map.getContainer().appendChild(container);
	return container;
}

LegendControl.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,37));
}

/**
 * Custom Overlay Functions
 */

/**
 * returns the custom map tile requested or return a blank file if out of bounds
 * @param {Object} a
 * @param {Object} b
 * @return png tile file
 */
function CustomGetTileUrl(a,b) 
{
	if(a.x>33228 || a.x<33222 || a.y>48244 || a.y<48237)
		return "common/images/tiles//blank.png";
	else
		return "common/images/tiles/" + a.x +"_" + a.y +"_17.png";
}

/**
 * creates the Copyright, tileLayers and adds the campusmap mapType
 */
function uwwCustomMap ()
{
	//create copyright statement
	var copyCollection = new GCopyrightCollection('Map Data:');
	var copyright = new GCopyright(1, 
		new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0, "&copy; 2008 UW-Whitewater");
	copyCollection.addCopyright(copyright);
	
	//create tile layer
	var tileLayers = [new GTileLayer(copyCollection,5,6)];
  	tileLayers[0].getTileUrl = CustomGetTileUrl;
	
	//create the maptype add it to the map
	campusmap = new GMapType(tileLayers, new GMercatorProjection(18), "Campus", {errorMessage:"No Tile data available"});
	map.addMapType(campusmap);
}

/**
 * creates custom Theatre Fest Overlay
 */
function theatreFestOverlay ()
{
	var theareBounds = new GLatLngBounds(new GLatLng(42.835260,-88.747345), new GLatLng(42.845900,-88.744499));
	var theatreParking = new GGroundOverlay("/maps/common/images/custom-overlays/theatre-fest-2009.png",theareBounds);
	map.addOverlay(theatreParking);
}

/**
 * Setup sidebar links
 * @param {String} name
 * @param {String} link
 */
function createLinks (name, link) {
	this.name = name;
	this.link = link;
}

/**
 * Sets up the links Object and the iterates though to build the side bar links
 */
function createSideBarLinks()
{	
	var links = new Array();
	links[0] = new createLinks('wifi','wifi');
	links[1] = new createLinks('coffee','coffee');
	links[2] = new createLinks('bookstore','bookstore');
	links[3] = new createLinks('hyer hall','hyer');
	links[4] = new createLinks('vistors center','visitor');
	
	for(var i=0;i<links.length;i++) {
		addlink2SideBar(links[i]);
	}
}

/**
 * Creates the starting sidebar links
 * @param {Object} data
 */
function addlink2SideBar(data)
{
	// build marker list item
	var item = $.create("li");
	
	// function to start a new search
	var openLinkSide = function() {
		newSearch(data.link,'search',1);
		return false;
	}
	
	var a = $.create('a').attr('href', './?search='+data.link).click(openLinkSide).text(data.name);
	item.append(a);
	$('#welcome ul').append(item);
}

/**
 * Search and Search Results Functions 
 */

function resetSideBar ()
{
	startLoad();
	$('#result-options').hide();
	resetSearchResults();
	$('#results').hide();
	$('#welcome').show();
	endLoad();
}

function prepSearch()
{
	startLoad();
	$('#result-options').hide();
	current_results_page = Math.min(current_results_page,
		Math.ceil(current_results_count/current_results_size));
	current_results_page = Math.max(current_results_page, 1);
	resetSearchResults();
}

function resetSearchResults()
{
	for (var key in searchResults)
		map.removeOverlay(searchResults[key]);
	$('#results ul').empty();
	$('.result-nav').hide();
	searchResults = [];
}

/**
 * Updates the result page and grabs the next set of data
 * @param {Integer} page
 */
function updateResultsPage(page) 
{
	current_results_page = page;
	runSearch();
}

/**
 * resets the number of items to show links
 */
function resetResultSizeLinks() 
{
	$('#size-15').find('span').hide();
	$('#size-15').find('a').show();
	
	$('#size-20').find('span').hide();
	$('#size-20').find('a').show();
	
	$('#size-'+current_results_size).find('a').hide();
	$('#size-'+current_results_size).find('span').show();

}

/**
 * sets the new size of results returned and runs the new search
 * @param {Integer} size
 */
function newResultSize(size) 
{
	current_results_size=size;
	resetResultSizeLinks();
	runSearch();
	return false;
}

/**
 * Sets up and displays number of results showing and total results
 * @param {Integer} count
 */
function setupSearchQuery(count) 
{
	if(count > 0) $("#no-results").hide();
	// setup local vars
	var page_size = current_results_size;
	var page_start = (current_results_page -1) * page_size +1;
	var page_end = Math.min(current_results_page * page_size|0, count);
	
	// setup link for current search
	var search_link = $.create("a").attr("href", "?"+current_search_type+"="+current_search);
	var search_link_text;
	if (current_search_type == "search" || current_search_type == "tag") search_link_text = current_search;
	if (current_search_type == "id") current_search_text = "location number "+current_search;
	search_link.text(search_link_text);
	
	var options = $("#result-query").empty();
	options.append($.create("span").text("Results "));
	options.append($.create('span').addClass('bold').text(page_start + ' - ' + page_end));
	options.append($.create('span').text(' of '));
	options.append($.create('span').addClass('bold').text(count));
	options.append($.create('span').text(' for '));
	options.append(search_link);
	
	if(count > 0) $('#result-options').show();
	$('.result-nav').show();
}

/**
 * Function to build navigation for the number of search pages
 * @param {Integer} count
 */
function setupSearchPages(count)
{
	var result_nav = $('.result-nav');
	result_nav.empty();

	var page_size = current_results_size;
	var page = current_results_page;
	var num_pages = Math.ceil(count/page_size);
	var max_page = Math.ceil(count/page_size);
	if (max_page < 2) return;

	if (current_results_page > 1)
		result_nav.append($.create('li').addClass('prev').append($.create('a').attr('href', '#').text('Prev').click(function() {
			updateResultsPage(current_results_page-1);
			return false;
		})));

	var start = Math.max(current_results_page-3, 1);
	var end = Math.min(current_results_page+3, max_page);

	for (var i = start; i <= end; i++) {
		var li = $.create('li');
		if (i != current_results_page) {
			var a = $.create('a').attr('href', '#').text(i).click(function() {
				updateResultsPage(parseInt($(this).text()));
				return false;
			});
			li.append(a);
		}
		else
			li.addClass('selected-page').text(i);
		result_nav.append(li);
	}

	if (current_results_page < max_page)
		result_nav.append($.create('li').addClass('next').append($.create('a').attr('href', '#').text('Next').click(function() {
			updateResultsPage(current_results_page+1);
			return false;
		})));
}

function createQuickMenu () {
	var ql = new Array();
	ql[0] = new createLinks('Admissions','admissions');
	ql[1] = new createLinks('Computing','lab');
	ql[2] = new createLinks('Residences','coed');
	ql[3] = new createLinks('Dining','dining');
	ql[4] = new createLinks('Sports and Recreation','athletics');
	ql[5] = new createLinks('Parking','parking');
	
	
	for(var j=0; j < ql.length; j++) {
		addQuickLinks(ql[j]);
	}
}

function addQuickLinks (linkData)
{
	// build marker list item
	var item = $.create("li");
	
	// function to start a new search
	var openLinkTop = function() {
		newSearch(linkData.link,'search',1);
		return false;
	}
	
	var menuItem = $.create('a').attr('href', './?search='+linkData.link).click(openLinkTop).text(linkData.name);
	item.append(menuItem);
	$('#ql').append(item);
}