$(document).ready(function() {
	
	// Create shipping drop down
	$('div#si').append('<div class="shipping_location"><label>Your Shipping Destination: </label><select name="shipping_location" id="shipping_location">'+
					   '<option value="0">Please choose your shipping destination...</option>'+
					   '<option value="3">Calgary, AB - Pick up</option>'+
					   '<option value="1">North America</option>'+
					   '<option value="2">International</select>'+
					   '</div>');
					
	$('select#shipping_location').change(function() {
		var val = $(this).val();
//		console.log(val);
		$.cookie('shipping_location', val, { expires: 356 });		
	});
	
	if($.cookie('shipping_location') != null){
		$('select#shipping_location').val($.cookie('shipping_location'));
	}
	
	
	// Create view cart button
	$('div#si').append('<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post">'+
	'<input type="hidden" name="cmd" value="_cart">'+
	'<input type="hidden" name="business" value="scott@vhfootwear.com">'+
	'<input type="image" class="viewcart" src="/images/b_viewcart.jpg" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">'+
	'<input type="hidden" name="display" value="1">'+
	'</form>');
	
	$.each(storeItems, function(i,item) {

		var id = item.store_item_id;
	
		
	
		// Create item
		$('div#si').append('<div class="store_item" id="id_'+id+'"></div>');
	
		if (item.photos)
		{
			$('div#id_'+id).append('<div class="item_image"><a href="'+APP_URI+'assets/images/'+item.photos[0].file_name+'-full.jpg" class="thickbox"><img src="'+APP_URI+'assets/images/'+item.photos[0].file_name+'-thumb.jpg" /></a></div>');
		}
	
		// Add title
		$('div#id_'+id).append('<div class="item_details"><h3>'+item.title+' - $'+item.price+'</h3><p class="desc">'+item.description+'</div>');
	
		// Add qty
	
	
		// Add options
		if (item.option1||item.services)
		{
			// Add item 1
			
			$('div#id_'+id+' div.item_details').append('<div class="item_options"></div>');
			
			addQtyItem(id,item,1);
		
			// Add plus sign
			$('div#id_'+id+' div.item_details').append('<p class="add"><a href="javascript:;" id="add_'+id+'" class="add">Add Item</a><a href="javascript:;" id="remove_'+id+'" class="remove">Remove Item</a><a href="javascript:;" class="buy" id="buy_'+id+'">Add to Cart</a></p>');
		}
		else
		{
			$('div#id_'+id+' div.item_details').append('<p class="qty"><lable>QUANTITY</label> <input type="text" name="qty_'+id+'" id="qty_'+id+'" value="1" class="qty" /><a href="javascript:;" class="buy" id="buy_'+id+'">Add to Cart</a></p>');
		}
		
		$('div#id_'+id).append('<div class="clear"><span></span></div>');
	
	});
	
	// Add bttn
	$('a.add').click(function(e) {
		e.preventDefault();
	
		var id = $(this).attr('id').replace('add_', '');

		addQtyItem(id, storeItems[id], $('div#id_'+id+' div.item_details div.item_options div').length + 1)
	});
	
	// Minus bttn
	$('a.remove').click(function(e) {
		e.preventDefault();
	
		var id = $(this).attr('id').replace('remove_', '');

		removeQtyItem(id)
	});
	
	// Buy button
	$('a.buy').click(function(e) {
		e.preventDefault();
		var id = $(this).attr('id').replace('buy_', '');
		addToCart(id);
	});
	
	if(typeof sIFR == "function")
	{
		sIFR.replaceElement("h2#page_title", named({
			sFlashSrc: "/js/sifr/avenir.swf", 
			sColor: '#FFFFFF',
			sBgColor: '#525861',
			sCase: 'upper',
			sWmode: 'transparent',
			sFlashVars: 'letterSpacing=3'
		}));
		
		sIFR.replaceElement("div#content h3", named({
			sFlashSrc: "/js/sifr/avenir.swf", 
			sColor: '#FFFFFF',
			sBgColor: '#525861',

			sWmode: 'transparent',
			sFlashVars: 'letterSpacing=2.5'
		}));
	}
});

addQtyItem = function(id, item, qty_num) {
	
	var count = $('div#id_'+id+' div.item_options div').length;
	
	if (count >= 4)
	{
		if (!confirm("If you are ordering 5 or more products, you can call us to receive bulk discount prices. Click Ok to continue."))
		{
			return;
		}
	}
	
	$('div#id_'+id+' div.item_details div.item_options').append('<div id="'+id+'_'+qty_num+'"><p class="qty_num">'+qty_num+'.</p></div>');
	
	$('div#'+id+'_'+qty_num+' a.remove').click(function(e) {
		e.preventDefault();
		
		var id = $(this).attr('id').replace('remove_', '');
		removeQtyItem(id);
	});
	
	
	// Add options for item 1
	if (item.option1)
	{
		addOptions(id, qty_num, item.option1, 1);
		if(item.option2)
		{
			addOptions(id, qty_num, item.option2, 2);
		}
	}
	
	
	// Add services
	if (item.services)
	{
		$.each(item.services, function() {
			addServices(id, qty_num, this);
		});
	}
	
	
	
	
}

removeQtyItem = function(id)
{
	if ($('div#id_'+id+' div.item_options div').length > 1)
		$('div#id_'+id+' div.item_options div:last').remove();
}

addOptions = function(id, qty_num, option, opt_num) {
	

	$('div#'+id+'_'+qty_num).append('<p class="options"><label>'+option.title+': </label><select class="option" name="opt'+opt_num+'_'+qty_num+'_'+id+'" id="opt'+opt_num+'_'+qty_num+'_'+id+'"></select></p>');
	$('select#opt'+opt_num+'_'+qty_num+'_'+id).append('<option value="0">Select an Option...</option>');

	
	var options = option.items.split(',');
	
	$.each(options, function() {
		$('select#opt'+opt_num+'_'+qty_num+'_'+id).append('<option value="'+this+'">'+this+'</option>');
	});
}

addServices = function(id, qty_num, service) {
	
	$('div#'+id+'_'+qty_num).append('<p class="services"><label>'+service.title+': </label><select clas="service" name="service'+id+'_'+service.service_id+'_'+qty_num+'" id="service'+id+'_'+service.service_id+'_'+qty_num+'"></select></p>');

	$('select#service'+id+'_'+service.service_id+'_'+qty_num).append('<option value="0">Select a Service...</option><option value="-1">No service required.</option>');
	
	$.each(service.items, function() {
	    if (this.price == '0.00')
	    {
	    	$('select#service'+id+'_'+service.service_id+'_'+qty_num).append('<option value="'+this.service_item_id+'">Free - '+this.title+'</option>');

	    }
	    else
	    {
	    	$('select#service'+id+'_'+service.service_id+'_'+qty_num).append('<option value="'+this.service_item_id+'">$'+this.price+' - '+this.title+'</option>');

	    }
	});

}

addToCart = function(id) {

	if ($('select#shipping_location').val() < 1)
	{
		alert('Please choose your location by using the drop down at the top of the page, then click add to cart.');
		return;
	}
	
	var item_details = storeItems[id];
	var item = {
					id: parseInt(id),
					title: item_details.title,
					price: parseFloat(item_details.price),
					services_price: 0
				};

	if ($('div#id_'+id+' div.item_options').length) 
	{	// Has options and/or services
		item.options = true;
		item.qty = $('div#id_'+id+' div.item_options div').length;
		item.details = [];
		$('div#id_'+id+' div.item_options div').each(function() {
			var det = {
				options: [],
				services: []
			};
			
			$(this).find('p.options').each(function(i,n) {
				var opt = {
					title: $(n).find('label').text(),
					value: $(n).find('select').val()
				}
				det.options.push(opt);
			});
			
			$(this).find('p.services').each(function(i,n) {
				var serv = {
					value: $(n).find('select').val()
				}
				
				
		
				var service = findService(id,serv.value);
				serv.title = service.title;
				det.services.push(serv);
				if (service)
				{
					item.services_price = parseFloat(item.services_price) + parseFloat(service.price);
				}
			});
			
			item.details.push(det);
		});
	}
	else
	{	// No options or services
		item.options = false;
		item.qty = parseInt($('#qty_'+id).val());
		item.details = false;
	}
	

	if ($('select#shipping_location').val() == 1)
	{ // North America
		item.shipping = item_details.shipping_north_america * item.qty;
	}
	else if ($('select#shipping_location').val() == 3)
	{ // International
		item.shipping = 0;
	}
	else
	{
		item.shipping = item_details.shipping_international * item.qty;
	}
	
	item.total_price = (item.price * item.qty) + item.services_price;

	/// sum up options for each item
	var summary = [];
	if (item.options)
	{
		$.each(item.details, function() {
			var o = [];
			for(i=0;i<this.options.length;i++)
			{
				if (this.options[i].value > 0)
					o.push(this.options[i].title +  this.options[i].value);
			}
			
			for(i=0;i<this.services.length;i++)
			{
				if (this.services[i].value > 0)
					o.push(this.services[i].title.replace(': ', ''));
			}
			
			summary.push(o.join(', '));
		});
		
		var addform = '<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" id="addcartform">'+
			'<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">'+
			'<input type="hidden" name="add" value="1">'+
			'<input type="hidden" name="cmd" value="_cart">'+
			'<input type="hidden" name="business" value="scott@vhfootwear.com">'+
			'<input type="hidden" name="item_name" value="'+item.title+'">'+
			'<input type="hidden" name="amount" value="'+item.total_price+'">'+
			'<input type="hidden" name="shipping" value="'+item.shipping+'">'+
			'<input type="hidden" name="no_shipping" value="0">'+
			'<input type="hidden" name="no_note" value="1">'+
			'<input type="hidden" name="currency_code" value="CAD">'+
			'<input type="hidden" name="lc" value="CA">'+
			'<input type="hidden" name="bn" value="PP-ShopCartBF">';

		// Add details
		$.each(summary, function(i,n) {
			addform = addform + '<input type="hidden" name="on'+i+'" value="Item '+(i+1)+'" />';
			addform = addform + '<input type="hidden" name="os'+i+'" value="'+addslashes(summary[i])+'" />';
		});	

		addform = addform + '</form>';
	}
	else
	{
			var addform = '<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" id="addcartform">'+
				'<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">'+
				'<input type="hidden" name="add" value="1">'+
				'<input type="hidden" name="cmd" value="_cart">'+
				'<input type="hidden" name="business" value="scott@vhfootwear.com">'+
				'<input type="hidden" name="item_name" value="'+item.title+'">'+
				'<input type="hidden" name="amount" value="'+item.price+'">'+
				'<input type="hidden" name="shipping" value="'+item.shipping+'">'+
				'<input type="hidden" name="shipping2" value="'+item.shipping+'">'+
				'<input type="hidden" name="no_shipping" value="0">'+
				'<input type="hidden" name="quantity" value="'+item.qty+'">'+
				'<input type="hidden" name="no_note" value="1">'+
				'<input type="hidden" name="currency_code" value="CAD">'+
				'<input type="hidden" name="lc" value="CA">'+
				'<input type="hidden" name="bn" value="PP-ShopCartBF"></form>';
	}
	
	
	
	$('div#si').append(addform);
	
	$('form#addcartform').submit();
	location.href = location.href;
}

findService = function(id, service_item_id) {
	var services = storeItems[id].services;
	var obj = false;
	$.each(services, function(i,n) {

		$.each(n.items, function(j,o) {
			if (o.service_item_id == service_item_id)
			{
				obj = o;
			}
		});
	});
	
	return obj;
}

function addslashes(str) {
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\0/g,'\\0');
return str;
}