$(document).ready(function() {
    
    // Browser Detection Object
    var browserD = new Object;
    browserD.safari = $('body').hasClass('safari');
    browserD.firefox = $('body').hasClass('firefox');
    browserD.ie = $('body').hasClass('ie');
    browserD.ffwin = $('body').hasClass('win');
    
    // Browser Detection Test
    // alert("safari: " + browserD.safari + "\n" + "firefox: " + browserD.firefox + "\n" + "ie: " + browserD.ie + "\n" + "firefox win: " + browserD.ffwin + "\n");

    // Send CSRF token in headers with ajax request
    $('html').ajaxSend(function(event, xhr, settings) {
    			    function getCookie(name) {
    			        var cookieValue = null;
    			        if (document.cookie && document.cookie != '') {
    			            var cookies = document.cookie.split(';');
    			            for (var i = 0; i < cookies.length; i++) {
    			                var cookie = jQuery.trim(cookies[i]);
    			                // Does this cookie string begin with the name we want?
    			                if (cookie.substring(0, name.length + 1) == (name + '=')) {
    			                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
    			                    break;
    			                }
    			            }
    			        }
    			        return cookieValue;
    			    }
    			    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
    			        // Only send the token to relative URLs i.e. locally.
    			        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    			    }
    			});
	
	// Generic open dialog hook
	$('.dialog_open').click(function() {
		var hook = $(this);
		var d = $(this).attr('rel');
		var content = hook.attr('href')+" #ajax_container";
		
		if (d == "#login_form_dialog") {
		    if (browserD.ie) { // If this is IE we need to make the login box a little bigger
		        $(d).dialog({
    				autoOpen: false,
    				modal: true,
    				resizable: false,
    				width: "380px"	
    			});
		    } else {
    			$(d).dialog({
    				autoOpen: false,
    				modal: true,
    				resizable: false,
    				width: "360px"	
    			});
		    }
		} else {
			$(d).dialog({
				autoOpen: false,
				modal: true,
				resizable: false,
				width: "670px"	
			});
		};
		$(d).load(content, function (response, status, xhr) {
			$(d).dialog( "open" );
		});
		return false;
	});
	
	// Carousel for related products
	$('.related_products_container').jcarousel({
		visible: 4,
		scroll: 4
	});
	
	// Print product button
	$('.static_button.print').click(function(){
		window.print();
		return false;
	});

    // Footer mailinglist form ajax and validation
	$("#footer_mailinglist").validate({
	    submitHandler: function() { 
				var the_form = $('#footer_mailinglist');
				var button = the_form.children('.submit');
		        button.after('<img class="ajax_loader" src="/media/images/ajax-loader.gif" alt="Loading" />');
		        var loader = the_form.children('.ajax_loader');
		         
		        button.hide(0, function(){
		            loader.show();
		        });
		        
				$('.ajax_response.error').remove();
				var action = the_form.attr('action');
				var form_data = the_form.serialize();
				$.post(action, form_data, function(data) {
					data = $.parseJSON(data);
					if (data.success) {
					    loader.remove();
						$("#footer_mailinglist").html('<h3 class="ajax_response success">Thank you for signing up</h3>');
					};
					if (data.errors) {
						if (data.errors.email) {
						    loader.remove();
						    button.show();
							$("#footer_mailinglist").append('<h3 class="ajax_response error">Error: '+data.errors.email+'</h3>');
						};
					};
				});
		}
	});

    // Send to a friend form ajax and validation
	$('.send_to_a_friend').click(function() {
		var hook = $(this);
		var d = "#coupon_stf_dialog";
		var coupon_id = $(this).attr('rel');
		var data_container = '#coupon_stf_data_'+coupon_id;
		var data = $(data_container).html();
		$(d).dialog({
			autoOpen: true,
			modal: true,
			resizable: false,
			width: "300px",
			open: function(event, ui) {
				$('#stf_message_display').html(data);
				$('#coupon_id').attr('value', coupon_id);
				var content = $('#coupon_stf_content').html();
				$('#coupon_stf_dialog').html(content);
				var the_form = $("#coupon_stf_dialog #coupon_stf_form");
				if (browserD.ie) {
                    the_form = $("#coupon_stf_dialog form");
				};
				    the_form.validate({
    				    submitHandler: function() {
    				        var button = $('.button.stf');
    				        button.after('<img class="ajax_loader" src="/media/images/ajax-loader.gif" alt="Loading" />');
    				        var loader = $('#coupon_stf_form .ajax_loader');

    				        button.hide(0, function(){
    				            loader.show();
    				        });


    						$('.ajax_response.error').remove();
    							var action = the_form.attr('action');
    							var form_data = the_form.serialize();
    							$.post(action, form_data, function(data) {

    								data = $.parseJSON(data);
    								if (data.success) {
    								    loader.remove();
    									$("#coupon_stf_dialog").empty();
    									$("#coupon_stf_dialog").html('<h3 id="coupon_stf_response" class="ajax_response success">An email has been sent to '+data.friend_email+'</h3>');
    								};
    								if (data.errors) {
    								    loader.remove();
    								    button.show();
    									if (data.errors.email) {
    										$("#coupon_stf_dialog").append('<h3 id="coupon_stf_error_email" class="ajax_response error">Error: '+data.errors.email+'</h3>');
    									};
    									if (data.errors.friend_email) {
    										$("#coupon_stf_dialog").append('<h3 id="coupon_stf_error_friend_email" class="ajax_response error">Error: '+data.errors.friend_email+'</h3>');
    									};
    								};
    							});
    					}
    				});
			}	
		});
		return false;
	});
	
	// HTML5 placeholder text fallback
	// https://github.com/danielstocks/jQuery-Placeholder
	$('input[placeholder], textarea[placeholder]').placeholder();
});
