/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * attaches a character counter to each textarea element in the jQuery object
	 * usage: $("#myTextArea").charCounter(max, settings);
	 */
	
	$.fn.charCounter = function (max, settings) {
		max = max || 100;
		settings = $.extend({
			container: "<p></p>",
			classname: "note",
			format: "(%1 characters remaining)",
			pulse: true,
			delay: 0
		}, settings);
		var p, timeout;
		
		function count(el, container) {
			el = $(el);
			if (el.val().length > max) {
			    el.val(el.val().substring(0, max));
			    if (settings.pulse && !p) {
					pulse(container, true);
			    }
			}
			if (settings.delay > 0) {
				if (timeout) {
					window.clearTimeout(timeout);
				}
				timeout = window.setTimeout(function () {
					container.html(settings.format.replace(/%1/, (max - el.val().length)));
				}, settings.delay);
			} else {
				container.html(settings.format.replace(/%1/, (max - el.val().length)));
			}
		}
		
		function pulse(el, again) {
			if (p) {
				window.clearTimeout(p);
				p = null;
			}
			el.animate({ opacity: 0.1 }, 100, function () {
				$(this).animate({ opacity: 1.0 }, 100);
			});
			if (again) {
				p = window.setTimeout(function () { pulse(el) }, 200);
			}
		}
		
		return this.each(function () {
			var container = (!settings.container.match(/^<.+>$/)) 
				? $(settings.container) 
				: $(settings.container)
					.insertAfter(this)
					.addClass(settings.classname);
			$(this)
				.bind("keydown", function () { count(this, container); })
				.bind("keypress", function () { count(this, container); })
				.bind("keyup", function () { count(this, container); })
				.bind("focus", function () { count(this, container); })
				.bind("mouseover", function () { count(this, container); })
				.bind("mouseout", function () { count(this, container); })
				.bind("paste", function () { 
					var me = this;
					setTimeout(function () { count(me, container); }, 10);
				});
			if (this.addEventListener) {
				this.addEventListener('input', function () { count(this, container); }, false);
			}
			count(this, container);
		});
	};

})(jQuery);	






// Document Ready
$(document).ready(function(){
	
	
	/**
	 *
	 * Common
	 * 
	 */
						   
	// Hide Messages
		$('div.message').fadeOut(3000);
	
				  
				  
						   
	/**
	 *
	 * Order Process
	 * 
	 */ 
	 
	// add hover styling to design and product thumbnails
		var fade_timer = false;
		$thumbs = $('#designs div.design, #products div.product');
		
		$thumbs.hover(
			function()
			{
				if(fade_timer !== false)
				{
					window.clearTimeout(fade_timer);
				}
				$thumbs.stop()
					.not(this).fadeTo('500', '.7')
					.end()
					
					.filter(this).css('opacity','1');
			},
			function()
			{
				fade_timer = window.setTimeout(
					function()
					{
						$thumbs.not(this).fadeTo('800', '1');
					},
					500);
			}
		);

	
	// Fancybox Jquery Plugin
	// Used for item previews on /order/add_info/...
		$('div.preview a').fancybox();
	
	
	// Clear Default Text on Click
		$('form.order input[type=text]').bind('click focus', function(evt)
			{
				$this = $(this);
				$val = $this.val();
				
				if($val === 'Enter Dates Here' || $val === 'Enter Times Here' || $val === 'Enter Ages Here')
				{
					$this.val('');
				}
			}
		);
	
	
	// Add Character Count to <textarea>
		$('textarea#who_extra').charCounter(120);
	
	
	
	//
	// Add Custom Form Submit Images
	//
		// Adding Info to Flyer
			$('form.order input#submit')
				.hide()
				.after('<a href="#" id="form_next" title="Send Message"><img src="/_img/btn_save_and_next.png" width="152" height="40" alt="Save and Next" /></a>');
		
			$('a#form_next').click(
				function(evt)
				{
					evt.preventDefault();
					$(this).prev('input').trigger('click');
				}
			);
			
		// Approving the Proof
			$('div#proof-approve input')
				.hide()
				.after('<a href="#" id="form_approve" title="Send Message"><img src="/_img/btn_save_and_next.png" width="152" height="40" alt="Save and Next" /></a>');
		
			$('a#form_approve').click(
				function(evt)
				{
					evt.preventDefault();
					$(this).prev('input').trigger('click');
				}
			);

			$('div#proof-change input')
				.hide()
				.after('<a href="#" id="form_change" title="Send Message"><img src="/_img/btn_back_up.png" width="102" height="40" alt="Back Up" /></a>');
		
			$('a#form_change').click(
				function(evt)
				{
					evt.preventDefault();
					$(this).prev('input').trigger('click');
				}
			);
		
		
		
	
	

	//
	// Warnings
	//

		// Confirm proof is ok
		$('div#proof-approve input').click(function() {
			
			if (confirm("This is exactly what we will print on this item. (We won't be sending you a proof). Is this ok?"))
			{
				return true;
			}
			else
			{
				return false;
			}
	
		});
		
		// Confirm that rush charge is ok
		$('form.shipping').submit(function() {
			
			if($('input[name="rush"]:checked').attr('value') === 'yes')
			{
				if (confirm('Rush orders are subject to an upcharge. (Just wanted to make sure you read the note). Is this ok?'))
				{
					return true;
				}
				else
				{
					return false;
				}
			}
	
		});
	
	
	
	
	/**
	 *
	 * Admin Area
	 * 
	 */
	 
	// Stripe Tables
		$('tr:even').addClass('alt');
	
	// Home Page Table
		$('table.admin-orders tr')
			// make rows look clickable
			.css('cursor','pointer')
			// jump to order detail on click
			.click(function(evt)
				{
					if($(evt.target).is('input'))
					{
						// do nothing
					}
					else
					{
						window.location = $(this).find('a').attr('href');
						evt.preventDefault;
					}
				}
			)
			// dim select boxes with hover
			.hover(
				function()
				{
					$(this).children('td.order-select').children('input').css('opacity', '1');
				},
				function()
				{
					$(this).children('td.order-select').children('input:not(:checked)').css('opacity', '.1');
				}
			);
		// set the default opacity for select elements
		$('td.order-select input').css('opacity', '.1');
		
		// Merge Orders Form
		$merge = $('input#merge');
		$merge.hide();
		$('#merge-able input:checkbox').change(function()
			{
				if($('#merge-able input:checked').length > 1)
				{
					$merge.show();
				}
				else
				{
					$merge.hide();
				}
			}
		);

	
	
	//
	// Warnings
	//
		// Confirm that you want to delete the order
		$('form.delete input').click(function() {
			
			if (confirm('You are about to permanently delete this order. Is that ok?'))
			{
				return true;
			}
			else
			{
				return false;
			}
	
		});
	



	/**
	 *
	 * AJAX Cost Calculator
	 * 
	 */
	$('select.ajax-cost').change(function(evt)
		{
			// defaults
			var $this = $(this);
			var $update = $this.siblings('span:first');
			var item_quantity	= $this.val();
			var product_slug	= $this.parent().attr('class');
			var design_slug		= 'classic'; // defaults to this design
			var banner_size		= 'none';
			var banner_type		= 'none';
			
			var url = window.location.pathname.split( '/' );
			
			if (url[0] !== 'welcome' && url[3] && url[4])
			{
				// get prodcut and design info from the URL
				product_slug = url[3];
				design_slug = url[4];
				if(product_slug === 'banner')
				{
					banner_size = $('#banner_size').val();
					banner_type = $('#banner_type').val();
				}
			}

			// empty the container
			$update.html('');

			$.ajax(
				{
					type: 'POST',
					url: '/ajax/cost_check/',
					data: 'item_quantity=' + item_quantity + '&product_slug=' + product_slug + '&design_slug=' + design_slug + '&banner_size=' + banner_size + '&banner_type=' + banner_type,
					dataType: 'text',
					success: function(data)
					{
						// update container with new cost
						$update.html(data);
					}
				}
			); // END .ajax
		}
	).trigger('change');
	// if you change banner size and type, make sure to update the price too
	$('#banner_size, #banner_type').change(function(){$('select.ajax-cost').trigger('change');});
	
	
	
	/**
	 *
	 * Admin Search Form
	 * 
	 */
	$('form.search').submit(function(evt) {
									 
		evt.preventDefault();
		
		var $this = $(this);
		var $update = $('div#results');
		$update.html('');
		
		if($('#order_id', $this).val() !== '')
		{
			window.location = '/admin/order_detail/' + $('#order_id', $this).val();
		}
		else
		{

			// defaults
			var $name			= $('input#name', $this).val();
			var $church_name	= $('input#church_name', $this).val();
									 
			$.ajax(
				{
					type: 'POST',
					url: '/ajax/search_results/',
					data: 'name=' + $name + '&church_name=' + $church_name,
					dataType: 'text',
					success: function(data)
					{
						$update.html(data);
					}
				}
			); // END .ajax
		}
	});
	


});// End Document Ready
