$(function(){

jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeOut = function(speed, callback) { 
    return this.animate({opacity: 'hide'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 
 
jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
}; 


function getCookie(c_name){
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

	//Home image functions
	$('.homeImageBox').hover(
		function(){
			if(!getCookie('fecms_autologout')){
				$(this).css("cursor","pointer");
				$('h2, h2 a',this).addClass("homeImageBoxH2Hover");
				$('img, div',this).stop().fadeTo(200, 0.4);
			}
		}, function(){
			$('h2, h2 a',this).removeClass("homeImageBoxH2Hover");
			$('img, div',this).stop().fadeTo(200, 1);
	});
	
	$('.homeImageBox').click(function(){ $('h2 a',this).attr('target')=='_blank' ? window.open($('h2 a',this).attr('href')) : window.location = $('h2 a',this).attr('href'); });

	//Menu Animation
	$('#topMenu li:not(.menuCurrent)').hover(
		function(){
			$(this).animate({'bottom':6,'height':41},150);
			$('a',this).addClass('menuaHOVER');
		},
		function(){
			$(this).animate({'bottom':0,'height':36},150);
			$('a',this).removeClass('menuaHOVER');
		}
	);
	
	//Menu Click
	$('#topMenu li:not(.menuCurrent)').click(function(){
		window.location = $('a',this).attr('href');
	});
	
	//Gallery
	$("a.galleryImg").fancybox(); 
	
	//YouTube Listings
	//Instead of normally going to the YouTube page to view the view, this will load the video in an overlay
	$('.youtubeListing .youtubeThumb a').click(function(e){e.preventDefault()});
	$('.youtubeListing .youtubeThumb').click(function(){
			var vidLink = $('a:first',this).attr('href');
			$('#fancyajax').html("<div id='youtubeVid' />");
			$('#fancyajax #youtubeVid').flash(
				{height:344, width:425},{version:8},
				function(htmlOptions) {
					htmlOptions.src = vidLink;
					$(this).html($.fn.flash.transform(htmlOptions));
				}
			);
			$("#fancyajaxtrigger").fancybox({'frameWidth':425,'frameHeight':344,'hideOnContentClick':false}).trigger('click');
	});
	
	//Form Validation
	$("#contactForm, #mailingForm, #blogCommentForm").submit(function(){ return formValidation($(this)); });
	
	//Shopping Cart	
	function ajaxCart(addItem){
		var dataVar = addItem ? 'itemId='+addItem : '';
		
		//If FE is running from a subdir, the cookie will be saved and is used to find the absolute path for the ajax file. Otherwise ignored and executed from the root of the domain
		subDirUrl = $.cookie('fecms_subdir')!=null ? $.cookie('fecms_subdir') : '';
		
		$.ajax({type: "POST", url:subDirUrl+"/fecms/objects/store/main.php", data:dataVar, success:function(xml){ 
				$(xml).find('xmldata').each(function(){
					var cookieId = $(this).find('cartid').text();
					if(!$.cookie('cartid') && cookieId!='') $.cookie('cartid',cookieId);
					var itemCount = $(this).find('itemcount').text();
					itemCount==0 ? $('.currStoreItems').addClass('hide') : $('.currStoreItems').removeClass('hide');
					itemCount = itemCount>1 ? itemCount+' items' : itemCount+' item';
					$('.currStoreItems .currStoreCount').text(itemCount);

					var itemTotal = $(this).find('carttotal').text();
					$('.currStoreItems .currStoreTotal').text(itemTotal);
				});
			} 
		});
	}
	
	function addToCart(){
		var $this = $(this);
		
		//Half the height and width of the animated object
		var aniWidth = 28;
		var aniHeight = 24;

		//Get the central positions of the cart button and the cart
		var itemPos = $this.offset();
		itemPos['left'] = itemPos['left'] + ($this[0].offsetWidth/2) - aniWidth;
		itemPos['top'] = itemPos['top'] + ($this[0].offsetHeight/2) - aniHeight;
		var cartPos = $('.currStoreItems').offset();
		cartPos['left'] = cartPos['left'] + ($('.currStoreItems')[0].offsetWidth/2) - aniWidth;
		cartPos['top'] = cartPos['top'] + ($('.currStoreItems')[0].offsetHeight/2) - aniHeight;

		//'Bounce' the add to cart button
		$this.animate({'top':'+6'},100).animate({'top':0},100);
		
		//The speed for the animated object to move at (relative to its distance from the cart)
		var speed = itemPos['top'] - cartPos['top'] + 100;
		
		//Animate to 'item' from the cart button to the cart
		$('<div class="animateItem" />')
			.prependTo('body')
			.css({'top':itemPos['top'],'left':itemPos['left']})
			.animate({'top':cartPos['top'],'left':cartPos['left']},speed,'linear',function(){ajaxCart(parseInt($this.parent().parent().attr('id').match(/[0-9]+$/gi)[0]))})
			.animate({'opacity':0},{queue:false,duration:speed+200})
			.animate({'opacity':0},200,function(){$(this).remove()});
	}
	
	$('.storeItem .itemAdd').click(addToCart);
	
	//Removes a cart if a cookie exists but the cart isn't visible (hence, the cart is invalid/empty
	if($.cookie('cartid') && $('.currStoreItems').hasClass('hide')) $.cookie('cartid',null);
})


//Form Validation
function formValidation($form){
	var errors = 0;
	
	$('.reqField',$form).each(function(){
									   
									  
		if(!$(this).val() || ($(this).val() && $(this).hasClass('reqEmail') && !validateEmail($(this).val()))){
			errors++;
			$(this).addClass('reqFieldError');
			$(this).click(function(){
				$('#validationNotice',$form).fadeOut(250,function(){ $(this).remove() });
				$(this).removeClass('reqFieldError').unbind('click');
			});
		}
	});
	
	if(errors){
		$('#validationNotice',$form).remove();
		$('#submit',$form).after('<span id="validationNotice">Please fill out all the required fields before submitting.</span>');
		return false;
	}
	
	return true;
}

function validateEmail(val){      
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailPattern.test(val); 
}