var map;
var showcampus = true; // variable that determines whether to show the campus overlay on google maps of not.

function initGmap(jsonForcedCoordinates, extraKmlFile) {
	//----- Stop page scrolling if wheel over map ----
	if (GBrowserIsCompatible()) {
		// We define the function first
		function TextualControls() {
		}
		
		// To "subclass" the GControl, we set the prototype object to
		// an instance of the GControl object
		TextualControls.prototype = new GControl();
		
		// Creates one DIV for each of the buttons and places them in a container
		// DIV which is returned as our control element. We add the control to
		// to the map container and return the element for the map class to
		// position properly.
		TextualControls.prototype.initialize = function(map) {
		  var container = document.createElement("div");
		  container.style.zIndex = 0;
		
		  var zoomOutDiv = document.createElement("div");
		  zoomOutDiv.className = "map_zoom_button map_zoom_out";
		  zoomOutDiv.setAttribute('href', '#');
		  this.setButtonStyle_(zoomOutDiv);
		  container.appendChild(zoomOutDiv);
		  zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
		  GEvent.addDomListener(zoomOutDiv, "click", function(e) {
			map.zoomOut();
			//e.preventDefault();
		  });
		
		  var zoomInDiv = document.createElement("div");
		  zoomInDiv.className = "map_zoom_button map_zoom_in";
		  zoomInDiv.setAttribute('href', '#');
		  this.setButtonStyle_(zoomInDiv);
		  container.appendChild(zoomInDiv);
		  zoomInDiv.appendChild(document.createTextNode("Zoom In"));
		  GEvent.addDomListener(zoomInDiv, "click", function(e) {
			map.zoomIn();
			//e.preventDefault();
		  });
		  
		  var panUpDiv = document.createElement("div");
		  panUpDiv.className = "map_pan_button map_pan_up";
		  panUpDiv.setAttribute('href', '#');
		  this.setButtonStyle_(panUpDiv);
		  container.appendChild(panUpDiv);
		  panUpDiv.appendChild(document.createTextNode("Pan Up"));
		  GEvent.addDomListener(panUpDiv, "click", function(e) {
			map.panDirection(0,1);
			//e.preventDefault();
		  });
		  
		  var panDownDiv = document.createElement("div");
		  panDownDiv.className = "map_pan_button map_pan_down";
		  panDownDiv.setAttribute('href', '#');
		  this.setButtonStyle_(panDownDiv);
		  container.appendChild(panDownDiv);
		  panDownDiv.appendChild(document.createTextNode("Pan Down"));
		  GEvent.addDomListener(panDownDiv, "click", function(e) {
			map.panDirection(0,-1);
			//e.preventDefault();
		  });
		  
		  var panLeftDiv = document.createElement("div");
		  panLeftDiv.className = "map_pan_button map_pan_left";
		  panLeftDiv.setAttribute('href', '#');
		  this.setButtonStyle_(panLeftDiv);
		  container.appendChild(panLeftDiv);
		  panLeftDiv.appendChild(document.createTextNode("Pan Left"));
		  GEvent.addDomListener(panLeftDiv, "click", function(e) {
		    map.panDirection(1, 0);
			//e.preventDefault();
		  });
		  
		  var panRightDiv = document.createElement("div");
		  panRightDiv.className = "map_pan_button map_pan_right";
		  panRightDiv.setAttribute('href', '#');
		  this.setButtonStyle_(panRightDiv);
		  container.appendChild(panRightDiv);
		  panRightDiv.appendChild(document.createTextNode("Pan Right"));
		  GEvent.addDomListener(panRightDiv, "click", function(e) {
			map.panDirection(-1,0);
			//e.preventDefault();
		  });
		
		  map.getContainer().appendChild(container);
		  return container;
		}
		
		// By default, the control will appear in the top left corner of the
		// map with 7 pixels of padding.
		TextualControls.prototype.getDefaultPosition = function() {
		  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
		}
		
		// Sets the proper CSS for the given button element.
		TextualControls.prototype.setButtonStyle_ = function(button) {
		  //button.style.textDecoration = "underline";
		  //button.style.color = "#0000cc";
		  //button.style.backgroundColor = "white";
		  //button.style.font = "small Arial";
		  //button.style.border = "1px solid black";
		  //button.style.padding = "2px";
		  //button.style.marginBottom = "3px";
		  //button.style.textAlign = "center";
		  //button.style.background = "transparent url(gWayfindingImgBase + '/wayfinding/zoom_bg.png') no-repeat 0 0";
		  //button.style.width = "35px";
		  //button.style.height = "36px";
		  //button.style.cursor = "pointer";
		  //button.style.float = "left";
		}
	
	
		map = new GMap2(document.getElementById("wayfinding_map"));
		
		// Set map center and zoom for Driving Directions 
        var lat = 41.448182;
        var lon = -81.706924;
        var zoom = 10;
        
        if (window.location.href.indexOf("main-campus/around-campus") > 0) {
            zoom = 16;
            lat = 41.502473048987596;
            lon = -81.620139;
        }
        if ((window.location.href.indexOf("ohio/driving-directions") > 0) || (window.location.href.indexOf("ohio/locations") > 0)) {
            zoom = 8;
            lat = 40.95543634999999;
            lon = -81.83710935
        }
        if ((window.location.href.indexOf("national/driving-directions") > 0) || (window.location.href.indexOf("national/locations") > 0)) {
            zoom = 4;
            lat = 33.7816267;
            lon = -97.6052597
        }
        if ((window.location.href.indexOf("international/driving-directions") > 0) || (window.location.href.indexOf("international/locations") > 0)) {
		    zoom = 2;
		    lat = 34.061821425;
		    lon = -30.392020199999997
		}
		
		if (jsonForcedCoordinates && jsonForcedCoordinates.IsForcedCoordinates) {
		    if (jsonForcedCoordinates.Latitude != null)
		        lat = jsonForcedCoordinates.Latitude;
    	    if (jsonForcedCoordinates.Longitude != null)
    	        lon = jsonForcedCoordinates.Longitude;
    	    if (zoom != 0)
    	        zoom = jsonForcedCoordinates.ZoomLevel;
		}
		
		map.setCenter(new GLatLng(lat,lon ),zoom );
		map.enableScrollWheelZoom();
		//map.setUIToDefault();
		//map.addControl(new GLargeMapControl3D());
		//map.addControl(new GLargeMapControl());
		//map.addControl(new GSmallMapControl());
		//map.addControl(new GSmallZoomControl3D());
		//map.addControl(new GScaleControl());
		
		map.addControl(new TextualControls());
		
		//Campus overlay from Russ at CCF
		if (showcampus) {
			var geoXml = new GGeoXml("http://my.clevelandclinic.org/radiology/documents/Cleveland_Clinic_Main_Hospital_Campus.kml");
			map.addOverlay(geoXml);

			if (typeof (extraKmlFile) != 'undefined') {
			    var geoXml2 = new GGeoXml(extraKmlFile);
			    map.addOverlay(geoXml2);
			}
		}		
	}
}

function initAccordians() {
	
	$('.accordian_wrapper').each(function(){
	
		var animationSpeed = 300;
		
		var $wrapper = $(this);
		var $triggers = $('.accordian_trigger', this);
		var $content = $('.accordian_content', this);
		
		// Hides all of the information on page load
		$content.hide();
		$("div#facility_content").show();
		
		$content.addClass("group");
	
		// Makes the entire trigger clickable and start subsequent function
		$triggers.click(function(){
		
			updateAccordionFilters($triggers);
		
			// Upon clicking the information for the department will expand down
			$(this).next(".accordian_content").slideToggle(animationSpeed).siblings(".accordian_content").slideUp(animationSpeed);
			// This adds the 'active' class to the div changing plus to a minus
			$(this).toggleClass("active");
			// This removes the 'active' class when another institute is clicked
			$(this).siblings(".accordian_trigger").removeClass("active");
			
			if( $(this).hasClass("active") ) {
				// accordian opening
			
				$("span.active_filters", this).fadeOut(animationSpeed);
				$(this).siblings("h3").find("span.active_filters").fadeIn(animationSpeed);
			}
		});
	
		$("div#wayfindingLocationFilters h3").hover(function(){
			$(this).addClass("hover");
		}, function() {
			$(this).removeClass("hover");	
		});

	});
}

function updateAccordionFilters($triggers) {
	
	var maxString = 64;
	var animationSpeed = 300;
	
	$triggers.each(function(){
		var newText = 'click to select';
		var $checkedFilters = $(this).next('.filters_info_box').find('input:checked');
		
		if ( $checkedFilters.length ) {
			newText = '( ';
			$checkedFilters.each(function(i){
				if(i > 0) {
					newText = newText + ', ';
				}
				newText = newText + $(this).val();
			});
			newText = newText + ' )';
		}
		
		if( newText.length > maxString ) {
			newText = newText.substr(0,(maxString-4)) + '... )';
		}
		
		$("span.active_filters", this).text(newText).fadeIn(animationSpeed);
	});

}

function flashMovie(movieName){  
	if(window.document[movieName]){  
		return window.document[movieName];  
	}else{  
		return document.getElementById(movieName);    
	}      
}

function launchTourFromFlash(tourURL) {
	$("#TB_window").remove();
	$("body").append("<div id='TB_window'></div>");
	tb_show('', tourURL + '?KeepThis=true&TB_iframe=true&height=530&width=930', '');
}

function launchTourFromStandalone(tourURL) {
	$("#TB_window").remove();
	$("body").append("<div id='TB_window'></div>");
	tb_show('', tourURL + '?KeepThis=true&TB_iframe=true&height=530&width=930', '');
}


function initFmap() {
	
	var $controls = $('#mapControl');
	
	//Show All Points of Interest
	$("input[type=checkbox]", $controls).change( function() {
		if( $(this).is(':checked') ){
			//alert('show this');
			flashMovie("main_campus_map").showCategory( $(this).val() );
		}else{
			//alert('hide this');
			flashMovie("main_campus_map").hideCategory( $(this).val() );
		}
	})
	.click(function(){ //Fix for change event not firing in IE
		$(this).change();
	}).next('label').click(function(){
		$(this).prev('input').change();
	});
	
	//Show building
	$('a.building', $controls).hoverIntent(
		function(){
			flashMovie("main_campus_map").activateBuilding( $(this).attr('rel') );
		},
		function(){
			flashMovie("main_campus_map").deactivateBuilding( $(this).attr('rel') );
		}
	);
	
	$('a.building').click(function(){ 
		flashMovie("main_campus_map").showBuildingOverlay( $(this).attr('rel') );
		return false;
	});	
	
	//Toggle Abbreviations
	$('#toggleBuildingAbbr', $controls).change( function() {
		if( $(this).is(':checked') ){
			flashMovie('main_campus_map').toggleBuildingAbbr( 'true' );
		}else{
			flashMovie('main_campus_map').toggleBuildingAbbr( 'false' );
		}
	});
	
}

function mousewheelFix() {

	$('#main_campus_map_wrapper').hover(
		
		function(){
			//alert('rollover map');
			
			$('#main_campus_map_wrapper').bind('mousewheel', function(event, delta){
				//alert( typeof( flashMovie('main_campus_map').externalZoom ) );
				flashMovie('main_campus_map').externalZoom(delta);
				event.preventDefault();
			});
			
		},
		function(){
			//alert('rolloff map');
			
			$('#main_campus_map_wrapper').unbind('mousewheel');
			
		}
	
	);
	
	// deactivate mousewheel on virtual tour overlay
	$('#TB_overlay, #TB_window, body').bind('mousewheel', function(event, delta){
		//alert( $(event.target).attr('id') );
		if ( ($(event.target).attr('id') == 'TB_overlay') || ($(event.target).attr('id') == 'TB_window') ) {
			event.preventDefault();
		}
	});

}

function initBuildingOverlayLinks() {
	var $ajaxHolder =$('<div id="ajaxHolder"></div>').css({ display: 'none' });
	$('body').append($ajaxHolder);
	
	$('.buildingOverlayCall').each(function(){
		var contentUrl = $(this).attr('href') + ' #building-overlay';
		
		$(this).click(function(event){
			$('#ajaxHolder').load(contentUrl, {}, function(){
				tb_show('', '#TB_inline?&height=355&width=814&inlineId=ajaxHolder');
				// this moves the green "X" button to sit inside the window corner for standalone building-overlays only
				$('#TB_window').css("background","transparent");
				$('#TB_closeAjaxWindow').css("right","7px");
				$('#TB_closeAjaxWindow').css("top","13px");
			});
			event.preventDefault();
		});
		
	});
}

function stripeTables() {
	
	$('table.zebra').each(function(i){
		$('tbody tr:visible', this).removeClass('odd').removeClass('even');
		$('tbody tr:visible:even', this).addClass('odd');
		$('tbody tr:visible:odd', this).addClass('even');
	});
}

function initDrivingDirections() {
	var instrText = 'Enter your Address, City, State, Zip';
	var instrCSS = { color: '#999', fontStyle: 'italic'}
	var regCSS = { color: '#000', fontStyle: 'normal'}

	if ($('#get_directions .fromAddress').val() == '') {

	    $('#get_directions .fromAddress').val(instrText)
	    .css(instrCSS).click(function() {

	        if ($(this).val() == instrText) {
	            $(this).val('').css(regCSS);
	        }

	    }).blur(function() {

	        if ($(this).val() == '') {
	            $(this).val(instrText).css(instrCSS);
	        }

	    });
	}
}


function checkboxTOGGLR() {
	$('#mapControl input:checked').each(function(){
		// added to uncheck all checkboxes if the user hits the back button to the page
		$(this).attr('checked', false);
	});
}

function fixVirtualTourLinks() {
    $("a[href$=virttour],area[href$=virttour]").each(function() {
        var firstCharIdx = this.href.indexOf("/", 8) + 1;
        if (firstCharIdx > 0) {
            var tourId = this.href.substring(firstCharIdx, this.href.length - 9);
            this.href = 'javascript:launchTourFromFlash("/virtualtours/' + tourId + '/default.aspx?iframe")';
        }
    });
}
$(document).ready(function() {

    checkboxTOGGLR();

    if ($('.accordian_wrapper').length) {
        initAccordians();
    }
    if ($('#wayfinding_map').length && GBrowserIsCompatible()) {

        // Initialize the map from these pages in case there is a lat/long/zoom passed
        // this way we do not set the map center twice.
        if (!(window.location.href.indexOf("main-campus/around-campus") > 0) &&
            !(window.location.href.indexOf("ohio/locations") > 0) &&
            !(window.location.href.indexOf("national/locations") > 0) &&
            !(window.location.href.indexOf("international/locations") > 0)
            ) {
            initGmap();
        }
    }
    if ($('#main_campus_map').length) {
        initFmap();
    }

    mousewheelFix();

    if ($('.buildingOverlayCall').length) {
        initBuildingOverlayLinks();
    }

    fixVirtualTourLinks();
    stripeTables();

});


