var submitClicked = false;
$(document).ready(function() {
    updateCartHeader();
    var galleryHref = $("#zoom1").attr("href");
    
    $('.galleryNav a').each(function() {
    	if($(this).attr('href') == galleryHref) {
			$(this).addClass('selected');    		
    	}
    });
    
    $('.galleryNav a').click(function() {
    	$(this).siblings().removeClass('selected');
    	$(this).addClass('selected');
    });
    
    $('#productSet li a').hover(
  		function () {
    		$(this).siblings(".productHover").show();
  		},
  		function () {
    		$(this).siblings(".productHover").hide();
  		}
	)
	
	$('#productSet li').click(function(e) {
		e.preventDefault();
		location.href = $('a', this).attr('href');
	});
	
	$('#relatedProducts li a').hover(
  		function () {
    		$(this).siblings(".productHover").show();
  		},
  		function () {
    		$(this).siblings(".productHover").hide();
  		}
	)
	
	$('#relatedProducts li').click(function(e) {
		e.preventDefault();
		location.href = $('a', this).attr('href');
	});
	
	$('#addToCart').click(function() {
		colourCount = $('.productColourIdInput').length;
		colourSelected = $('input:radio[name=productColourId]:checked').val();
		
		if($('input:radio[name=productColourId]:checked').siblings('img').is(':visible')) {
			return false;
		}
		//alert(colourSelected);
		//console.log($("#productSizeId option:selected").text());
		//return false;
		//console.log($('input:radio[name=productColourId]:checked').val());
		//return false;
		
		if ($("#productSizeId option:selected").text() == 'Please Select') {
			$('.sizeError').show();
			return false;
		} 
		
		if ($("#productSizeId option:selected").text() != 'Please Select' && colourCount != 0 && isNaN(colourSelected)) {
			$('.colourError').show();
			return false;
		} 
	});
    
    $('a.popupLink').bind('click', function(e) { popupWindow($(this).attr('href'), $(this).attr('title').replace(/[^A-z]/ig, ''),'width=650, height=800, scrollbars'); e.preventDefault(); });
    
    bVersion = getInternetExplorerVersion();
    
    // add the opaque bg to the menu item
    if($('#primaryNavigation li.selected').length > 0) {
        selectedElementWidth = $('#primaryNavigation li.selected a').width();
        $('#primaryNavigation li.selected:eq(0)').append('<span class="navItemBg" style="width: '+selectedElementWidth+'px;">&nbsp;</span>')
    }
    
    //find any images and round the corners
    if($('.stdContentImage').length > 0) {
        $('.stdContentImage').each(function() {
            $(this).append('<span class="tl border">&nbsp;</span><span class="tr border">&nbsp;</span><span class="bl border">&nbsp;</span><span class="br border">&nbsp;</span>');
        });
    }
    
    //find any images and round the corners
    if($('.stdSmallBrownImage').length > 0) {
        $('.stdSmallBrownImage').each(function() {
            $(this).append('<span class="tl border">&nbsp;</span><span class="tr border">&nbsp;</span><span class="bl border">&nbsp;</span><span class="br border">&nbsp;</span>');
        });
    }
    
    // Assign the change behavior to the size selection for a product
    $('#productSizeId').bind('change', function(e) {
    	submitClicked = false;
    	sizeUpdate();
    	productLoadColours($('#productId').val(), $(this).val());
    });
    
    productLoadColours($('#productId').val(), $('#productSizeId').val());
    
    $('.productColourIdInput').bind('click', function(e) {
        productLoadSizeColourInstance($('#productId').val(), $('#productSizeId').val(), $(this).val());
    });
    
    // Assign some functionality to the cart checkout link to submit the form and then go to checkout
    $('#cartCheckoutLink').bind('click', function (e) {
    	e.preventDefault();
    	$('#cartUpdateForm').attr('action', 'cart/cartUpdateCheckout');
    	$('#cartUpdateSubmit').click();
    });
});

function sizeUpdate() {
	//alert('size');
	//console.log(submitClicked);
	$('.sizeError').hide();
	$('.colourError').hide();	
}

function getInternetExplorerVersion() {
	var rv = -1;
	if (navigator.appName == 'Microsoft Internet Explorer') {
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
		rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

function popupWindow(url, name, attributes){
	// Append popup to the URL if it does not already exist
	var queryStringExists = false;
	if(url.match(/\?/)) {
		queryStringExists = true;
	}
	
	if(queryStringExists) {
		// Only append if we haven't already got the parameter popup defined
		if(!url.match(/(\?|&)popup=/)) {
			url = url + '&popup=true';
		}
	} else {
		url = url + '?popup=true';
	}
	
	var baseTags = document.getElementsByTagName('base');
	if(baseTags != undefined && baseTags.length > 0) {
		url = baseTags[0].href + url;
	}
	
	var newWindow = window.open(url, name.replace(/[^A-z]/ig, ''), attributes);
	newWindow.focus();
}

function productLoadColours(productId, productSizeId) {
	if(productId != undefined && productSizeId != undefined) {
		// Ensure productId and productSizeId are clean
		productId = productId.replace(/[^\d]/g, '');
		productSizeId = productSizeId.replace(/[^\d]/g, '');
		
		var url = 'rest/product-instances/' + productId + '/' + productSizeId + '.xml';
		
		// Get the related product instances
		$.get(url, function(data, textStatus, xmlHttpRequest) {
		    productUpdateColours(data, textStatus, xmlHttpRequest);
            productUpdateImages(data, textStatus, xmlHttpRequest);
		});
	}
}

function productUpdateColours(data, textStatus, xmlHttpRequest) {
    var productColourIdInputHtml = '';
    var numberOfColours = $('product-instances product-instance', data).length;
    var inputCheckedText = '';
    // Loop through the product instances and recreate the colours to add to the radio buttons
    $('product-instances product-instance', data).each(function(index) {
        inputCheckedText = '';
        if(numberOfColours == 1) inputCheckedText = ' checked="checked"';
        productColourIdInputHtml += '<input type="radio" name="productColourId" value="' + $('product-colour-id', this).text() + '" id="productColourId_' + $('product-colour-id', this).text() + '" class="productColourIdInput"' + inputCheckedText + '/>';
		productColourIdInputHtml += '<label for="productColourId_' + $('product-colour-id', this).text() + '">';
        productColourIdInputHtml += '<img src="admin-resources/image-tools.php?src=' + $('product-colour-image-swatch photos photo file', this).text() + '&amp;w=44&amp;h=25&amp;c=1" alt="' + $('product-colour-title', this).text() + '"/>';
        productColourIdInputHtml += '</label>';
        //console.log($('product-instance-flag-out-of-stock', this).text());
        if($('product-instance-flag-out-of-stock', this).text() == 1) {
        	productColourIdInputHtml += '<img class="outOfStock" src="images/buttons/out-of-stock-btn.jpg" alt="Out of Stock" /><a class="stockistsLink" href="' + stockistsUrl + '">View Stockists</a>';
        };
        productColourIdInputHtml += '<br />';
    });
    
    
    $('#productColourSelectionContainer').html(productColourIdInputHtml);
    
    // Re-bind new elements
    $('.productColourIdInput').bind('click', function(e) {
        productLoadSizeColourInstance($('#productId').val(), $('#productSizeId').val(), $(this).val());
    });
}

function productLoadSizeColourInstance(productId, productSizeId, productColourId) {
	if(productId != undefined && productSizeId != undefined && productColourId != undefined) {
		// Ensure productId, productSizeId and productColourId are clean
		productId = productId.replace(/[^\d]/g, '');
		productSizeId = productSizeId.replace(/[^\d]/g, '');
		productColourId = productColourId.replace(/[^\d]/g, '');
		
		var url = 'rest/product-instances/' + productId + '/' + productSizeId + '/' + productColourId + '.xml';
		
		// Get the related product instances
		$.get(url, productUpdateImages);
	}
}

function productUpdateImages(data, textStatus, xmlHttpRequest) {
    var productImageHtml = '';
    // Loop through the product instances and recreate images
    $('.productGalleryNav').empty();
    var x=1;
    $('product-instances product-instance product-instance-image photos photo', data).each(function(index) {
        fullImageFile = 'uploads/'+$('file', this).text();
        imageFile = $('file', this).text();
        if(x==5 || x==10 || x==15 || x==20) {
	        productImageHtml += '<a style="margin-right:0px;" rel="useZoom: \'zoom1\', smallImage: \'admin-resources/image-tools.php?w=475&amp;h=475&amp;q=95&amp;src=' + imageFile + '\'" title="" class="cloud-zoom-gallery" href="' + fullImageFile + '">';
        } else {
	        productImageHtml += '<a rel="useZoom: \'zoom1\', smallImage: \'admin-resources/image-tools.php?w=475&amp;h=475&amp;q=95&amp;src=' + imageFile + '\'" title="" class="cloud-zoom-gallery" href="' + fullImageFile + '">';
        }
        productImageHtml += '<span class="stdContentImage">';
        productImageHtml += '<img src="admin-resources/image-tools.php?w=91&amp;h=91&amp;q=95&amp;src=' + imageFile + '" alt="" />';
        productImageHtml += '<span class="tl border">&nbsp;</span><span class="tr border">&nbsp;</span><span class="bl border">&nbsp;</span><span class="br border">&nbsp;</span>';
        productImageHtml += '</span>';
        productImageHtml += '</a>';
        x++;
    });
    $('.productGalleryNav').append(productImageHtml);
    $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
    	var c = ca[i];
    	while (c.charAt(0)==' ') c = c.substring(1,c.length);
    	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function updateCartHeader() {
	var totalCartProducts = ""+parseInt(readCookie('totalCartProducts'));
	if(totalCartProducts == '' || totalCartProducts == 'null') {
		totalCartProducts = 0;
		$('.checkoutLink').hide();	
	} 
	
	if(totalCartProducts != 0) {
		$('.checkoutLink').show();	
	}
	
	var totalCartValue = ""+parseFloat(readCookie('totalCartValue'));
	if(totalCartValue == '' || totalCartValue == 'null') {
		totalCartValue = 0.00;	
	}
	$('#headerCartCount').html(totalCartProducts);
	$('#headerCartValue').html(Number(totalCartValue).toFixed(2));
}
