$(function() {
	//if ($.urlParam("title") != "") {
		$("#title").val($.urlParam("title"));
		$("#firstName").val($.urlParam("firstName"));
		$("#lastName").val($.urlParam("lastName"));
		$("#DOB1").val($.urlParam("DOB1"));
		$("#DOB2").val($.urlParam("DOB2"));
		$("#DOB3").val($.urlParam("DOB3"));
		$("#email").val(unescape($.urlParam("email")));
		$("#gender").val($.urlParam("gender"));
	//}
});

$(document).ready(function(){
						   
	//activate cufon
	var light = "Akzidenz Std Light";
	var regular = "Akzidenz Std Regular"; 
	Cufon.replace(".contactInfo h2", { letterSpacing: '-1px', fontFamily: regular });
	Cufon.replace(".contactInfo h2 .secondary", { letterSpacing: '-1px', fontFamily: light });
	
	Cufon.replace(".event_description .event_name", { letterSpacing: '-1px', fontFamily: regular });
	Cufon.replace(".event_description .event_type", { letterSpacing: '-1px', fontFamily: regular });
	Cufon.replace(".event_description .event_date", { letterSpacing: '-1px', fontFamily: regular });
	
	//calendarController.createCalendarDays();
	//Activate Calendar Controler
	$('#calendarControls span').click(function(){
		calendarController.dateControl(this); 
	});
	
	//iFrame integration: Get sourceId from query string
	if ($.urlParam("sourceId") != null && $.urlParam("sourceId") == "" && $.urlParam("sourceId") != 0) {
		$("#sourceId").val($.urlParam("sourceId"));
	}

	//Activate Facebook Connect
	//setFBconnect();
	
	// create calendar
	calendarController.createCalendarDays();
	
	var dateControl = function(objClicked){
		$(".calendarZooms").empty();
		if($(objClicked).hasClass('controlRight')){ // NEXT
			if(calendarController.month < 11)
				calendarController.month++;
			else{ 
				calendarController.month = 0;
				calendarController.year++;
			}
			calendarController.createCalendarDays();
			// particular events  at venue
			for (i=0; i<eventData.length; i++) {
				venue = eventData[i];
				calendarController.activateCalendar(venue);
			}
			
		}
		else{ // PREV
			if(calendarController.month > 0)
				calendarController.month--;
			else{
				calendarController.month = 11;
				calendarController.year--;
			}
		
			calendarController.createCalendarDays();
			// particular events  at venue
			for (i=0; i<eventData.length; i++) {
				venue = eventData[i];
				calendarController.activateCalendar(venue);
			}
		}
		
		// gotta recal stuff from callback function
		// callback will only run these things ONCE
		// dateControl function will reactivate the calendar
		
		// what is my city?
		var myCity = $(".selected-city").text();
		
		$(".eventType").each(function() {
			if (myCity !== "All Cities") {
				if ($(this).attr("data-city") != myCity) {
					$(this).hide();
					$(this).parent().removeClass("active");
				} else {
					$(this).show();
					$(this).parent().addClass("active");	
				}
			} else {
				$(this).show();	
				$(this).parent().addClass("active");
			}
		});
		
		// see if any events this month
		anyEventsThisMonth();
	};
	
	var anyEventsThisMonth = function() {
		// see if any events this month
		// if not, display no-events messaging
		var eventDays = 0;
		$(".row div").each(function() {
			if ($(this).hasClass("active")) {
				eventDays = eventDays + 1;	
			}
		});
		if (eventDays == 0) {
			$("#no-events-overlay").fadeIn();
			$("#no-events").fadeIn();
		} else {
			$("#no-events-overlay").fadeOut();
			$("#no-events").fadeOut();	
		}
	};
	
	var goToDefaultMonth = function() {
		// see if any events this month
		// if not, display no-events messaging
		var eventDays = 0;
		$(".row div").each(function() {
			if ($(this).hasClass("active")) {
				eventDays = eventDays + 1;	
			}
		});
		if (eventDays == 0 || calendarController.month == 1) {
			
			$(".calendarZooms").empty();
			if(calendarController.month < 11)
				calendarController.month++;
			else{ 
				calendarController.month = 0;
				calendarController.year++;
			}
			calendarController.createCalendarDays();
			// particular events  at venue
			for (i=0; i<eventData.length; i++) {
				venue = eventData[i];
				calendarController.activateCalendar(venue);
			}
			
			// what is my city?
			var myCity = $(".selected-city").text();
			
			$(".eventType").each(function() {
				if (myCity !== "All Cities") {
					if ($(this).attr("data-city") != myCity) {
						$(this).hide();
						$(this).parent().removeClass("active");
					} else {
						$(this).show();
						$(this).parent().addClass("active");	
					}
				} else {
					$(this).show();	
					$(this).parent().addClass("active");
				}
			});
			
			goToDefaultMonth();
			
		} else {
			$("#no-events-overlay").hide;
			$("#no-events").hide;	
		}
	};
	
	var callback = function(data) { 
		eventData = data.venues;
		eventDataCities = [];
		
		for (i=0; i<eventData.length; i++) {
			venue = eventData[i];
			
			// create list of cities
			justCity = venue.csz.split(",")[0];
			eventDataCities.push(justCity);
			
			calendarController.activateCalendar(venue);
		}
		
		// show/hide city list dropdown
		$('.selected-city').click(function() {
			$(this).next().toggle();								   
		});
		
		// build dropdown on calendar view
		eventDataCities.sort();
		for (i=0; i<eventDataCities.length; i++) {
			$('.event_cities ul').append('<li><a href="#">'+eventDataCities[i]+'</a></li>');	
		}
		
		// be able to swap out items in dropdown as needed
		$('.event_cities ul li a').bind("click", function(e) {
			e.preventDefault();	
			
			// get the new city value
			var newCity = $(this).text();
			
			// show this item back in the UL
			$(".event_cities ul li").show();
			
			// hide the chosen city from the UL
			$(".event_cities ul li a").each(function() {
				if ($(this).text() == newCity) {
					$(this).parent().hide();	
				}
			});									 
			
			// make the chosen LI the selected city value
			$(".selected-city").html(newCity);
			// hide the UL
			$(".event_cities ul").hide();
			
			// hide all events that aren't in this venue's city
			$(".eventType").each(function() {
				if (newCity !== "All Cities") {
					if ($(this).attr("data-city") != newCity) {
						$(this).hide();
						$(this).parent().removeClass("active");
					} else {
						$(this).show();	
						$(this).parent().addClass("active");
					}
				} else {
					$(this).show();
					$(this).parent().addClass("active");	
				}
			});
			
			// check if there are any events this month
			anyEventsThisMonth();
		});
		
		// check to see what city we're coming from
		if ($.urlParam("city") == null || $.urlParam("city") == 0 || $.urlParam("city") == "") {
			var myCity = $('.event_cities ul li a').eq(0).text();	
			$(".selected-city").html(myCity);
			
			// hide "all cities" option from faux dd
			$('.event_cities ul li').eq(0).hide();
		} else {
			var myCity = unescape($.urlParam("city"));
			if (myCity.indexOf("/") > 0) { myCity = myCity.slice(0,-1); }
			$(".event_cities ul li a").each(function() {
				if ($(this).text() == myCity) {
					$(this).parent().hide();	
				}
			});									 
			
			$(".selected-city").html(myCity);
			
			// hide all events that aren't in this venue's city
			$(".eventType").each(function() {
				if ($(this).attr("data-city") != myCity) {
					$(this).hide();
					$(this).parent().removeClass("active");
				}
			});
		}
		
		// see if any events this month
		// if not, display no-events messaging
		//anyEventsThisMonth();
		goToDefaultMonth();
	};
	
	$.ajax({
	   dataType: 'jsonp',
	   jsonp: false,
	   jsonpCallback: 'myFunction',
	   type:'GET',
	   data: {'appId':'05fab807-d5fd-4f41-b714-3a27fa8aafd8','cbm':'myFunction'},
	   url: constant.serverString+'getNestedLocations.ashx',
	   success: callback
	});
	
	$('.controlLeft').click(function() {
		id = $(this).attr('id');
		dateControl("#"+id);
	});
	$('.controlRight').click(function() {
		id = $(this).attr('id');
		dateControl("#"+id);
	});
	
	// CALENDAR ZOOM
	$(".active").live("mouseenter", function() {
		$('.calendarZoom').hide();
		$('.zoom_In').removeClass('zoom_In');
		pos = $(this).position();
		id = $(this).data("day");
		$('#zoom_'+id).css({'top': pos.top-10, 'left': pos.left-23});
		$('#zoom_'+id).addClass('zoom_In');
		//$('#zoom_'+id).show();
		
		var myCity = $(".selected-city").text();
		if (myCity !== "All Cities") {
			if ($('#zoom_'+id).attr("data-city") != myCity) {
				// hide the zoom container
				$('#zoom_'+id).hide();
				// remove "active" from the day in the calendar
				$('#daysOfMonth .row .day[data-day='+id+']').removeClass("active");
			} else {
				// show zoom container
				$('#zoom_'+id).show();
				// add "active" from the day in the calendar
				$('#daysOfMonth .row .day[data-day='+id+']').addClass("active");
			}
		} else {
			// show zoom container
			$('#zoom_'+id).show();
			// add "active" from the day in the calendar
			$('#daysOfMonth .row .day[data-day='+id+']').addClass("active");
		}
	});
	$(".zoom_In").live('mouseleave', function() {
		$('.calendarZoom').hide();
		$('.zoom_In').removeClass('zoom_In');
	});
	
	// CALENDAR EVENT LINKS
	$('.calendarZooms .event_type').live("click", function() {
		id = $(this).attr('id').replace("event_",""); //  event ID
		vId = $(this).attr('name').replace("venueId_","");  //  venue Id
		updateEventService(id, vId);
	});
	  
	function updateEventService(id, vId) {
		$.ajax({
			dataType: 'jsonp',
			jsonp: false,
			jsonpCallback: 'myFunction',
			type:'GET',
			data: {'appId':'05fab807-d5fd-4f41-b714-3a27fa8aafd8','cbm':'myFunction','all':'false', 'locId':vId, 'eventId':id},
			url: constant.serverString+'getNestedLocations.ashx',
			success: updateEventInfo
		});
	} 
		
	function updateEventInfo(data) {
		// when event clicks, hide poster image and reveal event info
		$(".calendar_no_events").fadeOut(250, function() { 
			$(".calendar_event").show(); 
		});
		
		
		myEvents = data.venues;
		venue = myEvents[0];
		venueId = venue.id;
		eventId = venue.events[0];
		$('.event_description .event_name').html(venue.title);
		$('.event_description .event_type').html(eventId.eventType);
		$('.event_description .event_date').html(eventId.startDate);
		$('.event_description .event_details').html(eventId.eventDetails+'<br/><div class="timeslot_info">Choose a timeslot that best fits your schedule. Please register responsibly (one per member, please).</div>');
		$('.event_time').html('<select name="slotId" class="slot_time"></select><input type="submit" class="rsvp-btn" value="RSVP" /><br/><br/><span class="slot-status" style="color:red"></span>');
		$('.event_time').prepend('<input type="hidden" name="venueId" value="'+venueId+'"/><input type="hidden" name="eventId" value="'+id+'"/>');
		for(var s=0; s < eventId.slots.length; s++){
			time = eventId.slots[s].startTime;
			hr = time.slice(0,2);
			mn = time.slice(-2)
	
			if(hr>12) {
			  hr = hr%12;
			  am = "pm";
			}else {
			  am = "am";
			}
			
			// figure out remaining slots by subtracing rsvps from capacity
			var remainingRSVPs = eventId.slots[s].capacity - eventId.slots[s].rsvp;
			var slotClosed = eventId.slots[s].slotIsClosed;
	
			// write <option> tags for select box
			$('.slot_time').append("<option value='"+eventId.slots[s].slotId+"' data-rsvps-remaining='"+remainingRSVPs+"' data-slot-closed='"+slotClosed+"'>"+hr+":"+mn+""+am+"</option>");
			
			// check first item
			if (eventId.slots[0].capacity - eventId.slots[0].rsvp < 1) {
				$(".rsvp-btn").hide();
				$(".slot-status").html("This time is sold out. Please choose another from the drop down above.");
			} else {
				rsvpsLeft = eventId.slots[0].capacity - eventId.slots[0].rsvp;
				$(".rsvp-btn").show();
				$(".slot-status").html("");	
			}
			
			
		}
		
		Cufon.refresh(".event_description .event_name");
		Cufon.refresh(".event_description .event_type");
		Cufon.refresh(".event_description .event_date");
		
	
		// when the select box changes determine if event is closed or not
		$(".slot_time").live("change", function() {
			if ($(this).find("option:selected").data("rsvps-remaining") < 1) {
				$(".rsvp-btn").hide();
				$(".slot-status").html("This time is sold out. Please choose another from the drop down above.");
			} else {
				rsvpsLeft = $(this).find("option:selected").data("rsvps-remaining");
				$(".rsvp-btn").show();
				$(".slot-status").html("");
			}
		});
		
	} 

	
	
});

