$(function() {
	$('#login_container').hide();
	$('#prayer_form_container').hide();
	$('.login_control').click(function(){
		$('#login_container').slideToggle("slow");
		return false;
	});
        
    var locationContent = $('#location').html();
    $('.groupThumbsLink').hover(function(){
    	$(this).nextAll('.groupThumbHover').show();	
    	var catRollover = $(this).parent().next('.author_name').html();
    	$('#location').html("<b>Read about: </b>"+catRollover);
    }, function(){
    	$(this).nextAll('.groupThumbHover').hide();
		$('#location').html(locationContent);
    });
        
    $('.prayer_control').click(function(){
    	$(this).toggleClass('prayer_open');
    	if($(this).hasClass('prayer_open')){
    		$(this).children().text('Close');
    		$(this).children().css({
    			"width" : 50,
    			"background-position" : "-210px bottom"
    		});
    	} else {
    		$(this).children().text('Click here to write a prayer request');
    		$(this).children().css({
    			"width" : 180,
    			"background-position" : "-80px bottom"
    		});
    	}
		$('#prayer_form_container').slideToggle("slow");
		return false;
	});   
        
        
    $("a[href^=http]").each(
    	function(){
        	if(this.href.indexOf(location.hostname) == -1) {
        		$(this).attr('target', '_blank');
      		}
    	}
  	)
        
	$("h2")
        .wrapInner("<span>")

    $("h2 br")
        .before("<span class='spacer'>")
        .after("<span class='spacer'>");

    $('.hover_marker').hide();
    $('.contributor_thumb_marker').hide(); 
    $('.related_marker').hide();

	$('.related_entry_container a, .frontpage_thumbnail a').hover(function(){
    	$(this).next().show();
    	var id = $(this).nextAll('.hover_entry_number').text();
    	
    	$.post("http://www.redeemercentral.com/scripts/related_hover.php", {entryid: id}, function(data){
  			$('#hover_entry_title').html("<b>"+data+"</b>");
		});
    }, function(){
    	$(this).next().hide();
    	$('#hover_entry_title').text("");
    	id = 0;
    });

	$('.spotlight_single_entry p:first').next().css("font-weight", "bold"); 
	
	

	//offy = $('#grid_container').offset().top;
	//offx = $('#grid_container').offset().left;	
	offy = 0;
	offx = 0;
	arrange();        

	weblogName = $('#weblog_name').text();

  	//Align Icons
  	iconAlign();
  	
	//Remove Entry
	removeEntry();
    
    //superScroller;
    superScroll();

    filterTag();
    
    filterAuthor();

	//Yellow group indicator
	var groupPosition = $('#group_filter_id').text();
	gPosition ="#id"+groupPosition;
	$(gPosition).show();
	
	//PRAYER FORM
	$('#prayer_form').validate({
		rules: {
			prayer_name: {
				minlength: 2,
				required: true
			},
			prayer_email: {
				required: true
			},
			prayer_content: {
				required: true,
				minlength: 5
			}
		},
		messages: {
		    prayer_name: {
		    	minlength: "Please enter 2 or more characters",
		    	required: "Please enter your Name"
		    },
		    prayer_email: {
		    	email: "Please enter a valid email address",
		    	required: "Please enter an email address"
		    },
		    prayer_content: {
		    	required: "Please enter your prayer request",
		    	minlength: "Please enter more than 5 characters"
		    }
		},
		submitHandler: function() {
			$('#prayer_form').ajaxSubmit({
				url: 'http://www.redeemercentral.com/scripts/prayerform.php',
				success: function() {
                 	$('#prayer_form').html('<p class="summary">Your prayer request has been successfully posted.</p><p>It will now go for moderation and will go onto the site if acceptable.</p>');
                 	Cufon.replace('.summary', {fontFamily: 'Archer', hover: true, fontWeight : 400});
                }
           	});
		}
    });
	
	//Prayer Entries    
    $('.prayer_entry a.img').hover(function(){
    	$(this).next('.prayer_image_rollover').show();
    }, function(){
    	$(this).next('.prayer_image_rollover').hide();
    });
     
    $('.prayer_entry a.img').click(function(e){  
    	$('.prayer_content_container').fadeOut(300);
    	$(this).nextAll('.prayer_content_container').children('.arrow').show();
    	$(this).nextAll('.prayer_content_container').children('.arrowRight').hide();
		if((860 - e.pageX) > 260){
			$(this).parent().children('.prayer_content_container')	
				.fadeIn(500);	
		} else {
			$(this).nextAll('.prayer_content_container').children('.arrow').hide();
			$(this).nextAll('.prayer_content_container').children('.arrowRight').show();
			$(this).parent().children('.prayer_content_container')
				.css('left', '-264px')
				.fadeIn(500);
				
		}
		return false;
	});
	
	$('a.prayer_info_close').click(function(){
		$(this).parent().parent().fadeOut(500);
		return false;
	});
});

//FILTER POSTS
function filterTag(){
	$('a.tag_filter').click(function(e){	
	   	e.preventDefault();
	   	var weblogName = $('#weblog_name').text();
	   	var $link = $(this);
		var catName = $link.text();
		var selectTag = $link.attr('rel');
		$('#selectedTag').html("").html(' / Category: <span id="set_tag_id" rel="C'+selectTag+'">'+catName+'</span> <a href="#" title="Clear Filter" class="remove_tag_filter"><span class="pink_cross"></span></a>');
		var authorIsset = $('#set_author_name').text();
		var authorPassed = $('#set_author_name').attr('rel');
		if(weblogName == "resources"){
			$('.resources_entry_outer_container').fadeOut(500).remove();
		} else {
			$('.spotlight_entry_grid_container').fadeOut(500).remove();
		}
		$('#grid_container').fadeTo(500, 0.01);
		$('#loading').show();
		if(authorIsset == ""){
			loadEntries("", selectTag, weblogName);				
		} else {
			loadEntries(authorPassed, selectTag, weblogName);	
		}
	});
}

function filterAuthor(){
	$('a.author_filter').click(function(e){	
	   	e.preventDefault();
	   	var weblogName = $('#weblog_name').text();
	   	var $authorLink = $(this);
		var $author = $authorLink.attr('rel');
		var $authorName = $authorLink.next('.author_name').text();
		$('#selectedAuthor').html("").html(' / Author: <span id="set_author_name" rel="'+$author+'">'+$authorName+'</span> <a href="#" title="Clear Filter" class="remove_tag_filter"><span class="pink_cross"></span></a>');		
		var $tagIsset = $('#set_tag_id').text();
		var $tagPassed = $('#set_tag_id').attr('rel');
		if(weblogName == "resources"){
			$('.resources_entry_outer_container').fadeOut(500).remove();
		} else {
			$('.spotlight_entry_grid_container').fadeOut(500).remove();
		}
		$('#grid_container').fadeTo(500, 0.01);
		$('#loading').show();
		if($tagIsset == ""){
			loadEntries($author, "", weblogName);			
		} else {
			loadEntries($author, $tagPassed, weblogName);		
		}		
	});
}

function removeFilter(web){
	$('a.remove_tag_filter').click(function(e){
		e.preventDefault();
		var $thisLink = $(this);		
		
		var tagCheck = $('#set_tag_id').text();	
		var authorCheck = $('#set_author_name').text();
		$thisLink.parent().html("");	
		
		if(tagCheck == "" || authorCheck == ""){
			$('.spotlight_entry_grid_container').fadeOut(500).remove();
			$('#loading').show();
			$('#grid_container').fadeTo(500, 0.01, function(){
				$("#grid_container").load(
					"http://www.redeemercentral.com/index.php/"+web+"/cleared_filter", 
					function(){
						$('#loading').hide();
						$('#grid_container').fadeTo(1000, 1);	
						arrange();
						iconAlign();
						removeEntry();				
						Cufon.replace('h3', {fontFamily: 'Archer', hover: true, fontWeight : 350});			
						Cufon.replace('.read_more', {fontFamily: 'Archer', hover: true, fontWeight : 350});	
	    				filterTag();
		 		});	
			});					
		} else if(tagCheck != "" && authorCheck != ""){
			var tagPassed = $('#set_tag_id').attr('rel');
			var authorPassed = $('#set_author_name').attr('rel');		
			$('.spotlight_entry_grid_container').fadeOut(500).remove();
			$('#loading').show();
			$('#grid_container').fadeTo(500, 0.01, function(){
				if(tagCheck !==""){
					loadEntries("", tagPassed, weblogName);
				}
				if(authorCheck !==""){
					loadEntries(authorPassed, "", weblogName);
				}
			});
		}
	});	
}

function loadEntries(author, tag, weblog){
$("#grid_container").load(
	"http://www.redeemercentral.com/index.php/"+weblog+"/filtered_results", 
	{authorN: author, catId: tag}, 
	function(){	
		arrange();
		iconAlign();
		removeEntry();
		Cufon.replace('h3', {fontFamily: 'Archer', hover: true, fontWeight : 350});			
		Cufon.replace('.read_more', {fontFamily: 'Archer', hover: true, fontWeight : 350});	
		Cufon.replace('.summary', {fontFamily: 'Archer', hover: true, fontWeight : 400});
		$('#loading').hide();
		$('#grid_container').fadeTo(1000, 1);
		filterTag();	
		removeFilter(weblog);	
	});	
}

//GRID VIEW FUNCTION
var MIN_COLS = 2;
var COL_WIDTH = 260;
var GAP = 40;
var GAPBOT = 20;
var offx, offy, topY = 0;
maxy = new Array();

function arrange() {
	// how many columns fits here?
	var columns = Math.max(MIN_COLS, parseInt($('#grid_container').innerWidth() / (COL_WIDTH+GAP)));
	$('.spotlight_entry_container_grid').css('width',COL_WIDTH + 'px');
		$('.twocols').css('width', COL_WIDTH*2 + GAP );
		$('.threecols').css('width', COL_WIDTH*3 + GAP*2);
	for (x=0; x < columns; x++) {
			maxy[x] = 0;
		}
		var maxHeight = 0;
	// lets iterate over all posts
	$('.spotlight_entry_container_grid').each(function(i) {
		var pos, cursor, w , altura= 0;
		w = (Math.floor($(this).outerWidth() / COL_WIDTH));
		cursor = 0;
		if (w>1) {
			for (x=0; x < columns-(w-1); x++) {
				cursor = maxy[x] < maxy[cursor] ? x : cursor;
			}
			pos = cursor;
			for (var x=0; x<w; x++) {
				altura = Math.max(altura, maxy[pos+x]);
			}
			for (var x=0; x<w; x++) {
				maxy[pos+x] = parseInt($(this).outerHeight()) + GAP + altura;
				$(this).css('left', pos*(COL_WIDTH+GAP) + offx).css('top',altura + offy);
				if (altura+topY > maxHeight) {
					maxHeight=maxy[pos+w-1];
				}
			}
		} else {
			for (x=0; x < columns; x++) {
				cursor = maxy[x] < maxy[cursor] ? x : cursor;
			}
			$(this).css('left', cursor*(COL_WIDTH+GAP) + offx).css('top',maxy[cursor] + offy);
			maxy[cursor] += $(this).outerHeight() + GAPBOT;
			if (maxy[cursor] > maxHeight) {
				maxHeight=maxy[cursor];
			}
		}
	});
	$('#grid_container').css("height", maxHeight+50+ 'px');
} 

//ALIGN VIDEO AND AUDIO ICONS FUNCTION
function iconAlign(){
    $('.video_icon').each(function(i) {  
    	var iconConta = parseInt($(this).parent().outerHeight());
    	var iconContb = (iconConta - 10);
    	var positionH = parseInt((iconContb/2)-12, 10);
    	$(this).css("top", positionH);
    });
    
    
    $('.audio_icon').each(function(i) {  
    	var aiconConta = parseInt($(this).parent().outerHeight());
    	var aiconContb = (aiconConta - 10);
    	var apositionH = parseInt((aiconContb/2)-12, 10);
    	$(this).css("top", apositionH);
    });
}

//REMOVE ENTRY FUNCTION
function removeEntry(){
    $('a.remove_entry').click(function(){
    	var leftVal = $(this).parent().parent().css("left");
    	var heightVal = parseInt($(this).parent().parent().outerHeight(), 10);
    	
    	var $entry = $(this).parent().parent();
    	var index = $("#grid_container .spotlight_entry_container_grid").index($entry);
    	$(this).parent().parent().fadeOut(500, function(){
					
				});
    	
    	$('.spotlight_entry_container_grid:gt('+index+')').each(function(i) {   
    		var curLeft = $(this).css("left");
	    	if(curLeft == leftVal){
	    		var topVal = parseInt($(this).css("top"), 10);
	    		var newTop = (topVal-(heightVal+13));
	    		$(this).animate({top: newTop});
	    	}
	    });
    	return false;
    }); 
}


//INFINITE SCROLL FUNCTION
function superScroll(){
	$('#grid_container').infinitescroll({
	    	debug           	: true,
			nextSelector    	: "a#next_page_link",
			loadingImg      	: "http://www.redeemercentral.com/images/ajax-loader.gif",
			loadingText         : " ",
			donetext        	: "<p>No more articles to load.</p>",
			navSelector     	: "#pagination",
			contentSelector 	: "#grid_container",
			animate      		: true,
			extraScrollPx		: 0,
			bufferPx     		: 40,
			itemSelector    	: "#grid_container > div.spotlight_entry_container_grid"
		},function(){ 
		$(function(){ 
			arrange();
			iconAlign();
			removeEntry();
			filterTag();
		   // filterAuthor();
			Cufon.replace('h3', {fontFamily: 'Archer', hover: true, fontWeight : 350});			
			Cufon.replace('.read_more', {fontFamily: 'Archer', hover: true, fontWeight : 350});
		});	
	});
}


//CUFON FUNCTIONS
Cufon.replace('h2', { 
	fontFamily: 'ITC Avant Garde Gothic', 
	hover: true
});

Cufon.replace('h3', { 
	fontFamily: 'Archer', 
	hover: true,
	fontWeight : 350
});

Cufon.replace('.read_more', { 
	fontFamily: 'Archer', 
	hover: true,
	fontWeight : 350
});

Cufon.replace('.summary', { 
	fontFamily: 'Archer', 
	hover: true,
	fontWeight : 400
});

Cufon.replace('ul#nav li', { 
	fontFamily: 'ITC Avant Garde Gothic', 
	hover: true
});

Cufon.replace('p.archer', { 
	fontFamily: 'Archer',
	hover: true,
	fontWeight : 350
});

Cufon.replace('p.archer_18', {
	fontFamily: 'Archer',
	fontWeight : 350
});