/**
 * jonnysport.js
 * Copyright 2009 Jonny Sport LLC
 * all rights reserved
 */

var jonnysport = (typeof(jonnysport) == 'undefined') ? {} : jonnysport;

jonnysport.live                  = (typeof(jonnysport.live) == 'undefined')                  ? false     : jonnysport.live;
jonnysport.allow_zero_items      = (typeof(jonnysport.allow_zero_items) == 'undefined')      ? false     : jonnysport.allow_zero_items;
jonnysport.shipping_per_item     = (typeof(jonnysport.shipping_per_item) == 'undefined')     ? 0         : jonnysport.shipping_per_item;
jonnysport.shipping_per_order    = (typeof(jonnysport.shipping_per_order) == 'undefined')    ? 0         : jonnysport.shipping_per_order;
jonnysport.free_shipping         = (typeof(jonnysport.free_shipping) == 'undefined')         ? false     : jonnysport.free_shipping;
jonnysport.max_quantity_per_item = (typeof(jonnysport.max_quantity_per_item) == 'undefined') ? 5         : jonnysport.max_quantity_per_item;
jonnysport.single_page           = (typeof(jonnysport.single_page) == 'undefined')           ? true      : jonnysport.single_page;
jonnysport.image_path            = (typeof(jonnysport.image_path) == 'undefined')            ? 'images/' : jonnysport.image_path;
jonnysport.page                  = (typeof(jonnysport.page) == 'undefined')                  ? 'index'   : jonnysport.page;
jonnysport.prefetch              = (typeof(jonnysport.prefetch) == 'undefined')              ? true      : jonnysport.prefetch;
jonnysport.cookie_name           = (typeof(jonnysport.cookie_name) == 'undefined')           ? 'cart'    : jonnysport.cookie_name;

(function() {
	imgs = {};
	
	function prefetch() {
	  var src = {
	    ebag: ["ebag-full-400x400.jpg", "ebag-detail-400x400.jpg", "ebag-pocket-400x400.jpg"],
	    wbag: ["wbag-full-400x400.jpg", "wbag-zip-400x400.jpg", "wbag-strap-400x400.jpg"],
	    kbag: ["kbag-full-400x400.jpg", "kbag-end-400x400.jpg"],
	    "45sp": ["45-spacer-400x400.jpg"]
	  }
	  for (var bag in src) {
	    imgs[bag] = [];
	    for (var i in src[bag]) {
	      var img = new Image();
	      img.src = jonnysport.image_path + src[bag][i];
	      imgs[bag].push(img);
	    }
	  }
	}
	
  if (jonnysport.prefetch) {
		setTimeout(prefetch, 1);
	}
	
	jonnysport.show_img = function($span, i) {
		if ($span.hasClass('bag_img_selected')) {
			return; // image already displayed
		}
    i = i - 1;
    var id = $span.parent().parent().attr('id'); 
		var img = imgs[id][i];
    if (img) {
			var $img = $span.find('img');
      if (img.src.substr((img.src.length - $img.attr('src').length)) == $img.attr('src')) {
				return; // image already displayed
			}
			$img.replaceWith(img);
      $span.find('span')
        .removeClass('bag_img_selected')
        .slice(i, i + 1)
        .addClass('bag_img_selected');
      }       
    }
})();

$(function() {
	
	/*
        5.) The RSS Feed Reader from http://www.reindel.com/five_javascript_tricks_jquery/

    $.ajax({
        type: "GET",
        url: "feed.xml",
        dataType: "xml",
        success: function(rss) {
            strRSS = "<h4>" + $("/rss/channel/title",rss).text() + "</h4>";
            $("/rss/channel/item/title:lt(5)",rss).each(function(i) {
                strRSS += "<p><strong><a href='";
                strRSS += $("/rss/channel/item/link:eq(" + i + ")",rss).text();
                strRSS += "'>";
                strRSS += $(this).text();
                strRSS += "</a></strong><br />";
                strRSS += ($("/rss/channel/item/description:eq(" + i + ")",rss).text()).substring(0,200) + "...</p>";
            });
            $("#feed_me").html(strRSS);
        }
    });
    */

  function toPrice(value) { return (new Number(value)).toFixed(2) }
    
	function recalculate() {
    var shop_total = 0;
    var shipping_total = 0;
    $('#shop .row_total').each(function() {
			$row = $(this).parent();
			var $input = $row.find('.quantity input');
	    var quantity = new Number($input.val());
			if (quantity > jonnysport.max_quantity_per_item) {
				alert('Please contact Jonny Sport if you would like to purchase more than ' 
				  + jonnysport.max_quantity_per_item 
					+ ' of any item.')
				quantity = jonnysport.max_quantity_per_item;
				$input.val(quantity);
			}
	    var price = new Number($row.find('.price').text());
			var row_total = quantity * price;
			$(this).text(toPrice(row_total));
      shop_total += row_total;
      shipping_total += quantity * jonnysport.shipping_per_item;
    });
    if (shop_total > 0) {
			shipping_total += jonnysport.shipping_per_order;
			shop_total += shipping_total;
		}
    $('#shop .shipping_total').text(toPrice(shipping_total));
    $('#shop .shop_total').text(toPrice(shop_total));
		writeCartCookie();
	}
	
  function writeCartCookie() {
    var cart = {};
    $('#shop .quantity input').each(function() {
      var name = $(this).attr('name');
      cart[name] = $(this).val();
    });
		$.cookie(jonnysport.cookie_name, JSON.stringify(cart), 1);
  }
    
  function readCartCookie() {
    var cookie = $.cookie(jonnysport.cookie_name);
    if (cookie) {
      var cart = JSON.parse(cookie);
      $('#shop .quantity input').each(function() {
        var name = $(this).attr('name');
				var quantity = cart[name] ? cart[name] : 0;
        $(this).val(quantity);
      });
    }
    recalculate();
  }
			
	function go_home() {
		history.go(0);
	}
	
	function header_click(e) {
    var $target = $(e.target);
    if (($target).attr('id') == 'blog_link') {
      return true;
    }
    if (($target).parent().attr('id') == 'blog_link') {
      return true;
    }
		if (!jonnysport.single_page) {
			return true;
		};
		go_home();	
	}
	
	function img_event(e) {
    var $target = $(e.target);
    var $span = $target.parent();
    var i = new Number($target.text());
    jonnysport.show_img($span, i);
	}
	
  function add_item(e) {
    var $input = $(e.target).parent().parent().find('.quantity input');
		var quantity = new Number($input.val());
		$input.val(quantity + 1);
		recalculate();
  }
	
	function check_order() {
		recalculate();
		if ("0.00" == $('#shop .shop_total').text()) {
			alert("There are no items in your shopping bag!");
			return jonnysport.allow_zero_items;
		}		
    if (jonnysport.live) {
			return true; // return true to submit form
		}
	  alert("Closed for maintenance. Come back soon.");
	  return false;
	}
	
	function clear_order() {
		$('#shop .quantity input').each(function() {
			$(this).val(0);
		});
		recalculate();
	}
	
  $('#hd span').click(header_click);
	if (jonnysport.single_page || (jonnysport.page == 'shop')) {
		var $shop = $('#shop');
	  $shop.find('td img').click(add_item);
	  $shop.find('table').change(recalculate);
	  $shop.find('form').submit(check_order);
	  $shop.find('#clear_button').click(function(){
	    clear_order();
		  return false;
	  });
	  $shop.find('#update_button').click(function() {
			recalculate();
			return false;
		});
		readCartCookie();        
  }
  if (jonnysport.single_page || (jonnysport.page == 'products')) {
		var $tabs = $('#products-tabs');
    $tabs.find('.left span').click(img_event);
		$tabs.tabs();
	}
  if (jonnysport.single_page) {
		$('#tabs').tabs();
	}
	
});
