// Tells jQuery before it sends to change the header type to Accept javascript format. 
// Rails will read this and send back the javascript request. 
var $j = jQuery.noConflict();

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

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

// Add an error message to the input field
$j.fn.addRailsErrorMessages = function(message) 
{
  parentContainer = $j(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()
{
  $j.getJSON('/api/private/security_tokens.js', function(data){
    $j('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    = $j.cookie('cart_quantity') || 0
	cart_total       = $j.cookie('cart_total') || 0.0
	current_currency = $j.cookie('cart_total') || 'USD'
	current_region   = $j.cookie('current_region') || 'us'

  if(cart_quantity === '1') {
    cart_quantity = cart_quantity + ' Item';
  } else {
    cart_quantity = cart_quantity + ' Items';
  }
  	
	$j('.cart-item-count').html(cart_quantity);
	//$j('.cart-revised-subtotal').html(cart_total).formatCurrency({ region: current_currency.toLowerCase()});
	
  // if($j.cookie("o_customer")) {
  //   customer_data_string = $j.base64Decode($j.cookie("o_customer")); 
  // } else {
  //   customer_data_string = "0.0,0," + $j.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 + ' Item';
  // } else {
  //   cart_item_count = cart_item_count + ' Items';
  // }
  // 
  // $j(".cart-item-count").html(cart_item_count);
  // $j(".cart-revised-subtotal").html(cart_total).formatCurrency();  
}

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

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

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

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

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

$j.fn.RemoteDelete = function() {
  $j(this).removeAttr("onclick");
  this.click(function() {
    if (typeof(AUTH_TOKEN) === "undefined") { return; }
    $j.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. $j('.pagination a').linkToRemote();
$j.fn.linkToRemote = function() { 
  this.click(function() {
    $j.ajax({type: "GET", url: this.href, dataType: "script"});
    $j(".loading_container").show();
    return false;
  });
};

// Function to preload images
$j(function() {
  var imgCache = [];
  // Arguments are image paths relative to the current page.
  $j.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){
  $j('html,body').animate({scrollTop: $j(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-$j(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%'}, "slow" );

  objNavCollection.css( 'backgroundPosition', intSlideTo + 'px 100%')
}

// Dropdown menu
$j.dropDownMenu = function()
{  
  // Men/Women
  $j(".gender_selection li").mouseover(function(){
    // Set nav select
    $j(".gender_selection").find(".current").removeClass("current");
    $j(this).addClass("current");  
    // Set drop down contents
    $j(".nav_slides").find("div.selected").removeClass("selected").hide();
    $j(".nav_slides ." + $j(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 = $j(this).find('div.dd').show();
    $j(this).addClass("hoverover");
  }
  // Close
  function dropdown_close(dropdown) {
    if(dropdownMenu) { dropdownMenu.hide(); }
    $j("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
  $j("li.products").bind('mouseenter', dropdown_open);
  $j("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()
{
  $j('.hoverable').bind('mouseenter', function(e) {
    $j(this).find('.popup-for-hoverable').css('display', 'block');
  }).bind('mouseleave', function(e) {
    $j(this).find('.popup-for-hoverable').css('display', 'none');
  });

  $j('.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 = $j(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=.oakley.com; path=/';
    }

    location.href = linkUrl;

    return false;
  });
}


// Global Page Ready
$j(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
  $j.preLoadImages("/images/css/default/ui/nav_primary/dd_fullwidth_cap_t.png", "/images/css/default/ui/nav_primary/dd_fullwidth_body.png", "/images/css/default/ui/nav_primary/dd_fullwidth_cap_b.png");
  // Setup our Drop Down Menu
  $j.dropDownMenu();
  
  // Updates the customer's header information based off a local cookie
  // which is base64 encoded.
  updateCustomerData();
	
	// Global Tabs
	$j( ".tabs ul" ).tabs( '.tabs > div' );
	$j( ".tabs_default > ul" ).tabs( '.tabs_default > div' );
	$j( ".tabs_default > ul li" ).bind( 'click', function( objEvent ){
		slideHighlight( $j( objEvent.currentTarget ));
	});

	// Set the slider to the opened tab by default
	$j( ".tabs_default .ui-tabs-nav .current" ).each( function(i){
		slideHighlight( $j( this ).parent());
	});  
 
  // International Selection
  $j("#int_selection li").mouseover(function(){
    $j("#int_label").html($j(this).find("a").attr("title"));
  }).mouseout(function(){
    $j("#int_label").html($j("#int_selection li.selected").find("a").attr("title"));
  });
  
  // Tron Drop Down
  $j('.tronDropdown').bind('mouseenter',function(){
    $j(this).find("dd").show();
  });
  $j(".tronDropdown").bind('mouseleave',function(){   
    $j("dd").animate({
      height: 'hide',
      opacity: 'hide'
    }, '100'); 
  });

  // Global Watermark functionality
  $j("input.watermark").each(function(){
  	$j(this).data('defaultValue',$j(this).val());
	  $j(this).focus(function(){  	
	  	if($j(this).val() === $j(this).data('defaultValue'))	{
	  		$j(this).val('');
	  	}
	 	}).blur(function() {
	 		if($j(this).val() === '') {
				$j(this).val($j(this).data('defaultValue'));
	  	}
	 	});
 	});
 	
 	// Global External Links
 	$j("a[rel='external']").attr('target','_blank');


  initRegionSelect();

});

