/*global $, bc_product, Shadowbox */

var OSCommerce = (function () {
	var 
		URLs = {
			osc_buy_now: '/catalog/index.php/action/buy_now/products_id/%ID%',
			osc_product_json: '/catalog/json/product_info.json.php/products_id/%ID%',
			osc_write_review_json: '/catalog/json/product_reviews_write.json.php/action/process/products_id/%ID%'
		},
		elements = {
			buylink: 'buylink',
			prodimg: '#ProductImage-img'
		},
		templates = null,
		sizes = [],
		default_image = null,
		ratings = [0, 0, 0, 0, 0, 0],
/*			"1": 0, 
			"2": 0, 
			"3": 0, 
			"4": 0, 
			"5": 0
		},*/
		hasSale = false,

	// functions
		init,
		addSizes,
		presentSize,
		presentRating,
		getSize,
		presentReview,
		submitReview;

	init = function () {
// -------------------- disabled until URLs.templates is defined. ---------------------
//		$.getJSON(URLs.templates, function (data) {
//			templates = data;
//		});
		if (typeof bc_product !== 'undefined' && typeof bc_product.templates !== 'undefined') {
			templates = bc_product.templates;
		}
		
		$('#ProductReviews').removeClass('hidden').accordion({
			active: false,
			header: 'div.ratingHeader',
			collapsible: true,
			autoHeight: false,
			clearStyle: true
		});
		
		$("#ProductSizesContainer").ready(function () {
			 addSizes();
		});

		default_image = $(elements.prodimg).attr('src');
		
		$("#ZoomLink > a").fancybox({
			cyclic: true
		});

		$(".ratingselector input[type='image']").bind("click", function (ev) {
			ev.preventDefault();
			var i, iLen, val = $(this).val();
			$('#review_rating').attr('value', val);

			for (i = 5; i > 0; i -= 1) {
				$('#rateit_' + i).attr('src', '/images/icons/bc-rate-' + (i > val ? 'g' : 'y') + '-15.jpg');
			}
		});
		
		if (templates !== null && typeof templates.reviewform !== 'undefined') {	
			$('#WriteAReview').bind('submit', submitReview);
		}
		$(elements.prodimg).attr('data-img',$(elements.prodimg).attr('src'));
		$('.swapimg')
			.hover(function () {
				var match = $(this).attr('id').match(/(\d)+$/);
				var sku;
				var image;
				if (typeof match[0] !== 'undefined' && typeof sizes[match[0]] !== 'undefined') {

					var ColorAttr = $('#AddToCart .Product').attr('data-color-code');
					var id = $(this).attr('data-id');
					var ProductImage;
					if(typeof ColorAttr !== 'undefined' && ColorAttr !== false) {
						if($('.ColorsContainer[data-id='+id+'] .colorset.all_colors_colorset .color[data-color-code=' + ColorAttr + ']').hasClass('product_swatch_switch') == true) {
							img= $('.ColorsContainer[data-id='+id+'] .colorset.all_colors_colorset .color[data-color-code=' + ColorAttr + '] input[name="products_colors_image"]').val();
							image = templates.img_md_full.replace(/%SKU%/g, img);
						} else { image = templates.img_md_full.replace(/%SKU%/g, $(this).attr('data-image')); }
					} else {
						sku = sizes[match[0]].sku;
						image = templates.img_md_full.replace(/%SKU%/g, $(this).attr('data-image'));
					}
					$(elements.prodimg).attr('src', image);
					$(elements.prodimg).attr('data-img-src', image);
					$(this).parent('#ProductSizesContainer').children('.swapimg').removeClass('hover');
					$(this).addClass('hover');
				}
			},function() {
				$(elements.prodimg).attr('src',$(elements.prodimg).attr('data-img'));
				$(this).removeClass('hover');
				
			}).bind('click.show',function(){
				var match = $(this).attr('id').match(/(\d)+$/), msrp, sellas;
				msrp = $(this).attr('data-msrp');
				sellas = $(this).attr('data-sell-as');
				if (typeof match[0] !== 'undefined' && typeof sizes[match[0]] !== 'undefined') {
					$('#ZoomLink > a').attr('href', templates.img_lg_full.replace(/%SKU%/g, $(this).attr('data-image')));
					$(elements.prodimg).attr('data-img', $(elements.prodimg).attr('data-img-src'));
					$('#AddToCart .Product .ProductImage img').attr('src', templates.img_xs_full.replace(/%SKU%/g, $(this).attr('data-image')));
					$('#AddToCart .Product').attr('data-sku',$(this).attr('data-sku')).attr('data-id',$(this).attr('data-id'));
					$('#cart_pid').val($(this).attr('data-id'));
					$('#add_to_cart_form').attr('data-sku',$(this).attr('data-sku')).attr('data-id',$(this).attr('data-id'));
					if (msrp !== sellas) {
						$('#cart_msrp').html('<span class="oldprice">' + msrp + '</span> ' + sellas);
					} else {
						$('#cart_msrp').html($(this).attr('data-msrp'));
					}
//					$('#cart_msrp').html($(this).attr('data-msrp'));
					//Shadowbox
					$(this).parent('#ProductSizesContainer').children('.swapimg').removeClass('hover');
					$(this).addClass('hover');
				}
				$(this).parent('#ProductSizesContainer').children('.swapimg').removeClass('selected');
				$(this).addClass('selected');
				if($(this).attr('data-outofstock') == 'true') {
					$('#AddToCart .AddToCart a').attr('href','#');
					$('#cart_add_button').attr('data-outofstock',true).addClass('outofstock').prop('disabled',true);
				} else {
					$('#AddToCart .AddToCart a').attr('href',templates.add_url.replace(/%ID%/g, $(this).attr('data-id'))).attr('data-id',$(this).attr('data-id'));
					$('#cart_add_button').attr('data-outofstock',false).removeClass('outofstock').prop('disabled',false);
					$('#AddToCart .Product .ProductRemove a').attr('href',templates.remove_url.replace(/%ID%/g, $(this).attr('data-id')));
				}
				$('#AddToCart .Product .ProductTitle .title').html($(this).attr('data-name'));
				$('#AddToCart .Product .ProductTitle .sku').html($(this).attr('data-sku'));
				if (msrp !== sellas) {
					$('#cart_msrp').html('<span class="oldprice">' + msrp + '</span> ' + sellas);
				} else {
					$('#cart_msrp').html($(this).attr('data-msrp'));
				}
			
//				$('#cart_msrp').html($(this).attr('data-msrp'));
			});
		$('.swapimg .outofstock').not('.hidden').parentsUntil('#ProductSizesContainer').parent().addClass('HasOutOfStock');
		$('#AddToCart .AddToCart a').click(function() {
			var sku = $(this).parentsUntil('#AddToCart').next('.Product').attr('data-sku');
			if($(this).attr('data-outofstock') == 'false') {
				if($('#InCartWrapper .Product[data-sku=' + sku + ']').length === 0)
				{
					$('#AddToCart .Product').clone(true).appendTo('#InCartWrapper').hide().show('slide');
					$.ajax($(this).attr('href') + '?qty=' + $('#AddToCart .Product .ProductQuantity .Quantity').val());
					$('#InCartWrapper .Product[data-sku=' + sku + '] input.Quantity').prop('disabled',true);
				} else {
					$('#InCartWrapper .Product[data-sku=' + sku + ']').animate({ backgroundColor: "#68BFEF" }, 300).animate({ backgroundColor: "#FFFFFF" }, 150);
					$('#InCartWrapper .Product[data-sku=' + sku + '] input[name=qty]').val(parseInt($('#InCartWrapper .Product[data-sku=' + sku + '] input[name=qty]').val())+parseInt($('#AddToCart .Product .ProductQuantity .Quantity').val()));
					$.ajax($(this).attr('href') + '?qty=' + $('#AddToCart .Product .ProductQuantity .Quantity').val());
					$('#InCartWrapper .Product[data-sku=' + sku + '] input.Quantity').prop('disabled',true);
				}
			}
			return false;
		});
		$('#AddToCart .AddToCart a').bind('click.show',function() { 
			if($(this).attr('data-outofstock') == 'false') {
				$('#InCart').show('slide');
				$(this).unbind('click.show');
			}
			return false;
		});
		$('#AddToCart .Product .ProductRemove a').click(function() {
			$.ajax($(this).attr('href'));
			$(this).parentsUntil('#InCartWrapper').remove();
			if($('#InCart .Product').length == 0) { $('#InCart').hide('slide');

			$('#AddToCart .AddToCart a').bind('click.showagain',function() { 
				if($(this).attr('data-outofstock') == 'false') {
					$('#InCart').show('slide');
					$(this).unbind('click.showagain');
				}
				return false;
			});
			}
			return false;
		});
		$('#AddToCart .Product .ProductUpdate a').click(function() {
			var qty;
			var sku;
			qty = parseInt($(this).parentsUntil('.Product').parent().children('.ProductQuantity').children('input').val());
			sku = $(this).parentsUntil('.Product').parent().attr('data-sku');
			$.post(templates.update_url,{'products_id[]': $(this).parentsUntil('.Product').parent().attr('data-id'),'cart_quantity[]':qty},
					function(){ $('#InCartWrapper .Product[data-sku=' + sku + ']').animate({ backgroundColor: "#68BFEF" }, 300).animate({ backgroundColor: "#FFFFFF" }, 150); });
			return false;
		});
		$('.swapimg:first-child').addClass('selected').trigger('click.show');
	};

	addSizes = function () {
		if (templates === null) {
			window.setTimeout(addSizes, 1000);
			return;
		}
		if (typeof bc_product !== 'undefined' && typeof bc_product.sizes !== 'undefined' && $.isArray(bc_product.sizes)) {
			var i, iLen, text;
			sizes = {};
			if (bc_product.sizes.length !== 0) {
				for (i = 0, iLen = bc_product.sizes.length; i < iLen; i += 1) {
					sizes[bc_product.sizes[i].oscommerce_id] = bc_product.sizes[i];
					/*
					if (typeof bc_product.sizes[i].oscommerce_id !== 'undefined' && bc_product.sizes[i].oscommerce_id !== null) {
						$("#ProductSizesContainer").append(
							$("<div></div>").attr("id", "ProductSizesContainer_" + bc_product.sizes[i].oscommerce_id).addClass('swapimg')
						);
						presentSize(bc_product.oscommerce[i]);
					}
					if (hasSale === true) {
						$('#ProductSizesContainer').addClass('hassale');
					}
					*/
				}
			} else if (bc_product.sizes.length === 0) {
				/*
				if (typeof bc_product.details.oscommerce_id !== 'undefined' && bc_product.details.oscommerce_id !== null) {
					$("#ProductSizesContainer").append(
						$("<div></div>").attr("id", "ProductSizesContainer_" + bc_product.details.oscommerce_id).addClass('swapimg')
					);
					presentSize(bc_product.oscommerce[0]);
				}
				if (hasSale === true) {
					$('#ProductSizesContainer').addClass('hassale');
				}
				*/
			}
			presentRating();
			
		}
	};

	presentSize = function (data) {
		var i, iLen, size, template;

		if (typeof data.error === "string") {
			$("#ProductsSizesContainer_" + data.requested_products_id).html(data.error);
			return;
		}
		if (data.new_price !== null) {
			hasSale = true;
		}
		
		if (typeof data.product_options !== 'undefined' && data.product_options !== null) {
			size = data.product_options[0].text;
		} else if (typeof sizes[data.product_info.products_id] !== 'undefined') {
			size = sizes[data.product_info.products_id].size;
		} else {
			size = "";
		}

		template = (data.new_price === null ? templates.msrp : templates.sale);

		$("#ProductSizesContainer_" + data.product_info.products_id)
			.html(template.replace(/%ID%/g, data.product_info.products_id)
				.replace(/%TITLE%/g, data.product_info.products_name)
				.replace(/%SIZE%/g, size)
				.replace(/%MSRP%/g, data.product_info.products_price)
				.replace(/%SALE%/g, data.new_price)
				.replace(/%SKU%/g, data.product_info.products_model)
				);
		for (i = 0, iLen = data.product_reviews.length; i < iLen; i += 1) {
			ratings[data.product_reviews[i].reviews_rating] += 1;
			presentReview(data.product_reviews[i], data.product_info.products_name);
		}
		
	};

//	initSocialTools = function () {
//		$('.SocialTools').html('<div id="fb-root"></div><fb:like href="" send="true" layout="button_count" width="450" show_faces="true" action="recommend" font="arial"></fb:like>');
//	};

	presentRating = function () {
		return;
		var i, iLen, entries = 0, total = 0;
		for (i = 1, iLen = ratings.length; i < iLen; i += 1) {
			entries += ratings[i];
		}
		for (i = 1, iLen = ratings.length; i < iLen; i += 1) {
			$('#ratings_' + i).attr("style", "width: " + ((ratings[i] / entries) * 100) + "%");
			total += ratings[i] * i;
		}
		
		$('#rating_count').html(
			templates.votes
				.replace(/%VOTES%/g, entries)
				.replace(/%PLURAL%/g, parseInt(entries, 10) !== 1 ? 's' : '')
		);
		$('#ratings_avg').html(entries === 0 ? "N/A" : (total / entries).toFixed(2));
		
	};
	
	presentReview = function (review) {
		var stars = "@@@__";
		if (typeof templates.review !== 'undefined' && typeof review !== 'undefined') {
			$('#reviewsContainer').append(
				templates.review.replace(/%ID%/g, review.reviews_id)
					.replace(/%STARS%/g, stars)
					.replace(/%RATING%/g, review.reviews_rating)
					.replace(/%LOCATION%/g, review.location)
					.replace(/%HELPFUL%/g, review.is_helpful)
					.replace(/%HELPFULTOTAL%/g, parseInt(review.is_helpful, 10) + parseInt(review.is_not_helpful, 10))
					.replace(/%HIDEHELPFUL%/g, (parseInt(review.is_helpful, 10) + parseInt(review.is_not_helpful, 10)) === 0 ? "hidden" : "")
					.replace(/%DATE%/g, review.date_added)
					.replace(/%REVIEW%/g, review.reviews_text)
			);
			
		}
	};
	
	getSize = function () {
	};
	
	submitReview = function (event) {
		event.preventDefault();
		$('#reviewsubmit').addClass('hidden');
		$('#reviewcancel').addClass('hidden');
		$.ajax({
			url: URLs.osc_write_review_json.replace(/%ID%/g, bc_product.details.oscommerce_id), 
			type: 'POST',
			data: $('#WriteAReview').serialize(),
			success: function (data, textStatus) {
				var result, message = '', i, iLen;
				// $('#review_debug').html(data + "<br>" + textStatus);
				result = $.parseJSON(data);
				if (result === null) {
					$('#review_debug').html('malformed response: ' + data);
				} else {
					if (typeof result.error !== 'undefined' && result.error !== false) {
						if ($.isArray(result.error)) {
							message = '<ul>';
							for (i = 0, iLen = result.error.length; i < iLen; i += 1) {
								message += '<li>' + result.error[i] + '</li>';
							}
							message += '</ul>';
							$('#review_debug').html(message);
						} else {
							$('#review_debug').html(result.error);
						}
						$('#reviewsubmit').removeClass('hidden');
						$('#reviewcancel').removeClass('hidden');
					} else if (typeof result.success !== 'undefined') {
						$('#WriteAReviewContainer').html(result.success);
					}
				}
			},
			error: function (jqXHR, textStatus, errorThrown) {
				$('#review_debug').html(textStatus + ": " + errorThrown);
			}
		});
	};

	$('#ProductSizesContainer').ready(init);

	$('.radioselector input[type="radio"]').live('click', function () {
		$('.radioselector').removeClass('selected ui-state-default');
		$(this).parents('div.radioselector').addClass('selected ui-state-default');
	});

	$('#shippingSelector input[type="radio"]').live('click', function () {
		var subtotal = parseFloat($('#ot_subtotal').attr('data-value') || 0), 
			discount = parseFloat($('#ot_discount').attr('data-value') || 0), 
			shipping = parseFloat($('#ot_shipping').attr('data-value') || 0), 
			tax = parseFloat($('#ot_tax').attr('data-value') || 0), 
			total = parseFloat($('#ot_total').attr('data-value') || 0),
			newShipping = parseFloat($(this).attr('data-rate')),
			newTotal = 0;

		$('#ot_shipping').text('$' + newShipping.toFixed(2));
		newTotal = subtotal + discount + newShipping + tax;
		$('#ot_total').text('$' + newTotal.toFixed(2));
	});

}());

