/**
	@base Panagora.Class
	@constructor
	@author Niklas Bergius
*/
Panagora.ProductView = new (Panagora.Class.create(
/** @lends Panagora.ProductView */
function ProductView() {
	var self = this;
	var productId = 0;
	var currentImage;
	var stdPriceText;
	var addingInProgress;
	
	function init() {
		// If you have multiple submits, attach onclick-events instead!
		// Always use onclick event...
		$j('#add-to-cart-form .button.available').click(onSizeChange);
		$j('#add-to-cart-form .button.unavailable').click(onUnavailableClick);
		$j('#add-to-cart-form').submit(onFormSubmit);
		
		// Flash switcher
		$j('#flash-movie-switcher').bind('click', flashFadeIn);
		
		if ($j('#myContent').length > 0) {
			flashFadeIn();
		}
		
		// Image switcher
		$j('#image-container li').each(function(index){
			if ($j(this).attr('panagora:zoom') == $j('#primary-image-node').attr('panagora:zoom')) {
				currentImage = $j('#image-container li:eq('+index+')');
			}
		});
		$j("#image-container li").click(imageSwitch);
		
		$j('#primary-image').fancybox({
			'autoScale': false,
			'titleShow': false
		});

		// Attach the productId selector on all distinct images
		$j('#add-to-cart-form .distinct').click(fetchProductId);

		// if only one dimension 
		if ($j('#add-to-cart-form .distinct:visible').length == 0) {
			$j('#add-to-cart-form .distinct').click();

			// if all sizes are out of stock
			if ($j('#selectable-products-container button.available').length == 0) {
				$j('#select-size-legend').hide();
				$j('#out-of-stock-legend').show();
			} else if ($j('#selectable-products-container button.available').length == 1) {
				$j('#selectable-products-container button.available').click(0);
			}
		}
		
		// get standard price text
		stdPriceText = $j('span.price').html();
		
		// Add size chart 
		$j('.sizeguide-open').click(function() { $j('#sizeguide').show(); });
		$j('.sizeguide-close').click(function() { $j('#sizeguide').hide(); });
		
	}

	function flashFadeIn() {
		$j('#flash-movie-container').fadeIn('slow', function(){
			//document.getElementById('myContent').startMovie();
			$j('#product-flash-controller').attr('src', '/static/images/stop.png');
		});
		$j('#primary-image').fadeOut('slow');
		$j('#flash-movie-switcher')
			.unbind('click')
			.bind('click', flashFadeOut);
	}
	this.flashFadeIn = flashFadeIn;
	function flashFadeOut() {
		$j('#primary-image').fadeIn('slow');
		
		$j('#flash-movie-container').fadeOut('slow', function () {
			//document.getElementById('myContent').stopMovie();
			$j('#product-flash-controller').attr('src', '/static/images/play.png');
		});
		
		$j('#flash-movie-switcher')
			.unbind('click')
			.bind('click', flashFadeIn);
	}
	this.flashFadeOut = flashFadeOut;
	
	function fetchProductId() {
		disableAddButton();

		$j('.distinct-row .selected').removeClass('selected');

		$j('#color-image-container')
			.attr('panagora:image', '')
			.attr('panagora:zoom', '');
		
		var distincts = $j(this);
		
		
		var products = [];
		
		for (var i = 0; i < distincts.length; i++) {
			if (productMatrix[distincts[i].name][distincts[i].value]) {
				var selectedProducts = productMatrix[distincts[i].name][distincts[i].value].clone();
				products.push(selectedProducts);
			} else if (distincts[i].value == 0) {
				var selectedProducts = [];
				for (tmp in productMatrix[distincts[i].name]) {
					selectedProducts = selectedProducts.concat(productMatrix[distincts[i].name][tmp].clone());
				}
				products.push(selectedProducts);
			} else {
				return;
			}
		}

		// This is brokezor... FIX!
		var first = products.pop();
		var temp = [];
		var tempImages = []
		if (first) {
			temp = first;
			while(el = products.pop()) {
				temp = temp.intersect(el);
			}

			if (temp.length > 0 && temp[0]) {
				// Show the buttons that is included in the array
				tempImages = temp.slice(0);
				showActiveProducts(temp);
			} 
		}
		
		if($j(this).hasClass('color'))
			var selectedOption = $j(this).next();
		else
			var selectedOption = $j(this);
	
		selectedOption.addClass('selected');

		for (var i = 0; i < tempImages.length; i++) {
			var selectedImage = $j('#selectable-products-container #' + tempImages[i]);
			if (selectedImage.attr('panagora:image') && selectedImage.attr('panagora:image') != '') {
				$j('#color-image-container')
					.attr('panagora:image', selectedImage.attr('panagora:image'))
					.attr('panagora:zoom', selectedImage.attr('panagora:zoom'));
				
				// show product image
				$j('#color-image-container').click();
				break;
			} else if ($j('#image-container li:eq(0)').length > 1) {
				// show first image
				$j('#image-container li:eq(0)').click();
			}
		}
	}
	
	function showActiveProducts(productIds) {

		$j('#selectable-products-container button').hide().removeClass('selected');
		
		var productId;
		var sizeInStock = false;
		while (productId = productIds.pop()) {
			var button = $j('#selectable-products-container #product-' + productId);
			button.show();
			sizeInStock = button.is('.available') || sizeInStock;
		}
		
		// reset price text
		$j('span.price').html(stdPriceText);

		if (!sizeInStock) {
			$j('#selectable-products-container #select-size-legend').css('display', 'none');
			$j('#selectable-products-container #out-of-stock-legend').css('display', 'block');
		} else {
			$j('#selectable-products-container #select-size-legend').css('display', 'block');
			$j('#selectable-products-container #out-of-stock-legend').css('display', 'none');
		}
		
		// show button container
		$j('#selectable-products-container').show();
	}
	
	function onUnavailableClick() {
		Panagora.alert('@{SIZE_UNAVAILABLE}');
		return false;
	}
	
	function onSizeChange(e) {
		e.preventDefault();
		
		if (addingInProgress)
			return;
		
		if (this.getAttribute('panagora:value') == productId) {
			productId = 0;

			// Remove any dimmed buttons and selected buttons
			$j("#add-to-cart-form .button")
				.removeClass("dimmed")
				.removeClass("selected");

			// reset specific size and color
			$j('.product-name').html('&nbsp;');

			// Switch image on the submit-image to the highlighted one.
			disableAddButton();
		} else {
			productId = this.getAttribute('panagora:value');
			
			// Remove any selected buttons
			$j("#add-to-cart-form .button").removeClass("selected");
			
			// Selected the one you clicked.
			var button = $j(this);
			button.addClass("selected");
			$j("#add-to-cart-form .button:not(.selected)").addClass("dimmed");
	
			// show specific price
			var priceText = $j('<span class="pricevalue"></span>')
				.append(button.attr('panagora:price'));
			
			$j('span.price').html(
				button.attr('panagora:isonsale') == 'False'
					? ''
					: '<strike>' + button.attr('panagora:originalprice') + '</strike> '
			);
			
			$j('span.price').append(priceText);
			
			// show specific size and color
			var nameText = button.children('img').attr('alt');
			$j('.product-name').html(nameText);
	
			// Switch image on the submit-image to the highlighted one.
			enableAddButton();
		}
	}

	function onFormSubmit(e) {
		e.preventDefault();
		
		if (productId > 0) {
			$j('#add-to-cart').get(0).disabled = true;
			
			Panagora.post({
				'url': this.action,
				'data': {
					'id': productId,
					'partial': 'cart-summary'
				},	
				'dataType': 'html', 
				'success': cartAddSuccess,
				'error': cartAddFailure
			});
			
			addingInProgress = true;
		} else {
			if ($j('#selectable-products-container:visible').length)
				Panagora.alert('@{PLEASE_SELECT_SIZE}');
			else
				Panagora.alert('@{PLEASE_SELECT_COLOR}');
		}
		
		return false;
	}
	
	function cartAddSuccess(response) {
		if (Panagora.CartComponent && Panagora.CartComponent.refresh)
			Panagora.CartComponent.refresh(response);
		showGoToCheckout();
		$j('#add-to-cart').get(0).disabled = false;
		addingInProgress = false;
	}
	
	function showGoToCheckout() {
		productId = 0;
		// Remove any dimmed buttons and selected buttons
		$j("#add-to-cart-form .button")
			.removeClass("dimmed")
			.removeClass("selected");

		$j('#add-to-cart')
			.removeClass('active')
			.addClass('nocursor');
		$j('#go-to-cart').show('slide', {}, 500);
	}
	
	function enableAddButton() { 
		$j('#add-to-cart').get(0).disabled = false;
		$j('#add-to-cart')
			.removeClass('nocursor')
			.addClass('active');
	}
	
	function disableAddButton() { 
		productId = 0;
		$j('#add-to-cart')
			.removeClass('active')
			.addClass('nocursor');
	}

	function cartAddFailure(response) {
		var json = eval('(' + response.responseText + ')');
		Panagora.errorAlert(json.Status);
		$j('#add-to-cart').get(0).disabled = true;
		addingInProgress = false;
	}
	
	function imageSwitch() {
		currentImage = $j(this);

		var imageURL = this.getAttribute('panagora:image');
		var zoomURL = this.getAttribute('panagora:zoom');
		var imageHeight = this.getAttribute('panagora:height');
		var imageWidth = this.getAttribute('panagora:width');
		document.getElementById("primary-image-node").src = imageURL;
		document.getElementById("primary-image-node").setAttribute('panagora:height', imageHeight);
		document.getElementById("primary-image-node").setAttribute('panagora:width', imageWidth);
		document.getElementById("primary-image").setAttribute('href', zoomURL);

		flashFadeOut();
	}
	
	function imageSwitchNext() {
		var next = currentImage.next('li');
		if (!next.length || next.attr('panagora:image') == '')
			next = $j('#image-container li:eq(0)');
		
		if (next.attr('panagora:image') != '')	
			next.click();
	}

	// init on dom ready
	Panagora.ready(init);

}))();

// Intersect prototype
Array.prototype.intersect = function (arr) {
	var primary = this.length <= arr.length ? this : arr;
	var secondary = this.length <= arr.length ? arr : this;
	
	var output = [];
	for (var i = 0; i < primary.length; i++) {
		if (secondary.indexOf(primary[i]) > -1) {
			output.push(primary[i]);
		}
	}
	return output;
}

Array.prototype.clone = function () {
	var clone = [];
	for (var i = 0; i < this.length; i++) {
		clone.push(this[i]);
	}
	
	return clone;
}

// Prototype an indexOf-method for IE...
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}
