$(function(){
/*
     * Styling
     */
    $('#header').append('<div id="header-cap-left"></div><div id="header-cap-right"></div>');
    $('#footer').append('<div id="footer-cap-left"></div><div id="footer-cap-right"></div>');
    
    /*
     * Pretty forms
     */
    $('form.prettyform input[type*=radio]').css('border','none');
    $('form.prettyform input[type*=checkbox]').css('border','none');
    if($.browser.mozilla) { prettyform(); }
    
    /*
     * LI hover fix for IE6
     */
    $('#navigation ul li').each( function(){
        $(this).mouseover( function(){ $(this).addClass('hover'); } ).mouseout( function(){ $(this).removeClass('hover'); } );
    });
    
    /*
     * Blur on focus
     */
    $('a').focus(function() { this.blur(); });
    $('input[type*=submit]').focus(function() { this.blur(); });
    $('input[type=text], input[type=password]').addClass("input");
    
    if (location.pathname == '/search') {
    	$('#nav li').removeClass('active');
    	$('#nav_node6785').addClass('active');
    }
    
    $('#navigation ul li.active').append("<div id='activeBG' />");
    
    if (getCookie('mj_pid')) {
    	toggleCat(getCookie('mj_pid'));
    }
    
    updateSearchCount();
    
    if ($('.cart-contents').length) {
    	var data = new Object();
    	data.popup = true;
        getCart(data, true);
    }
    
    if ($('.page-numbers').length) {
    	goToPage(1, $('#numpages').html());
    }
    
    var maxHeight = 0;
    $('#nav3 li').each(function() {
    	if ($(this).height() > maxHeight) {
    		maxHeight = $(this).height();
    	}
    });
    $('#nav3 li').height(maxHeight);
    
    $('#step-form').before('<a href="/Bulk-Freight?message=Please list items and sizes wanted in comments box below&KeepThis=true&TB_iframe=true&height=600&width=500" class="thickbox">For bulk freight options (more than 3 pieces) click here</a>');
    
    checkArea();
    
    $('#newsletterForm #postalCountry').change(checkArea);
    
    $('#newsletterForm label.required').append(' *');
    
    $('#fieldset-deliveryaddress legend').after('<p style="font-size: 11px">Delivery address must be a Physical address, not a PO Box.</p>');
});

function checkArea() {
	var firstOption = $('#area option:first');
	if ($('#newsletterForm #postalCountry').val() == 'NZ') {
		if (firstOption.val() == "N/A") {
			firstOption.remove();
		}
		$('#area-label, #area-element').show();
	} else {
		if (firstOption.val() != "N/A") {
			$('#area').prepend('<option value="N/A">N/A</option>');
			$('#area').val("N/A");
		}
		$('#area-label, #area-element').hide();
	}
}

function getProduct(id) {
	currentImage = false;
	
    $('#product-image').html('');
    $('#product-information').html('');
    $('#view-more').html('');
    
	$('#product-image, #product-information').css('background', 'url("/asset/images/ajax-loader.gif") no-repeat scroll center center transparent');

	$.ajax({
	      url: "/product/get-product",
	      type: "POST",
	      data: ({id : id, xml : 0}),
	      success: function(msg){
			var msg = msg.split("!!!---Product Info Separator---!!!");
			var productImages = msg[0];
			var productInfo = msg[1];
			//var productTags = msg[2];
			
	         $('#product-image').html(productImages);
	         $('#product-information').html(productInfo);
	         //$('#view-more').html(productTags);
	         
			 $('#product-image, #product-information, #view-more').css('background', 'none');
	         
	         $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
	         
	         $('#wrap').css('z-index', '99');
	         
	         updateAttributes();
	         updateImages();
	         $('select').selectmenu({
	             style: 'dropdown',
	             format: optionFormatting
	         });
	      }
	   }
	);
}

function toggleCart() {
	$('#cart-popup').toggle();
}

function addToCartSuccess(msg) {
    if (msg == "success") {
    	//setCookie('mj_show_cart', '1', 1);
    	//document.location = document.location;
    	data = new Object();
    	data.popup = true;
        getCart(data);
    } else {
        alert("An error occurred while trying to purchase item");
    }
}

function getCart(data, doNotShowCart) {
    if (data == null) {
        var data = new Object();
    }
    $.ajax({
        url: "/order/get-cart",
        type: "POST",
        data: data,
        success: function(msg) {
	        $.ajax({
	            url: "/order/get-cart/total",
	            type: "POST",
	            data: data,
	            success: function(msg) {
	                $('#cartbox .total').html(msg);
	            }
	        });
	        $.ajax({
	            url: "/order/get-cart/itemcount",
	            type: "POST",
	            data: data,
	            success: function(msg) {
	                $('#cartbox .number').html(msg);
	            }
	        });
	        if (data.popup) {
	        	$('#cart-popup .cart-contents').html(msg);
	            if (doNotShowCart == null) {
	            	$('#cart-popup').show();
	            }
	        } else {
	        	$('.content .cart-contents').remove();
	        	$('#order-steps').after("<div class='cart-contents'>" + msg + "</div>");
	        	$('.content .cart-contents .footer').remove();
	        }
        }
    });
}
    

function removeFromCart(key) {
    $.ajax({
        url: "/order/remove-from-cart",
        type: "POST",
        data: ({key : key}),
        success: function(msg) {
	    	//setCookie('mj_show_cart', '1', 1);
	    	//document.location = document.location;
        	data = new Object();
        	data.popup = true; 
	        getCart(data);
        },
        error: function(request, textStatus, errorThrown) {
            alert("An error occurred while trying to remove item");
        }
    });
    
}

function unblockUI() {
    clearTimeout(t);
    $.unblockUI();
}

function updateCart() {
    $.ajax({
        url: "/order/get-cart/total",
        type: "POST",
        success: function(msg) {
            $('#cartbox .total').html('$' + msg);
        },
        error: function(request, textStatus, errorThrown) {
            alert("An error occurred while trying to purchase item");
        }
    });
    $.ajax({
        url: "/order/get-cart/itemcount",
        type: "POST",
        success: function(msg) {
            $('#cartbox .number').html(msg);
        },
        error: function(request, textStatus, errorThrown) {
            alert("An error occurred while trying to purchase item");
        }
    });
}

var relatedProductsHeight = 435;

/* from w3schools.com */
function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

/* from w3schools.com */
function getCookie(c_name) {
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
}

var currentPage = 1;

function goToPage(num, totalPages) {
	if (num >= 1 && num <= totalPages) {
		$('#next').addClass('disabled');
		$('#previous').addClass('disabled');
		
		// Show page of items
		$('#related-products').fadeOut('fast', function() {
			var bottom = relatedProductsHeight * (num - 1);
			$('#related-products .related-product').css('bottom', bottom);
			$('#related-products').fadeIn('fast');
			
			currentPage = num;
			
			if (num != 1) {
				$('#previous').removeClass('disabled');
			}
			if (num != totalPages) {
				$('#next').removeClass('disabled');
			}
			
			updateSearchCount();
		});
		
		var centerPage = 4;
		if (num > 4) centerPage = num;
		if (num > (totalPages - 3)) centerPage = totalPages - 3;
		centerPage = Math.max(4, centerPage);
		
		//$('#previous.disabled, #next.disabled').removeClass('disabled');
		$('.page-numbers.current').removeClass('current');
		
		var displace = num - centerPage;
		$('.page-numbers').eq(3 + displace).addClass('current');
		
		// Hide page numbers so only 7 show
		$('.page-numbers').eq(0).html(centerPage - 3).unbind('click').click(function() { goToPage(centerPage - 3, totalPages); });
		$('.page-numbers').eq(1).html(centerPage - 2).unbind('click').click(function() { goToPage(centerPage - 2, totalPages); });
		$('.page-numbers').eq(2).html(centerPage - 1).unbind('click').click(function() { goToPage(centerPage - 1, totalPages); });
		$('.page-numbers').eq(3).html(centerPage + 0).unbind('click').click(function() { goToPage(centerPage + 0, totalPages); });
		$('.page-numbers').eq(4).html(centerPage + 1).unbind('click').click(function() { goToPage(centerPage + 1, totalPages); });
		$('.page-numbers').eq(5).html(centerPage + 2).unbind('click').click(function() { goToPage(centerPage + 2, totalPages); });
		$('.page-numbers').eq(6).html(centerPage + 3).unbind('click').click(function() { goToPage(centerPage + 3, totalPages); });
		
		$('.page-numbers.current').unbind('click');
	}
}

function incrementPage(increment, totalPages) {
	goToPage(currentPage + increment, totalPages);
}

function toggleCat(id) {
	$('.cat').hide();
	$('#' + id).toggle();
}

function getCurrentPage() {
	var bottom = $('#related-products .related-product').css('bottom');
	bottom = parseInt(bottom.substring(0, bottom.length - 2));
	return (bottom / relatedProductsHeight + 1);
}

function updateSearchCount() {
	var start = (currentPage - 1) * 6 + 1;
	$('#search-count .start').html(start);
	
	var total = $('#numresults').html();
	$('#search-count .total').html(total);
	
	var end = Math.min($('.related-product').length, start + 5);
	$('#search-count .end').html(end);
}

/*
 * Pretty forms
 */
function prettyform(){
  /*
   * Hide forms
   */
  $( 'form.prettyform' ).hide().end();
  /*
   * Label & list formatting
   */
  $( 'form.prettyform' ).find( 'label' ).not( '.noprettyform' ).each( function( i ){
    var labelContent = this.innerHTML;
    var labelWidth = document.defaultView.getComputedStyle( this, '' ).getPropertyValue( 'width' );
    var labelSpan = document.createElement( 'span' );
        labelSpan.style.display = 'block';
        labelSpan.style.width = labelWidth;
        labelSpan.innerHTML = labelContent;
    this.style.display = '-moz-inline-box';
    this.innerHTML = '';
    this.appendChild( labelSpan );
  } ).end();
  
  /*
   * Show forms
   */
  $( 'form.prettyform' ).show().end();
}

function enquireClick(element) {
	var selectorVal = $(element).parent().parent().find('#selector').val();
	var subject = $(element).parent().parent().find('#selector option[value="' + selectorVal + '"]').html();
	var parts = subject.split(' | ');
	subject = parts[0];
	
	$(element).attr('href', $(element).attr('href') + subject);
}
