// Tells jQuery before it sends to change the header type to Accept javascript format. 
// Rails will read this and send back the javascript request. 

jQuery.ajaxSetup({
	'beforeSend': function(xhr) {
		xhr.setRequestHeader("Accept", "text/javascript");
	}
});

$.fn.resetRailsErrorMessages = function() {
	$(this).find('.error').removeClass("error");
	$(this).find(".error_message").remove();
	$(this).find("span").show();
};

// Add an error message to the input field
$.fn.addRailsErrorMessages = function(message) {
	parentContainer = $(this).parent();
	parentContainer.addClass("error");
	parentContainer.find("p.error_message").remove();
	parentContainer.find("span").hide();
	parentContainer.append("<p class='error_message'>" + message + "</p>");
};



function updateAuthenticityToken() {
	$.getJSON('/api/private/security_tokens.js', function(data) {
		$('input[name=authenticity_token]').val(data.token);
	});
}

// Update the application header with cookie based information. This includes the
// cart total, cart item count and if the current customer is logged in or not.
function updateCustomerData() {
	cart_quantity = $.cookie('cart_quantity') || 0;
	cart_total = $.cookie('cart_total') || 0.0;
	current_currency = $.cookie('cart_total') || 'USD';
	current_region = $.cookie('current_region') || 'us';

	if (cart_quantity === '1') {
		cart_quantity = cart_quantity + ' artículo(s)';
	} else {
		cart_quantity = cart_quantity + ' artículo(s)';
	}

	$('.cart-item-count').html(cart_quantity);
	//$('.cart-revised-subtotal').html(cart_total).formatCurrency({ region: current_currency.toLowerCase()});
	// if($.cookie("o_customer")) {
	//   customer_data_string = $.base64Decode($.cookie("o_customer")); 
	// } else {
	//   customer_data_string = "0.0,0," + $.cookie("o_customer_auth");
	// }
	// 
	// customer_data_array  = customer_data_string.split(",");
	// 
	// cart_total         = customer_data_array[0];
	// cart_item_count    = customer_data_array[1];
	//  
	// if(cart_item_count === '1') {
	//   cart_item_count = cart_item_count + ' artículo(s)';
	// } else {
	//   cart_item_count = cart_item_count + ' artículo(s)';
	// }
	// 
	// $(".cart-item-count").html(cart_item_count);
	// $(".cart-revised-subtotal").html(cart_total).formatCurrency();  
}



function capturePromotion() {
	if ($.query.get('promotion_id')) {
		$.cookie('pid', $.md5('' + $.query.get('promotion_id')), {
			path: '/'
		});
	} else if ($.query.get('promo_id')) {
		$.cookie('pid', $.md5('' + $.query.get('promo_id')), {
			path: '/'
		});
	}
}

// Update all available cart elements on the screen with the order object
function updateCart(order) {
	$(".cart-item-count").html(order.product_count);
	$(".cart-subtotal").html(order.subtotal);
	//$(".cart-revised-subtotal").html(order.revised_subtotal);
	$(".cart-savings").html(order.savings);
	$(".cart-shipping").html(order.shipping);
	$(".cart-tax").html(order.tax);
	$(".cart-total").html(order.total);
	$("#order_shipping_speed_id").replaceWith(order.shipping_options);
	$(".shipping_message").html(order.shipping_message);
	$(".incentive_message").html(order.incentive_message);
}

// This updates the line item quantity with an ajax call to the server.
function updateLineItemQty() {
	$(".line_item_qty").change(function() {
		$.post($(this).parent().attr("action"), $(this).parent().serialize(), null, "script");
		return false;
	});
}

$.fn.submitSearch = function() {
	$(this).change(function() {
		$(this).parents("form").submit();
		$(".loading_container").show();
	});
};

// Submits a form using an ajax call
// ex. $('#post-form').submitWithAjax();
$.fn.submitWithAjax = function() {
	this.submit(function() {
		$.post($(this).attr("action"), $(this).serialize(), null, "script");
		return false;
	});
};

$.fn.RemoteDelete = function() {
	$(this).removeAttr("onclick");
	this.click(function() {
		if (typeof(AUTH_TOKEN) === "undefined") {
			return;
		}
		$.ajax({
			type: "POST",
			url: this.href,
			data: {
				'_method': 'delete',
				'authenticity_token': AUTH_TOKEN
			},
			dataType: "script"
		});
		return false;
	});
};

// Submits an ajax request to the controller
// ex. $('.pagination a').linkToRemote();
$.fn.linkToRemote = function() {
	this.click(function() {
		$.ajax({
			type: "GET",
			url: this.href,
			dataType: "script"
		});
		$(".loading_container").show();
		return false;
	});
};

// Function to preload images
$(function() {
	var imgCache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			imgCache.push(cacheImage);
		}
	};
});

// Contra Code
// ex. up up down down left right left right a b
if (window.addEventListener) {
	var kkeys = [],
		konami = "38,38,40,40,37,39,37,39,66,65";
	window.addEventListener("keydown", function(e) {
		kkeys.push(e.keyCode);
		if (kkeys.toString().indexOf(konami) >= 0) {
			window.location = "/contra";
		}
	},
	true);
}

// Scroll page to ID/anchor
function goToByScroll(selector) {
	$('html,body').animate({
		scrollTop: $(selector).offset().top
	},
	'slow');
}

// Tab slider
function slideHighlight(objNavItem) {

	// Build the value that we're gonna slide the bg image to
	// bg image for our highlight is 9px (hence the 9 in the formula)
	var intSlideTo = Math.round(((objNavItem.offset().left - $(objNavItem.parent()).offset().left)) + Math.floor(objNavItem.width() / 2) - Math.floor(9 / 2));

    // Debuggins
    // console.log( objNavItem );
    // console.log( "Offset: " + objNavItem.offset().left );
    // console.log( "Parent Offset: " + objNavItem.parent().offset().left );
    // console.log( "Width: " + objNavItem.width());
    // console.log( "SlideTo: " + intSlideTo );
        
    // Do the sliding
	objNavCollection = objNavItem.parent();

    // objNavCollection.animate({backgroundPosition: intSlideTo + 'px 100%'}, "fast" );
    objNavCollection.css('backgroundPosition', intSlideTo + 'px 100%');
}

// Dropdown menu
$.dropDownMenu = function() {
	// Men/Women
	$(".gender_selection li").mouseover(function() {
		// Set nav select
		$(".gender_selection").find(".current").removeClass("current");
		$(this).addClass("current");
		// Set drop down contents
		$(".nav_slides").find("div.selected").removeClass("selected").hide();
		$(".nav_slides ." + $(this).find("a").attr("rel")).addClass("selected").show();
	});

	// Variables
	var dropdown = "";
	var dropdownTimeout = 400;
	var dropdownTimer = 0;
	var dropdownMenu = 0;

	// Open
	function dropdown_open() {
		dropdown_cancel_timer();
		dropdown_close();
		dropdownMenu = $(this).find('div.dd').show();
		$(this).addClass("hoverover");
	}
	// Close
	function dropdown_close(dropdown) {
		if (dropdownMenu) {
			dropdownMenu.hide();
		}
		$("li.products").removeClass("hoverover");
	}
	// Timer
	function dropdown_timer() {
		dropdownTimer = window.setTimeout(dropdown_close, dropdownTimeout);
	}
	// Cancel Timeout
	function dropdown_cancel_timer() {
		if (dropdownTimer) {
			window.clearTimeout(dropdownTimer);
			dropdownTimer = null;
		}
	}

	// Our Action Listeners
	$("li.products").bind('mouseenter', dropdown_open);
	$("li.products").bind('mouseleave', dropdown_timer);

};

/* footer language/locale select popup controls
 * this can be built out to be much more inclusive for popup structures, but I
 * assume those exist on the migration site anyway
 *----------------------------------------------------------------------------*/
function initRegionSelect() {
	$('.hoverable').bind('mouseenter', function(e) {
		$(this).find('.popup-for-hoverable').css('display', 'block');
	}).bind('mouseleave', function(e) {
		$(this).find('.popup-for-hoverable').css('display', 'none');
	});

	$('.hoverable .popup-for-hoverable a').bind('click', function(e) {

		var date = new Date();
		date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();

		linkUrl = $(this).attr('href');

		// We're matching http to make sure its a domain link and not a relative path
		if (linkUrl.match('http')) {
			// Set the cookie if they click on any domain besides CA or JP
			document.cookie = 'akamai_redirect=' + linkUrl + '; expires=' + expires + '; domain=www.salelsol.com; path=/';
		}

		location.href = linkUrl;

		return false;
	});
}

// Global Page Ready
$(function() {

	// Captures any promotions from the url query and 
	// sets them as a cookie on the client side.
	capturePromotion();

	// Preload Images for the drop down
	$.preLoadImages("/estilo/img/dd_fullwidth_cap_t.png", "/estilo/img/dd_fullwidth_body.png", "/estilo/img/dd_fullwidth_cap_b.png");
	// Setup our Drop Down Menu
	$.dropDownMenu();

	// Updates the customer's header information based off a local cookie
	// which is base64 encoded.
	updateCustomerData();

	// Global Tabs
	$(".tabs ul").tabs('.tabs > div');
	$(".tabs_default > ul").tabs('> div');
	$(".tabs_default > ul li").bind('click', function(objEvent) {
		slideHighlight($(objEvent.currentTarget));
	});

	// Set the slider to the opened tab by default
	$(".tabs_default .ui-tabs-nav .current").each(function(i) {
		slideHighlight($(this).parent());
	});

	// International Selection
	$("#int_selection li").mouseover(function() {
		$("#int_label").html($(this).find("a").attr("title"));
	}).mouseout(function() {
		$("#int_label").html($("#int_selection li.selected").find("a").attr("title"));
	});

	// Tron Drop Down
	$('.tronDropdown').bind('mouseenter', function() {
		$(this).find("dd").show();
	});
	$(".tronDropdown").bind('mouseleave', function() {
		$("dd").animate({
			height: 'hide',
			opacity: 'hide'
		},
		'100');
	});

	// Global Watermark functionality
	$("input.watermark").each(function() {
		$(this).data('defaultValue', $(this).val());
		$(this).focus(function() {
			if ($(this).val() === $(this).data('defaultValue')) {
				$(this).val('');
			}
		}).blur(function() {
			if ($(this).val() === '') {
				$(this).val($(this).data('defaultValue'));
			}
		});
	});

	// Global External Links
	$("a[rel='external']").attr('target', '_blank');

	initRegionSelect();

});

