$(document).ready(function() {
	Suddenly.init();
});
var debug = true;
var suddenlySearch;
var currentInfoWin;
var Suddenly =  {
	init: function() { 
		this.Map.init();
		this.Interaction.init();
		this.linkHandler.init();
                this.loadContent.armSectionTitle();
                this.mapControls.init();
                this.ui.init();
 	},
        ui : {
            init: function() {
                $(".mainnav a, #eventsAll, a.readMore").button();
                $(".mainnav").buttonset();

                $('.accordion').accordion({autoHeight: false});
            }
        },
	appState: {
		showMap: true,
		theMap: '',
		initialMapLoad: true,
		initialInterfaceHeight: '',
		theMapShowing: false,
		windowTop: 0,
		firstTime: {
		    tip: '',
		    mapLoaded: true
		},
		currentPageToLoad: '',
		currentEventElement: ''
	},
	linkHandler: {
		init: function() {
			$("a[rel!=control]").live('click', function(e) {
                               // $.address.value($(this).attr('href'));
				e.preventDefault();
				Suddenly.linkHandler.handle(this);
			});
		},
		handle: function(el) {
			rel = $(el).attr('rel');
			if(rel == 'event' ) {
				Suddenly.linkHandler.eventLinks(el);
			} else if (rel == 'news') {
				Suddenly.linkHandler.newsLinks(el);
			} else {
				Suddenly.linkHandler.interiorPage(el);
			}          
		},
		eventLinks: function(el) {				
                                  url = $(el).attr('href');
                                  Suddenly.loadContent.init('event', url);
		},
		modalLoad: function() {

			Suddenly.Map.center(o.Lat, o.Long);
		},
		modalCustomize: function() {
			$('#cBoxTitle').append('Loading...');
			$('#cBoxClose').hide();
		},
		interiorPage: function(el) {
			url = $(el).attr('href');
			Suddenly.loadContent.init(null, url);
		},
		newsLinks: function(el) {
			url = $(el).attr('href');
			Suddenly.loadContent.init("news", url);
		}
	},
	Interaction : {
		init: function() {
			this.mapState();
		//	this.toolTips();
		//	this.aboutTip();
			this.buttons();
			this.slides();
		},
		slides: function() {
			$("a[rel='gallery']").colorbox({transition:"elastic", width: "800px"});
		},
		buttons: function() {
			$("#mapBack").live('click', function(e) {
				Suddenly.Map.hide();
				Suddenly.appState.theMapShowing = false;
			});
		},
		aboutTip: function() {
			$('.nav li.about').qtip({
				api: {
				   onRender: function() {
						Suddenly.appState.firstTime.tip = this.elements.tooltip;
						setTimeout("$(Suddenly.appState.firstTime.tip).fadeOut(500);", 3000);
				   }
				},
				hide: {
					fixed: true
				},
				content: 'First time here? Click here to learn about this site and how to use it...',
				show: { 
					ready: true 
				},
				position: {
				corner: {
						target: 'leftMiddle',
						tooltip: 'rightMiddle'
					}
				},
				style: { 
					width: 200,
					'font-size': '14px',
					textAlign: 'left',
					border: {
						width: 7,
						radius: 5
					},
					tip: 'rightMiddle',
					name: 'light' // Inherit the rest of the attributes from the preset dark style
				}	
			});
		},
		toolTips: function() {
			$('li.eventItem').qtip({
				api: {
				   onRender: function() {
						theDate = this.elements.target.children('span.startDate').html();
					    this.elements.content.html(theDate);
				   }
				},
				show: 'mouseover',
				hide: 'mouseout',
				style: {
					tip: 'rightMiddle',
					width: 120,
					padding: 5,
					color: '#666',
					background: 'white',
					border: {
						width: 7,
						radius: 5,
						color: 'white'
					}
				},
				position: {
					corner: {
						target: 'leftMiddle',
						tooltip: 'rightMiddle'
					}
				}
			});	
		},
		mapState: function() {
			// Set up hover stuff
			$("#cboxOverlay > *").hover(
				function () {
					Suddenly.appState.showMap = false;	
				}, 
				function () {
					Suddenly.appState.showMap = true;
				});
			$("body").live("click", function() {
				if(Suddenly.appState.showMap) {
					Suddenly.Map.reveal();
				}
			});
			$("#Main > *").hover(
				function () {
					Suddenly.appState.showMap = false;	
				}, 
				function () {
					Suddenly.appState.showMap = true;
				});
		},
		scrollWindows: function() {
			sw = $('.lists .events ul').scrollWindow();
		}
	},
	Interface: {
		init: function() {
			if(Suddenly.appState.initialMapLoad) {
				this.openInterface();
			}
		},
		openInterface: function(height) {
			
			set = Suddenly.Interface.setHeight();
			Suddenly.Interface.openMiddle(set);			
			Suddenly.appState.initialMapLoad = false;
		},
		setHeight: function(yVal) {
			if(!yVal){
				h = $("#Interface").height();
				m = $(".boxMiddle").height();
				set = h+m;
				Suddenly.appState.initialInterfaceHeight = set;
			} else {
				set = height;
			}
			
			return set;
		},
		openMiddle: function(heightVal) {
			$(".boxMiddle").animate({
					height: heightVal
				}, 500, function() {
				$(".boxMiddle").css("height", "auto");
				Suddenly.Interface.showInterface();
				$('#Window').scrollTop(Suddenly.appState.windowTop);
			});
		},
		showInterface: function() {
			$("#Interface").css("visibility", "visible");
		}
	},
	Map: {
		init: function() {
			if (GBrowserIsCompatible()) {
			    Suddenly.appState.theMap = new GMap2(document.getElementById("Map"));
				GEvent.addListener(Suddenly.appState.theMap, "tilesloaded", function() {
					if(Suddenly.appState.initialMapLoad) {
						Suddenly.Events.init();
					}	
				});
				
			    Suddenly.appState.theMap.addMapType(G_SATELLITE_3D_MAP);
			    Suddenly.appState.theMap.setCenter(new GLatLng(39.50, -98.35), 3);
				Suddenly.appState.theMap.setMapType(G_SATELLITE_MAP);
				Suddenly.appState.theMap.enableDoubleClickZoom();
				Suddenly.appState.theMap.enableContinuousZoom();	
			}
			
		},
		theMapLoaded: function() {
			if(!Suddenly.appState.firstTime.mapLoaded) {
				if(Suddenly.appState.transitionMapShowing) {
						$("#transitionMap").css("display", "none");
						$("#Map").css("display", "none");		
						$("#Map").css("visibility", "visible");
						$("#Map").show(100);
						Suddenly.appState.theMapShowing = true;
				}
			} 
		},
		reveal: function() {
			if(!Suddenly.appState.theMapShowing) {	
				Suddenly.appState.windowTop = $('#Window').scrollTop();
				$('#Window').scrollTop(0);
				$(".boxMiddle").animate({height: "73px"}, 200, function() {
					$("#MapUtility").show();
				});
				$("#Content > *").hide();
				$("#Content .header").show();
				$("#Window").css(
					{	
						'height': '170px',
						'overflow-y': 'hidden'
				});
				Suddenly.appState.theMapShowing = true;
			}
		},
		hide: function() {
			$("#MapUtility").hide();
			$("#Content > *").show();
			$("#Window").css(
				{	
					'height': '100%',
					'overflow-y': 'scroll'
				});
			Suddenly.Interface.openInterface(Suddenly.appState.initialInterfaceHeight);
		},
		center: function(lat,lng) {
			Suddenly.appState.theMap.setCenter(new GLatLng(lat, lng), 13);
		},
		Markers: {
			init: function() {
				$.each(Suddenly.Events.index, function() {
					if(this.Lat && this.Long) {
						var point = new GLatLng(this.Lat, this.Long);
						var marker = new GMarker(point);
						var markerId = this.ID;
						Suddenly.appState.theMap.addOverlay(marker);
						GEvent.addListener(marker, "click", function() {
                                                    if(currentInfoWin) {
                                                        Suddenly.appState.theMap.removeOverlay(currentInfoWin);
                                                    }
                                                    Suddenly.appState.theMap.setCenter(point);
                                                    currentInfoWin = new SuddenlyOverlay(point, markerId);
						    Suddenly.appState.theMap.addOverlay(currentInfoWin);
						});
					}
				});
			}
		}
	},
        mapControls: {
            init: function() {
                this.zoomControl();
            },
            zoomControl: function() {
                $('#zoomIn').bind('click', function() {
                        Suddenly.appState.theMap.zoomIn();
                });

                $('#zoomOut').bind('click', function() {
                        Suddenly.appState.theMap.zoomOut();
                });
            }
        },
	Events: {
		index: '',
		eventsAnchorSel: '.events .content .items ul li a',
		init: function() {
			this.getData();
			//this.bind();
		},
		getData: function() {
			$.getJSON('/api/v1/LocationNode', function(data){
                            
			   Suddenly.Events.index = data.items;
				Suddenly.Interface.init();
				Suddenly.Map.Markers.init();
			});
		},
		getById: function(id) {
			var event = '';
			$.each(this.index, function() {
				if(id == this.ID) {
					event = this;
				}
			});
			return event;
		},
		getDateById: function(id) {	
			eventSel = '#Event-'+id;
			return $(eventSel).siblings('span.startDate').html();
		}
	},
	loadContent: {
		pageInitialized: true,
		pageAlreadyOpen: false,
		init: function(context, url) {
			if(context == 'event') {
                                this.openOverlay();
				Suddenly.appState.currentPageToLoad = url;
				this.openPage();
			} else if (context == 'news') {
				this.openOverlay();
				Suddenly.appState.currentPageToLoad = url;
				this.openPage();
			} else {

				this.openOverlay();
				Suddenly.appState.currentPageToLoad = url+'/content';
				this.openPage();
			}
		},
		openOverlay: function() {
			$.fn.colorbox({
                                transition: "none",
				inline: true,
				href:"#Loader", 
				overlayClose: false
			});
		},
		event: function(id) {
			$('.lists h2').addClass('active');
		},
		interior: function(el) {
			url = $(el).attr('href');
			this.loadByURLSegment(url);
		},
		armSectionTitle: function() {
			
				$('.lists .headers h2.sectionTitle a').bind('click', function(e){
					e.preventDefault();

					if( $('#ListsContent').css("display") == "block" ) { 
						$('#ListsContent').slideUp(function() {
                                                        $('.lists .headers h2.sectionTitle a').removeClass("open").addClass("closed");
							Suddenly.loadContent.pageInitialized = true;
						});
					}
				
					if($('#ListsContent').css("display") == "none" ) {
						$('#ListsContent').slideDown(function() {
                                                     $('.lists .headers h2.sectionTitle a').removeClass("closed").addClass("open");
							Suddenly.loadContent.pageInitialized = true;
						});
					}
				return false;
				});
			
		},
		openPage: function() {
			e = $('#ListsContent');
			if(e.css('display') == 'block') {
				e.slideUp(500, function() {
					Suddenly.loadContent.emptyPage();
				});
			} else {
				Suddenly.loadContent.emptyPage();
			}

		},
		loadByURLSegment: function(seg) {
			$('.lists .events .content').hide(50, function() {
				$('.lists h2').addClass('active');
			});
			Suddenly.loadContent.emptyPage();
			// load the page content and slap it in.
			apiCall = '/api/v1/Page/?URLSegment=about';
			o = jQuery.getJSON(apiCall)
			$('#Page').slideDown(1000);
//			this.armSectionTitle();
		},
		loadPage: function() {
			this.loadDirections();
		},
                buildDirectionsCall: function() {
                   seg = Suddenly.appState.currentPageToLoad;
                   url = seg.replace('content', 'directions');
			return url;
                },
		buildMetaCall: function() {
			seg = Suddenly.appState.currentPageToLoad;
			url = seg.replace('content', 'meta');
                        url = url+'/?flush=1';
			return url;
		},
		buildMainContentCall: function() {
			url = Suddenly.appState.currentPageToLoad;
			url = url+'/?flush=1';
			return url;
		},
		buildSideBarCall: function() {
			seg = Suddenly.appState.currentPageToLoad;
			url = seg.replace('content', 'related');
			url = url+'/?flush=1';
			return url;
		},
                loadDirections: function() {
                    call = this.buildDirectionsCall();
			$.getJSON(call, function(data) {
                                if(data.Lat && data.Long) {
                                    Suddenly.Map.center(data.Lat,data.Long);
                                }
			});
                        Suddenly.loadContent.loadMeta();
                },
		loadMeta: function() {
			call = this.buildMetaCall();
			$.get(call, function(data) {
				$('#Page .left .sideBarMiddle').append(data);				
				$('.left .sideBarMiddle .inner').slideDown(500);
				Suddenly.loadContent.loadMainContent();
			});
		},
		loadMainContent: function() {
			call = this.buildMainContentCall();
			$.get(call, function(data) {
				$('#Page .middle .inner').append(data);				
				$('#Page .middle .inner').slideDown(500);
				Suddenly.loadContent.loadSideBar();
			});
		},
		loadSideBar: function() {
			call = this.buildSideBarCall();
			$.get(call, function(data) {
                               
				$('#Page .right .sideBarMiddleRight').append(data);
				Suddenly.loadContent.doAfterSideBar();
				$('.sideBarMiddleRight .inner').slideDown(500, function() {
					    
				});
                                Suddenly.ui.init();
                                $.fn.colorbox.close();
//                                Suddenly.linkHandler.init();
			});
		},
		doAfterSideBar: function() {
			//makes sure that ligthbox works on related images
			Suddenly.Interaction.slides();
		},
		emptyPage: function() {
			Suddenly.loadContent.clearMeta();
		},
		clearMeta: function() {
			if($('.left .sideBarMiddle .inner')) { 
				$('.left .sideBarMiddle .inner').slideUp(250, function() {
				    $('.sideBarMiddle').css("display", "inline-block");
					$('.left .sideBarMiddle').empty();
					Suddenly.loadContent.clearMainContent();
				});
			}
			
		},
		clearMainContent: function() {
			if($('.middle .inner')) {
				$('.middle .inner').slideUp(250, function() {
				    $('.middle').css("display", "inline-block");
					$('.middle .inner').empty();
					Suddenly.loadContent.clearSideBar();
				});
			}
		},
		clearSideBar: function() {
			if($('.sideBarMiddleRight .inner')) {
				$('.sideBarMiddleRight .inner').slideUp(250, function() {
				    $('.sideBarMiddleRight').css("display", "inline-block");
					$('.sideBarMiddleRight').empty();
					Suddenly.loadContent.afterClear();
				});
			}
		},
		afterClear: function() {
			this.loadPage();
			if(!this.pageAlreadyOpen) {
				$('#Page').slideDown();	
				this.pageAlreadyOpen = true;
			}
//			this.armSectionTitle();
		}
	},
	searchBox: function() {
		suddenlySearch = new google.search.WebSearch();
		suddenlySearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
		suddenlySearch.setSearchCompleteCallback(this, Suddenly.searchExecute, null);
		
	},
	searchExecute: function() {
		results = suddenlySearch.results;
    	for (var i = 0; i < results.length; i++) {
      	// For each result write it's title and image to the screen
      		 result = results[i];
      	}	
	}
}

function SuddenlyOverlay(point, id) {
    this.point_ = point;
    this.id_ = id;
}

SuddenlyOverlay.prototype = new GOverlay();

SuddenlyOverlay.prototype.initialize = function(map) {
    
    var div = document.createElement("div");
    div.style.position = "absolute";
    div.style.display = "block";
    div.id = "SuddenlyOverlay";

    	var top = document.createElement("div");
top.className = "top";

var content = document.createElement("div");
content.className = "content";

var bottom = document.createElement("div");
bottom.className = "bottom";

var close = document.createElement("div");
close.className = 'close';

content.appendChild(close);

var loader = document.createElement("div");
loader.className = 'loading';

html = $("#MapLoader").html();
$(loader).append(html);
$(content).append(loader);

div.appendChild(top);
div.appendChild(content);
div.appendChild(bottom);
Suddenly.appState.theMap.getPane(G_MAP_FLOAT_PANE).appendChild(div);

$(close).bind('click', function() {
    Suddenly.appState.theMap.removeOverlay(currentInfoWin);
 });

call = '/locations/mapcontent/'+this.id_+"/?flush=1";
$.get(call, function(data) {
        $("#SuddenlyOverlay .content .loading").hide();
	$("#SuddenlyOverlay .content").append(data);
	 $("#SuddenlyOverlay a").bind('click', function(e) {
	     e.preventDefault();
	     Suddenly.appState.theMap.removeOverlay(currentInfoWin);
	     Suddenly.Map.hide();
	     Suddenly.appState.theMapShowing = false;
	     Suddenly.linkHandler.handle(this);
	 });
});
    this.map_ = Suddenly.appState.theMap;
    this.div_ = div;
}

SuddenlyOverlay.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}


SuddenlyOverlay.prototype.copy = function() {
    return new SuddenlyOverlay(this.point_);
}

SuddenlyOverlay.prototype.redraw = function(force) {
    if (!force) return;
    var c1 = this.map_.fromLatLngToDivPixel(this.point_);
    c1y = c1.y-47;
    this.div_.style.left = c1.x-240 + "px";
    this.div_.style.bottom = "-"+c1y + "px";

}