(function($){
	$.fn.colorTip = function(settings){

		var defaultSettings = {
			color		: 'yellow',
			timeout		: 500
		}
		
		var supportedColors = ['red','green','blue','white','yellow','black'];
		
		/* Combining the default settings object with the supplied one */
		settings = $.extend(defaultSettings,settings);

		/*
		*	Looping through all the elements and returning them afterwards.
		*	This will add chainability to the plugin.
		*/
		
		return this.each(function(){

			var elem = $(this);
			
			// If the title attribute is empty, continue with the next element
			if(!elem.attr('title')) return true;
			
			// Creating new eventScheduler and Tip objects for this element.
			// (See the class definition at the bottom).
			
			var scheduleEvent = new eventScheduler();
			var tip = new Tip(elem.attr('title'));

			// Adding the tooltip markup to the element and
			// applying a special class:
			
			elem.append(tip.generate()).addClass('colorTipContainer');

			// Checking to see whether a supported color has been
			// set as a classname on the element.
			
			var hasClass = false;
			for(var i=0;i<supportedColors.length;i++)
			{
				if(elem.hasClass(supportedColors[i])){
					hasClass = true;
					break;
				}
			}
			
			// If it has been set, it will override the default color
			
			if(!hasClass){
				elem.addClass(settings.color);
			}
			
			// On mouseenter, show the tip, on mouseleave set the
			// tip to be hidden in half a second.
			
			elem.hover(function(){

				tip.show();
				
				// If the user moves away and hovers over the tip again,
				// clear the previously set event:
				
				scheduleEvent.clear();

			},function(){

				// Schedule event actualy sets a timeout (as you can
				// see from the class definition below).
				
				scheduleEvent.set(function(){
					tip.hide();
				},settings.timeout);

			});
			
			// Removing the title attribute, so the regular OS titles are
			// not shown along with the tooltips.
			
			elem.removeAttr('title');
		});
		
	}


	/*
	/	Event Scheduler Class Definition
	*/

	function eventScheduler(){}
	
	eventScheduler.prototype = {
		set	: function (func,timeout){

			// The set method takes a function and a time period (ms) as
			// parameters, and sets a timeout

			this.timer = setTimeout(func,timeout);
		},
		clear: function(){
			
			// The clear method clears the timeout
			
			clearTimeout(this.timer);
		}
	}


	/*
	/	Tip Class Definition
	*/

	function Tip(txt){
		this.content = txt;
		this.shown = false;
	}
	
	Tip.prototype = {
		generate: function(){
			
			// The generate method returns either a previously generated element
			// stored in the tip variable, or generates it and saves it in tip for
			// later use, after which returns it.
			
			return this.tip || (this.tip = $('<span class="colorTip">'+this.content+
											 '<span class="pointyTipShadow"></span><span class="pointyTip"></span></span>'));
		},
		show: function(){
			if(this.shown) return;
			
			// Center the tip and start a fadeIn animation
			this.tip.css('margin-left',-this.tip.outerWidth()/2).fadeIn('fast');
			this.shown = true;
		},
		hide: function(){
			this.tip.fadeOut();
			this.shown = false;
		}
	}
	
})(jQuery);

$(document).ready(function() {
	
	has_subscribed = 0;
	
	$("a[rel='colorbox']").colorbox();
	
	//$(".stylish_table table tr:odd").addClass('odd');

	var is_order = $("#is_order").val();
	var is_sample = $("#is_sample").val();
	
	if ( is_sample == '1' ) {

		// This is the virtual sample request page.
		
		$(".half_section").hide();
		$("#step_art_selection").show();
		$("#step_art_selection_sidebar").show();
		
		$("#design_continue2").click(function() {
			
			// I already have my own artwork.
			
			$(".half_section").hide();			
			$("#step_file_upload").show();
			$("#step_file_upload_sidebar").show();
			
			$('#file_upload_field').uploadify({
				'uploader'  : '/includes/uploadify/uploadify.swf',
				'script'    : '/home/sample_request_artwork_upload',
				'cancelImg' : '/includes/uploadify/cancel.png',
				'buttonImg' : '/images/browse.png',
				'folder'    : '',
				'auto'      : true,
				'buttonText': "Browse for Artwork",
				height		: 54,
				width		: 196,
				'scriptData'  : {},
				'onComplete'  : function(event, ID, fileObj, response, data) {

					// Display sample request form.
					
					var new_filename = response;

					$(".half_section").hide();
					$("#step_sample_form").show();
					$("#step_sample_form_sidebar").show();

					$("#sample_request_submit").click(function() {

						var sku = $("#your_sku").val();
						var qty = $("#your_qty").val();

						var first_name = $("#first_name").val();
						if ( first_name == '' ) {
							alert("First name is a required field.");
							$("#first_name").trigger('focus');
							return false;
						}
						
						var last_name = $("#last_name").val();
						if ( last_name == '' ) {
							alert("Last name is a required field.");
							$("#last_name").trigger('focus');
							return false;
						}

						var company = $("#company").val();

						var phone = $("#phone").val();
						if ( phone == '' ) {
							alert("Phone number is a required field.");
							$("#phone").trigger('focus');
							return false;
						}

						var email = $("#email").val();
						if ( email == '' ) {
							alert("Email address is a required field.");
							$("#email").trigger('focus');
							return false;
						}

						var zip = $("#zip").val();
						if ( zip == '' ) {
							alert("Shipping zip code is a required field.");
							$("#zip").trigger('focus');
							return false;
						}

						var notes = $("#notes").val();
						
						$.post("/home/AJAX_submit_sample_request_form", {
							sku : sku,
							qty : qty,
							first_name : first_name,
							last_name : last_name,
							company : company,
							phone : phone,
							email : email,
							zip : zip,
							notes : notes,
							filename : new_filename
						}, function(result) {
							
							$(".half_section").hide();
							$("#thankyou").show();
							
						});

					});

				},
				'onError'     : function (event,ID,fileObj,errorObj) {
					alert(errorObj.type + ' Error: ' + errorObj.info);
				}
			});
			
		});
		
		$("#design_continue3").click(function() {
			
			// I do not have my own artwork.
			
			$(".half_section").hide();
			$("#step_customizer").show();
			$("#step_customizer_sidebar").show();
			
			var flashvars = false;
			var params = false;
			var attributes = false;
			
		    swfobject.embedSWF("/includes/customizer/customizer-halfsize.swf", "customizer", "450", "500", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
			
		});

	}

	if ( is_order == '1' ) {
		
		// This is the order page.
		
		$(".half_section").hide();
		$("#artwork_selection").show();
		$("#artwork_selection_sidebar").show();
		
		$(".half_section").hide();					
		$("#options_form").show();
		$("#options_form_sidebar").show();
		
		/*
		$(".half_section").hide();					
		$("#order_form").show();
		$("#order_form_sidebar").show();
		$("#steps_img").attr('src', '/images/steps2.gif');
		$("#section_title").html("Checkout - Submit Payment Information");
		*/

		$("#design_continue2").click(function() {
			
			// I already have my own artwork.
			$(".half_section").hide();
			
			$("#file_upload").show();
			$("#file_upload_sidebar").show();
			
			$('#file_upload_field').uploadify({
				'uploader'  : '/includes/uploadify/uploadify.swf',
				'script'    : '/home/artwork_upload',
				'cancelImg' : '/includes/uploadify/cancel.png',
				'buttonImg' : '/images/browse.png',
				'folder'    : '',
				'auto'      : true,
				'buttonText': "Browse for Artwork",
				height		: 54,
				width		: 196,
				'scriptData'  : {},
				'onComplete'  : function(event, ID, fileObj, response, data) {
					
					// Display order form.

					$(".half_section").hide();					
					$("#order_form").show();
					$("#order_form_sidebar").show();
					$("#steps_img").attr('src', '/images/steps2.gif');
					$("#section_title").html("Checkout - Submit Payment Information");

				},
				'onError'     : function (event,ID,fileObj,errorObj) {
					alert(errorObj.type + ' Error: ' + errorObj.info);
				}
			});

		});
		
		$("#design_continue3").click(function() {
			
			// I do not have my own artwork.
			
			$(".half_section").hide();
			
		});

	}

	var slug = $("#hidden_slug").val();
	
	if ( slug != undefined && slug != '' ) {

		$(".extra_image").click(function() {
			var image_rel = $(this).attr('rel'); // 500
			var image_rel2 = $(this).attr('rel2'); // 250
			$("#zoom_text_link").attr('href', image_rel);
			$("#main_thumb").attr('src', image_rel2);
			$("#zoom1").attr('href', image_rel);
			$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
		});

		$("#pcq_text").keyup(function() {
			
			var qty = $(this).val();
			
			var price1 = $("#price1").val() * 1;
			var price2 = $("#price2").val() * 1;
			var price3 = $("#price3").val() * 1;
			var price4 = $("#price4").val() * 1;
			var price5 = $("#price5").val() * 1;
			var qty1 = $("#qty1").val() * 1;
			var qty2 = $("#qty2").val() * 1;
			var qty3 = $("#qty3").val() * 1;
			var qty4 = $("#qty4").val() * 1;
			var qty5 = $("#qty5").val() * 1;
			var setup = $("#setup_fee").val() * 1;
			
			if ( qty < qty1 ) {
				$("#dynamic_price").html("The minimum quantity for this product is " + qty1 + ".");
				return false;
			}
			
			var new_price = 0;
			
			if ( qty1 != undefined && qty1 != '' && qty1 > 0 && qty >= qty1 ) {
				new_price = price1 * qty;
				new_price = new_price + setup;
			}
			
			if ( qty2 != undefined && qty2 != '' && qty2 > 0 && qty >= qty2 ) {
				new_price = price2 * qty;
				new_price = new_price + setup;
			}
			
			if ( qty3 != undefined && qty3 != '' && qty3 > 0 && qty >= qty3 ) {
				new_price = price3 * qty;
				new_price = new_price + setup;
			}
			
			if ( qty4 != undefined && qty4 != '' && qty4 > 0 && qty >= qty4 ) {
				new_price = price4 * qty;
				new_price = new_price + setup;
			}
			
			if ( qty5 != undefined && qty5 != '' && qty5 > 0 && qty >= qty5 ) {
				new_price = price5 * qty;
				new_price = new_price + setup;
			}

			if ( new_price == 0 ) {
				new_price = 'Error';
			} else {
				new_price = formatCurrency(new_price);
			}
			
			$("#dynamic_price").html('Your Price: ' + new_price);
			
		});
		
		$("#instant_quote_button").removeAttr("disabled");
		
		$(".sample-button").click(function() {
			$('#tabs').tabs({ selected: 2 })
		});

		var product_info = $("#product_info").html();
		if ( product_info == '' ) {
			$("#product_info").append("<b>Personalize this product with your logo or message today.</b><br /><br />This product can be imprinted with your unique logo or message. <a href='/place_order/" + slug + "'>Click here to place your order</a>, or call us toll-free at 1-866-798-0345 for immediate assistance.<br /><br /><b>How does the ordering process work?</b><br /><br />You will receive a free virtual proof prior to the production of your order. This proof will illustrate how your final order will appear after production. Payment is not required until you have reviewed and approved your proof. <i>100% satisfaction is guaranteed.</i>");
		} else {
			$("#product_info").append("<br /><br /><b>Personalize this product with your logo or message today.</b><br /><br />This product can be imprinted with your unique logo or message. <a href='/place_order/" + slug + "'>Click here to place your order</a>, or call us toll-free at 1-866-798-0345 for immediate assistance.<br /><br /><b>How does the ordering process work?</b><br /><br />You will receive a free virtual proof prior to the production of your order. This proof will illustrate how your final order will appear after production. Payment is not required until you have reviewed and approved your proof. <i>100% satisfaction is guaranteed.</i>");	
		}
		$("#tabs").tabs();
		
		$("#instant_quote_button").click(function() {
			$("#instant_quote_button").attr("disabled", "true");
			var this_qty = $(".qt_quote_field").val();
			var quote_sku = $("#hidden_sku").val();

			$("#your_quoted_price").html("<img src='/images/ajax.gif' class='ajax_load' />");
			
			$.post("/home/generate_instant_quote", { sku : quote_sku , qty : this_qty }, function(result) {				
				var json = eval("(" + result + ")");
				$("#your_quoted_price").html(json.your_price);
				$("#your_unit_price").html(json.your_unit_price);
				$("#your_subtotal").html(json.your_subtotal);

				var shipping_field_size = $("#your_quoted_shipping").size();
				
				if ( json.your_shipping != undefined && json.your_shipping != '' && shipping_field_size == 1 ) {
					$("#your_quoted_shipping").html(json.your_shipping);
				}

				$("#instant_quote_button").removeAttr("disabled");
			});

			//$("#your_quoted_price").html(this_qty);
		});

	}

	$(".stylish_table table tbody tr:odd").addClass("odd");
	
	$("input[name='search']").focus(function() {
		var val = $(this).val();
		if ( val == 'Search for promotional products...' ) {
			$(this).val('');
		}
	});
	
	$("input[name='qty']").focus(function() {
		$(this).val('');
	});
	
	$("#revision_notes_textarea").focus(function() {
		var value = $(this).val();
		if ( value == 'If you would like to see additional changes made to this sample, enter your instructions in this field and press the "Submit Changes" button below.' ) {
			$(this).val('');
		}
	});
	
	$("#newsletter_submit").click(function() {
		var email = $("input[name='newsletter']").val();
		$.post("/home/add_newsletter_subscriber", { email : email }, function(result) {
		});
		alert(email + " has been added to our list of newsletter subscribers.");	
	});
	
	$("#newsletter_submit2").click(function() {
		var email = $("input[name='newsletter2']").val();
		$.post("/home/add_newsletter_subscriber", { email : email }, function(result) {
		});
		alert(email + " has been added to our list of newsletter subscribers.");	
	});

	$("input[name='newsletter']").keyup(function(e) {
		if ( e.keyCode == 13 && has_subscribed == 0 ) {
			var email = $(this).val();
			$.post("/home/add_newsletter_subscriber", { email : email }, function(result) {
			});
			alert(email + " has been added to our list of newsletter subscribers.");
			has_subscribed = 1;
		}
	});
	
	$(".free_virtual_sample_banner").click(function() {
		
		var slug = $(this).attr("slug");
		window.location = '/virtual_sample/' + slug;
		
	});

	$('.tooltip').colorTip({color:'yellow'});

	var i = $(".introduction");
	var ic = $(i).html();

	if ( ic != null ) {

		$(i).remove();
		var new_i = "<div class='i" + "n" + "t" + "r" + "o" + "d" + "u" + "c" + "t" + "i" + "o" + "n" + "'>" + ic + "</div>";
		
		$("#final_clear").after(new_i);
		
		/*
		var di = $("#details_info");
		if ( $(di).size() == 1 ) {
			$("#details_info").html(ic);
		} else {
			$("#final_clear").after(new_i);
		}
		*/

	}

	var cn = $("#category_navigation");
	var cn_c = $(cn).html();
	$(cn).remove();
	$("#n" + "a" + "v").html(cn_c);
	
	$("#use_billing").change(function() {
		
		var val = $(this).val();
		
		var billing_first_name = $("input[name='billing_first_name']").val();
		var billing_last_name = $("input[name='billing_last_name']").val();
		var billing_phone = $("input[name='billing_phone']").val();
		var billing_email = $("input[name='billing_email']").val();
		var billing_address_1 = $("input[name='billing_address_1']").val();
		var billing_address_2 = $("input[name='billing_address_2']").val();
		var billing_city = $("input[name='billing_city']").val();
		var billing_state = $("select[name='billing_state']").val();
		var billing_zip = $("input[name='billing_zip']").val();
		
		$("input[name='shipping_first_name']").val(billing_first_name);
		$("input[name='shipping_last_name']").val(billing_last_name);
		$("input[name='shipping_phone']").val(billing_phone);
		$("input[name='shipping_email']").val(billing_email);
		$("input[name='shipping_address_1']").val(billing_address_1);
		$("input[name='shipping_address_2']").val(billing_address_2);
		$("input[name='shipping_city']").val(billing_city);
		$("select[name='shipping_state']").val(billing_state);
		$("input[name='shipping_zip']").val(billing_zip);		
		
	});

	/*
	$(".fb").fancybox({
		'hideOnContentClick': true
	});
	
	$.fancybox('content');
	*/
	
});

function displayAccountSupport()
{
	$.post("/home/AJAX_account_support_view", {}, function(result) {
		$("#account_content").html(result);
	});
}

function displayAccountOrderHistory()
{
	$.post("/home/AJAX_account_order_history_view", {}, function(result) {
		$("#account_content").html(result);
	});	
}

function editDefaultBilling()
{
	$.post("/home/AJAX_edit_default_billing", {}, function(result) {
		$("#account_content").html(result);
	});
}

function editDefaultShipping()
{
	$.post("/home/AJAX_edit_default_shipping", {}, function(result) {
		$("#account_content").html(result);
	});
}

function editContactInformation()
{
	$.post("/home/AJAX_edit_contact_information_view", {}, function(result) {
		$("#account_content").html(result);
	});
}

function editPassword()
{
	$.post("/home/AJAX_edit_password_view", {}, function(result) {
		$("#account_content").html(result);
	});	
}

function toggleFeatured(product_id)
{
	$.post("/home/AJAX_toggle_product_featured/" + product_id, {}, function(result) {
	});
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

/*
function flashOrderProcess(customizer_file)
{
	var the_name = $("#your_name").val();
	var the_email = $("#your_email").val();
	var the_phone = $("#your_phone").val();
	var the_zip = $("#shipping_zip").val();
	var the_date = $("#due_date").val();
	var the_color = $("#product_color").val();
	var the_notes = $("#notes").val();
	var the_sku = $("#your_sku").val();
	var the_qty = $("#your_qty").val();
	$.post("/home/artwork_upload", {
		name : the_name,
		email : the_email,
		phone : the_phone,
		zip : the_zip,
		date : the_date,
		color : the_color,
		notes : the_notes,
		sku : the_sku,
		qty : the_qty,
		customizer_file : customizer_file
	}, function(result) {
		showOrderSuccess();
	});
}
*/

function flashOrderProcess(customizer_file)
{
	
	// Display sample request form.
	
	var new_filename = customizer_file; // filename=1303281062%2Dcustomizer%2Epng

	$(".half_section").hide();
	$("#step_sample_form").show();
	$("#step_sample_form_sidebar").show();

	$("#sample_request_submit").click(function() {

		var sku = $("#your_sku").val();
		var qty = $("#your_qty").val();

		var first_name = $("#first_name").val();
		if ( first_name == '' ) {
			alert("First name is a required field.");
			$("#first_name").trigger('focus');
			return false;
		}
		
		var last_name = $("#last_name").val();
		if ( last_name == '' ) {
			alert("Last name is a required field.");
			$("#last_name").trigger('focus');
			return false;
		}

		var company = $("#company").val();

		var phone = $("#phone").val();
		if ( phone == '' ) {
			alert("Phone number is a required field.");
			$("#phone").trigger('focus');
			return false;
		}

		var email = $("#email").val();
		if ( email == '' ) {
			alert("Email address is a required field.");
			$("#email").trigger('focus');
			return false;
		}

		var zip = $("#zip").val();
		if ( zip == '' ) {
			alert("Shipping zip code is a required field.");
			$("#zip").trigger('focus');
			return false;
		}

		var notes = $("#notes").val();
		
		$.post("/home/AJAX_submit_sample_request_form", {
			sku : sku,
			qty : qty,
			first_name : first_name,
			last_name : last_name,
			company : company,
			phone : phone,
			email : email,
			zip : zip,
			notes : notes,
			flash_filename : new_filename
		}, function(result) {
			
			$(".half_section").hide();
			$("#thankyou").show();
			
		});

	});
	
}

function showOrderSuccess()
{
	$("#step1_work").hide();
	$("#step2_work").hide();
	$("#step3_work").hide();
	$("#step4_work").hide();
	$("#design_sidebar").hide();
	$("#step5_work").show();	
}

function placeOrder() {

	var qty = $("#pcq_text").val();
	var qty1 = $("#qty1").val() * 1;
	if ( qty < qty1 ) {
		alert("The minimum quantity available for purchase is " + qty1 + ".");
	} else {
		var the_slug = $("#hidden_slug").val();
		window.location = '/place_order/' + the_slug + '/' + qty;		
	}

}

function placeOrderNoCustomize() {

	var qty = $("#pcq_text").val();
	var qty1 = $("#qty1").val() * 1;
	if ( qty < qty1 ) {
		alert("The minimum quantity available for purchase is " + qty1 + ".");
	} else {
		var the_slug = $("#hidden_slug").val();
		window.location = 'https://www.mightypromos.com/place_order_step_three/' + the_slug + '/' + qty;		
	}

}

function sampleForm() {

	var qty = $("#pcq_text").val();
	var qty1 = $("#qty1").val() * 1;
	if ( qty < qty1 ) {
		alert("The minimum quantity available for purchase is " + qty1 + ".");
	} else {
		var the_slug = $("#hidden_slug").val();
		window.location = '/virtual_sample/' + the_slug + '/' + qty;		
	}

}
