/*global $, bc_product, Shadowbox */

var BeyondCoastal = (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 () {
//		$.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);
		}

		$('.swapimg')
			.bind('mouseover', function () {
				var match = $(this).attr('id').match(/(\d)+$/);
				if (typeof match[0] !== 'undefined' && typeof sizes[match[0]] !== 'undefined') {
					$(elements.prodimg).attr('src', templates.img_md.replace(/%SKU%/g, sizes[match[0]].sku));
					$('#ZoomLink > a').attr('href', templates.img_lg.replace(/%SKU%/g, sizes[match[0]].sku));
					//Shadowbox
				}
			});
	
	};

	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);

}());

