/*******************************************************************************************************************************************
 * Autoalign */

jQuery(document).ready(function() {
	jQuery(".sb_wrapper").autoAlign(".widget-container", 55);
	jQuery(".featured_boxes").autoAlign(".featured", 50);
	jQuery(".services").autoAlign(".service_box", 50);
	jQuery(".services2").autoAlign(".service_box", 50);
	jQuery(".services3").autoAlign(".service_box", 0);
	jQuery(".services4").autoAlign(".service_box", 0);
});

/*******************************************************************************************************************************************
 * Nivo Slider */

$(document).ready(function(){
	$('#nivo-slider').nivoSlider({
		effect:'fade', //Specify sets like: 'fold,fade,sliceDown'
		captionOpacity:0.9,
		animSpeed:500,
		pauseTime:6000,
		directionNav:true, //Next and Prev
		directionNavHide:false,
		controlNav:false //1,2,3...
	});
});

/*******************************************************************************************************************************************
 * jQuery Tabs */

$(document).ready(function() {
	$("#tabs").tabs({ fx: { height: 'toggle', opacity: 'toggle' } });
});
		
/*******************************************************************************************************************************************
 * Cufon */

var cufon_font = "FallForYou";

//Cufon.replace('h1, h2, h3, h4, h5, h6, .big_btn', { fontFamily: 'MgOpen Modata', hover: true });
//Cufon.replace('a.big_btn', { fontFamily: 'MgOpen Modata', color: '#fff', hover: true });
//Cufon.replace('#f_sidebar h3', { fontFamily: 'MgOpen Modata', color: '#fff', textShadow: '1px 1px rgba(0, 0, 0, 0.4)' });
//Cufon.replace('.error404, .s3sliderImage b.title');
Cufon.replace('h1, h2, h3, h4, h5, h6, .big_btn', { fontFamily: cufon_font, hover: true });
Cufon.replace('a.big_btn', { fontFamily: cufon_font, color: '#fff', hover: true });
Cufon.replace('#f_sidebar h3', { fontFamily: cufon_font, color: '#fff', textShadow: '1px 2px rgba(0, 0, 0, 0.4)' });
Cufon.replace('.error404, .s3sliderImage b.title');
Cufon.replace('#menu li a', { fontFamily: cufon_font, hover: true });
Cufon.replace('a.schedule-title, a.blog-title', { fontFamily: cufon_font, hover: true });


/*******************************************************************************************************************************************
 *  Image fading plugin */

$(document).ready(function() { 
	var apply = ".pic, .about-box img";
	$(apply).css({
		backgroundColor: "#fff",
		borderColor: "#D5D5D5"
	});
	$(apply).hover(function() {
		$(this).stop().animate({
			backgroundColor: "#666",
			borderColor: "#333"
		}, 300);
	},function() {
		$(this).stop().animate({
			backgroundColor: "#fff",
			borderColor: "#D5D5D5"
		}, 500);
	});
});
		
/*******************************************************************************************************************************************
 * Tiny Carousel */

$(document).ready(function(){
	$('.carousel_container').tinycarousel({
		start: 1, // where should the carousel start?
		display: 1, // how many blocks do you want to move at a time?
		axis: 'x', // vertical or horizontal scroller? 'x' or 'y' .
		controls: true, // show left and right navigation buttons?
		pager: false, // is there a page number navigation present?
		interval: 1000, // move to the next block on interval.
		intervaltime: 3000, // interval time in milliseconds.
		rewind: true, // If interval is true and rewind is true it will play in reverse if the last slide is reached
		animation: true, // false is instant, true is animate.
		duration: 1000, // how fast must the animation move in milliseconds?
		callback: null // function that executes after every move
	});	
});
		
/*******************************************************************************************************************************************
 * Tipsy */

$(function() {
	$('.social a').tipsy(
	{
		gravity: 's', // nw | n | ne | w | e | sw | s | se
		fade: true
	}); 
	$('.our-friends li a').tipsy(
	{
		gravity: 'w', // nw | n | ne | w | e | sw | s | se
		fade: true
	}); 
	$('.upcoming li span').tipsy(
	{
		gravity: 'w', // nw | n | ne | w | e | sw | s | se
		fade: true
	}); 
});

/**jQuery Quicksand */

function reloadPrettyPhoto() {
	jQuery(".pp_pic_holder").remove();
	jQuery(".pp_overlay").remove();
	jQuery(".ppt").remove();
	// edit it with your initialization
	jQuery('#portfolio a[rel^="prettyPhoto"]').prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		opacity: 0.70, /* Value between 0 and 1 */
		showTitle: false, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'dark_rounded' /* light_rounded / dark_rounded / light_square / dark_square / facebook */
	});
}
jQuery(document).ready(function($) {

	// bind radiobuttons in the form
	var $filterType = $('#filter a');

	// get the first collection
	var $list = $('#portfolio');

	// clone applications to get a second collection
	var $data = $list.clone();

	$filterType.click(function(event) {

		if ($(this).attr('rel') == 'everyone') {
			var $sortedData = $data.find('li');
		} else {
			var $sortedData = $data.find('.'+ $(this).attr('rel'));
		}

		$('#filter li a').removeClass('current_link');
		$(this).addClass('current_link');

		$list.quicksand($sortedData, {
			attribute: 'id',
			duration: 800,
			easing: 'easeInOutQuad',
			adjustHeight: 'auto',
			useScaling: 'false'
		}, function() {
			jQuery(".pic").css({
				backgroundColor: "#fff",
				borderColor: "#D5D5D5"
			});
			jQuery(".pic").hover(function() {
				jQuery(this).stop().animate({
					backgroundColor: "#666",
					borderColor: "#333"
				}, 300);
			},function() {
				jQuery(this).stop().animate({
					backgroundColor: "#fff",
					borderColor: "#D5D5D5"
				}, 500);
			});
			reloadPrettyPhoto();

		});

		return false;
	});

});
	
/*******************************************************************************************************************************************
 * Fading and preloading images */
 
$(document).ready(function() {
	// find the div.fade elements and hook the hover event
	$('a.gall').hover(function() {
		// on hovering over find the element we want to fade *up*
		var fade = $('> .hover_img', this);
 
		// if the element is currently being animated (to fadeOut)...
		if (fade.is(':animated')) {
			// ...stop the current animation, and fade it to 1 from current position
			fade.stop().fadeTo(300, 1);
		} else {
			fade.fadeIn(300);
		}
	}, function () {
		var fade = $('> .hover_img', this);
		if (fade.is(':animated')) {
			fade.stop().fadeTo(300, 0);
		} else {
			fade.fadeOut(300);
		}
	});
 
	// get rid of the text
	$('a.gall > .hover_img').empty();
});

$(document).ready(function() {
	// find the div.fade elements and hook the hover event
	$('a.gall').hover(function() {
		// on hovering over find the element we want to fade *up*
		var fade = $('> .hover_vid', this);
 
		// if the element is currently being animated (to fadeOut)...
		if (fade.is(':animated')) {
			// ...stop the current animation, and fade it to 1 from current position
			fade.stop().fadeTo(300, 1);
		} else {
			fade.fadeIn(300);
		}
	}, function () {
		var fade = $('> .hover_vid', this);
		if (fade.is(':animated')) {
			fade.stop().fadeTo(300, 0);
		} else {
			fade.fadeOut(300);
		}
	});
 
	// get rid of the text
	$('a.gall > .hover_vid').empty();
});

/*******************************************************************************************************************************************
 * HTML5 Placeholder Fix */

jQuery.placeholder = function() {
	$('[placeholder]').focus(function() {
		var input = $(this);
		if (input.hasClass('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function() {
		var input = $(this);
		if (input.val() === '') {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		}
	}).blur().parents('form').submit(function() {
		$(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.hasClass('placeholder')) {
				input.val('');
			}
		});
	});
  
	// Clear input on refresh so that the placeholder class gets added back
	$(window).unload(function() {
		$('[placeholder]').val('');
	});
};

// If using AJAX, call this on all placeholders after submitting to 
// return placeholder
jQuery.fn.addPlaceholder = function() {
	return this.each(function() {
		var input = $(this);
		input.addClass('placeholder');
		input.val(input.attr('placeholder'));
	});
};

//Call function on page load
$(document).ready(function(){	
	$.placeholder();
});

/*******************************************************************************************************************************************
 * Lightbox functions */

var lb_close_btn = '<a href="#" onclick="javascript: return hide_lightbox(500);" class="btn close-btn">Close</a>';

function set_lightbox(content, show_close)
{
	if (show_close == null || show_close == true)
		show_close = lb_close_btn;
	else
		show_close = '';
	$('#lightbox-content').html(content + show_close);
	Cufon.replace('#lightbox-container h3', { fontFamily: cufon_font, hover: true });
	return false;
}

function ajax_lightbox(url, size, speed, show_close)
{
	scroll(0,0);
	set_lightbox("<div class='loader'></div>", show_close);
	show_lightbox(speed, function(){
		if (show_close == null || show_close == true)
			show_close = lb_close_btn;
		else
			show_close = '';
		set_lightbox_size(size);
		$('#lightbox-content').load(url, function(){
			$('#lightbox-content').append(show_close);
			Cufon.replace('#lightbox-container h3, #lightbox-container h6', { fontFamily: cufon_font, hover: true });
		});
	});
	return false;
}

function show_lightbox(speed, callback)
{
	if (speed == null || speed < 0) speed = 500;
	$('#lightbox-container, #lightbox-overlay').css({'opacity' : '0', 'display' : 'block'});
	$('#lightbox-container').animate({'opacity' : '1'}, speed, 'linear', function(){
		if (callback != null) callback();
	});
	$('#lightbox-overlay').animate({'opacity' : '0.8'}, speed, 'linear');
	return false;
}

function hide_lightbox(speed)
{
	if (speed == null || speed < 0) speed = 500;
	$('#lightbox-container').animate({'opacity' : '0'}, speed, 'linear',function(){
		$('#lightbox-container').css({'display' : 'none'});
	});
	$('#lightbox-overlay').animate({'opacity' : '0'}, speed, 'linear', function(){
		$('#lightbox-overlay').css({'display' : 'none'});
		set_lightbox(" ",false);
	});
	return false;
}

function set_lightbox_size(size)
{
	$('#lightbox-content').removeClass().addClass("size-" + size);
}

$("#lightbox-overlay").live("click", function(){
	hide_lightbox(500);
});

/*******************************************************************************************************************************************
 * Cart Scripts */

function is_int(input){
	return parseInt(input) == input;
}

function initialize_cart_ajax(site_url)
{
	if (site_url == "") site_url = "/";
	
	//Ajax script for managing cart item deletion
	$('.ajax-delete').each(function(){
		var currItem = $(this);
		var row_id = $(currItem).attr('id').replace("ajax-delete-","");
		var loadUrl = site_url + "ajax/store-update-quantity/" + row_id + "/0/";
		$(currItem).click(function() {
			$("#ajax-notify").load(loadUrl, function(){
				if(confirm("Remove this item from your cart?"))
				{
					$(currItem).removeClass('ajax-delete');
					$(currItem).closest('.item').fadeOut(800);
					// If there are no more links with the 'ajax-delete'
					// class, then we must have already deleted
					// everything - thus we need to reload the page
					if ($('.ajax-delete').length == 0) location.reload();
				}
			});
			return false;
		});
	});
	
	//Ajax script for managing cart item quantity change
	var last_quantity = [];
	$('.ajax-quantity').each(function(){
		var row_id = $(this).attr('id').replace("ajax-quantity-","");
		last_quantity[row_id] = $(this).val();	//Preload with starting quantity
		$(this).bind('change keyup', function() {
			var quantity = $(this).val();
			if (quantity == "")
			{
				quantity = 1;
				$(this).val('1');
			}
			if ((is_int(quantity) && quantity >= 1))
			{
				if (last_quantity[row_id] != quantity)
				{
					last_quantity[row_id] = quantity;
					var loadUrl = site_url + "ajax/store-update-quantity/" + row_id + "/" + quantity;
					$("#ajax-notify").load(loadUrl);
					$("#ajax-item-total-" + row_id).fadeOut(100).text("$" + ($("#ajax-price-" + row_id).val().replace("$","") * quantity).toFixed(2)).fadeIn(100);
					var sub_total = 0.0;
					$('.item-total').each(function(){
						sub_total += 1 * $(this).text().replace("$","");
					});
					$("#ajax-sub-total").fadeOut(100).text("$" + sub_total.toFixed(2)).fadeIn(100);
				}
			}
			else
				$(this).val("" + last_quantity[row_id]);
		});
	});	
}

//Checks for any invalid fields on cart submit
function check_cart_submit(){
	errors = validate_cart();
	if (errors > 0)
	{
		if (errors == 1)
			alert("There is 1 product with an invalid quantity. Please correct it before proceeding.");
		else
			alert("There are " + errors + " products with invalid quantities. Please correct them before proceeding.");
		return false;
	}
	else
		return true;	
}

//Create jQuery checks for quantity on product page
function initialize_qty_check(inc)
{
	if (inc > 1)
	{
		$('#quantity-field').bind('change keyup', function() {
			if ($('#quantity-field').val() <= 0)
				$('.qty-alert').show();
		});
	}
}

//Shows submit button for product order form once javascript has loaded
function initialize_submit()
{
	$('#product-submit').show();
}

//Confirms before emptying a user's cart
function confirm_empty_cart()
{
	return confirm("Are you sure you wish to empty your cart?");
}

function add_to_cart(entry_id){
	$.ajax({
		'url': "/ajax/add-to-cart/" + entry_id + "/return-cart", 
		success: function(returned){
			if (returned == "")
				alert("You must be logged in first!");
			else
			{
				$('#cart-container').html(returned);
				Cufon.replace('#cart-container h4', { fontFamily: cufon_font, hover: true });
			}
		}
	});
	return false;
}

/*******************************************************************************************************************************************
 * Checkout Scripts */

function show_checkout_warnings(){
	if (class_schedule_warn != null && class_schedule_warn == true)
		$('#checkout-warnings, #class-schedule-warn').removeClass('hidden');

	if (local_pickup_warn != null && local_pickup_warn == true)
		$('#checkout-warnings, #local-pickup-warn').removeClass('hidden');
}

//Toggles visibility of the "add a coupon" form
function show_add_coupon()
{
	$('.enter-coupon').toggle();
	return false;
}

//This gives the "copy shipping address to billing address" checkbox all its power
$(document).ready(function(){
	//If reloading the page, make sure fields stay disabled if the box is selected
	if ($('#same-address').attr('checked') == 'checked')
		$('fieldset.billing input, fieldset.billing select').each(function(){
			if ($(this).attr('id') != 'same-address')
				$(this).attr('disabled','disabled');
		});
	//Copy info over on clicking the button
	$('#same-address').change(function(){
		if ($('#same-address').attr('checked') == 'checked')
		{
			$('fieldset.shipping_saved input, fieldset.shipping select').each(function(){
				$('fieldset.billing #' + $(this).attr('id').replace('shipping_','')).val($(this).val());
			});
			$('fieldset.billing input, fieldset.billing select').each(function(){
				if ($(this).attr('id') != 'same-address')
					$(this).attr('disabled','disabled');
			});
		}
		else
			$('fieldset.billing input, fieldset.billing select').each(function(){
				$(this).removeAttr('disabled');
			});
	});
	//Add an event to copy over an individual field after it's been changed as long as the box is checked
	$('fieldset.shipping input, fieldset.shipping select').change(function(){
		if ($('#same-address').attr('checked') == 'checked')
			$('fieldset.billing #' + $(this).attr('id').replace('shipping_','')).val($(this).val());
	});
});

//Checkout verification

function confirm_submit()
{
	var required = [];
	$('input.required, select.required').each(function(){
		if($(this).val() == "")
		{
			var temp = $("label[for='" + $(this).attr('name') + "']").text();
			if ($(this).parents('fieldset.shipping').length == 1)
				temp = "Shipping " + temp;
			if ($(this).parents('fieldset.billing').length == 1)
				temp = "Billing " + temp;
			required[required.length] = temp;
		}
	});
	if (required.length == 0)
	{
		$('input:disabled, select:disabled').removeAttr('disabled');
		$('#same-address').attr('checked',false);
		return true
	}
	else
	{
		alert("The following field(s) are required: " + required.join(', '));
		return false;
	}
}
