/**
 * Copyright (c) Zeros 2 Heroes All Rights Reserved.
 *
 * TABLE OF CONTENTS
 *
 * A. GLOBAL VARIABLES
 * B. DOCUMENT READY
 *
 * 1. initViewPage
 * 2. animateHighlighter
 * 3. searchHandler
 * 4. filterHandler
 * 5. paginatorHandler
 * 6. contestSelectorHandler
 * 7. loadAjax 
 * 8. animateSubmissionList
 * 9. animateBrowseScroller
 * 10. addPadding
 * 11. reset
 * 12. storyPagination 
 * 13. browseFilter
 * 14. changeState
 * 15. showEmailPopup
 * 16. submitVote
 */

/* A. GLOBAL VARIABLES
********************************************************************/
var dropdown_val = "";//null;  // variable for our custom select


/* B. DOCUMENT READY - wait for the window to load before doing anything
********************************************************************/
$(document).ready( function() {

    if ($("#jq_vote_now").length > 0) {
	$("#jq_vote_now").click(function(e) { 
	    e.preventDefault(); 
	    animateBrowseScroller();
	    return false;
	});
    }

    initViewPage();
    animateHighlighter();  // scrolls the page down to your vote
    
    addPadding(); // add class to middle user tile for padding
    reset();      // sets up the event handlers for ajax calls

    if ($('#my_stories_filter').length > 0) {
	$('#my_stories_filter').find('a').bind('click', filterMyStories);
    }

    // social network
    if ($('.browse_filter').length > 0) {
	$('.browse_filter').find('#browse_submit').bind('click', function(e) {
	    e.preventDefault();
	    browseFilter(e);
	    return false;
	});

	$('.browse_filter').find('input').bind('change', changeState);
    }

    if ($('.vote_btn').length > 0) {
	$('.vote_btn').bind('click', function(e) {
	    e.preventDefault();
	    showEmailPopup();
	    return false;
	});
    }

    if ($('#email_popup').length > 0) {
	$('#email_popup').find('.email_submit').bind('click', function(e) {
	    e.preventDefault();
	    submitVote(e);
	    return false;
	});

	$('#email_popup').find('.skip').bind('click', function(e) {
	    //$('form').submit();
	    e.preventDefault();
	    submitVote(e);
	    return false;
	});
    }

    // initialize contest selection click handlers
    if ($(".timeline_container").length > 0) {
	if ($('#jq_browse_entries').length > 0) {
	    $(".timeline_container a").bind("click", contestSelectorHandler);
	}
    }

    // initialize the dropkick plugin
    if ($('.custom_select').length > 0) {  //only apply the dropkick plugin if the custom select is on the page

	// get the default value of the dropdown
	$('option').each(function(index){
	    var item = $(this);
	    if (item.attr('selected') == 'selected') {
		dropdown_val = item.val();
		return false;
	    }
	});


	$('.custom_select').dropkick({
	    change: function(value, label) {    
		if (value != dropdown_val) {  // only execute if there is a change in value
		    filterHandler(value);
		    dropdown_val = value;
		}
	    }
	}); 
    }
    
    // initialize search handler
    if ($("#jq_filter_search").length > 0) {
	$("#jq_submit").click(function(e) {
	    e.preventDefault();
	    searchHandler();
	    return false;
	});

	$("#jq_filter_search").submit(function(e) {
	    e.preventDefault();
	    searchHandler();
	    return false;
	});
    }
});


/**
 * 1. initViewPage - performs the page animations, updates the page counter, and enables the buttons
 *
 * @params
 * @return
 */
function initViewPage() {
    var prev = $("#jq_prev");
    var home = $("#jq_home");
    var next = $("#jq_next");
    var pages = $("#jq_pages");
    var current = 1;  

    if (pages.length > 0) {  
	var max_margin_left = -(pages.children().size()-1)*520;  // the max left margin we're allowed to have

	 $("#page_of_page").html(current + ' of ' + pages.children().size());  // set up the page counter
    
	// Buttons are disabled by default.  Enable the next button if there's more than one page
	if (pages.children().size() > 1) {  
	    next.addClass("enabled");
	}
	
	// animated the pages on click and enable/disable buttons if necessary
	prev.click(function() {
	    if (parseInt(pages.css("margin-left")) < 0 ) {
		pages.animate({"margin-left": "+=520px"}, "slow");
		current--;
		$("#page_of_page").html(current + ' of ' + pages.children().size());

		if (!next.hasClass("enabled")) {
		    next.addClass("enabled");
		}

		if (current == 1) {
		    if (prev.hasClass("enabled")) {
			prev.removeClass("enabled");
		    }

		    if (home.hasClass("enabled")) {
			home.removeClass("enabled");
		    }
		}
	    }
	});

	home.click(function() {     
	    if (parseInt(pages.css("margin-left")) < 0 ) {
		pages.animate({"margin-left": "0px"}, "slow");
		current = 1;
		$("#page_of_page").html(current + ' of ' + pages.children().size());

		if (!next.hasClass("enabled")) {
		    next.addClass("enabled");
		}

		if (home.hasClass("enabled")) {
		    home.removeClass("enabled");
		}

		if (prev.hasClass("enabled")) {
		    prev.removeClass("enabled");
		}

	    }
	});

	next.click(function() {
	    if (parseInt(pages.css("margin-left")) > max_margin_left) {
		pages.animate({"margin-left": "-=520px"}, "slow");
		current++;
		$("#page_of_page").html(current + ' of ' + pages.children().size());
		
		if (!prev.hasClass("enabled")) {
		    prev.addClass("enabled");
		}

		if (!home.hasClass("enabled")) {
		    home.addClass("enabled");
		}

		if (current == pages.children().size() && next.hasClass("enabled")) {
		    next.removeClass("enabled");
		}
	    }
	});
    }
}


/**
 * 2. animateHighlighter - scrolls down the ranking page 
 *
 * @params
 * @return
 */
function animateHighlighter() {
    if ($("#jq_your_vote").length > 0 && $("#jq_rankings").length > 0) {
	var newPos = $("#jq_your_vote").position().top;  // the end position of the scroller
	
	if (typeof(FB) != "undefined") {
	    FB.Canvas.scrollTo(0,newPos);
	}
	else {
	    $('html,body').animate({scrollTop: newPos}, "slow");
	}
    }
}


/**
 * 3. searchHandler - handles the search box on the list partial view
 *
 * @params
 * @return
 */
function searchHandler() { 
    var url = $("#jq_filter_search").attr('action');
    var keyword = $("#jq_search_disabled").val();
    var input = $("#jq_search_disabled");
    keyword = keyword.replace(/^\s+|\s+$/g, '');

    var keyword_start = url.indexOf('/keyword/');

    // if the url already contains keyword
    if(keyword_start >= 0) {   
	if (keyword.length == 0) {
	    url = url.replace(url.substring(keyword_start), "");
	}
	else {                                  
	    var keyword_end = url.indexOf('/', keyword_start+2);
	    var key_end = url.indexOf('/', keyword_end+1);

	    // otherwise just replace the existing value
	    if (key_end >= 0) {
		url = url.replace(url.substring(keyword_end+1, url.indexOf('/', keyword_end+1)), keyword);
	    }
	    else {
		url = url.replace(url.substring(keyword_end+1), keyword);
	    }
	}
    }
    else {
	if (keyword.length > 0) {
	    url = url + "/keyword/" + keyword;  // otherwise just append it
	}
    }

    if ($("#jq_browse_entries").length > 0) {
	loadAjax('#jq_content_tiles', url);
    }
}


/**
 * 4. filterHandler - handles the filter drop down in list partial view
 *
 * @params - value (the value of the selected element)
 * @return
 */
function filterHandler(value) {
    if ($("#jq_filter_search").length > 0) {
	var url = $("#jq_filter_search").attr('action');
	var sort_field_start = url.indexOf('sort_field/');
	var sort_field_end = url.indexOf('/', sort_field_start);

	var sort_order_start = url.indexOf('sort_order/');
	var sort_order_end = url.indexOf('/', sort_order_start);

	var sort_field_replace = url.substring(sort_field_end+1, sort_order_start-1);  // the first string we want to replace
	var sort_order_replace = url.substring(sort_order_end+1, url.indexOf('/', sort_order_end+2));  // the second string we want to replace

	switch(value) {
	case "most_recent":
	    if (sort_field_start >= 0) {
		url = url.replace(sort_field_replace, 'creation_date');  
		url = url.replace(sort_order_replace, 'desc');
	    }
	    else {
		url = url + "/sort_field/creation_date/sort_order/desc";
	    }
	    break;
	case "least_recent":
	    if (sort_field_start >= 0) {
		url = url.replace(sort_field_replace, 'creation_date');  
		url = url.replace(sort_order_replace, 'asc');
	    }
	    else {
		url = url + "/sort_field/creation_date/sort_order/asc";
	    }
	    break;
	case "most_votes":
	    if (sort_field_start >= 0) {
		url = url.replace(sort_field_replace, 'total_votes');  
		url = url.replace(sort_order_replace, 'desc');
	    }
	    else {
		url = url + "/sort_field/total_votes/sort_order/desc";
	    }
	    break;
	case "least_votes":
	    if (sort_field_start >= 0) {
		url = url.replace(sort_field_replace, 'total_votes');  
		url = url.replace(sort_order_replace, 'asc');
	    }
	    else {
		url = url + "/sort_field/total_votes/sort_order/asc";
	    }
	    break;
	case "is_winner":
	    var is_winner_start = url.indexOf('is_winner');
	    if (is_winner_start >= 0) {
		var is_winner_end = url.indexOf('/', is_winner_start);
		var is_winner_replace = url.substring(is_winner_end + 1);
		url = url.replace(is_winners_replace, '1');
	    }
	    else {
		url = url + "/is_winner/1";
	    }
	    break;
	default:
	    break;
	}



	if ($("#jq_browse_entries").length > 0) {
	    loadAjax('#jq_content_tiles', url);
	}
    }
}


/**
 * 5. paginatorHandler - handles the click event for the paginator.  $(this) refers to the jquery object that fired the event.  
 *
 * @params 
 * @return
 */
function paginatorHandler(e) {
    e.preventDefault();
    var jq_clicked = $(e.currentTarget);   // the DOM object that fired the event
    var parent = jq_clicked.parent();
    var current = $("#jq_browse_entries .current");           // need to add parent class here so it won't affect the story pagination
    var url = jq_clicked.attr('href');
    var page = jq_clicked.find('span').html();                // the page we're going to
    var container = $(".submission_list_container");


    // we need to create the url for the current paginator
    var current_page = current.find('span').html();
    var url_start = url.substring(0, url.indexOf('/', url.indexOf('page')));
    var url_end = '';
    var current_url = '';
    if (url.indexOf('entries') >=0) {
	current_url = url_start + '/' + current_page;
    }
    else {
	url_end = url.substring(url.indexOf('id')); 
	current_url = url_start + '/' + current_page + '/' + url_end;
    }
    
    // set the selected object to unselected status
    current.html('<a class="ajax_paginator img_replace" href="' + current_url + '">' + current.html() + '</a>');
    current.children("a").bind("click", paginatorHandler);  // add the event listener to the newly created a tag
    current.removeClass("current img_replace");
    
    // set the unselected object to selected status and add anchor if needed
    if (!jq_clicked.hasClass("prev") && !jq_clicked.hasClass("next")) {
	parent.addClass("current img_replace");  // set the clicked object to selected status
	parent.html(jq_clicked.html());          // remove the a tags, but keep the span tags
    }
    else if (jq_clicked.hasClass("prev")) {
	if (parseInt(current_page) > 1) {
	    var prev = current.prev();
	    url = prev.find('a').attr('href');
	    prev.addClass("current img_replace");      // set the prev object to selected status
	    prev.html(prev.find('a').html());          // remove the a tags, but keep the span tags
	    page = prev.find('span').html();
	}
    }
    else {
	var last_page = parent.prev().find('span').html();
	if (parseInt(current_page) < parseInt(last_page)) {  // next was clicked
	    var next = current.next();
	    url = next.find('a').attr('href');
	    next.addClass("current img_replace");      // set the next object to selected status
	    next.html(next.find('a').html());          // remove the a tags, but keep the span tags
	    page = next.find('span').html();
	}
    }

    // if the page exists, just animate it
    if (container.find("ul#page_"+ page).length > 0) { 
	// handle the next and prev links
	var existing_pages = container.find('ul').length;
	var page_li = $('#jq_browse_entries .pagination').find('li');
	var total_pages = $('#jq_browse_entries .pagination').find('li').length;
	var prev_exists = false;
	var next_exists = false;
	
	if (page_li.find('.prev').length > 0) {  // if the prev link is there
	    total_pages--;
	    prev_exists = true;
	}

	if (page_li.find('.next').length > 0) {  // if the next link is there
	    total_pages--;
	    next_exists = true;
	}

	// we need to generate or change the next link if we're not on the last page
	if (parseInt(page) < total_pages) {
	    var next_page = parseInt(page) + 1;
	    var next_url = url_start + '/' + next_page + '/' + url_end;

	    if (!next_exists) {  // generate the link
		$('<li><a class="next img_replace" href="' + next_url + '"><span>Next</span></a></li>').appendTo('#jq_browse_entries .pagination ul');
		$("#jq_browse_entries .next").bind("click", paginatorHandler);
	    }
	    else {  // just change the href
		$('#jq_browse_entries .next').attr('href', next_url);
	    }
	}
	else {  // remove next link from view
	    $('#jq_browse_entries .next').parent().remove();
	}

	// we need to generate or change the prev link if we're not on the first page
	if (parseInt(page) > 1) {
	    var prev_page = parseInt(page) - 1;
	    var prev_url = url_start + '/' + prev_page + '/' + url_end;
	    
	    if (!prev_exists) {
		$('<li><a class="prev img_replace" href="' + prev_url + '"><span>Next</span></a></li>').prependTo('#jq_browse_entries .pagination ul');
		$("#jq_browse_entries .prev").bind("click", paginatorHandler);
	    }
	    else {  // just change the href
		$('#jq_browse_entries .prev').attr('href', prev_url);
	    }
	}
	else {  // remove the prev link from view
	    $('#jq_browse_entries .prev').parent().remove();
	}

	// get the position of the element we want to show
	var pos = container.find("ul#page_" + page).position().left;    
	var offset = 0;
	
	// set variables for changing container height
	var base_height = 0;
	var rows = 0;
	var container_height = base_height*rows;

	if (container.parents('.animism_hp').length > 0) {
	    if ($(".tiles_container").css('position') != 'relative') {
		offset = $(".tiles_container").position().left;
		pos = pos - offset;
	    }
	}

	if (container.parents('.my_tiles_container').length > 0) {
	    if ($(".my_tiles_container").css('position') != 'relative') {
		offset = $(".my_tiles_container").position().left;
		pos = pos - offset;
	    }

	    // update the container height;
	    base_height = 274;
	    rows = Math.ceil(container.find("ul#page_"+ page).find('li').length/3);
	    container_height = base_height*rows;
	    $('.my_tiles_container').css('height', container_height);
	}

	if (container.parents('#jq_content_tiles').length > 0) {
	    base_height = 262;
	    rows = Math.ceil(container.find("ul#page_"+ page).find('li').length/3);
	    container_height = base_height*rows;
	    $('.submission_list_container').css('height', container_height);
	}


	// do the animations
	if (parseInt(current_page) < parseInt(page)) {
	    animateSubmissionList(container, -1, pos);
	}
	else {
	    animateSubmissionList(container, 1, pos);
	}
    }
    else {   // otherwise call ajax
	if ($("#jq_browse_entries").length > 0) {
	    if (container.parents('.animism_hp').length > 0) {
		loadAjax('#jq_browse_entries', url, page, 4);
	    }
	    else if (container.parents('.my_tiles_container').length > 0) {
		loadAjax('#jq_browse_entries', url, page, 9);
	    }
	    else {
		loadAjax('#jq_browse_entries', url, page);
	    }
	}
    }
    return false;
}


/**
 * 6. contestSelectorHanlder - handles the click event for the contest selector.  $(this) refers to the jquery object that fired the event.
 *
 * @params 
 * @return
 */
function contestSelectorHandler(e) { 
    e.preventDefault();
    var jq_clicked = $(e.currentTarget);   // the DOM object that fired the event
    var parent = jq_clicked.parent();
    var url = jq_clicked.attr('href');

    var current = $(".selected");
    var theme = 'theme/'+$('.contest_timeline').find('li').index(current);
    var new_url = url.substring(0, url.indexOf('theme')) + theme + '/page/1'; 
    var html = '<a href="' + new_url + '">' + current.html() + '</a>';

    // only make the changes if the object clicked is not selected
    if (!parent.hasClass("selected")) {
	// change the selected object to unselected
	if (current.length > 0) {
	    current.html(html);
	    current.find('a').bind("click", contestSelectorHandler);
	    current.removeClass("selected");    // remove selected class 
	}

	// set the clicked object to selected status
	parent.addClass("selected");      // add the selected class to the parent of the clicked object

	if ($('#jq_filter_search').length > 0) {
	    $('#jq_filter_search').attr('action', url);

	    // reset drop down menu
	    $('.custom_select').find('[selected="selected"]').removeAttr('selected');
	    $('.custom_select').find('[value="most_recent"]').attr('selected', 'selected');
	    dropdown_val = $('.custom_select').find('[selected="selected"]');
	    
	    $('.dk_toggle').find('.dk_label').html('Most Recent');
	    var current_select = $('.dk_option_current');
	    current_select.removeClass('dk_option_current');
	    $('.dk_options_inner').find('li').first().addClass('dk_option_current');

	    // reset search box
	    if ($('#jq_filter_search').length > 0) {
		if ($('#jq_filter_search').length > 0) {
		    $('#jq_search_disabled').attr('value', '');
		}
	    }
	}

	if ($("#jq_browse_entries").length > 0) {
	    loadAjax('#jq_content_tiles', url);
	}
    }

    return false;
}


/**
 * 7. loadAjax - makes the ajax code and updates the DOM
 *
 * @params - id (the id of the DOM we want to update), url (the url we're sending the ajax call to), page (optional argument: page number), 
 *           total_pages (optional argument: total number of tiles to return to the DOM)
 * @return
 */
function loadAjax(id, url, page, total_pages) {
    var dom = $(id);
    var send_to = url;
    var loading = $("#load_ajax_content_loading");
    var page_num = page;

    if (send_to.indexOf('/format/json') == -1) {
	send_to = send_to + '/format/json';
    }

    $.ajax({
	url: send_to,
	type: "POST",
	dataType: "html",
	beforeSend: function() {
	    //loading.show();
	},
	success: function(response) {
	    var offset = 0;                 // we need this for the homepage and the browse entries/mystories page
	    var position_css = "none";      // used to decide if we need the offset amount
	    var container_height = '';      // the height of the container

	    // change just the page and paginator only
	    if (page_num != null && page_num != undefined) {
		// strip the response html
		var paginator = response.substr(response.indexOf('<div class="pagination">'));
		var new_dom = response.replace(paginator, "");
		var new_page = new_dom.substring(new_dom.indexOf('<ul class="submission_list" id="page_1">'), new_dom.lastIndexOf('</ul>')) + '</ul>';
		new_page = new_page.replace('page_1', 'page_' + page_num);

		// strip depending on what page we're on and set up the variables
		if (total_pages == 4) {      // animism homepage
		    paginator = paginator.substr(0, paginator.indexOf('</div>')) + '</div>';
		    new_page = new_dom.substring(new_dom.indexOf('<ul'), new_dom.indexOf('</ul>')) + '</ul>';
		    position_css = $(".tiles_container").css('position');

		    if (position_css != 'relative') {
			offset = $(".tiles_container").position().left;
		    }
		}
		else if (total_pages == 9) {  // browse entries
		    paginator = paginator.substr(0, paginator.indexOf('</div>')) + '</div>';
		    new_page  = new_dom.substring(new_dom.indexOf('<ul class="submission_list" '), new_dom.lastIndexOf('</ul>')) + '</ul>';
		    position_css = $(".my_tiles_container").css('position');

		    // set the height of the container div
		    new_dom = new_dom.replace(new_dom.substr(new_dom.indexOf('<div class="submission_list_container')), '');
		    container_height = new_dom.substring(new_dom.indexOf(':')+2, new_dom.indexOf(';'))
		    $('.my_tiles_container').css('height', container_height);

		    if (position_css != 'relative') {
			offset = $(".my_tiles_container").position().left;
		    }
		}
	
		// replace paginator with the new one
		$('#jq_browse_entries .pagination').replaceWith(paginator);
		if ($("#jq_browse_entries .pagination").length > 0) {
		    $("#jq_browse_entries .pagination a").bind("click", paginatorHandler);
		}

		// create the new page
		var container = $(".submission_list_container");
		container.width(container.width() + $(".submission_list").outerWidth());  // increase the size of our container
		var pos;  // displacement amount for the animation

		// iterate through the existing pages
		$(".submission_list").each(function(index) {  
		    var child = $(this);
		    var child_id = child.attr('id').slice(child.attr('id').indexOf("_")+1);  // get only the numerical part of the id

		    // if we find an id greater than this one, stop
		    if (parseInt(child_id) > parseInt(page_num)) {  
			var childPos = child.offset().left;
			
			// properly calculate childPos for animism homepage or browse entries
			if (total_pages == 4 || total_pages == 9) {
			    childPos = child.position().left;

			    if (position_css != 'relative') {
				childPos = childPos - offset;
			    }
			}

			child.before(new_page);               // insert new html in front of it
			var childWidth = $(".submission_list").outerWidth();
			var rightEdge = childWidth;           // the rightmost edge of our container

			// calculate the rightmost edge on the homepage
			if (total_pages == 4) {
			    rightEdge = $(".tiles_container").width();
			}
			else if (total_pages == 9) {
			    rightEdge = $(".my_tiles_container").width();
			}
			

			if (childPos <= 0) {   // the page is onscreen or offscreen to the left
			    container.css('margin-left', "-=" + childWidth + "px");  // adjust the margin so it doesn't appear onscreen right away
			    pos = container.find("ul#page_" + page_num).offset().left;

			    // calculate position for animism homepage or browse entries
			    if (total_pages == 4 || total_pages == 9) {
				pos = container.find("ul#page_" + page_num).position().left;

				if (position_css != 'relative') {
				    pos = pos - offset;
				}
			    }

			    animateSubmissionList(container, 1, pos);
			    
			}
			else if (childPos >= rightEdge) {   // the page is offscreen to the right
			    pos = container.find("ul#page_" + page_num).position().left;

			    // calculate position for animism homepage or browse entries
			    if (total_pages == 4 || total_pages == 9) {
				if (position_css != 'relative') {
				    pos = pos - offset;
				}
			    }

			    animateSubmissionList(container, -1, pos);
			}

			return false;  // break out of the loop
		    }
		    else {
			if (index == container.children().length - 1) {  // we didn't find any id's greater than this one, just appened our new ul at the end
			    $(new_page).appendTo(container);
			    pos = container.find("ul#page_" + page_num).position().left;   // we want the new page's left position inside the container

			    // animism homepage or browse entries
			    if (total_pages == 4 || total_pages == 9) {
				if (position_css != 'relative') {
				    pos = pos - offset;
				}
			    }
			    animateSubmissionList(container, -1, pos);
			}
			
		    }

		});
		addPadding();

		// set the height of the submission list container if we're on facebook
		if ($('#jq_content_tiles')) {
		    var base_height = 262;
		    var rows = Math.ceil(container.find("ul#page_" + page_num).find('li').length/3);
		    var container_height = base_height*rows;
		    container.css('height', container_height);
		}
	    }
	    else {
	//	console.log(response);
		dom.html(response);
		addPadding();   // reset padding
		reset();        // reset event handlers
	    } 
	},
	error: function(response, exception) {
	    console.log(response + " " + exception);
	}
    });
    
}


/**
 * 8. animateSubmissionList - animates the submission list
 *
 * @params - obj, (the object to animate) direction (-1 animate left, 1 animate right), displace (displacement amount)
 * @return
 */
function animateSubmissionList(obj, direction, displace) {
    var container = obj;

    if (displace < 0) {
	displace = -displace;
    }

    if (direction == -1) {
	container.animate({"margin-left": "-=" + displace + "px"}, "slow");
    }
    else {
	container.animate({"margin-left": "+=" + displace + "px"}, "slow");
    }
}


/**
 * 9. animateBrowseScroller - animates scrolling to browse entries on the fan fiction page.
 *
 * @params
 * @return
 */
function animateBrowseScroller() {
    if ($("#jq_browse_entries").length > 0 && $("#jq_scroll_to").length > 0) { 
		var newPos = $("#jq_scroll_to").position().top;  // the end position of the scroller
		// scroll the screen if we're going out of view
	    if (typeof(FB) != "undefined") {
			FB.Canvas.scrollTo(0,newPos);
	    } else {  
		console.log("here");
			$('html,body').animate({scrollTop: newPos}, "slow");
	    }
	     
		// lights on and off.
  	 	var container = $("#jq_browse_entries");  
		var callback = function(){container.removeClass("lights_on", 600);};			
		container.addClass("lights_on", 900, callback);
    }
}  


/**
 * 10. addPadding - add a class to the middle user tiles for padding
 *
 * @params
 * @return
 */
function addPadding() {
    if ($(".submission_list").length > 0) {

	// for each submission list
	$(".submission_list").each(function(index) { 
	    var total = $(this).find('li').length;
	    var child = $(this).find('li').first();  // get the first child of all the li's
	    
	    var i = 0;
	    var pos;
	    for (i = 0; i < total; i++) {
		pos = child.index();

		if ((pos-1)%3 == 0) {
		    if (!child.hasClass("middle")) {
			child.addClass("middle");
		    }
		}

		child = child.next();
	    }

	});
    }
}


/**
 * 11. reset - resets the event handlers and dropkick plugin
 *
 * @params
 * @return
 */
function reset() {
    // initialize pagination click handlers
    if ($(".pagination").length > 0) {

	if ($("#jq_browse_entries").length > 0) { 
	    $("#jq_browse_entries .pagination a").bind("click", paginatorHandler);
	}

	if ($(".story").length > 0) {
	    $(".story .pagination a").bind("click", storyPagination);
	}
    }

    // set the height for the submission list container
    if ($('#jq_content_tiles')) {
	var container = $('.submission_list_container');
	var base_height = 262;
	var rows = Math.ceil(container.find("ul#page_1").find('li').length/3);
	var container_height = base_height*rows;
	container.css('height', container_height);
    }
    
} 



/**
 * 12. storyPagination - animates the pages of the story
 *
 * @params
 * @return
 */
function storyPagination(e) {
    e.preventDefault();
    var jq_clicked = $(e.currentTarget);   // the DOM object that fired the event
    var parent = jq_clicked.parent();
    var current = $(".story .current");           // need to add parent class here so it won't affect the story pagination
    var url = jq_clicked.attr('href');
    var page = jq_clicked.find('span').html();    // the page we're going to
    var container = $("#jq_pages");

    // we need to create the url for the current paginator
    var current_page = current.find('span').html();
    var url_start = url.substring(0, url.indexOf('/', url.indexOf('page')));
    var url_end = url.substring(url.indexOf('id'));
    var current_url = url_start + '/' + current_page + '/' + url_end;

    // set the selected object to unselected status
    current.html('<a class="ajax_paginator img_replace" href="' + current_url + '">' + current.html() + '</a>');
    current.children("a").bind("click", storyPagination);  // add the event listener to the newly created a tag
    current.removeClass("current img_replace");

    // set the unselected object to selected status and add anchor if needed
    if (!jq_clicked.hasClass("prev") && !jq_clicked.hasClass("next")) {
	parent.addClass("current img_replace");  // set the clicked object to selected status
	parent.html(jq_clicked.html());          // remove the a tags, but keep the span tags
    }
    else if (jq_clicked.hasClass("prev")) {
	if (parseInt(current_page) > 1) {    
	    var prev = current.prev();
	    url = prev.find('a').attr('href');
	    prev.addClass("current img_replace");      // set the prev object to selected status
	    prev.html(prev.find('a').html());          // remove the a tags, but keep the span tags
	    page = prev.find('span').html();
	}
    }
    else {
	var last_page = parent.prev().find('span').html();
	if (parseInt(current_page) < parseInt(last_page)) {
	    var next = current.next();
	    url = next.find('a').attr('href');
	    next.addClass("current img_replace");      // set the next object to selected status
	    next.html(next.find('a').html());          // remove the a tags, but keep the span tags
	    page = next.find('span').html();
	}
    }

    // handle the next and prev links
    var page_li = $('.story .pagination').find('li');
    var total_pages = $('.story .pagination').find('li').length;
    var prev_exists = false;
    var next_exists = false;
    
    if (page_li.find('.prev').length > 0) {  // if the prev link is there
	total_pages--;
	prev_exists = true;
    }

    if (page_li.find('.next').length > 0) {  // if the next link is there
	total_pages--;
	next_exists = true;
    }

    // we need to generate or change the next link if we're not on the last page
    if (parseInt(page) < total_pages) {
	var next_page = parseInt(page) + 1;
	var next_url = url_start + '/' + next_page + '/' + url_end;

	if (!next_exists) {  // generate the link
	    $('<li><a class="next img_replace" href="' + next_url + '"><span>Next</span></a></li>').appendTo('.story .pagination ul');
	    $(".story .next").bind("click", storyPagination);
	}
	else {  // just change the href
	    $('.story .next').attr('href', next_url);
	}
    }
    else {  // remove next link from view
	$('.story .next').parent().remove();
    }

    
    // we need to generate or change the prev link if we're not on the first page
    if (parseInt(page) > 1) {
	var prev_page = parseInt(page) - 1;
	var prev_url = url_start + '/' + prev_page + '/' + url_end;
	
	if (!prev_exists) {
	    $('<li><a class="prev img_replace" href="' + prev_url + '"><span>Next</span></a></li>').prependTo('.story .pagination ul');
	    $(".story .prev").bind("click", storyPagination);
	}
	else {  // just change the href
	    $('.story .prev').attr('href', prev_url);
	}
    }
    else {  // remove the prev link from view
	$('.story .prev').parent().remove();
    }

    // get the position of the element we want to show
    var pos = container.find("#page_" + page).position().left;

    // do the animations
    if (parseInt(current_page) < parseInt(page)) {
	animateSubmissionList(container, -1, pos);
    }
    else {
	animateSubmissionList(container, 1, pos);
    }
    
    return false;
}



/**
 * 13. browseFilter - gets the values of the checked input boxed for the browse entries filter
 *
 * @params
 * @return
 */
function browseFilter(e) {
    var inputs = $('.browse_filter').find('input');
    var url = $('.browse_filter').attr('action');
    var url_canon = url.indexOf('/canon');
    var url_themes = url.indexOf('/themes');
    var url_start = '';
    var temp_url = '';
    var canon = $('.browse_filter').find('[name="canon"]');
    var canon_val = 0;
    var input_vals = '';
    
    // get the value of canon
    if (canon.attr('checked') == 'checked' || canon.attr('checked') == true) {
	canon_val = 1;
    }
    else {
	canon_val = 0;
    }
    
    // get the values of the other check boxes
    inputs.each(function(index) {
	if (inputs[index].name != "canon") {
	    if (inputs[index].checked == 'checked' || inputs[index].checked == true) {
		if (input_vals.length == 0) {
		    input_vals = inputs[index].value;
		}
		else {
		    input_vals = input_vals + ',' + inputs[index].value;
		}
	    }
	}
    });

    // if nothing is checked, set it to 0
    if (input_vals.length == 0) {
	input_vals = 0;
    }
    
    // if the url already has canon in it
    if (url_canon >= 0) {
	url_start = url.substring(0, url_canon);
	url = url_start + '/canon/' + canon_val + '/themes/' + input_vals
    }
    else {
	url = url + '/canon/' + canon_val + '/themes/' + input_vals;
    }
	
    // call ajax with the new url
    loadAjax('#jq_browse_entries', url);
}



/**
 * 14. filterMyStories - gets the values of the selected filter option
 *
 * @params
 * @return
 */
function filterMyStories(e) {
    e.preventDefault();
    var clicked = $(e.currentTarget);
    var url = clicked.attr('href');
    var selected = "";

    // call ajax
    if (!clicked.hasClass('selected')) {
	// find the link with the selected class
	selected = $('#my_stories_filter').find('.selected');

	// removed the selected class
	selected.removeClass('selected');

	// add the selected class to the clicked link
	clicked.addClass('selected');

	// call ajax
	loadAjax('#jq_filter_entries', url);
    }

    return false;
}



/**
 * 14. changeState - changes the state of the browse entries filter
 *
 * @params
 * @return
 */
function changeState(e) {
    var jq_clicked = $(e.currentTarget);
    var inputs = $('.browse_filter').find('input');
    var canon = $('.browse_filter').find('[name="canon"]');

    // if canon was checked
    if (jq_clicked.attr('name') == 'canon') {
	// uncheck everything else
	if (jq_clicked.attr('checked') == 'checked' || jq_clicked.attr('checked') == true) {  // canon is selected
	    // uncheck all the other inputs
	    inputs.each(function(index) {
		if (inputs[index].name != "canon") {
		    inputs[index].checked = false;
		}
	    });
	}	
    }
    else {  // otherwise uncheck the canon checkbox
	canon = canon.attr('checked', false);
    }
}


/**
 * 15. showEmailPopup - shows the email popup when the user votes on a story
 *
 * @params - 
 * @return
 */
function showEmailPopup() {
    var popup = $('#email_popup');

    if (popup.length > 0) {
	popup.css('display', 'block');
    }
}


/**
 * 16. submitVote - validates the email form and sends it if everything is valid or the skip button is pressed
 *
 * @params - e (click event)
 * @return
 */
function submitVote(e) {
    var jq_clicked = $(e.currentTarget);
    var email = $('#email').val();
    var error = $('#email_popup').find('.error');
    var errors = 0;
    var email_filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (jq_clicked.hasClass('email_submit')) {   // only validate if it's the submit button
	// validate input field
	if (email.length == 0) {
	    error.html('Please enter your email before submitting.');
		error.css('display', 'block');
	}
	else {
	    if (!email_filter.test(email)) {
		errors++;
	    }

	    if (errors > 0) {  // display error message
		error.html('Please enter a valid email address.');
		error.css('display', 'block');
	    }
	    else {   // submit the form
		$('#email_popup').submit();
	    }
	}
    }
    else {  // otherwise just submit an empty form
	$('#email_popup').submit();
    }
}
