$(document).ready(function() {
	initComments();
	initContentRatings($('input[type=radio].rating-star'), $('form.rating_form')); // Initiate jQuery star-rating plugin for all input type=radio with class of rating-star
});

function searchFilter(url) {
	$("input#search_button").remove();

	$(".ajax_loader").ajaxStart(function() {
		$(this).show();
		$(this).next().fadeTo("medium", 0.25);
	});

	$(".ajax_loader").ajaxStop(function() {
		$(this).hide();
		$(this).next().fadeTo("medium", 1);
	});

	$("#browse_search_form .vSelectField").change(function () {
        var query = "";   

		$("#browse_search_form .vSelectField").each(function(i){
			if ($(this).val() != "") {
				query += $(this).attr("name") + "=" + $(this).val() + "\&";
			}
		});

		query = query.substring(0, query.length-1);

		$.ajax({
			type: "GET",
			url: url,
			data: query,
			dataType: "html",
			success: function(results){
				$("ul.browse_list").html(results);
			}
		});
	});
}

function yahooMap(id, lat, long, name, address, city, zip, width, height) {
	// Create a map object
	var mapsize = new YSize(width, height);
	var map = new YMap(document.getElementById('mapwindow_' + id), YAHOO_MAP_REG, mapsize);

	// Add map controls
	map.addZoomShort();
	map.disableKeyControls();
	map.removeZoomScale(); 

	// Create geopoint and marker
    var geopoint = new YGeoPoint(lat, long);
    var newMarker = new YMarker(geopoint);

	// Insert address into marker
    var markerMarkup = "<div style='padding: 3px 7px; font-family: Verdana; font-size: 0.8em; width: 175px;'><strong>" + name + "</strong><br/>" + address +"<br/>" + city + " " + zip + "</div>";

	// Bind marker to click event
    YEvent.Capture(newMarker, EventsList.MouseClick,
        function(){
           newMarker.openSmartWindow(markerMarkup) ;
        });

	// Add marker to map, center on marker and set zoom to 5
    map.addOverlay(newMarker);
	map.drawZoomAndCenter(geopoint, 5);

	// Handle clicks on map buttons - slide down to reveal map
    $("#mapbutton_" + id).click(function () {
		$(this).next('div.list_map').slideToggle();
		return false;
	});
}
function mainEvents() {
    /* 
    Handle clicks on date tabs of the main Events browse/search page. Also handles filtering
    and AJAX requests for filtered event lists.
    */
	var query;
	$("input#search_button").remove(); // Remove the search button for results filtering

	$("#events_browse ul.cal_tab_header li a").click(function () {
		$("#events_browse .ajax_loader").ajaxStart(function() {
			$(this).show();
			$(this).next().fadeTo("medium", 0.25);
		});

		$("#events_browse .ajax_loader").ajaxStop(function() {
			$(this).hide();
			$(this).next().fadeTo("medium", 1);
		});
		
		$(this).parent().siblings().removeClass("ui-tabs-selected"); // Remove active state from all other days
		$(this).parent().addClass("ui-tabs-selected"); // Set clicked day to be active
		
		if ($(this).hasClass("browse_cal")) {
			function monthNav () {
				$("td.month_nav a").click(function () {
					query = $(this).attr("value");
					
					$.ajax({
						type: "GET",
						url: "/calendar/event/_async_month_calendar/",
						data: query,
						dataType: "html",
						success: function(results){
						    // Insert results into the wrapper div
							$("#events_browse .search_results_wrapper").html(results);
							monthNav();
					    }
					});
					return false;
				});
			}
			
			$.ajax({
				type: "GET",
				url: "/calendar/event/_async_month_calendar/",
				data: query,
				dataType: "html",
				success: function(results){
				    // Insert results into the wrapper div
					$("#events_browse .search_results_wrapper").html(results);
					monthNav();
			    }
			});
		} else {
			query = "start_date=" + $(this).attr("value") + "&framing=event_day_list"; // Create query based on the clicked day
			
			$.ajax({
				type: "GET",
				url: "/events/",
				data: query,
				dataType: "html",
				success: function(results){
				    // Insert results into the wrapper div
					$("#events_browse .search_results_wrapper").html(results);
				
					$("input#search_button").remove();
				
					$("#browse_search_form .vSelectField").change(function () {
			            $("#filter_load").ajaxStart(function() {
			                $(this).show();
			                $(this).next().fadeTo("medium", 0.25);
						});

						$("#filter_load").ajaxStop(function() {
			                $(this).hide();
			                $(this).next().fadeTo("medium", 1);
						});
					
						query = filterQuery();	// build query string from form fields
		
						query += "&framing=event_filter_list"
		
						$.ajax({
							type: "GET",
							url: "/events/",
							data: query,
							dataType: "html",
							success: function(results){
								$("ul.browse_list").html(results);
							}
						});
					});
				}
			});
		}
		return false;
	});
	
	// Handle selections in form drop-downs - submit AJAX request with updated query each time a selection is made
	$("#browse_search_form .vSelectField").change(function () {
	    // Hide / show loader div when AJAX request submitted
		$("#filter_load").ajaxStart(function() {
			$(this).show();
			$(this).next().fadeTo("medium", 0.25);
		});

		$("#filter_load").ajaxStop(function() {
			$(this).hide();
			$(this).next().fadeTo("medium", 1);
		});
		
		query = filterQuery();	// Build query string from form fields
		
		query += "&framing=event_filter_list"  // Append framing parameter
		
		$.ajax({
			type: "GET",
			url: "/events/",
			data: query,
			dataType: "html",
			success: function(results){
			    // Insert results into the list
				$("ul.browse_list").html(results);
			}
		});
	});
	
	// Creates a query string from the form select fields
	function filterQuery(query) {
		var query = "";
		
		// Get the date for the day tab that was clicked
		$("#events_browse ul.cal_tab_header li").each(function () {
			if ($(this).hasClass("ui-tabs-selected")) {
				date = $(this).children("a").attr("value");
			}
		});
		
		// Iterate through each drop-down and build query string
		$("#browse_search_form .vSelectField").each(function(i){
			if ($(this).val() != "") {
				query += $(this).attr("name") + "=" + $(this).val() + "\&";
			}
		});
		
		return query += "&start_date=" + date;
	}
}
function eventTabs() {
	// Old events code
	$("input#search_button").remove(); // Remove the search button for results filtering

    // On each click for a day, submit AJAX request and load that day's events and reload filters
	$("#events_browse ul.cal_tab_header a").click(function () {
	    // Hide & show calendar tab
		if ($(this).hasClass("browse_cal")) {
			$(".search_results_wrapper").hide();
			$("#browse_cal").show();
		} else {
			$("#browse_cal").hide();
			$(".search_results_wrapper").show();
		}

		// Loader div when AJAX request is submitted
		$("#day_load").ajaxStart(function() {
			$(this).show();
			$(this).next().fadeTo("medium", 0.25);
		});

		$("#day_load").ajaxStop(function() {
			$(this).hide();
			$(this).next().fadeTo("medium", 1);
		});

		$(this).parent().siblings().removeClass("ui-tabs-selected"); // Remove active state from all other days

		$(this).parent().addClass("ui-tabs-selected"); // Set clicked day to be active

		query = "start_date=" + $(this).attr("value") + "&framing=event_day_list"; // Create query based on the clicked day

		$.ajax({
			type: "GET",
			url: "/events/",
			data: query,
			dataType: "html",
			success: function(results){
			    // Insert results into the wrapper div
				$(".search_results_wrapper").html(results);

				// Rebind event handler after new content is loaded, otherwise filters will fail
				$("input#search_button").remove();

				$("#browse_search_form .vSelectField").change(function () {
		            $("#filter_load").ajaxStart(function() {
		                $(this).show();
		                $(this).next().fadeTo("medium", 0.25);
					});

					$("#filter_load").ajaxStop(function() {
		                $(this).hide();
		                $(this).next().fadeTo("medium", 1);
					});

					query = filterQuery();	// build query string from form fields

					query += "&framing=event_filter_list"

					$.ajax({
						type: "GET",
						url: "/events/",
						data: query,
						dataType: "html",
						success: function(results){
							$("ul.browse_list").html(results);
						}
					});
				});
			}
		});
		return false;
	});

	// Handle selections in form drop-downs - submit AJAX request with updated query each time a selection is made
	$("#browse_search_form .vSelectField").change(function () {
	    // Hide / show loader div when AJAX request submitted
		$("#filter_load").ajaxStart(function() {
			$(this).show();
			$(this).next().fadeTo("medium", 0.25);
		});

		$("#filter_load").ajaxStop(function() {
			$(this).hide();
			$(this).next().fadeTo("medium", 1);
		});

		query = filterQuery();	// Build query string from form fields

		query += "&framing=event_filter_list"  // Append framing parameter

		$.ajax({
			type: "GET",
			url: "/events/",
			data: query,
			dataType: "html",
			success: function(results){
			    // Insert results into the list
				$("ul.browse_list").html(results);
			}
		});
	});

	// Creates a query string from the form select fields
	function filterQuery(query) {
		var query = "";

		// Get the date for the day tab that was clicked
		$("#events_browse ul.cal_tab_header li").each(function () {
			if ($(this).hasClass("ui-tabs-selected")) {
				date = $(this).children("a").attr("value");
			}
		});

		// Iterate through each drop-down and build query string
		$("#browse_search_form .vSelectField").each(function(i){
			if ($(this).val() != "") {
				query += $(this).attr("name") + "=" + $(this).val() + "\&";
			}
		});

		return query += "&start_date=" + date;
	}
}
/* COMMENTS */
function loadComments(baseurl, page, comment) {
	var getComment = comment || 0;
	var getPage = page || 0;
	var getURL = baseurl + getPage + "/";
	var loaderElement = '<div id="filter_load" class="ajax_loader" style="display: block;"><img src="' + loadImgURL + '" alt="Loading content" /><p>&nbsp;&nbsp;&nbsp;Loading...</p></div>';
	var jcomments = $("#comments_container");
	
	jcomments.html(loaderElement);
	
	if (getComment != 0) {
		var d = {comments_id: getComment};
	} else {
		var d = {};
	}
	
	$.get(getURL, d,
		function(data){
			jcomments.html(data);
			handleCommentsLinks();
			initNonPublicCommentLinks();
			updateCommentCounts(".dynamic_comment_count");
			if (d['comments_id'] && firstCommentsLoad) {
				// There is a comment to jump to on first load, before next/prev have been clicked
				//window.location.hash = "c" + d['comments_id'].toString();
				$.scrollTo($("#c" + d['comments_id'].toString()));
			}
			firstCommentsLoad = false;
		}
	);
}
function revealComment(element) {
	var comment = $("#ccr" + element);
	var warning = $("#cch" + element);
	//var comment = document.getElementById('ccr' + element);
	//var warning = document.getElementById('cch' + element);

	if (comment.length > 0 && warning.length > 0) {
		comment.show();
		warning.hide();
	}
}
function writeCommentCookie(action) {
	document.cookie = "hidecomments=" + encodeURIComponent(action) + "; path=/; max-age=" + (60 * 60 * 24 * 365);
}
function toggleComments(toggleLink, commentsDiv) {
	if (toggleLink.text() == "Hide") {
		// Hide Comments
		commentsDiv.hide();
		writeCommentCookie("out");
		toggleLink.text("Show");
	} else {
		// Show Comments
		loadComments(commentsURL, 0, 0);
		commentsDiv.show();
		writeCommentCookie("in");
		toggleLink.text("Hide");
	}
}
function handleCommentsLinks() {
	$(".comments_prev").click(function(event) {
		// Previous link
		event.preventDefault();
		$.scrollTo($("#comments"));
		loadComments(commentsURL, commentsPreviousPage, 0);
	});
	$(".comments_next").click(function(event) {
		// Next link
		event.preventDefault();
		$.scrollTo($("#comments"));
		loadComments(commentsURL, commentsNextPage, 0);
	});
	$("select.comments_pages_select").change(function() {
		$.scrollTo($("#comments"));
		var selectedOption = $(this).children("option:selected");
		var re = /\d+/;
		var newIndex = re.exec(selectedOption.attr("class"))[0] * 1; // Gets the new index from the id of the selected option
		loadComments(commentsURL, newIndex, 0);
	});
	
}
function updateCommentCounts(destinationSelector) {
	var re = /\d+/;
	var commentCount = re.exec($("#comment_wrapper .comment_list_wrapper:first").attr("id"))[0] * 1;
	if ($('#titlebar_comment_count').length == 0) {
		// Comment count is not yet in the titlebar
		var titlebarCommentCount = ' <span id="titlebar_comment_count">&raquo; <span class="' + destinationSelector.replace(".","") + '"></span></span>';
		$("#comments .titlebar:first h3:first").append(titlebarCommentCount); // Add comment count container to the titlebar
	}
	$(destinationSelector).each(function() {
		$(this).text(commentCount); // Update all dynamic comment counts
	});
}
function initNonPublicCommentLinks() {
	/* Reveals hidden flagged comments by clicking on a link */
	$("p.comment-not-public-warning a").click(function(event) {
		event.preventDefault();
		var link = $(this);
		var href = getTargetID(link); // Get only "#cnpIDHERE" from the href
		var commentDiv = $(href);
		// Fade out the warning then fade in the comment
		link.parent().fadeOut("fast", function() {
			commentDiv.fadeIn();
		});
	});
	
}
function initComments() {
	var commentsDiv = $("#comments");
	var toggleDiv = $("#comment_wrapper");
	if (commentsDiv.length > 0) {
		if (hideComments == true) {
			toggleDiv.hide(); // Hide comments div
			var toggleText = 'Show';
		} else {
			var toggleText = 'Hide';
		}
		var toggleUL = '<ul class="deeplinks"><li><a href="#comments" id="comments_toggle">' + toggleText + '</a></li></ul>';
		var commentsTitlebar = $("#comments .titlebar:first");
		commentsTitlebar.append(toggleUL); // Write the show/hide link to the titlebar

		$("#comments_toggle").click(function(event) {
			// Handle the click event of the show/hide link
			event.preventDefault();
			toggleComments($(this), toggleDiv);
		});
		handleCommentsLinks();
		initNonPublicCommentLinks();
	}
}
ratingSubmit = function(value, link){
	value = value || 0;
	if (value != 0) {
		// User has rated this
		var f = $(this.form);
		
		if(!f.hasClass("user_rating_form")) {
			f.addClass("user_rating_form");
		}
	} else {
		// User has cleared his rating
		var f = cancelThisForm;
		f.removeClass("user_rating_form");
	}
	$.post(f.attr("action"), {rating: value}, function(data, textStatus) {
		if (value == 0) {
			// Since user has cleared the rating, remove the users rating info and reinitialize this form
			// To get the overall rating
			var newData = eval("(" + data + ")");
			var newRating = newData.rating
			
			
			var inputs = f.children('input[type=radio].rating-star');
			var input = inputs.filter("[value=" + newRating + "]");
			var overallInput = $(input[0]);
			
			overallInput.attr("checked", "checked");
			inputs.attr("class", "rating-star");
			f.find('span.star-rating-control').remove();
			
			initContentRatings(inputs, f);
		}
	});
}

function initContentRatings(inputObjects, cancelScope){
	inputObjects.rating( {callback: ratingSubmit} );
	$('.star-rating-readonly').click(function() {
		alert("Please login to rate content");
	});
	cancelScope.find('div.rating-cancel a').click(function() {
		cancelThisForm = $($(this).parents("form")[0]);
	});
}

function sidebarEvents() {
	function monthNav () {
		$("td.month_nav a").click(function () {
			query = $(this).attr("value");
			
			$.ajax({
				type: "GET",
				url: "/calendar/event/_async_month_calendar/",
				data: query,
				dataType: "html",
				success: function(results){
				    // Insert results into the wrapper div
					$("#calendar_results").html(results);
					monthNav();
			    }
			});
			return false;
		});
	}
	
    // Handle clicks on date and calendar tabs
    function calTabs () {
        var query = "";
        
	    $("#sidebar_events li.cal_tab_last a").click(function () {
    		$("#sidebar_events_loader").ajaxStart(function() {
    			$(this).show();
    			$("#calendar_results").fadeTo("medium", 0.25);
    		});

    		$("#sidebar_events_loader").ajaxStop(function() {
    			$(this).hide();
    			$("#calendar_results").fadeTo("medium", 1);
    		});
		
    		$(this).parent().siblings().removeClass("ui-tabs-selected"); // Remove active state from all other days
    		$(this).parent().addClass("ui-tabs-selected"); // Set clicked day to be active
		
		    query = "";
		    
			$.ajax({
				type: "GET",
				url: "/calendar/event/_async_month_calendar/",
				data: query,
				dataType: "html",
				success: function(results){
				    // Insert results into the wrapper div
					$("#calendar_results").html(results);
					monthNav();
			    }
			});
    		return false;
    	});
    }   
    
    calTabs();
}
