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

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;
	}
}

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();
}
var jSING = {
	videoPlayer: {
		doEmbedSWF: function(p) {
			var self = this;
			swfobject.embedSWF(p.embedParams.playerSrc, p.embedParams.containerId, p.embedParams.playerWidth, p.embedParams.playerHeight, "9.0.115", p.installSWFURL, p.flashvars, p.params, p.attrs, self.embedCallback);
			window[p.playerName] = document.getElementById(p.playerName);
		},
		embedPlayers: function() {
			/*
			jSINGconf.videoPlayers hash is set in base.html
			Each instance of player/player_include.html adds a player instance to the hash
			*/
			var self = this;
			for (var p in jSINGconf.videoPlayers) {
				self.doEmbedSWF(jSINGconf.videoPlayers[p]);
			}
		},
		embedCallback: function(e) {
			if (!e.success) {
				// Video was not embedded properly, show the fallback flash download HTML instead of the loader
				var playerContainer = $("#" + e.id);
				playerContainer.html(playerContainer.data('fallbackHTML'));
			}
		},
		showLoaders: function() {
			$('.player_container').each(function() {
				var playerContainer = $(this);

				// Store the flash download fallback HTML
				playerContainer.data('fallbackHTML', playerContainer.html());

				// Replace the flash download HTML with a loading gif
				// TODO: Ditch the embedded style
				playerContainer.html('<img src="' + jSINGconf.theme.CORP_MEDIA_URL + '/img/ajax-loader-video.gif" alt="Loading video" style="margin-top: 20px; text-align: center;"/>');
			});
		},
		init: function() {
			/*
			DO NOT CALL THIS INIT FROM jSING.init()
			because the required SWFObject library isn't loaded until *after* jSING.init() runs
			*/
			this.showLoaders();
		}
	},
	comments: {
		firstLoad: true, // Certain functions are only run on page load. Once init runs, this variable is set to false

		commentsContainer: $("#comments.comments_enabled"), // Wraps around all comments stuff, including the titlebar
		commentsWrapper: $("#comment_wrapper"), // Wraps pagination and comments
		commentsListContainer: $("#comment_list"), // Contains the list of actual comments
		commentsAd: $("#comments_ad"),
		commentsLoader: $('<div id="comments_loader" style="position: absolute; width: 575px; margin: 14px auto; text-align: center; font-size: .75em; color: #666;"><img src="' + jSINGconf.theme.CORP_MEDIA_URL + '/img/ajax-loader.gif" alt="Loading comments" /><p>Loading comments</p></div>'),
		commentsPagination: $('.comments_paginated_arrows'),
		commentsPaginationContainers: $('.pagination_comments'),
		commentsTitlebar: $('#comments .titlebar:first'),
		commentsCountStorage: $('.comment_count_storage'),
		commentsPageSelectors: $('.comments_pages_select'),
//		commentsList: $('.comment_wrapper'),
//		commentsFormWrapper: $('.comment_list_wrapper')

		handlePagination: function() {
			var self = this;

			// Capture clicks on next/previous links
			$('.comments_paginated_arrows li a').live('click', function(e) {
				e.preventDefault();
				self.loadCommentsData(this.href.replace('/list/', '/json/'));
			});

			// Capture selection via dropdown menu
			$("select.comments_pages_select").live('change', function() {
				if (!self.firstLoad) {
					self.loadCommentsData($(this).val());
				}
			});

			// Get the loader ready
			self.commentsLoader.hide().insertBefore(self.commentsListContainer);
		},
		
		updatePagination: function(paginationHTML) {
			var self = this;
			self.commentsPaginationContainers.each(function() {
				$(this).html(paginationHTML);
			});
			//self.handlePagination.selectChange();
		},
		updateCommentCounts: function(destinationSelector, commentCount) {
			var destinationSelector = destinationSelector || ".dynamic_comment_count",
				commentCount = commentCount || $("#comment_wrapper .comment_list_wrapper:first").attr("id").match(/\d+/)[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
			});
		},
		loadCommentsData: function(commentsURL) {
			/*
			The JSON response is rendered by the comments/paginated_list_json.html template
			*/
			var self = this;

			$.scrollTo(self.commentsContainer, 200); // Scroll to the comments div

			// Fade comments out, put loader on top
			self.commentsListContainer.fadeTo(100, .2, function() {
				self.commentsLoader.fadeIn(200);

				$.getJSON(commentsURL, function(results) {
					/*
					When loading is complete, do all the hard work
					*/

					// Remove newlines and tabs from the rendered data so that it'll be safe for JSON parsing
					var renderedData = results.rendered_data.replace(self.whitespaceRegEx, '');

					self.changePage($.parseJSON(renderedData));
				});
			});

		},
		removeComments: function() {
			/*
			Remove the comments while leaving the ad in place
			*/
			$('.comment_wrapper').remove();
		},
		renderComments: function(commentList) {
			/*
			Render the comments around an ad if it exists
			*/
			var self = this,
				commentsCount = commentList.length,
				commentsBeforeAdHTML = '',
				commentsAfterAdHTML = '';

			if (self.commentsAdIndex != -1) {
				// There is an ad. Use its index as the breakpoint
				var hasAd = true,
					breakpoint = self.commentsAdIndex;
			} else {
				// There is no ad, so break at the end
				var hasAd = false,
					breakpoint = commentsCount;
			}


			// Loop from the beginning to the breakpoint, which is an ad if it exists, if not it's the end
			for (var i = 0; i < breakpoint; i++) {
				commentsBeforeAdHTML += commentList[i];
			}

			self.removeComments();

			// Insert the comments at the beginning of the comments list
			var commentsBeforeAd = $(commentsBeforeAdHTML);
			commentsBeforeAd.prependTo(self.commentsListContainer);

			// If there's an ad, loop from the breakpoint to the end
			if (hasAd) {
				for (var i = breakpoint; i < commentsCount; i++) {
					commentsAfterAdHTML += commentList[i];
				}
				// Insert the comments at the end of the comments list
				var commentsAfterAd = $(commentsAfterAdHTML);
				commentsAfterAd.appendTo(self.commentsListContainer);
			}

			// Fade comments in, remove loader
			self.commentsLoader.fadeOut(100, function() {
				self.commentsListContainer.fadeTo(100, 1);

			});


		},
		changePage: function(commentsData) {
			var self = this;

			self.renderComments(commentsData.commentList);
			self.updatePagination(commentsData.paginationHTML);
			self.updateCommentCounts(null, commentsData.commentCount);
		},
		getComment: function() {
			/*
			Specific comments can be linked to in the URL using:
			?comments_id=12345 (From {{ comment.get_absolute_url }}), PREFERRED METHOD
			or
			#c12345 (Anchor of the comment on the page)
			*/
			fromGet = function() {
				return jSING.utils.getUrlAttr('comments_id');
			}
			fromHash = function() {
				if (window.location.hash) {
					var re_exec = /c[\d]+/.exec(window.location.hash);
					if (re_exec) {
						return re_exec[0].replace('c', '');
					} else {
						return null;
					}
				} else {
					return null;
				}

			}
			return function() {
				/*
				If a comment is specified, scroll to it
				*/
				var self = this,
					commentId = fromGet() || fromHash() || null;

				if (commentId) {
					$.scrollTo($("#c" + commentId), 200);
				}
			}();
		},
		initNonPublicCommentLinks: function() {
			/* Reveals hidden flagged comments by clicking on a link */
			$("p.comment-not-public-warning a").live('click', function(event) {
				event.preventDefault();
				var link = $(this),
					href = jSING.utils.getTargetID(link),
					commentDiv = $(href);
				// Fade out the warning then fade in the comment
				link.parent().fadeOut("fast", function() {
					commentDiv.fadeIn();
				});
			});
		},
		hideComments: function() {
			var self = this;
			self.commentsContainer.addClass('hidecomments');
			self.commentsToggleLink.text("Show"); // Change the text of the link to Show
			self.commentsWanted = false;
			$.cookie("hidecomments", 'out', { expires: 730, path: '/' }); // Set the cookie to hide comments
		},
		showComments: function() {
			var self = this;
			self.commentsContainer.removeClass('hidecomments');
			self.commentsToggleLink.text("Hide"); // Change the text of the link to Hide
			self.commentsWanted = true;
			$.cookie("hidecomments", null, { path: '/' }); // Delete the font size cookie if it exists
		},
		handleCommentsToggle: function() {
			var self = this;

			self.commentsToggleLink.click(function(event) {
				// Handle the click event of the show/hide link
				event.preventDefault();
				if (self.commentsToggleLink.text() == "Hide") {
					self.hideComments();

				} else {
					self.showComments();
				}
			});
		},
		getCommentsVisibilityCookie: function() {
			if ($.cookie("hidecomments")) {
				return false;
			}
			return true;
		},
		hideUnwantedComments: function() {
			var self = this;

			if (!self.commentsWanted) {
				self.hideComments();
			}
		},
		insertToggleLink: function() {
			var self = this;

			if (self.commentsWanted) {
				var toggleText = "Hide";
			} else {
				var toggleText = "Show";
			}
			self.commentsToggleUL = $('<ul class="deeplinks"><li><a href="#comments" id="comments_toggle">' + toggleText + '</a></li></ul>');
			self.commentsToggleUL.appendTo(self.commentsTitlebar);
			self.commentsToggleLink = $('#comments_toggle');
		},
		selectInputRefresh: function() {
			/*
			Fixes a problem where after selecting any page of comments but the first,
			reloading the page sets the comment lists back to page 0, 
			but shows the previously selected page as selected
			*/
			var self = this;

			self.commentsPageSelectors.each(function() {
				var select = $(this),
					selected = select.children(':selected:first'),
					selectedIndex = selected.index();

				if (selectedIndex == 0) {
					select.trigger('change');
				}
			});
		},
		init: function() {
			var self = this;

			if (self.commentsContainer.length) {
				self.commentsWanted = self.getCommentsVisibilityCookie();
				self.selectInputRefresh();
				self.insertToggleLink();
				self.hideUnwantedComments();
//				self.updateCommentCounts();
				self.whitespaceRegEx = /[\t\r\n]/g; // Used to clean out JSON responses

				// Get the ad index once and never do it again
				self.commentsAdIndex = self.commentsAd.index();

				self.handlePagination();

				// Scroll to a specified comment
				if (self.firstLoad) {
					self.getComment();
				}

				self.initNonPublicCommentLinks();
				self.handleCommentsToggle();
				self.firstLoad = false;
			}
		}
	},
};