/**
 * Contains various scripts that help the Geibtastic theme work properly.
 */
currentURL = document.URL;
searchWord ='';
searchWordArray = '';
blogSearch = 's=';
searchStrLocation = currentURL.indexOf(blogSearch);

$.ajaxSetup ({
    // Disable caching of AJAX responses */
    cache: false
});

// Makes IE6 and under active links work properly.
$(function() {
	if ($.browser.msie && $.browser.version < 7) {
	    $('a, input').live('mouseover',function () {
			$(this).addClass('hover');
		});
	    $('a, input').live('mouseout',function () {
			$(this).removeClass('hover');
		});
	    $('a, input').live('mousedown',function () {
			$(this).addClass('active');
		});
	    $('a, input').live('mouseup',function () {
			$(this).removeClass('active');
		});
	}
});

// Defines a global element to use for scrolling.
if ($.browser.safari) {
	scrollElement = 'body';	
} else {
	scrollElement = 'html';
};

// Scroll to Top
$('a.goTop').live('click',function () {
	$(scrollElement).animate({scrollTop: 0},'slow');
});

// Main function for retrieving Ajax pages.
function getAjaxContent(url, highlight, data){
    $('#ajaxContent').hide();
	$('#ajaxHolder').addClass('loading');
	$('#ajaxHolder').load(url+' #ajaxContent',data, function() {
		$('#ajaxContent .globalSearchInput').val('Search Blog').addClass('fieldDefaultText');
		if (highlight) {
			$('#ajaxContent').highlight(highlight);
		}
		$('#ajaxHolder').removeClass('loading');
		$('#ajaxContent').show();
	});
}

// Allows the archives dropdown and blog nav to load into the ajaxHolder. Also controls their selected styling.
$('#archiveDropdown').live('change',function () {
	var archiveLink = $(this).find('option:selected').val();
	searchWord = '';
	searchWordArray = '';
	getAjaxContent(archiveLink, searchWordArray, '');
	$('.blogNavLink').removeClass('selected');
	if($("option.defaultOption:selected").length){
		$('.blogNavLink:last').addClass('selected')
	}
});
$('.blogNavLink').live('click',function () {
	var categoryLink = $(this).find('a').attr('href');
	searchWord = '';
	searchWordArray = '';
	getAjaxContent(categoryLink, searchWordArray, '');
	$('.blogNavLink').removeClass('selected');
	$('#archiveDropdown').find('option:first').attr('selected', 'selected').parent('select');
	$(this).addClass('selected');
	return false;
});	

// Loads previous and next pages using ajax.
$('.postNavOld a').live('click', function() {
	var oldLink = $(this).attr('href');
	$(scrollElement).animate({scrollTop: 0},'slow');
	getAjaxContent(oldLink, searchWordArray, '');
    return false;
});
$('.postNavNew a').live('click', function() {
	var newLink = $(this).attr('href');
	$(scrollElement).animate({scrollTop: 0},'slow');
	getAjaxContent(newLink, searchWordArray, '');
    return false;
});

// Loads highlights on blog page using ajax.
$(function() {
	if ($('#ajaxContent').length) {
		$('.highlightHolder a').live('click', function() {
			var highlightLink = $(this).attr('href');
			$(scrollElement).animate({scrollTop: 0},'slow');
			searchWord = '';
			searchWordArray = '';
			getAjaxContent(highlightLink, searchWordArray, '');
			$('#archiveDropdown').find('option:first').attr('selected', 'selected').parent('select');
			$('.blogNavLink').removeClass('selected');
		    return false;
		});
	}
});

// Displays Facebook status updater when logged in.
$('#statusUpdateLink').live('click',function(){
  if($(this).text() == 'Update') {
    $(this).text('Cancel');
	$('#statusUpdater').slideDown();
	$('#facebookStatusEntry').focus();
  }else{
    $(this).text('Update');
	$('#statusUpdater').slideUp();
	$('#facebookStatusEntry').val('');
  }
});

// Submits the Facebook status and updates the status with ajax.
$('.facebookStatusForm').live('submit',function() {
	var newStatusInput = $(this).find('#facebookStatusEntry').val();
	$('.blogNavLink').last().addClass('selected');
	$('#facebookAjaxHolder').load(wordpress_url+'/blog #facebookStatusText',{facebookStatusEntry: newStatusInput}, function() {
        $('#statusUpdateLink').text('Update');
		$('#statusUpdater').slideUp();
		$('#facebookStatusEntry').val('');
		$('#facebookStatusText').text(newStatusInput);
	});
	return false;
});

//Makes a set of images for lightbox per blog entry
$('.post, #featurelistContent .page').livequery(function(){
	$('.entry, .featureThumbHolder').each(function() {
		$(this).find('a:has(img)').lightBox({ // Select all links in object with gallery ID
			overlayOpacity: 0.2,
			overlayBgColor: '#000',
			imageLoading:template_directory+'/scripts/jquery-lightbox-0.5/images/lightbox-ico-loading.gif',
			imageBtnClose:template_directory+'/scripts/jquery-lightbox-0.5/images/lightbox-btn-close.gif',
			imageBtnPrev:template_directory+'/scripts/jquery-lightbox-0.5/images/lightbox-btn-prev.png',
			imageBtnNext:template_directory+'/scripts/jquery-lightbox-0.5/images/lightbox-btn-next.png',
			imageBlank:template_directory+'/scripts/jquery-lightbox-0.5/images/lightbox-blank.gif'
		});
	});
});

// Adds "search blog" to the search field.
$(function() {
	$('.globalSearchInput').val('Search Blog').addClass('fieldDefaultText');
	$('.globalSearchInput').live('focus',function() {
		if ($(this).val() == 'Search Blog') {
			$(this).val('').removeClass('fieldDefaultText');
		}
	});
	$('.globalSearchInput').live('blur',function() {
		if ($(this).val() == '') {
			$(this).val('Search Blog').addClass('fieldDefaultText');
		}
	});
	$('.globalSearchInput').live('keyup',function(){
		if ($(this).val() != '') {
			$(this).parents('.searchHolder').find('.searchReset').show();
			$(this).removeClass('fieldDefaultText');
			$('.globalSearchInput').not(this).val('Search Blog').addClass('fieldDefaultText');
			$('.globalSearchInput').not(this).parents('.searchHolder').find('.searchReset').hide();
		}
		else {
			$(this).parents('.searchHolder').find('.searchReset').hide();
		}
	});
	$('.searchReset').live('click',function(){
		var currentSearchVal = $(this).next('.searchPadder').find('.globalSearchInput').val();
		$(this).hide().next('.searchPadder').find('.globalSearchInput').val('').focus();
		if(searchWord == currentSearchVal){
			$('.blogNavLink').last().addClass('selected');
			$('#archiveDropdown').find('option:first').attr('selected', 'selected').parent('select');
			searchWordArray = '';
			getAjaxContent('blog', searchWordArray, '');
		};
	});
});

// Submits blog search via ajax if a user is on the blog tab.
$(function() {
	if ($('#ajaxContent').length) {
		if (searchStrLocation > -1){
			var searchUrlStr = currentURL.substring(searchStrLocation+2);
			searchWordArray = searchUrlStr.split("+");
			$('#ajaxContent').highlight(searchUrlStr.split("+"));
		};
		$('.searchform').live('submit',function() {
			searchWord = $(this).find('.globalSearchInput').val();
			searchWordArray = searchWord.split(" ");
			var searchHref = wordpress_url;
			var searchData = blogSearch + searchWord;
			if (searchWord == '') {
				$('.blogNavLink').last().addClass('selected');
				getAjaxContent('blog', searchWordArray, '');
			}
			else {
				$('.blogNavLink').removeClass('selected');
				getAjaxContent(searchHref, searchWordArray, searchData);
			}
			$('#archiveDropdown').find('option:first').attr('selected', 'selected').parent('select');
			return false;
		});
	};
});

// Image Hovers
$(function() {
	$('.highlightCycle1, .highlightCycle2, .highlightCycle3, .highlightCycle4').mouseover(function() {
		$(this).animate({opacity: 0.65}, { duration: 500, queue: false });
	}).mouseout(function(){
		$(this).animate({opacity: 1}, {duration: 500, queue: false });
	});
	$('#globalSidebar a img').mouseover(function() {
		$(this).animate({opacity: 0.65}, { duration: 500, queue: false });
	}).mouseout(function(){
		$(this).animate({opacity: 1}, {duration: 500, queue: false });
	});
	$('#blogContent a img').live('mouseover',function() {
		$(this).animate({opacity: 0.65}, { duration: 500, queue: false });
	})
	$('#blogContent a img').live('mouseout',function(){
		$(this).animate({opacity: 1}, {duration: 500, queue: false });
	});
	$('#featurelistContent a img').live('mouseover',function() {
		$(this).animate({opacity: 0.65}, { duration: 500, queue: false });
	})
	$('#featurelistContent a img').live('mouseout',function(){
		$(this).animate({opacity: 1}, {duration: 500, queue: false });
	});
	$('#galleryScrubber a span').live('mouseover',function() {
		$(this).not('.selected').animate({opacity: 0.65}, { duration: 500, queue: false });
	})
	$('#galleryScrubber a span').live('mouseout',function(){
		$(this).animate({opacity: 1}, {duration: 500, queue: false });
	});
	$('#galleryScrubber a span').live('mouseup',function(){
		$(this).animate({opacity: 1}, {duration: 500, queue: false });
	});
	$('#homeImageSecondaryHolder').mouseover(function() {
		$(this).find('img').animate({opacity: 0.65}, { duration: 500, queue: false });
	}).mouseout(function(){
		$(this).find('img').animate({opacity: 1}, {duration: 500, queue: false });
	});
});

// Input Styling
$('input, select, textarea').live('focus',function() {
	$(this).addClass('inputFocus');
}).live('blur',function() {
	$(this).removeClass('inputFocus');
});

// Round Corner Boxes
$(function(){
	if ($.browser.msie && $.browser.version < 7) {
	}else{
		$('.roundCornerBox').prepend('<div class="rcbtlc"></div><div class="rcbtrc"></div>'); // Select all links in object with gallery ID
		$('.roundCornerBox').append('<div class="rcbblc"></div><div class="roundCornerBoxFooter"></div><div class="rcbbrc"></div>'); // Select all links in object with gallery ID
		$('.roundCornerBox').addClass('roundCornerBoxActive');
	}
});

//ContactBar Cycler
$('#globalContactCycle').cycle({ 
    fx:'fade',
    easIn:'easeInQuad',
    easeOut:'easeOutQuad',
	timeout:4000,
	delay:-2000,
    speed:2000,
	pause:1
});

//Highlight Cyclers
$('.highlightCycle1').cycle({ 
    fx:'fade',
    easIn:'easeInQuad',
    easeOut:'easeOutQuad',
	timeout:8000,
	delay:-2000,
    speed:2000
});
$('.highlightCycle2').cycle({ 
    fx:'fade',
    easIn:'easeInQuad',
    easeOut:'easeOutQuad',
	timeout:8000,
	delay:0,
    speed:2000
});
$('.highlightCycle3').cycle({ 
    fx:'fade',
    easIn:'easeInQuad',
    easeOut:'easeOutQuad',
	timeout:8000,
	delay:2000,
    speed:2000
});
$('.highlightCycle4').cycle({ 
    fx:'fade',
    easIn:'easeInQuad',
    easeOut:'easeOutQuad',
	timeout:8000,
	delay:4000,
    speed:2000
});

//Gallery Scroller
$(function() {
	var itemsPerFrame = 17;
	var frameWidth = '867';
	var maxFrame = Math.floor($('#galleryScrubber .entry a').size() / itemsPerFrame);
	var currentFrame = 0;
	$('.galleryFrameIndicatorDot').first().addClass('selected');
	$('#galleryScrubberRight a').live('click',function() {
		if (currentFrame != maxFrame) {
			currentFrame += 1;
			$('.entry').scrollTo('+='+frameWidth, 500);
		};
		if (currentFrame == maxFrame) {
			$('#galleryScrubberRight a').addClass('disabled');
		};
		if (currentFrame > 0) {
			$('#galleryScrubberLeft a').removeClass('disabled');
		};
		$('.galleryFrameIndicatorDot').removeClass('selected');
		$(".galleryFrameIndicatorDot").eq(currentFrame).addClass('selected');
		return false;
	});
	$('#galleryScrubberLeft a').live('click',function() {
		if (currentFrame > 0) {
			currentFrame -= 1;
			$('.entry').scrollTo('-='+frameWidth, 500);
		};
		if (currentFrame != maxFrame) {
			$('#galleryScrubberRight a').removeClass('disabled');
		};
		if (currentFrame == 0) {
			$('#galleryScrubberLeft a').addClass('disabled');
		};
		$('.galleryFrameIndicatorDot').removeClass('selected');
		$(".galleryFrameIndicatorDot").eq(currentFrame).addClass('selected');
		return false;
	});
	$('#galleryFrameIndicator').css({width:(maxFrame + 1) * 12}).show();
	$('.galleryFrameIndicatorDot').live('click',function() {
		var index = $(".galleryFrameIndicatorDot").index(this);
		var indicatorLocation = index * frameWidth;
		currentFrame = index;
		$('.galleryFrameIndicatorDot').removeClass('selected');
		$(this).addClass('selected');
		$('.entry').scrollTo( indicatorLocation, 500);
		if (currentFrame == maxFrame) {
			$('#galleryScrubberRight a').addClass('disabled');
		};
		if (currentFrame > 0) {
			$('#galleryScrubberLeft a').removeClass('disabled');
		};
		if (currentFrame != maxFrame) {
			$('#galleryScrubberRight a').removeClass('disabled');
		};
		if (currentFrame == 0) {
			$('#galleryScrubberLeft a').addClass('disabled');
		};
		return false;
	});
});

// Image Reflections
$(function() {
	$("#galleryScrubber img").reflect({height: 7, opacity: 0.4});
	$(".featureMainImage").reflect({height: 30, opacity: 0.4});
});

//Gallery Image Select Function
function galleryImgSelect(elem) {
	if (!$(elem).find('span.selected').length) {
		$('#galleryScrubber span').removeClass('selected');
		$(elem).find('span').addClass('selected');
		var selectedImgSrc = $(elem).attr('href');
		var selectedImgTitle = $(elem).find('img').attr('title');
		var selectedImgDescr = $(elem).find('img').attr('alt');
		if ($.browser.msie) {
			$('#galleryDisplayTitle, #galleryDisplayDiscription').fadeTo('normal', 0);
		}
		$('#galleryDisplayHolder').fadeTo('normal', 0,function(){
			$('.galleryDisplayImage').remove();
			$('#galleryDisplayTitle').html('<a href="'+selectedImgSrc+'" target="_blank" title="View Full Size Image">'+selectedImgTitle+'</a>');
			$('#galleryDisplayDiscription').html(selectedImgDescr);
			$('#galleryDisplayImageHolder td').append('<img class="galleryDisplayImage" src="'+selectedImgSrc+'" />');
			$('#galleryDisplayImageHolder img').reflect({height: 30, opacity: 0.4}).load(function(){
				$('#galleryDisplayHolder, #galleryDisplayTitle, #galleryDisplayDiscription').fadeTo('normal', 1);
			});
		});
	}
};
//Runs the Gallery Image Select Function
$(function() {
	galleryImgSelect($('#galleryScrubber a').first());
	$('#galleryScrubber a').live('click',function(){
		galleryImgSelect($(this));
		return false;
	});
});

// Shows comments sections under posts with ajax.str.replace
thisCommentsLinkText = '';
thisCommentsPostCount = '';
thisCommentsLinkHref = '';
thisParentHolder = '';
$('a.commentsLink').live('click', function() {
	var thisCommentsLink = $(this);
	thisCommentsLinkHref = $(thisCommentsLink).attr('href').replace(/\u0023.*/, '');
	thisParentHolder = $(thisCommentsLink).parents('.post').find('.commentsAjaxHolder');
	var previousCommentsLink = $('a.commentsLink.opened').not(this);
	var previousParentHolder = $(previousCommentsLink).parents('.post').find('.commentsAjaxHolder');
	if ($(previousCommentsLink).length) {
		$(previousCommentsLink).text(thisCommentsLinkText);
		$(previousCommentsLink).removeClass('opened');
		$(previousParentHolder).slideUp('normal', function(){
			$(this).removeClass('loading');
			$(this).find('.commentsAjaxContent').remove();
		});
	}
	if ($(thisParentHolder).css('display') == 'none') {
		thisCommentsLinkText = $(thisCommentsLink).text();
		$(thisCommentsLink).addClass('opened');
		$(thisCommentsLink).text('Close Comments');
		$(thisParentHolder).find('.commentsAjaxContent').remove();
		$(thisParentHolder).addClass('loading');
		$(thisParentHolder).slideDown('normal', function(){
			$(this).load(thisCommentsLinkHref+' .commentsAjaxContent','', function() {
				$(this).removeClass('loading');
				$(this).find('.commentsAjaxContent').slideDown('slow');
				commentStyling();
				commentValidate($('#commentform'));
				thisCommentsPostCount = $(thisParentHolder).find('.approvedMod').size();
				if (thisCommentsPostCount > 1) {
					thisCommentsLinkText = thisCommentsPostCount + ' Comments';
				}else if (thisCommentsPostCount == 1) {
					thisCommentsLinkText = thisCommentsPostCount + ' Comment';
				}else{
						thisCommentsLinkText = 'Leave a Comment';
				}
			});
		});
	}else{
		$(thisCommentsLink).text(thisCommentsLinkText);
		$(thisCommentsLink).removeClass('opened');
		$(thisParentHolder).slideUp('normal', function(){
			$(this).removeClass('loading');
			$(this).find('.commentsAjaxContent').remove();
		});
	}
    return false;
});

commentValidateForm = '';
$('a.singleCommentsLink').live('click', function() {
	var thisCommentsLink = $(this);
	thisCommentsLinkHref = $(thisCommentsLink).attr('href').replace(/\u0023.*/, '');
	thisParentHolder = $(thisCommentsLink).parents('.post').find('.commentsAjaxHolder');
	if ($(thisParentHolder).css('display') == 'none') {
		thisCommentsLinkText = $(thisCommentsLink).text();
		$(thisCommentsLink).addClass('opened');
		$(thisCommentsLink).text('Close Comments');
		$('.commentsAjaxContent').show();
		commentStyling();
		commentValidate($('#commentform'));
		thisCommentsPostCount = $(thisParentHolder).find('.approvedMod').size();
		if (thisCommentsPostCount > 1) {
			thisCommentsLinkText = thisCommentsPostCount + ' Comments';
		}else if (thisCommentsPostCount == 1) {
			thisCommentsLinkText = thisCommentsPostCount + ' Comment';
		}else{
				thisCommentsLinkText = 'Leave a Comment';
		}
		$(thisParentHolder).slideDown('slow');
	}else{
		$(thisCommentsLink).text(thisCommentsLinkText);
		$(thisCommentsLink).removeClass('opened');
		commentValidateForm.resetForm();
		$(thisParentHolder).slideUp('normal');
	}
    return false;
});

function commentFormSubmit(commentForm){
	$('.submitStatus').show();
	var commentAuthorInput = $(commentForm).find('#author').val();
	var commentEmailInput = $(commentForm).find('#email').val();
	var commentUrlInput = $(commentForm).find('#url').val();
	var commentCommentInput = $(commentForm).find('#comment').val();
	var commentCommentPostID = $(commentForm).find('#comment_post_ID').val();
	var commentCommentParent = $(commentForm).find('#comment_parent').val();
	var commentCommentUnfiltered = $(commentForm).find('#_wp_unfiltered_html_comment').val();
	if (!commentCommentUnfiltered) {
		commentCommentUnfiltered = '';
	}
	if (commentUrlInput == 'Website') {
		commentUrlInput = '';
	}
	$.ajax({
		type: 'POST',
		url: wordpress_url+'/wp-comments-post.php',
		data: {
			author: commentAuthorInput,
			email: commentEmailInput,
			url: commentUrlInput,
			comment: commentCommentInput,
			comment_post_ID: commentCommentPostID,
			comment_parent: commentCommentParent,
			_wp_unfiltered_html_comment: commentCommentUnfiltered
		},
		success: function (){
			$('.commentsAjaxContent').remove();
			$('.commentsAjaxHolder').addClass('loading');
			$('.commentsAjaxHolder').load(thisCommentsLinkHref + ' .commentsAjaxContent', '', function(){
				$(this).removeClass('loading');
				$(this).find('.commentsAjaxContent').slideDown('slow');
				commentStyling();
				commentValidate($('#commentform'));
				thisCommentsPostCount = $(thisParentHolder).find('.approvedMod').size();
				if (thisCommentsPostCount > 1) {
					thisCommentsLinkText = thisCommentsPostCount + ' Comments';
				}else if (thisCommentsPostCount == 1) {
					thisCommentsLinkText = thisCommentsPostCount + ' Comment';
				}else{
						thisCommentsLinkText = 'Leave a Comment'
				}
			});
		},
		error: function(){
			alert('The comment you entered is a duplicate.');
			$('.submitStatus').hide();
		}
	});
}

// Comment form Validation and Styling
function commentValidate(commentForm) {
	commentValidateForm = $(commentForm).validate({
		errorElement: "span",
		focusInvalid: false,
		onfocusout: false,
		errorPlacement: function(error, element) {
				error.appendTo( element.parent("p").find("label") );
		},
		rules: {
			author: 'required',
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			author: 'Please enter your name.',
			email: 'Please enter a valid email address.'
		},
		submitHandler:function(form) {
			commentFormSubmit(form);
			return false;
		}
	});
}

function commentStyling(){
	inputLabel($('#commentform #author'),'Name');
	inputLabel($('#commentform #email'),'Email (Will not be shown)');
	inputLabel($('#commentform #url'),'Website');
	inputLabel($('#commentform #comment'),'Comments...');
}

function inputLabel(element, text){
	$(element).addClass('fieldDefaultText');
	$(element).val(text);
	$(element).live('focus', function(){
		if ($(this).val() == text) {
			$(this).val('').removeClass('fieldDefaultText');
		}
	});
	$(element).live('blur', function(){
		if ($(this).val() == '') {
			$(this).val(text).addClass('fieldDefaultText');
		}
	});
}
