$.snippet = function(template, data) { 
	var i, value;

	for (i in data) {
		value = data[i];
		if (!value) value = '';
		template = template.split('{' + i + '}').join(value);
		template = template.split('%7B' + i + '%7D').join(value);
	}

	return template;
}

jQuery.fn.center = function () {
	var popup = this;
	if ($.browser.msie){
		popup.css('left','0px');
		popup.css('top','0px');
	}
	
	popup.find('.content, .popup-content').css("margin-left", "0");
	popup.find('.content, .popup-content').css("margin-top", "0");
	popup.css({ position: "absolute", visibility: "hidden", display: "block" });
	popup.find('.content, .popup-content').css("left", ( $(window).width() - popup.find('.content, .popup-content').width() ) / 2 + "px");
	popup.find('.content, .popup-content').css("top", ( $(window).height() - popup.find('.content, .popup-content').height() ) / 2 + "px");
	
	popup.css({ position: "", visibility: "", display: "" });
	
    return this;
}

function checkMinimumTradeSubtotal( minimum ) {	
	var string = $('.subtotal-container').find('.subtotal-update span').html();
	var parts = string.match(/[\d\.]+/g);
	
	var subtotal = parseFloat(parts.join(""));
	
	if( subtotal < minimum ) {
		$('.popup-meetminimum-contact').fadeIn('slow', function() {
			$(this).delay(3000).fadeOut('slow');
		});
		return false;
	}
	
	return true;
}

Object.sizeof = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function classAttributes( classString, className ) {
	var data = [];
	var regex = new RegExp(className+"\\[(.*?)\\]");
	var matches = classString.match(regex);
	
	if ( matches ) {
		//matches[1] refers to options inside [] "required, email, ..."
		var spec = matches[1].split(/,\s*/);
		
		if ( spec.length > 0 ) {
			data = spec;
		}
	}
	
	return data;
}

$.widget('ui.ajaxsearch', {
	options: {
		container: '.search-container-results'
	},
	_create: function() {
		var obj = this;
		var container = this.options.container;
		this.element.find('form .search-bar').helperValue();
		this.element.find('form .search-bar').attr('autocomplete', 'off');
		
		this.element.find('form .search-bar').attr('autocomplete', 'off');
		
		$(container).find('ul li').live('click', function() {
			var url = $(this).find('.s-name a').attr('href');
			window.location = url;
		});
		
		$(container).find('ul li').live('mouseover mouseout', function(event) {
			if (event.type == 'mouseover') {
				$(this).addClass('hover');
			} else {
				$(this).removeClass('hover');
			}
		});
		
		this.element.find('form').submit(function() {
			if($(this).find('.search-bar').val() != $(this).find('.search-bar').attr('title')){
				$(this).find('.search-preloader').show();
				var formdata = $(this).serialize();
				obj.searching(formdata, container);
			}
			return false;
		});
		
		this.element.find('form .search-bar').keyup(function() {
			if($(this).val().length > 0 && $(this).val() != 'SEARCH'){
				$(this).parents('form').find('.search-preloader').show();
				var formdata = $(this).parents('form').serialize();
				obj.searching(formdata, container, $(this).val().length);
			}else{
				obj.closesearch(container, '.mainoverlay');
			}
		});
		
		$('#overlay, .mainoverlay').click(function() {
			obj.closesearch(container, this);
		});
		
		$('body').click(function(event){
			if($(event.target).closest('.search').length == 0){
				obj.closesearch(container, '.mainoverlay');
			}
		});
	},
	
	searching: function(formdata, container, itemlength) {
		$.ajax({
			type: 'POST',
			url: '/search/search-ajax?ajax',
			data: formdata,
			success: function(data) {
				var jsonArray = $.parseJSON(data);
				var json = jsonArray['search'];
				
				if(json['confirm'] == 'success'){
					$(container).fadeIn(300);
					$('.search form .search-preloader').hide();
					$('#overlay').show();
					$('.mainoverlay').show();
					var html = '';
					for(var i in json['results']){
						html += '<li>';
							if(json['results'][i]['order_nr'] == 1){
								html += '<div class="s-image"><a href="'+json['results'][i]['link']+'/'+json['results'][i]['pseo']+'"><img alt="" src="/misc/products/'+json['images']+'/'+json['results'][i]['url']+'" /></a></div>';
							}else{
								html += '<div class="s-image"><a href="'+json['results'][i]['link']+'/'+json['results'][i]['pseo']+'/'+json['results'][i]['seo']+'"><img alt="" src="/misc/products/'+json['images']+'/'+json['results'][i]['url']+'" /></a></div>';
							}
							html += '<div class="s-container" rel="'+json['results'][i]['order_nr']+'">';
								if(json['results'][i]['order_nr'] == 1){
									html += '<div class="s-name"><a href="'+json['results'][i]['link']+'/'+json['results'][i]['pseo']+'">'+json['results'][i]['name']+'</a></div>';
								}else{
									html += '<div class="s-name"><a href="'+json['results'][i]['link']+'/'+json['results'][i]['pseo']+'/'+json['results'][i]['seo']+'">'+json['results'][i]['name']+'</a></div>';
								}
								if(json['results'][i]['sale_price'] > 0){
									if(json['results'][i]['percent'] != '0'){
										html += '<div class="s-sale-item">'+json['results'][i]['sale_price_formated']+' (SAVE '+json['results'][i]['percent']+'%)</div>';
									}else{
										html += '<div class="s-price">'+json['results'][i]['sale_price_formated']+'</div>';
									}
									
									html += '<div class="s-was">(was '+json['results'][i]['price_formated']+')</div>';
								}else{
									html += '<div class="s-price">'+json['results'][i]['price_formated']+'</div>';
								}
							html += '</div>';
						html += '</li>';
					}
					
					$(container).find('ul').html(html);
					
				}
				
			}
			
		});
		
		if(itemlength == 0){
			obj.closesearch(container, '.mainoverlay');
		}
	},
	
	closesearch: function(container, overlay) {
		$(container).fadeOut(200, function(){
			$(this).find('ul').html('');
		});
		$(overlay).hide();
	}
	
});
	
$.widget('ui.productScroller', {

	_create: function() {
		var obj = this;
		var parent = this.element;
		var items = this.element.find('li');
		var itemWidth = items.width();
		this.element.find('ul').css('width', (items.length*itemWidth));
		parent.find('.item-content').attr('rel', '0');
		
		parent.find('.prev-arrow').click(function(){
			obj.scrollLeft(parent.find('.item-content'), itemWidth);
		});
		parent.find('.next-arrow').click(function(){
			obj.scrollRight(parent.find('.item-content'), itemWidth);
		});
	},
	
	scrollLeft: function(el, width){
		var parent = this.element;
		var mleft = parseInt(el.css('margin-left'));
		var itMoved = parseInt(el.attr('rel'));
		var citems = parseInt(el.parent().width()/width);
		itMoved -= citems;
		
		if(mleft < 0 && !el.hasClass('scrolling')){
			parent.find('.next-arrow').removeClass('hidden');
			el.addClass('scrolling');
			mleft += el.parent().width();
			el.animate({'margin-left': mleft+'px'},800,function(){
				el.removeClass('scrolling');
			});
			
			el.attr('rel', parseInt(itMoved));
			if(mleft == 0){
				parent.find('.prev-arrow').addClass('hidden');
			}
			
		}
	},
	
	scrollRight: function(el, width){
		var parent = this.element;
		var count = el.find('.item').length;
		var mleft = parseInt(el.css('margin-left'));
		//items  moved
		var itMoved = parseInt(el.attr('rel'));
		var citems = parseInt(el.parent().width()/width);
		//increase the "items moved" count
		itMoved += citems;
		var max = (count-citems)*width*-1;
		
		if(mleft > max && !el.hasClass('scrolling') && itMoved < count){
			parent.find('.prev-arrow').removeClass('hidden');
			el.addClass('scrolling');
			mleft -= el.parent().width();
			el.animate({'margin-left': mleft+'px'},1000,function(){
				el.removeClass('scrolling');
			});
			el.attr('rel', parseInt(itMoved));
			if((itMoved*2) > count || (itMoved*2) == count){
				parent.find('.next-arrow').addClass('hidden');
			}
			
		}
		
	}
	
});

$.widget('ui.basketPageAction', {
	options: {
		itemcont: '.product-item',
		url: '/basket/manage-basket?ajax',
		price: '.row-prod .price',
		totalprice: '.row-prod .total-price',
		productamount: '.row-prod .amount',
		quantity: '.row-prod .quantity',
		itemadd: '.row-prod .add',
		itemsubtract: '.row-prod .subtract',
		basket_background: 'FFFFFF'
	},
	
	_init: function(){
		this.basket_background = this.options.basket_background;
	},
	
	_create: function() {
		var obj = this;
		this.basket_background = this.options.basket_background;
		var itemcont = this.options.itemcont;
		var url = this.options.url;
		var price = this.options.price;
		var totalprice = this.options.totalprice;
		var quantity = this.options.quantity;
		var productamount = this.options.productamount;
		var itemadd = this.options.itemadd;
		var itemsubtract = this.options.itemsubtract;
		var increaseid;
		var decreaseid;
		var $subelement = $('.subtotal-update');
		var $totalelement = $('.total-update');
		var $basketitem = $('.baskettotal-update');
		
		this.element.find(itemadd).live('click', function() {
			var $button = $(this);
			var quntityinc = 0;
			increaseid = $(this).attr('rel').split(',');
			quntityinc = parseInt($(this).parents(itemcont).find(quantity).html());
			$('.basket-container .amount-overlay').show();
			
			
			$.ajax({
				type: 'POST',
				url: url,
				data: $.param({ calltype: 'checkquantity', colorid: increaseid, quantity: (quntityinc+1) }),
				success: function(data) {
					var json = $.parseJSON(data);
					var increase = quntityinc+1;
					
					if(json['conf'] == 'true' && increase != 0){
						$button.parents(itemcont).find(quantity).html(increase);
						$button.parents(itemcont).find(totalprice).html(''+json['item_total_formated']);
						obj.update(json, itemcont, totalprice);
						obj.animatebackcont($subelement, $totalelement, $basketitem);
						$button.parents(itemcont).find(itemsubtract).removeClass('disabled');
					}else{
						if(json['stock'] < quntityinc && json['stock'] != 0){
							$button.parents(itemcont).find(quantity).html(json['stock']);
							$button.parents(itemcont).find(totalprice).html(''+json['item_total_formated']);
							obj.update(json, itemcont, totalprice);
							obj.animatebackcont($subelement, $totalelement, $basketitem);
						}
						tooltip($button);
					}
					if(json['stock'] == quntityinc){
						$button.addClass('disabled');
					}
					$('.basket-container .amount-overlay').hide();
				}
				
			});
			
		});
		
		this.element.find(itemsubtract).live('click', function() {
			var buttonadd = $(this);
			var quntitydec = 0;
			decreaseid = $(this).attr('rel').split(',');
			quntitydec = parseInt($(this).parents(itemcont).find(quantity).html());
			$('.basket-container .amount-overlay').show();
			
			$.ajax({
				type: 'POST',
				url: url,
				data: $.param({ calltype: 'checkquantity', colorid: decreaseid, quantity: (quntitydec-1) }),
				success: function(data) {
					var json = $.parseJSON(data);
					var decrease = quntitydec-1;
					
					if(decrease == 1){
						$(buttonadd).addClass('disabled');
					}
					
					if(json['conf'] == 'true' && decrease != 0){
						$(buttonadd).parents(itemcont).find(quantity).html(decrease);
						$(buttonadd).parents(itemcont).find(totalprice).html(''+json['item_total_formated']);
						obj.update(json, itemcont, totalprice);
						obj.animatebackcont($subelement, $totalelement, $basketitem);
						$(buttonadd).parents(itemcont).find(itemadd).removeClass('disabled');
					}else{
						if(json['stock'] < quntitydec && json['stock'] != 0){
							$(buttonadd).parents(itemcont).find(quantity).html(json['stock']);
							$(buttonadd).parents(itemcont).find(totalprice).html(''+json['item_total_formated']);
							obj.update(json, itemcont, totalprice);
							obj.animatebackcont($subelement, $totalelement, $basketitem);
						}
					}
					$('.basket-container .amount-overlay').hide();
				}
				
			});
			
		});
		
		this.element.find('.products .remove-item').live('click', function(event) {
			var $currentbutton = $(this);
			var $product = $currentbutton.closest('.product-item');
			var delid = $(this).attr('rel').split(',');
	 
			event.preventDefault();
			$('.removing-product').css('top', $product.position().top + 'px').fadeIn(200,function() {
				$.ajax({
					type: 'POST',
					url: '/basket/remove-product?ajax',
					data: $.param({ calltype: 'removeproduct', colourid: delid }),
					success: function(data) {
						var json = $.parseJSON(data);
						if(json['itemcount'] == 0){
							var htmlelement = "<div style=\"display:none;\" class=\"no-items\"><div class=\"no-items-text\">There were no items in your shopping basket</div><div class=\"no-items-continue\"><a href=\"/\" title=\"Continue Shopping\">Continue Shopping</a></div></div>";
							$('.basket-container').fadeOut(400, function(){
								$('.basket-container').after(htmlelement);
								$('.basket-container').remove();
								$('.no-items').fadeIn();
							});
							
						}
						obj.update(json);
						
						obj.animatebackcont($subelement, $totalelement, $basketitem);
							
						$product.stop(true).slideUp(400);
						$('.removing-product').slideUp();
						
						
					}
				});
			});
		});
		
	},
	
	animatebackcont: function($subelement, $totalelement, $basketitem){
		var obj = this;
		if(!$subelement.hasClass('background-update-false')){
			$subelement.css('backgroundColor', '').stop().animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
				$subelement.css('backgroundColor', '#bde8ff').animate({ 'backgroundColor': '#ffffff' }, 1000);
			});
		}
		if(!$totalelement.hasClass('background-update-false')){
			$totalelement.css('backgroundColor', '').stop(true).animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
				$totalelement.animate({ 'backgroundColor': '#' + 'ffffff' }, 1000);
			});
		}
		if(!$basketitem.hasClass('background-update-false')){
			$basketitem.css('backgroundColor', '').stop(true).animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
				$basketitem.animate({ 'backgroundColor': '#' + obj.basket_background }, 1000);
			});
		}
	},
	
	update: function(json, itemcont, totalprice){
		if(parseInt(json['discount']) > 0 && $('#delivery-total .discount-row').is(':hidden')){
			$('#delivery-total .discount-row').slideDown();
		}else if(parseInt(json['discount']) == 0){
			$('#delivery-total .discount-row').hide();
		}
		
		$('.shopping-bag a span').html(json['itemcount']);
		$('.contains-items').html(json['itemcount']);
		$('.mini-cart .small-basket-total').html(json['summary']['total_formated']);
		$('#delivery-total .total-row span').html(json['summary']['total_formated']);
		$('.subtotal-container .stotal span').html(json['summary']['subtotal_formated']);
		$('#delivery-total').find('.delivery-price a#'+json['did']).html(''+json['summary']['delivery_amount_formated']);
		$('.deliv-summary .del-item-price strong').html(''+json['summary']['delivery_amount_formated']);
		$('#delivery-total .discount-row').find('.right-cell span').html(json['summary']['discount_amount_formated']);
		$('.shopping-bag-cont .basket-total-amount').html(json['summary']['total_no_delivery_formated']);
		$('.deliv-summary .del-item-desc span').html(json['summary']['delivery']);
		
		if(json['discount'].length > 0){
			$('.deliv-summary .del-item-desc span').html(json['promotion']['delDesc']);
		}else{
			$('.deliv-summary .del-item-desc span').html(json['summary']['delivery']);
		}
	}
	
});

$.widget('ui.deliveryupdate', {
	options: {
		delselect: '.delivery-type',
		delinput: 'input',
		url: '/basket?ajax&summary',
		deliveryprice: '.deliv-summary .del-item-price strong',
		deliverydesc: '.deliv-summary .del-item-desc span',
		basket_background: 'FFFFFF'
	},
	
	_init: function(){
		this.basket_background = this.options.basket_background;
	},
	
	_create: function() {
		var obj = this;
		this.basket_background = this.options.basket_background;
		var delselect = this.options.delselect;
		var delinput = this.options.delinput;
		var deliveryprice = this.options.deliveryprice;
		var deliverydesc = this.options.deliverydesc;
		var url = this.options.url;
		var $elements = $('.total-update');
		var $basketitem = $('.baskettotal-update');
		
		this.element.find(delselect).click(function() {
			
			if(!$(this).hasClass('active')){
				obj.element.find('.delivery-type').removeClass('active');
				$(this).addClass('active');
				$(this).find(delinput).attr('checked', true);
				var delid = $(this).find(delinput).val();
				
				$.ajax({
					type: 'POST',
					url: url,
					data: $.param({ calltype: 'delivery', delid: delid }),
					success: function(data) {
						var json = $.parseJSON(data);
						
						if(json['summary']['discount_delivery'].length > 0){
							if(json['summary']['discount_delivery'].length > 26){
								var str = json['summary']['discount_delivery'];
								obj.element.find(deliverydesc).html(str.substring(0,26)+'...');
							}else{
								obj.element.find(deliverydesc).html(json['summary']['discount_delivery']);
							}
						}else{
							if(json['summary']['delivery'].length > 26){
								var str = json['summary']['delivery'];
								obj.element.find(deliverydesc).html(str.substring(0,26)+'...');
							}else{
								obj.element.find(deliverydesc).html(json['summary']['delivery']);
							}
						}
						obj.element.find(deliveryprice).html(''+json['summary']['delivery_amount_formated']);
						
						obj.update(json);
						obj.animateback($elements, $basketitem);
					}
					
				});
			}
		});
	},
	
	animateback: function($elements, $basketitem){
		var obj = this;
		$elements.css('backgroundColor', '').stop(true).animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
			$(this).animate({ 'backgroundColor': '#' + 'fff' }, 1000);
		});
		$basketitem.css('backgroundColor', '').stop(true).animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
			$(this).animate({ 'backgroundColor': '#' + obj.basket_background }, 1000);
		});
	},
	
	update: function(json){
		$('.mini-cart .small-basket-total').html(json['summary']['total_formated']);
		$('#delivery-total .total-row span').html(json['summary']['total_formated']);
		$('#delivery-total').find('.delivery-price a#'+json['summary']['delivery_id']).html(''+json['summary']['delivery_amount_formated']);
	}
	
});

$.widget('ui.archiveaddress', {
	options: {
		addersscont: '.address-block li',
		archive: '.archive-address',
		removing: '.removing'
	},
	_create: function() {
		var obj = this;
		var addersscont = this.options.addersscont;
		var archive = this.options.archive;
		var removing = this.options.removing;
		var url = this.options.url;
		
		this.element.find(archive).click(function() {
			var addressid = $(this).attr('rel');
			var button = $(this)
			$(button).parents(addersscont).find(removing).fadeIn();
			
			$.ajax({
				type: 'POST',
				url: url,
				data: $.param({ archive: addressid }),
				success: function(data) {
					var json = $.parseJSON(data);
					
					if(json['conf'] == 'success'){
						$(button).parents(addersscont).find(removing).delay(400).animate({opacity: 1}, 400, function(){
							$(button).parents(addersscont).remove();
						});
					}else{
						$(button).parents(addersscont).find(removing).hide();
					}
				}
				
			});
		});
	}
	
});


$.widget('ui.sliderwidget', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		var container = this.options.container;
		var itemcount = this.options.itemcount;
		var handler = this.options.handler;
		var handlercont = $(handler).parent();
		var item = this.options.item;
		var itemWidth = $(container).find(item).width();
		var items = $(container).find(item).length;
		var handle_width = $(handlercont).width();
		
		if(items > itemcount){
			var handle_width = Math.round( handle_width / (100 / (100 - (((items - itemcount) / items)*100))) );
			$(handler).css('width',handle_width+'px');
		}else{
			$(handler).css('width',handle_width+'px');
		}
		
		var scrollarea = $(handlercont).width()-$(handler).width();
		
		items = (items*itemWidth);
		
		$(container).css('width', items);
		
		var multiplier = (items-$(obj.element).width())/scrollarea;
		
		parent.find('.scroll-container').click(function(event){
			var original_pos = $(handler).offset();
			var target_pos = event.pageX;
			var left_side = original_pos.left;
			var right_side = original_pos.left + parseInt($(handler).css('width'));
			
			if(target_pos < left_side){
				var handleleft = parseInt( $(handler).css('left') ) - Math.round((left_side - target_pos)) + 'px';
				
				$(handler).stop(true,true).animate({ 'left': handleleft }, {
					duration: 600,
					step: function(){
						var pos = $(handler).position();
						var positionleft = (-1*multiplier)*(pos.left);
						$(container).css('margin-left', positionleft);
					}
				});
				
			}else if(target_pos > right_side){
				var handleleft = parseInt( $(handler).css('left') ) - Math.round((right_side - target_pos)) + 'px';
				
				$(handler).stop(true,true).animate({ 'left': handleleft }, {
					duration: 600,
					step: function(){
						var pos = $(handler).position();
						var positionleft = (-1*multiplier)*(pos.left);
						$(container).css('margin-left', positionleft);
					}
				});
			}
			
		});
		
		parent.find('.prev').click(function(){
			var handleleft = Math.max(0, parseInt( $(handler).css('left') ) - 30) + 'px';
			if(!$(handler).hasClass('animated')){
				$(handler).addClass('animated');
				$(handler).stop(true,true).animate({ 'left': handleleft }, {
					duration: 600,
					step: function(){
						var pos = $(handler).position();
						var positionleft = (-1*multiplier)*(pos.left);
						$(container).css('margin-left', positionleft);
					},
					complete: function(){
						$(this).removeClass('animated');
					}
				});
			}
		});
		
		parent.find('.next').click(function(){
			var handleleft = Math.min(scrollarea, parseInt( $(handler).css('left') ) + 30) + 'px';
			
			if(!$(handler).hasClass('animated')){
				$(handler).addClass('animated').stop(true,true).animate({ 'left': handleleft }, {
					duration: 600,
					step: function(){
						var pos = $(handler).position();
						var positionleft = (-1*multiplier)*(pos.left);
						$(container).css('margin-left', positionleft);
					},
					complete: function(){
						$(this).removeClass('animated');
					}
				});
			}
		});
		
		$(document).keydown(function(event){
			if (event.keyCode == '37') {
				parent.find('.prev').click();
			}
			if (event.keyCode == '39') {
				parent.find('.next').click();
			}
		});
		
		var result = (items-$(obj.element).width())/scrollarea;
		$(handler).draggable({
			containment: handlercont,
			scroll: false,
			drag: function(event, ui) {
				var pos = $(handler).position();
				
				var positionleft = (-1*result)*(pos.left);
				$(container).css('margin-left', positionleft);
			}
		});
		
	}
	
});

$.widget('ui.productAction', {
	options: {
		container: '.product',
		addtobasket: '.add-to-basket',
		instantcheckout: '.instant-checkout',
		itemquntity: '.item-count span',
		countcont: '.item-count',
		itemadd: '.add',
		subtract: '.subtract',
		quntity: 'span',
		amount: '.item-price',
		url: '/products-module/manage?ajax&quantity&conf'
	},
	_create: function() {
		var obj = this;
		var parent = this.element;
		var instantcheckout = this.options.instantcheckout;
		var itemquntity = this.options.itemquntity;
		var selectCont = $('.size-selection');
		var colourCont = $('.size-selection');
		
		this.add_tobasket_button = this.options.addtobasket;
		this.countcont = this.options.countcont;
		this.container = this.options.container;
		this.itemadd = this.options.itemadd;
		this.url = this.options.url;
		this.subtract = this.options.subtract;
		this.quntity = this.options.quntity;
		this.amount = this.options.amount;
		this.basketUrl = this.options.basketUrl;
		this.redirectUrl = this.options.redirectUrl;
		
		
		$('.size-selection').find('.stock-selection a').live('click', function(){
			if(!$(this).parent().hasClass('selected') && !$(this).parent().hasClass('out-of-stock')){
				$('.size-selection').find('.selected').removeClass('selected');
				$(this).parent().addClass('selected');
				parent.find('.add-to-basket').attr('rel', $(this).attr('rel'));
				parent.find('.item-count .subtract').attr('rel', $(this).attr('rel'));
				parent.find('.item-count .add').attr('rel', $(this).attr('rel'));
				obj.validate('false');
				$(obj.countcont).find(obj.quntity).html('1');
				$(obj.countcont).find(obj.subtract).addClass('disabled');
				$(obj.countcont).find(obj.itemadd).removeClass('disabled');
				
				var sizeName = $('.size-selection').find('.selected a').html();
				var cName = parent.find('.basket-actions .item').attr('title');
				if(sizeName != null){
					parent.find('.basket-actions .item').html(cName+', '+sizeName);
				}else{
					parent.find('.basket-actions .item').html(cName);
				}
			}else if($(this).parent().hasClass('out-of-stock')){
				stockTooltip($(this));
			}
		});
		
		$('.size-selection').find('select').change(function(){
			if(!$(this).closest('.size-selection').is('hidden')){
				
				parent.find('.add-to-basket').attr('rel', $(this).val());
				parent.find('.item-count .subtract').attr('rel', $(this).val());
				parent.find('.item-count .add').attr('rel', $(this).val());
				obj.validate('false');
				$(obj.countcont).find(obj.quntity).html('1');
				$(obj.countcont).find(obj.subtract).addClass('disabled');
				$(obj.countcont).find(obj.itemadd).removeClass('disabled');
				
				var sizeName = $('.size-selection').find('.selected a').html();
				var cName = parent.find('.basket-actions .item').attr('title');
				if(sizeName != null){
					parent.find('.basket-actions .item').html(cName+', '+sizeName);
				}else{
					parent.find('.basket-actions .item').html(cName);
				}
			}else if($(this).parent().hasClass('out-of-stock')){
				stockTooltip($(this));
			}
		});
		
		parent.find(obj.add_tobasket_button).live('click', function() {
			var $button = $(this);
			var selection = selectCont.find('.selected');
			if(selection.length == 0 && $('.size-selection').find('select').length > 0){
				selection = $('.size-selection').find('select').val();
			}
			var colours = colourCont.find('.stock-selection');
			if(selection.length > 0){
				colours = $('.size-selection').find('option:selected').val();
			}
			obj.validateCustomPricing('true', $(this));
			
			if(!$(this).hasClass('disabled') && selection.length > 0 && colours.length > 1){
				obj.validate('false');
				obj.addToBasket($button, itemquntity);
			}else if(!$(this).hasClass('disabled') && (selectCont.length == 0 || selectCont.hasClass('hidden')) && (colourCont.length == 0 || colourCont.hasClass('hidden')) && selection.length == 0 && colours.length == 0 && parseInt($(itemquntity).html()) > 0){
				//if there is no colours and sizes
				obj.validate('false');
				obj.addToBasket($button, itemquntity);
			}else{
				if(!$(this).hasClass('disabled') && colours.length == 1){
					obj.validate('false');
					obj.addToBasket($button, itemquntity);
				}else{
					obj.validate('true');
				}
			}
			
		});
		
		parent.find(obj.itemadd).live('click', function() {
			$button = $(this);
			var selection = $('.size-selection').find('.selected');
			if(selection.length == 0 && $('.size-selection').find('select').length > 0){
				selection = $('.size-selection').find('select').val();
			}
			
			var colours = $('.size-selection').find('.stock-selection');
			if(selection.length > 0){
				colours = $('.size-selection').find('option:selected').val();
			}
			obj.validateCustomPricing('true', $(this));
			
			if(!$(this).hasClass('action-disabled') && selection.length > 0 && colours.length > 1){
				obj.validate('false');
				obj.addQuantity($button);
			}else if(!$(this).hasClass('action-disabled') && (selectCont.length == 0 || selectCont.hasClass('hidden')) && (colourCont.length == 0 || colourCont.hasClass('hidden')) && selection.length == 0 && colours.length == 0 && parseInt($(itemquntity).html()) > 0){
				//if there is no colours and sizes
				obj.validate('false');
				obj.addQuantity($button);
			}else{
				if(!$(this).hasClass('action-disabled') && colours.length == 1){
					obj.validate('false');
					obj.addQuantity($button);
				}else{
					obj.validate('true');
				}
			}
		});
		
		parent.find(obj.subtract).live('click', function() {
			$button = $(this);
			var selection = $('.size-selection').find('.selected');
			if(selection.length == 0 && $('.size-selection').find('select').length > 0){
				selection = $('.size-selection').find('select').val();
			}
			var colours = $('.size-selection').find('.stock-selection');
			if(selection.length > 0){
				colours = $('.size-selection').find('option:selected').val();
			}
			obj.validateCustomPricing('true', $(this));
			
			if(!$(this).hasClass('action-disabled') && selection.length > 0 && colours.length > 1){
				obj.validate('false');
				obj.subtractQuantity($button);
			}else if(!$(this).hasClass('action-disabled') && !$(this).hasClass('disabled') && (selectCont.length == 0 || selectCont.hasClass('hidden')) && (colourCont.length == 0 || colourCont.hasClass('hidden')) && selection.length == 0 && colours.length == 0 && parseInt($(itemquntity).html()) > 0){
				//if there is no colours and sizes
				obj.validate('false');
				obj.subtractQuantity($button);
			}else{
				if(!$(this).hasClass('action-disabled') && colours.length == 1){
					obj.validate('false');
					obj.subtractQuantity($button);
				}else if(!$(this).hasClass('action-disabled') && !$(this).hasClass('disabled')){
					obj.validate('true');
				}
			}
		});
		
		parent.find('.buy-product-as-case a').live('click', function(){
			var data = classAttributes( $(this).attr('class'), 'quantity' );
			if(data[0] != null){
				parent.find('.basket-actions .item-count span').html(data[0]);
				parent.find('.basket-actions .add-to-basket').click();
			}
			return false;
		});
	},
	
	_init: function(){
		this.add_tobasket_button = this.options.addtobasket;
		this.countcont = this.options.countcont;
		this.container = this.options.container;
		this.itemadd = this.options.itemadd;
		this.url = this.options.url;
		this.subtract = this.options.subtract;
		this.quntity = this.options.quntity;
		this.amount = this.options.amount;
		this.basketUrl = this.options.basketUrl;
		this.redirectUrl = this.options.redirectUrl;
	},
	
	addQuantity: function($button) {
		var obj = this;
			
		if(!$button.hasClass('processing') && !$button.hasClass('disabled')){
			$button.addClass('processing');
			var elementid = $button.attr('rel').split(',');
			var quntityvar = parseInt($button.closest(obj.countcont).find(obj.quntity).html());
			
			var custom_pricing = obj.customPricing();
			
			$.ajax({
				type: 'POST',
				url: obj.url,
				data: $.param({ calltype: 'checkquantity', colorid: elementid, quantity: (quntityvar+1), custom_pricing: custom_pricing }),
				success: function(data) {
					var json = $.parseJSON(data);
					var increase = quntityvar+1;
					
					if(json['quantity']['conf'] == 'true'){
						$button.closest(obj.countcont).find(obj.quntity).html(increase);
						$button.closest(obj.countcont).find(obj.subtract).removeClass('disabled');	
						$button.closest(obj.container).find(obj.amount).each(function(){
							$(this).html(json['quantity']['data']['item_total_formated']);
						});
					}else{
						if(json != null && json['quantity']['stock'] < quntityvar && json['quantity']['stock'] != 0){
							$button.closest(obj.countcont).find(obj.quntity).html(json['quantity']['stock']);
						}
						tooltip($button);
					}
					if(json['quantity']['stock'] == quntityvar+1){
						$button.closest(obj.countcont).find(obj.itemadd).addClass('disabled');
					}
					$button.removeClass('processing');
				}
				
			});
		}else{
			if(!$button.hasClass('processing')){
				tooltip($button);
			}
		}
	},
		
	subtractQuantity: function($button) {
		var obj = this;
		
		if(!$button.hasClass('processing') && !$button.hasClass('disabled')){
			$button.addClass('processing');
			var elementid = $button.attr('rel').split(',');
			var quntityvar = parseInt($button.closest(obj.countcont).find(obj.quntity).html());
			
			var custom_pricing = obj.customPricing();
			
			$.ajax({
				type: 'POST',
				url: obj.url,
				data: $.param({ calltype: 'checkquantity', colorid: elementid, quantity: (quntityvar-1), custom_pricing: custom_pricing }),
				success: function(data) {
					var json = $.parseJSON(data);
					var decrease = quntityvar-1;
					
					if(decrease == 1){$button.closest(obj.countcont).find(obj.subtract).addClass('disabled');}
					
					if(json['quantity']['conf'] == 'true' && decrease != 0){
						$button.closest(obj.countcont).find(obj.quntity).html(decrease);
						$button.closest(obj.countcont).find(obj.itemadd).removeClass('disabled');
						$button.closest(obj.container).find(obj.amount).each(function(){
							$(this).html(json['quantity']['data']['item_total_formated']);
						});
					}else{
						if(json['quantity']['stock'] < quntityvar && json['quantity']['stock'] != 0){
							$button.closest(obj.countcont).find(obj.quntity).html(json['quantity']['stock']);
						}
					}
					$button.removeClass('processing');
				}
				
			});
		}
	},
	
	addToBasket: function($button, itemquntity){
		var obj = this;
		
		if(!$button.hasClass('disabled')){
			$button.parent().addClass('processing');
			var elementid = $button.attr('rel').split(',');
			if( $button.closest(obj.container).find(itemquntity).html() ){
				var quntity = parseInt( $button.closest(obj.container).find(itemquntity).html() );
			}else{
				var quntity = 1;
			}
			
			var custom_pricing = obj.customPricing();
			
			$.ajax({
				type: 'POST',
				url: obj.basketUrl,
				data: $.param({ colorid: elementid[0], coloursize: elementid[1], quantity: quntity, custom_pricing: custom_pricing }),
				success: function(data) {
					if( obj.redirectUrl != null ) {
						window.location = obj.redirectUrl;
						return false;
					}
				
					$('#overlay').show();
					var json = $.parseJSON(data);
					var $popup = $('.window-popup');
					
					if($popup.length > 0){
						$popup.hide();
						$popup.find('.continue-shopping-btn').unbind('click').click(function(){
							if(!$.browser.msie){
								$popup.stop(true,true).fadeOut();
							}else{
								$popup.hide();
							}
							$('#overlay').hide();
						});

						$button.animate({ marginTop: 0 }, { duration: 500 });
						$button.fadeIn(400);
						var sizeName = $('.size-selection').find('.selected a').html();
						
						if($('.size-selection').find('select').length > 0){
							sizeName = $('.size-selection').find('select option:selected').html();
						}
						
						$popup.find('.product-count').html(quntity+'x');
						$popup.find('.product-total font').html(json['add']['total_formated']);
						
						// $popup.find('.name strong').html(json['add']['group'] + " - ");
						$popup.find('.name strong').html(json['add']['group']);
						if( sizeName != null && $popup.find('.name span').length > 0 ){
							$popup.find('.name span').html(json['add']['name']+', '+sizeName);
						}else{
						}
						
						$popup.css('left', (($button.offset().left - Math.round($popup.width() / 2))+($button.width()/2)) + 'px').css('top', ($button.offset().top - $popup.height()) + 'px');
						if(!$.browser.msie){
							$popup.stop(true,true).fadeIn(600,function(){
								$('#overlay').unbind().bind('click',function(){
									$(this).hide();
									$popup.hide();
								});
								$button.parent().removeClass('processing');
								if(json['add']['conf'] == 'success'){
									$('.shopping-bag a span').html(json['add']['items']);
									$('.shopping-bag-cont .basket-total-amount').html(json['add']['total_no_delivery_formated']);
								}
								
							});
						}else{
							$popup.show();
							$('#overlay').unbind().bind('click',function(){
								$(this).hide();
								$popup.hide();
							});
							$button.parent().removeClass('processing');
							if(json['add']['conf'] == 'success'){
								$('.shopping-bag a span').html(json['add']['items']);
								$('.shopping-bag-cont .basket-total-amount').html(json['add']['total_no_delivery_formated']);
							}
						}
					}else{
						$button.animate({ marginTop: 0 }, { duration: 500 });
						$button.fadeIn(400);
						$button.parent().removeClass('processing');
					}
				
				}
				
			});
		}
	},
	
	validate: function(validated){
		var error1 = $('.size-picker-error1');
		var error2 = $('.size-picker-error2');
		
		if(validated == 'true'){
			var size = $('.size-selection');
			var addbasket = $('.basket-actions .right');
			
			var sizeOffset = $(size).position();
			var addbasketOffset = $(addbasket).position();
			if(sizeOffset != null){
				$(error1).css('left', (sizeOffset.left-(error1.width()+25)));
				$(error1).css('top', (sizeOffset.top-((error1.height()/2)-5)));
				$(error1).show();
			}
			if(addbasketOffset != null){
				$(error2).css('left', (addbasketOffset.left-($(error2).width()))+($(addbasket).width()/2));
				$(error2).css('top', (addbasketOffset.top+addbasket.height()+10));
				$(error2).show();
			}
		}else{
			$(error1).hide();
			$(error2).hide();
		}
	},
	
	customPricing: function(){
		var obj = this;
		var spaceregex = /^[\s]*(.*?)[\s]*$/ig;
		
		Registry.set('/CustomPricing/', '');
		
		if(this.element.find('.custom-pricing li').length > 0){
			this.element.find('.custom-pricing li').each(function(){
				if($(this).hasClass('textfield-input') && $(this).find('input').val().length > 0 && $(this).find('input').val() != $(this).find('input').attr('title')){
					Registry.set('/CustomPricing/'+$(this).attr('value')+'/id/', $(this).attr('value'));
					Registry.set('/CustomPricing/'+$(this).attr('value')+'/value/', $(this).find('input').val());
					Registry.set('/CustomPricing/'+$(this).attr('value')+'/type/', 'textfield');
				}
				if($(this).hasClass('textarea-input') && $(this).find('textarea').val().length > 0 && $(this).find('textarea').val() != $(this).find('textarea').attr('title')){
					Registry.set('/CustomPricing/'+$(this).attr('value')+'/id/', $(this).attr('value'));
					Registry.set('/CustomPricing/'+$(this).attr('value')+'/value/', $(this).find('textarea').val());
					Registry.set('/CustomPricing/'+$(this).attr('value')+'/type/', 'textarea');
				}
				if($(this).hasClass('dropdown-list') && $(this).find('select').val().length > 0){
					var value = $(this).find('select option[value="'+$(this).find('select').val()+'"]').html();
					
					//removes spaces at the bigging and the end of the string
					value = value.replace(spaceregex, "$1");
					
					Registry.set('/CustomPricing/'+$(this).find('select').val()+'/id/', $(this).find('select').val());
					Registry.set('/CustomPricing/'+$(this).find('select').val()+'/value/', value);
					Registry.set('/CustomPricing/'+$(this).find('select').val()+'/type/', 'select');
				}
			});
		}
		
		return Registry.get('/CustomPricing/');
	},
	
	validateCustomPricing: function(validated, $button){
		var obj = this;
		var error3 = '.size-picker-error3';
		
		if(validated == 'true'){
			var custom_price = obj.element.find('.custom-pricing');
			var k = 0;
			
			custom_price.find('li').each( function(){
				var offset = $(this).position();
				if(offset != null && ($(this).find('input').hasClass('required') || $(this).find('textarea').hasClass('required') || $(this).find('select').hasClass('required'))){
					var check = 1;
					if($(this).hasClass('textfield-input') && $(this).find('input').val().length > 0 && $(this).find('input').val() != $(this).find('input').attr('title')){
						check = 0;
					}
					if($(this).hasClass('textarea-input') && $(this).find('textarea').val().length > 0 && $(this).find('textarea').val() != $(this).find('textarea').attr('title')){
						check = 0;
					}
					if($(this).hasClass('dropdown-list') && $(this).find('select').val().length > 0){
						check = 0;
					}
					
					if(check == 1){
						$(this).find(error3).css('left', (offset.left-($(this).find(error3).width()+25)));
						$(this).find(error3).css('top', (offset.top-(($(this).find(error3).height()/2)-5)));
						$(this).find(error3).show();
						k++;
					}else{
						$(this).find(error3).hide();
					}
				}
			});
			
			if(k > 0){
				$button.closest(obj.container).find(obj.add_tobasket_button).addClass('disabled');
				$button.addClass('action-disabled');
			}else{
				$button.closest(obj.container).find(obj.add_tobasket_button).removeClass('disabled');
				$button.removeClass('action-disabled');
				$(error3).hide();
			}
		}else{
			$(error3).hide();
		}
	}
	
});

function tooltip($button) {
	var $popup;
	var description;
	var button_class = classAttributes( $button.attr('class'), 'title' );
	Registry.set('/helperInfo/', $button);
	
	$popup = $('.helper-info');
	if(!$popup.is(':visible')){
		$popup.css('left', $button.offset().left + 'px').css('top', ($button.offset().top - $popup.height()) + 'px').fadeIn();
	}
   
	description = $popup.find('.desc').html();
	if ($button.attr('title') && $button.attr('title').length == 0){
		description = "Sorry, this product is not available for the quantity you selected.";
	}else if ($button.attr('title') && $button.attr('title').length > 0){
		description = $button.attr('title');
	}
	
	$popup.find('.desc').html(description);
	if(button_class[0]){
		$popup.find('.tooltip-title').html(button_class[0]);
	}
}

$.widget('ui.popup', {
	options: {
		closebutton: '.close-button a, .overlay, #overlay, #login-overlay',
		button: '.popup-button'
	},
	_init: function() {
		var obj = this;
		var closebutton = this.options.closebutton;
		var button = this.options.button;
		var parent = this.element;
		var popup = parent.attr('rel');
		
		$('body').find(button).live('click', function(){
			popup = $(this).attr('rel');
			/*if($(this).parent().hasClass('delivery-info')){
				var seo = 'delivery-info-rates';
				$.ajax({
					type: 'POST',
					url: '/page/request',
					data: $.param({ seo: seo }),
					success: function(data) {
						$(popup).find('.delivery-content').html(data);
					}
				});
			}*/
			
			if(popup == '.popup-pwd-retrieve'){
				$(popup).find('.valmsg').hide();
				$(popup).find('.pwd-content').show();
				$(popup).find('input[name="emailreset"]').val('');
				$(popup).find('.close-button').hide();
			}
			if(popup == '.popup-login'){
				$(popup).find('.error-msg').hide();
			}
		
			$(popup).find('form').removeClass('validated');
			$(popup).find('form .validation-msg').remove();
			$(popup).find('.content').css("left", ( $(window).width() - $(popup).find('.content').outerWidth() ) / 2 + "px");
			
			var visiblepops = $('.popup:visible').length;
			$(popup).center();
			if(visiblepops > 0){
				if(!$.browser.msie){
					$('.popup:visible').fadeOut(function(){
						$(popup).fadeIn();
					});
				}else{
					$('.popup:visible').hide();
					$(popup).show();
				}
			}else{
				if(!$.browser.msie){
					$(popup).fadeIn();
				}else{
					$(popup).show();
				}
			}
		});
		
		$(popup).find('.close-button a, .overlay, #overlay, .cancel, #login-overlay').live('click', function(){
			$(popup).fadeOut();
		});
		
	}
	
});

$.widget('ui.downloadpopup', {
	options: {
		closebutton: '.download-cancel .cancel'
	},
	_create: function() {
		var obj = this;
		var closebutton = this.options.closebutton;
		var parent = this.element.find('.category-scroller .image a');
		var popup = '.popup-download';
		
		$(parent).click(function(){
			var linkvar = $(this).attr('rel');
			
			$(popup).find('.content').css("left", ( $(window).width() - $(popup).find('.content').outerWidth() ) / 2 + "px");
			
			var visiblepops = $('.popup:visible').length;
			$(popup).center();
			if(visiblepops > 0){
				if(!$.browser.msie){
					$('.popup:visible').fadeOut(function(){
						$(popup).fadeIn();
					});
				}else{
					$('.popup:visible').hide();
					$(popup).show();
				}
			}else{
				$(popup).fadeIn();
			}
			
			$(popup).find('.download-image a').attr('href', linkvar);
			
		});
		
		$(popup).find('.download-image a').click(function(){
			$(popup).fadeOut();
		});
		
		$(popup).find(closebutton).click(function(){
			$(popup).fadeOut();
		});
		
	}
	
});

$.widget('ui.validation', {
	options: {
		validate: '',
		valtype: 'outline' //outline, inline
	},
	_create: function() {
		var obj = this;
		var parent = this.element;
		var items = parent.find('.validate');
		var validated = 0;
		var validate = this.options.validate;
		var valtype = this.options.valtype;
		
		items.blur(function(){
			validated = 0;
			validated = obj.validate($(this));
		});
		parent.submit(function(){
			validated = 0;
			items.each(function(){
				if($(this).is(':visible')){
					validated += obj.validate($(this));
				}
			});
			if(validated != 0){
				parent.removeClass('validated');
				return false;
			}else{
				parent.addClass('validated');
				return true;
			}
		});
		
	},
	
	_init: function(){
		var obj = this;
		var validate = this.options.validate;
		var items = this.element.find('.validate');
		var validated = 0;
		var valtype = this.options.valtype;
		
		if(validate == 'validate'){
			validated = 0;
			items.each(function(){
				validated += obj.validate($(this));
			});
			if(validated != 0){
				this.element.removeClass('validated');
			}else{
				this.element.addClass('validated');
			}
		}
	},
	
	validate: function(el){
		var content = el.val();
		var emailregex = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/;
		var spaceregex = /^[\s]*(.*?)[\s]*$/ig;
		var creditregex = /^[0-9\-\ ]+$/;
		var cvvregex = /^([0-9]{3,4})$/;
		var passregex = /^([A-Za-z0-9]+)$/;
		var passlength = /^([A-Za-z0-9]{6,25})$/;
		var errors = 0;
		var error_msg = '';
		var valtype = this.options.valtype;
		
		//removes spaces at the bigging and the end of the string
		el.val(content.replace(spaceregex, "$1"));
		content = el.val();
		
		if(el.hasClass('vldemail')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(el.val() != el.attr('title') || el.attr('title') == ''){
					if(content.search(emailregex) == -1){
						errors+=1;
						error_msg += '<li class="entry">A valid email is required</li>';
					}
				}
			}
		}
		if(el.hasClass('vldcheckbox')){
			if(!el.is(':checked')){
				errors+=1;
				error_msg += '<li class="entry">This field is required</li>';
			}
		}
		if(el.hasClass('vldcredit')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(content.search(creditregex) == -1){
					errors+=1;
					error_msg += '<li class="entry">A valid credit card number is required</li>';
				}
			}
		}
		if(el.hasClass('vldcvv')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(content.search(cvvregex) == -1){
					errors+=1;
					error_msg += '<li class="entry">A valid CSV code is required</li>';
				}
			}
		}
		if(el.hasClass('vldpass')){
			if(el.hasClass('vldrequired') || el.val().length > 0){
				if(el.val().length < 6){
					errors+=1;
					error_msg += '<li class="entry">Minimum length 6 characters</li>';
				}
			}
		}
		if(el.hasClass('vldpasslength')){
			if(el.hasClass('vldrequired') && el.val().length > 0){
				if(content.search(passlength) == -1){
					errors+=1;
					error_msg += '<li class="entry">A minimum of 6 characters long</li>';
				}
			}
		}
		if(el.hasClass('vldrequired')){
			if(content.length == 0 || el.val() == el.attr('title')){
				errors+=1;
				error_msg += '<li class="entry">This field is required</li>';
			}
		}
		
		el.next('.validation-msg').remove();
		if(errors > 0){
			el.addClass('error');
			if(valtype == 'outline'){
				el.parent().css('z-index', (el.parent().css('z-index')+1));
				el.after('<div class="validation-msg"><ul class="list">'+ error_msg +'</ul><div class="validation-bottom"></div></div>');
				el.next('.validation-msg').show();
				el.next('.validation-msg').mouseleave(function(){
					if(!$.browser.msie){
						$(this).fadeOut(function(){
							el.parent().css('z-index', '');
							$(this).remove();
						});
					}else{
						el.parent().css('z-index', '');
						$(this).remove();
					}
				});
			}
		
			return 1;
		}else{
			el.parent().css('z-index', '');
			el.removeClass('error');
			return 0;
		}
		
	}
	
});

$.widget('ui.customeraddress', {
	options: {
		popupcont: '.new-address',
		actionedit: '.action-links .edit',
		actionnew: '.action-links .add-new-address a',
		addressupdate: '.address-list',
		addressselect: '.address-selector'
	},
	_create: function() {
		var obj = this;
		var parent = this.element;
		var actionedit = this.options.actionedit;
		var addressupdate = this.options.addressupdate;
		var popupcont = this.options.popupcont;
		var addressselect = this.options.addressselect;
		var actionnew = this.options.actionnew;
		this.button = '';
		
		/**
		 * edit Returning customer address
		 */
		this.element.find(actionedit).live('click', function() {
			obj.button = $(this);
			var button = $(this);
			var editid = $(button).attr('rel');
			
			$.ajax({
				type: 'POST',
				url: '/account/get-user-address-data?ajax',
				data: $.param({ addressid: editid }),
				success: function(data) {
					var json = $.parseJSON(data);
					json = json['data'];
					if(json != null && json['conf'] != null && json['conf'] == 'true'){
						$(popupcont).find('form input[name="first-name"]').val(json['address']['first_name']);
						$(popupcont).find('form input[name="last-name"]').val(json['address']['last_name']);
						$(popupcont).find('form input[name="address1"]').val(json['address']['address1']);
						$(popupcont).find('form input[name="address2"]').val(json['address']['address2']);
						$(popupcont).find('form input[name="city"]').val(json['address']['city']);
						$(popupcont).find('form input[name="country-state"]').val(json['address']['county']);
						$(popupcont).find('form input[name="postcode"]').val(json['address']['postcode']);
						$(popupcont).find('form input[name="phonenumber"]').val(json['address']['home_no']);
						$(popupcont).find('form select[name="country"]').val(json['address']['country']);
						
						$(popupcont).find('form input[name="newaddress"]').val('update');
						$(popupcont).find('form input[name="itemid"]').val(json['address']['id']);
						$(popupcont).find('form .continue').removeClass('continue').addClass('save');
						$(popupcont).center();
						$(popupcont).show();
					}else{
						$(this).addClass('error');
					}
				}
				
			});
			
		});
		
		$(popupcont).find('form ul .save, form ul .continue').live('click', function(){
			var formdata = $(this).closest('form').serialize();
			$(this).closest('form').validation({validate: 'validate'});
			var type = $(this).closest('form').find('input[name="newaddress"]').val();
			
			var url = '';
			if(type == 'update'){
				url = '/account/update-user-address?ajax';
			}else if(type == 'save'){
				url = '/account/save-user-address?ajax';
			}
			
			if($(this).closest('form').hasClass('validated')){
				$.ajax({
					type: 'POST',
					url: url,
					data: formdata,
					success: function(data) {
						var json = $.parseJSON(data);
						if(json['data']['conf'] != null && json['data']['conf'] == 'true'){
							json = json['data'];
							if(type == 'update'){
								$('.return-cust-add').find('.address-selector').each(function(){
									$(this).find('option[value="'+json['id']+'"]').text(json['title']);
								});
								
								if($('.billing-address .action-links .edit').attr('rel') == $('.delivery-address .action-links .edit').attr('rel')){
									$('.billing-address .address-selector').change();
									$('.delivery-address .address-selector').change();
								}else{
									obj.button.closest('.action-links').parent().find('.address-selector').change();
								}
								$(popupcont).find('.cancel').click();
							}else if(type == 'save'){
								var option = '<option value="'+json['address']['id']+'">'+json['address']['first_name']+' '+json['address']['last_name']+''+json['address']['address1']+''+json['address']['city']+'</option>';
								$('.return-cust-add').find('.address-selector').each(function(){
									$(this).append(option);
								});
								//$('.return-cust-add').closest('.regist-addr').find('.address-selector').append(option);
								obj.button.closest('.action-links').parent().find('.address-selector').val(json['address']['id']);
								obj.button.closest('.action-links').parent().find('.address-selector').change();
								
								$(popupcont).find('.cancel').click();
							}else{
								alert('fail');
							}
						}
					}
				});
			}
		});
		
		$(popupcont).find('.cancel, #overlay, .close-button').click(function(){
			$(popupcont).fadeOut(function(){
				$(this).find('form').removeClass('validated');
				$(this).find('form .validation-msg').remove();
				$(this).find('form input').each(function(){
					$(this).val('');
				});
			});
		});
		
		/**
		 * Save Returning customer address
		 */
		this.element.find(actionnew).live('click', function() {
			obj.button = $(this);
			
			$(popupcont).find('form input').each(function(){
				$(this).val('');
			});
				
			$(popupcont).find('form input[name="newaddress"]').val('save');
			$(popupcont).find('form .save').removeClass('save').addClass('continue');
			$(popupcont).center();
			$(popupcont).show();
		});
		
		this.element.find(addressselect).live('change', function() {
			var selector = $(this);
			var addressid = $(this).val();
			var type = $(this).parents('.address-block').attr('title');
			
			$.ajax({
				type: 'POST',
				url: '/account/get-user-address-data?ajax',
				data: $.param({ addressid: addressid }),
				success: function(data) {
					var json = $.parseJSON(data);
					json = json['data'];
					var html = '<li id="'+addressid+'"><strong>'+json['address']['first_name']+' '+json['address']['last_name']+'</strong></li><li>'+json['address']['address1']+'</li><li>'+json['address']['address2'];
					if(json['address']['address2'].length > 0){
						html += ', ';
					}
					html += json['address']['city']+'</li><li>'+json['address']['county']+', '+json['address']['postcode']+'</li><li>'+json['address']['country']+'</li><li><strong>Phone:</strong> '+json['address']['home_no']+'</li>';
					selector.next(addressupdate).html(html);
					selector.parent().find(actionedit).attr('rel',addressid);
				}
			});
		});
		
	}
	
});

$.widget('ui.helperValue', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		
		if(parent.val().length == 0){
			parent.val(parent.attr('title'));
		}
		
		parent.focus(function(){
			if($(this).val() == $(this).attr('title')){ $(this).val(''); }
		});
		
		parent.blur(function(){
			if($(this).val() == ''){ $(this).val($(this).attr('title')); }
		});
		
	}
	
});

$.widget('ui.csvtooltip', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		var tooltip = this.element.attr('rel');
		
		parent.click(function(){
			var offset = $(this).offset();
			$(tooltip).css('left',offset.left+30);
			$(tooltip).css('top',offset.top-(217+$(this).height()));
			if(!$.browser.msie){
				$(tooltip).stop(true,true).fadeIn('normal',function(){
					$(this).css('opacity','1');
				});
			}else{
				$(tooltip).stop(true,true).show();
				$(this).css('opacity','1');
			}
		});
		
		$(tooltip).mouseover(function(){
			$(this).stop(true,true).show();
		});
		$(tooltip).mouseout(function(){
			if(!$.browser.msie){
				$(this).delay(800).fadeOut(1000);
			}else{
				$(this).hide();
			}
		});
		$(tooltip).find('.close').click(function(){
			$(tooltip).hide();
		});
		
	}
	
});

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

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 "";
}

$.widget('ui.wallpapers', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		
		
		parent.click(function(){
			$('.customer-nav .wallpaper-cont').stop(true,true).slideToggle(function() {
				if($('#overlay').is(':hidden')){
					$('#overlay').show();
				}else{
					$('#overlay').hide();
				}
			});
			$
		});
		
		$('#overlay').click(function(){
			$('.customer-nav .wallpaper-cont').stop(true,true).fadeOut();
			$('#overlay').hide();
		});
		
		$('.customer-nav .wallpaper-list .entry a').click(function(){
			var image = 'url("'+$(this).find('img').attr('src')+'")';
			
			$('body').css('background-image',image);
			$('body').css('background-repeat','repeat');
			$('body').addClass('wallpaper-background');
			
			setCookie('wallpaper', image);				
		});
	}
	
});

$.widget('ui.ajaxform', {
	options: {
		reqclass: '',
		type: 'POST',
		address: ''
	},
	
	_create: function() {
		var obj = this;
		var parent = this.element;
		var reqclass = this.options.reqclass;
		
		parent.submit(function(){
			if(reqclass.length > 0){
				if(parent.hasClass(reqclass)){
					obj.sendout();
				}
			}else{
				obj.sendout();
			}
			return false;
		});
	},
	
	sendout: function(){
		var formdata = this.element.serialize();
		var callback = this.options.change;
		var type = this.options.type;
		var address = this.options.address;
		var parent = this.element;
		if( address.length == 0 ){
			address = parent.attr('action');
		}
		
		$.ajax({
			type: type,
			url: address,
			data: formdata,
			success: function(data) {
				if ($.isFunction(callback)) callback(data); 
			}
		});
	}
	
});

$.widget('ui.promohelper', {
	options: {
		firsthelper: '.promo-first-helper-popup',
		secondhelper: '.promo-second-helper-popup',
		thirdhelper: '.promo-third-helper-popup',
		overlay: '.promo-helper-overlay'
	},
	
	_create: function() {
		var obj = this;
		var firsthelper = this.options.firsthelper;
		var secondhelper = this.options.secondhelper;
		var thirdhelper = this.options.thirdhelper;
		var overlay = this.options.overlay;
		
		this.element.find('.need-some-help a').click(function() {
			var button = $(this);
			var firstwidth = obj.element.find('.promo-code-cont .promotionalcode').width();
			var secondwidth = $(secondhelper).height();
			var thirdwidth = $(thirdhelper).width();
			var thirdcontheight = obj.element.find('.mini-cart .checkout-button').height();
			
			$(overlay).fadeIn();
			$(firsthelper).css('left', (obj.element.find('.promo-code-cont .promotionalcode').offset().left+(firstwidth/2)) + 'px').css('top', (obj.element.find('.promo-code-cont .promotionalcode').offset().top - $(firsthelper).height()) + 'px').fadeIn();
			$(secondhelper).css('left', obj.element.find('.delivery-row').offset().left + 'px').css('top', (obj.element.find('.delivery-row').offset().top + (secondwidth/3)) + 'px').fadeIn();
			$(thirdhelper).css('left', (obj.element.find('.mini-cart .checkout-button').offset().left - (thirdwidth/4)) + 'px').css('top', (obj.element.find('.mini-cart .checkout-button').offset().top + (thirdcontheight/2)) + 'px').fadeIn();
		});
		
		$(overlay).click(function() {
			obj.hidehelper(firsthelper, secondhelper, thirdhelper, this);
		});
	},
	
	hidehelper: function(firsthelper, secondhelper, thirdhelper, overlay){
		$(firsthelper).hide();
		$(secondhelper).hide();
		$(thirdhelper).hide();
		$(overlay).fadeOut();
	}
	
});


$.widget('ui.promocode', {
	options: {
		submitbutton: '.promo-code-cont form .submit-promotion',
		promoForm: '.promo-code-cont form',
		promocont: '.input-code',
		promocode: '.promotionalcode',
		basket_background: 'FFFFFF',
		url: '/basket/run-code-promotion?ajax'
	},
	
	_init: function(){
		this.basket_background = this.options.basket_background;
	},
	
	_create: function() {
		var obj = this;
		this.basket_background = this.options.basket_background;
		var submitbutton = this.options.submitbutton;
		var promoinput = this.options.promocont;
		var promoval = this.options.promocode;
		var promoForm = this.options.promoForm;
		var url = this.options.url;
		var $subelement = $('.subtotal-update');
		var $totalelement = $('.total-update');
		var $basketitem = $('.baskettotal-update');
		
		$(promoForm).submit(function(){
			$(submitbutton).click();
			return false;
		});
		
		$(submitbutton).click(function() {
			if(!$(this).hasClass('submiting')){
				$(this).addClass('submiting');
				var clickcont = $(this);
				var promocont = $(clickcont).parents('form').find(promoinput);
				var promocode = $(clickcont).parents('form').find(promoval).val();
				var promotitle = $(clickcont).parents('form').find(promoval).attr('title');
				
				if(promocode.length > 1 && promocode != promotitle){
					$('.promo-validation-proc .promo-close a, .promo-validation-proc .close-button a').hide();
					$('.promo-validation-proc .promo-loader').show();
					$('.promo-validation-proc .promo-loader img').show();
					$('.promo-validation-proc .promo-valid-text').show();
					$('.promo-validation-proc .promo-conde-invalid').hide();
					$('.promo-validation-proc').show();
					$('.promo-validation-proc .overlay').show();
					$.ajax({
						type: 'POST',
						url: url,
						data: $.param({ promocode: promocode }),
						success: function(data) {
							var json = $.parseJSON(data);
							
							switch(json['promotion']['status']){
								case 'fail':
									$('.promo-validation-proc .promo-close a, .promo-validation-proc .close-button a').show();
									$('.promo-validation-proc .promo-loader').hide();
									$('.promo-validation-proc .promo-loader img').hide();
									$('.promo-validation-proc .promo-valid-text').hide();
									$('.promo-validation-proc .promo-conde-invalid').html(json['promotion']['results']);
									$('.promo-validation-proc .promo-conde-invalid').show();
									
									if(!$(promocont).hasClass('wrong-promotion')){
										$(promocont).addClass('wrong-promotion');
									}
									$('.popup-button').popup();
									break;
								case 'success':
									$('#delivery-total .discount-row').find('.right-cell span').html(json['promotion']['discount_formated']);
									if(json['promotion']['summary']['discount_code'].length > 1){
										$('#delivery-total .discount-row').find('.cell span').html('('+json['promotion']['summary']['discount_code']+')');
									}else{
										$('#delivery-total .discount-row').find('.cell span').html('');
									}
									obj.update(json['promotion']);
									obj.animatebackcont($subelement, $totalelement, $basketitem);
									$(clickcont).parents('form').find(promoval).val(promotitle);
									$(promocont).removeClass('wrong-promotion');
									$(promocont).parent().removeClass('wrong-promotion');
									$(promocont).parent().addClass('verified-promotion');
									$(promocont).addClass('verified-promotion');
									
									$('.promo-validation-proc .promo-loader img').fadeOut(600, function(){
										obj.closeValidation();
									});
									break;
							}
							
							$(clickcont).removeClass('submiting');
						}
					
					});
				}else{
					$(promocont).addClass('wrong-promotion');
					$(clickcont).removeClass('submiting');
				}
			}
		});
		
		$('.promo-validation-proc .promo-login .join-now, .promo-validation-proc .promo-login .register').live('click', function(){
			$('.promo-validation-proc .promo-loader').show();
			obj.closeValidation();
		});
		
		$('.promo-validation-proc .promo-close a, .promo-validation-proc .close-button a').live('click', function(){
			$('.promo-validation-proc .promo-loader').show();
			obj.closeValidation();
		});
	},
	
	closeValidation: function(){
		$('.promo-validation-proc .overlay').hide();
		$('.promo-validation-proc .promo-close a, .promo-validation-proc .close-button a').hide();
		$('.promo-validation-proc').fadeOut(function(){
			$('.promo-validation-proc .promo-valid-text').html('Checking Promotion...');
		});
		$('.promo-validation-proc .promo-valid-text').removeClass('promo-valid-error');
		
	},
	
	update: function(json){
		if(parseInt(json['discount']) > 0 && $('#delivery-total .discount-row').is(':hidden')){
			$('#delivery-total .discount-row').slideDown();
		}else if(parseInt(json['discount']) == 0){
			$('#delivery-total .discount-row').hide();
		}
		$('.shopping-bag a span').html(json['itemcount']);
		$('.contains-items').html(json['itemcount']);
		$('.mini-cart .small-basket-total').html(json['total_formated']);
		$('#delivery-total .total-row span').html(json['total_formated']);
		$('.subtotal-container .stotal span').html(json['subtotal_formated']);
		$('#delivery-total').find('.delivery-price a#'+json['did']).html(''+json['delamount_formated']);
		$('.deliv-summary .del-item-price strong').html(''+json['delamount_formated']);
		$('#delivery-total .discount-row').find('.right-cell span').html(json['discount_formated']);
		if(json['discount'] != null && json['promotion'] != null && json['discount'].length > 0){
			$('.deliv-summary .del-item-desc span').html(json['promotion']['delDesc']);
		}else{
			$('.deliv-summary .del-item-desc span').html(json['summary']['delivery']);
		}
	},
	
	animatebackcont: function($subelement, $totalelement, $basketitem){
		var obj = this;
		
		if(!$subelement.hasClass('background-update-false')){
			$subelement.css('backgroundColor', '').stop().animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
				$subelement.css('backgroundColor', '#bde8ff').animate({ 'backgroundColor': '#ffffff' }, 1000);
			});
		}
		if(!$totalelement.hasClass('background-update-false')){
			$totalelement.css('backgroundColor', '').stop(true).animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
				$totalelement.animate({ 'backgroundColor': '#' + 'fff' }, 1000);
			});
		}
		if(!$basketitem.hasClass('background-update-false')){
			$basketitem.css('backgroundColor', '').stop(true).animate({ 'backgroundColor': '#bde8ff' }, 1000, function() {
				$basketitem.animate({ 'backgroundColor': '#' + obj.basket_background }, 1000);
			});
		}
	}
	
});

$.widget('ui.feedbackSlider', {

	_create: function() {
		var obj = this;
		var parent = this.element;
		
		parent.find('.feedback-handle').click(function(){
			var button = $(this);
			if(!button.hasClass('working')){
				button.addClass('working');
				
				if(parent.css('right') == '0px'){
					parent.animate({right : '-=320'}, 1000, function(){
						button.removeClass('working');
					});
				}else{
					parent.animate({right : '+=320'}, 1000, function(){
						button.removeClass('working');
					});
				}
			}
		});
		
		parent.find('.feedback-form textarea').keydown(function(){
			$(this).removeClass('error');
			var string = $(this).val();
			if(string.length > 500){
				var newStr = string.substring(0, string.length-1);
				$(this).val(newStr);
			}
		});

		parent.find('.close-button').click(function(){
			var button = parent.find('.feedback-handle');
			if(!button.hasClass('working')){
				button.addClass('working');
				
				parent.animate({right : '-=320'}, 1000, function(){	
					$('.feedback-slider .feedback-thankyou').hide();
					$('.feedback-slider .feedback-form').show();
					button.removeClass('working');
				});
			}
		});

		parent.find('.more-feedback').click(function(){
			$('.feedback-slider .feedback-thankyou').hide();
			$('.feedback-slider .feedback-form').fadeIn();
		});

	}
	
});


$.widget('ui.imageSlideShow', {
	options: {
		image: '.image'
	},
	_create: function() {
		var obj = this;
		var parent = this.element;
		var image = this.options.image;
		
		var images = parent.find(image);
		var counter = 0;

		$(images).hide();
		$(images[0]).show();
		
		
		if(images.length > 1){
			var refreshIntervalId = setInterval(function() {
				$(images[counter]).stop(true,true).fadeOut('slow');
				
				counter++;
				if (counter == images.length) {
					counter = 0;
				}
				$(images[counter]).stop(true,true).fadeIn(1000);
				
			}, 5000);
			
			images.mouseenter(function(){
				clearInterval(refreshIntervalId);
			});
			images.mouseleave(function(){
				refreshIntervalId = setInterval(function() {
					$(images[counter]).stop(true,true).fadeOut('slow');
					
					counter++;
					if (counter == images.length) {
						counter = 0;
					}
					$(images[counter]).stop(true,true).fadeIn(1000);
					
				}, 5000);
			});
		}
	}
	
});

$.widget('ui.recentlyViewed', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		var container = parent.find('.box');
		
		container.find('.item').live('mouseenter mouseleave', function(event) {
			if (event.type == 'mouseenter') {
				if(!$.browser.msie){
					$(this).find('.pr-desc-cont').show();
					$(this).find('.pr-desc-cont .pr-desc-overlay').stop(false, true).fadeIn();
					$(this).find('.pr-desc-cont .descr-cont').stop(false, true).fadeIn();
				}else{
					$(this).find('.pr-desc-cont').show();
					$(this).find('.pr-desc-cont .descr-cont').show();
					$(this).find('.pr-desc-cont .pr-desc-overlay').show();
				}
			} else {
				$(this).find('.pr-desc-cont').hide();
				$(this).find('.pr-desc-cont .descr-cont').hide();
				$(this).find('.pr-desc-cont .pr-desc-overlay').hide();
			}
		});
		
		container.find('.item .pr-desc-cont').live('click', function(){
			window.location = $(this).find('.recent-link').attr('href');
		});
		
		container.find('.item .remove-cont a').live('click', function(){
			var element = $(this).closest('.item');
			var id = $(this).attr('rel');
			$.ajax({
				type: 'POST',
				url: '/products-module/unset-recent-item?ajax',
				data: $.param({ remove: id }),
				success: function(data) {
					var json = $.parseJSON(data);
					if(json['data'] == 'ok'){
						element.fadeTo(200, 0, function(){
							element.animate({width:0}, 400, function(){
								element.remove();
							});
						});
					}
				}
			
			});
			
		});
	}
	
});

$.widget('ui.categoryPage', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		var originalImages = [];
		var images = [];
		var currentImage = '';
		
		parent.find('li').click(function(){
			if(!$(this).closest(parent).hasClass('full-item-click-off')){
				window.location = $(this).find('a').attr('href');
			}
		});
		
		var k = 0;
		parent.find('li').each(function(){
			var currentElement = $(this);
			var secondImageLink = '';
			secondImageLink = $(currentElement).find(".image a").attr("rel");
			if(secondImageLink != null && secondImageLink.length > 0){
				$('<img />').attr('src', currentElement.find('.image a').attr('rel')).load(function(){
					currentElement.addClass('loaded');
				});
				images[$(this).index('.category-list li')] = currentElement.find('.image a').attr('rel');
				k++;
			}
		});
		
		parent.find('li').hover(
			function(event) {
				currentImage = $(this).find('.image img').attr('src');
				if($(this).hasClass('loaded') && images[$(this).index('.category-list li')] != null && images[$(this).index('.category-list li')].length > 0){
					$(this).find('.image img').attr('src', images[$(this).index('.category-list li')]);
				}
			},
			function() {
				if($(this).hasClass('loaded')){
					$(this).find('.image img').attr('src', currentImage);
				}
			}
		);
		
	}
	
});

$.widget('ui.customPricing', {
	_create: function() {
		var obj = this;
		var parent = this.element;
		var spaceregex = /^[\s]*(.*?)[\s]*$/ig;
		
		$('.custom-pricing input').helperValue();
		$('.custom-pricing textarea').helperValue();

		
		$('.custom-pricing input, .custom-pricing textarea').live('keyup', function(){
			var input_value = $(this).val();
			var string = $(this).closest('li').find('.field-character-count').attr('class');
			var data = [];
			if(string && string.length > 0){
				data = classAttributes(string, "max_character");
			}
			
			if(data != null && data[0] != null){
				var count = parseInt(data[0])-parseInt(input_value.length);
				$(this).closest('li').find('.field-character-count font').html(count);
				if(count < 0){
					$(this).val(input_value.substr(0, data[0]).replace(spaceregex, "$1"));
					$(this).closest('li').find('.field-character-count font').html(0);
					$(this).closest('li').find('.field-character-count').stop(true).animate({ 'color': '#cc0000' }, 1000);
				}else if(count == 0){
					$(this).closest('li').find('.field-character-count').stop(true).animate({ 'color': '#cc0000' }, 1000);
				}else{
					$(this).closest('li').find('.field-character-count').stop(true).animate({ 'color': '#BFBFBF' }, 1000);
				}
			}
			
		});
		
		/*$('.custom-pricing textarea').live('keyup', function(){
			var input_value = $(this).val();
			var string = $(this).closest('li').find('.field-character-count').attr('class');
			var data = [];
			if(string && string.length > 0){
				data = classAttributes(string, "max_character");
			}
			
			if(data != null && data[0] != null){
				var count = parseInt(data[0])-parseInt(input_value.length);
				$(this).closest('li').find('.field-character-count font').html(count);
				if(count < 0){
					$(this).val(input_value.substr(0, data[0]).replace(spaceregex, "$1"));
					$(this).closest('li').find('.field-character-count font').html(0);
				}
			}
			
		});*/
		
	}
	
});

$.widget('ui.rotatingImages', {
	options: {
		images: '.banner-image'
	},
	_create: function() {
		var obj = this;
		var parent = this.element;
		var images = this.options.images;
		this.elements = parent.find(images);
		this.homepageSlideshow;
		
		if( this.elements.length > 1 ){
			obj.counter = 0;
			$(this.elements).hide();
			$(this.elements[0]).show();
			obj.interval();
		}

		parent.find(images).hover(function(){
			if( !$(this).hasClass('active') ){
				$('.main-banner .main-banner-menu a.active').removeClass('active');
				$(this).addClass('active');
				clearInterval( obj.homepageSlideshow );
				
				//parent.find(images+':visible').hide();
				$(obj.elements[ $(this).attr('rel') ]).stop(true,true).fadeIn(400);
			}
		},
		function(){
			if( $(this).hasClass('active') ){
				$(this).removeClass('active');
				obj.interval();
			}
		});
		
		parent.find('.left-arrow a').click(function(){
			if( obj.elements.length > 1 ){
				obj.prevImage();
			}
		});
		
		parent.find('.right-arrow a').click(function(){
			if( obj.elements.length > 1 ){
				obj.nextImage();
			}
		});
		
	},
	
	interval: function(){
		var obj = this;
		obj.homepageSlideshow = setInterval(function() {
			$(obj.elements[obj.counter]).fadeOut('slow');
				obj.counter++;
				if (obj.counter == obj.elements.length) {
					obj.counter = 0;
				}
			$(obj.elements[obj.counter]).fadeIn(400);
			$('.main-banner .main-banner-menu a.active').removeClass('active');
			$('.main-banner .main-banner-menu a').eq(obj.counter).addClass('active');
		}, 4000);
	},
	
	prevImage: function(){
		var obj = this;
		clearInterval( obj.homepageSlideshow );
		$(obj.elements[obj.counter]).fadeOut('slow');
			obj.counter = obj.counter - 1;
			if (obj.counter < 0) {
				obj.counter = obj.elements.length-1;
			}
		
		$(obj.elements[obj.counter]).fadeIn(400);
		$('.main-banner .main-banner-menu a.active').removeClass('active');
		$('.main-banner .main-banner-menu a').eq(obj.counter).addClass('active');
		obj.interval();
	},
	
	nextImage: function(){
		var obj = this;
		clearInterval( obj.homepageSlideshow );
		$(obj.elements[obj.counter]).stop(true, true).fadeOut('slow');
			obj.counter++;
			if (obj.counter >= obj.elements.length) {
				obj.counter = 0;
			}
		$(obj.elements[obj.counter]).fadeIn(400);
		$('.main-banner .main-banner-menu a.active').removeClass('active');
		$('.main-banner .main-banner-menu a').eq(obj.counter).addClass('active');
		obj.interval();
	}
	
});


$.widget('ui.allProductSizeAction', {
	options: {
		actions: '.size-actions',
		subtract: '.subtract',
		increase: '.add',
		qty: '.size-qty',
		total: '.total-item-price',
		addToBasketButton: '.add-all-to-basket'
	},
	
	_init: function(){
		this.actions = this.options.actions;
		this.subtract = this.options.subtract;
		this.increase = this.options.increase;
		this.qty = this.options.qty;
		this.total = this.options.total;
		this.addToBasketButton = this.options.addToBasketButton;
	},
	
	_create: function() {
		var obj = this;
		this.parent = this.element;
		this.actions = this.options.actions;
		this.subtract = this.options.subtract;
		this.increase = this.options.increase;
		this.qty = this.options.qty;
		this.total = this.options.total;
		this.addToBasketButton = this.options.addToBasketButton;
		
		var actions = this.parent.find(this.actions);
		actions.find(this.increase).live('click', function(){
			var item_data = $(this).attr('rel').split(',');
			var product_id = item_data[0];
			var colour_id = item_data[1];
			var size_id = item_data[2];
			var qty = parseInt($(this).closest(obj.actions).find(obj.qty).html());
			
			actions.find(obj.qty).each(function(){
				var product_data = classAttributes( $(this).attr('class'), 'product_data' );
				if( product_data != null && product_data[0] != null ){
					Registry.set('/quantity_count/'+product_data[0]+'/'+product_data[1]+'/'+product_data[2]+'/', parseInt($(this).html()));
				}
			});
			
			if( !$(this).hasClass('disabled') && !$(this).hasClass('processing') ){
				obj.quantity( parseInt(qty)+1, product_id, colour_id, size_id, Registry.get('/quantity_count/'), $(this), 'increase' );
			}else{
				if( !$(this).hasClass('processing') ){
					tooltip($(this));
				}
			}
			
			return false;
		});
		
		actions.find(this.subtract).live('click', function(){
			var item_data = $(this).attr('rel').split(',');
			var product_id = item_data[0];
			var colour_id = item_data[1];
			var size_id = item_data[2];
			var qty = parseInt($(this).closest(obj.actions).find(obj.qty).html());
			
			if(parseInt(qty) > 0){
				actions.find(obj.qty).each(function(){
					var product_data = classAttributes( $(this).attr('class'), 'product_data' );
					if( product_data != null && product_data[0] != null ){
						Registry.set('/quantity_count/'+product_data[0]+'/'+product_data[1]+'/'+product_data[2]+'/', parseInt($(this).html()));
					}
				});
				
				if(!$(this).hasClass('processing')){
					obj.quantity( parseInt(qty)-1, product_id, colour_id, size_id, Registry.get('/quantity_count/'), $(this), 'subtract' );
				}
			}
			return false;
		});
		
		this.parent.find(this.addToBasketButton).live('click', function(){
			var k = 0;
			actions.find(obj.qty).each(function(){
				var product_data = classAttributes( $(this).attr('class'), 'product_data' );
				if( product_data != null && product_data[0] != null ){
					Registry.set('/quantity_count/'+product_data[0]+'/'+product_data[1]+'/'+product_data[2]+'/', parseInt($(this).html()));
					
					if(parseInt($(this).html()) > 0){
						k++;
					}
				}
			});
			
			if(k > 0){
				$('.size-picker-error1').hide();
				obj.addToBasket( Registry.get('/quantity_count/'), $(this) );
			}else{
				$('.size-picker-error1').show();
			}
			return false;
		});
	},
	
	quantity: function( qty, product_id, colour_id, size_id, quantity_count_data, button, call_type ){
		var obj = this;
		
		button.addClass('processing');
		
		$.ajax({
			type: 'POST',
			url: '/products-module/all-product-size-actions-quantity?ajax',
			data: $.param({ quantity: qty, product_id: product_id, colour_id: colour_id, size_id: size_id, quantity_count_data: quantity_count_data, call_type: call_type }),
			success: function(data) {
				var json = $.parseJSON(data);
				button.removeClass('processing');
				
				if(json['quantity']['conf'] == 'true'){
					$('.size-picker-error1').hide();
					button.removeClass('disabled');
					button.closest(obj.actions).find(obj.qty).html( qty );
					obj.parent.find(obj.total).html(json['quantity']['total_formated']);
					if(call_type == 'subtract'){
						button.closest(obj.actions).find(obj.increase).removeClass('disabled');
					}
				}else{
					if(qty == 0){
						button.closest(obj.actions).find(obj.qty).html( 0 );
						obj.parent.find(obj.total).html(json['quantity']['total_formated']);
					}else{
						button.addClass('disabled');
						tooltip(button);
					}
				}
				
			}
		
		});
	},
	
	addToBasket: function( quantity_count_data, button ){
		var obj = this;
		button.animate({'opacity': 0.5}, 300);
		button.addClass('processing');
		
		$.ajax({
			type: 'POST',
			url: '/products-module/all-product-size-actions-add-to-basket?ajax&data',
			data: $.param({ quantity_count_data: quantity_count_data }),
			success: function(data) {
				var json = $.parseJSON(data);
				
				button.removeClass('processing');
				button.animate({'opacity': 1}, 500);
				
				if(json['data']['conf'] == 'true'){
					var items = json.data.data;
					var item_length = items.length;
					var html = '';
					var clone_html = $('.product .my-rail .items .list .clonable').clone().removeClass('clonable').wrap('<div>').parent().html();
					
					for( var i=0; i<item_length; i++ ){
						if( $('.product .my-rail .items .list .item .image a[href="'+items[i].url+'"]').length === 0 ){
							html += $.snippet( clone_html, {
								url: items[i].url,
								group: items[i].group,
								img_path: items[i].image_name,
								colour_id: items[i].colour_id,
								key: items[i].key
							} );
						}
					}
					$('.product .my-rail .items .list').prepend(html).find('.item:hidden').not('.clonable').css('opacity', 0).animate({
						"height": "show",
						"marginTop": "show",
						"marginBottom": "show",
						"paddingTop": "show",
						"paddingBottom": "show"
					}, {
						step: function(now, fx){
							$('.product .my-rail .list-container').scrollbar();
						},
						complete: function(){
							$(this).animate({
								opacity: 1
							}, 500, 'linear');
						}
					}, 'linear', 2000);
				}
				
			}
		
		});
	}
	
});

$.widget('ui.allProductBasketSizeAction', {
	options: {
		actions: '.size-actions',
		subtract: '.subtract',
		increase: '.add',
		qty: '.size-qty',
		total: '.basket-subtotal-cont .total-total',
		count: '.basket-subtotal-cont .total-count',
		addToBasketButton: '.add-all-to-basket'
	},
	
	_init: function(){
		this.actions = this.options.actions;
		this.subtract = this.options.subtract;
		this.increase = this.options.increase;
		this.qty = this.options.qty;
		this.total = this.options.total;
		this.count = this.options.count;
		this.addToBasketButton = this.options.addToBasketButton;
	},
	
	_create: function() {
		var obj = this;
		this.parent = this.element;
		this.actions = this.options.actions;
		this.subtract = this.options.subtract;
		this.increase = this.options.increase;
		this.qty = this.options.qty;
		this.total = this.options.total;
		this.count = this.options.count;
		this.addToBasketButton = this.options.addToBasketButton;
		
		var actions = this.parent.find(this.actions);
		actions.find(this.increase).live('click', function(){
			var item_data = $(this).attr('rel').split(',');
			var product_id = item_data[0];
			var colour_id = item_data[1];
			var size_id = item_data[2];
			var qty = parseInt($(this).closest(obj.actions).find(obj.qty).html());
			
			if( !$(this).hasClass('disabled') && !$(this).hasClass('processing') ){
				obj.quantity( parseInt(qty)+1, item_data, $(this), 'increase' );
			}else{
				if( !$(this).hasClass('processing') ){
					tooltip($(this));
				}
			}
			
			return false;
		});
		
		actions.find(this.subtract).live('click', function(){
			var item_data = $(this).attr('rel').split(',');
			var product_id = item_data[0];
			var colour_id = item_data[1];
			var size_id = item_data[2];
			var qty = parseInt($(this).closest(obj.actions).find(obj.qty).html());
			
			if(parseInt(qty) > 0 && (parseInt(qty)-1) > 0){
				if(!$(this).hasClass('processing')){
					obj.quantity( parseInt(qty)-1, item_data, $(this), 'subtract' );
				}
			}
			return false;
		});
		
		this.parent.find('.product-item').hover(
			function() { $(this).find('img').stop(true, true).animate({ opacity: 0.7 }, 300 ); },
			function() { $(this).find('img').stop(true, true).animate({ opacity: 1 }, 300 ); }
		);
		
		this.parent.find('.remove-product').live('click', function() {
			var url = $(this).attr('href');
			var button = $(this);
			obj.removeItemInit(button);
			
			$.ajax({
				type: 'POST',
				url: url+'&ajax',
				success: function(data) {
					var json = $.parseJSON(data);
					if(json['conf'] == 'true'){
						obj.removeItem(button);
						obj.parent.find(obj.total).html( json['summary']['total_formated'] );
						obj.parent.find(obj.count).html( json['summary']['bag'] );
					}else{
						button.closest('.product-item').animate({ opacity: 1 }, 300);
					}
				}
			});
			return false;
		});
		
		this.parent.find('.size-entry').hover(
			function() { $(this).find('.remove-size-cont').show(); },
			function() { $(this).find('.remove-size-cont').hide(); }
		);
		
		this.parent.find('.remove-size').live('click', function() {
			var url = $(this).attr('href');
			var button = $(this);
			button.css({ visibility: 'hidden' });
			button.css({ opacity: 0 });
			
			$.ajax({
				type: 'POST',
				url: url+'&ajax',
				success: function(data) {
					var json = $.parseJSON(data);
					if(json['conf'] == 'true'){
						if(json['colour_price_total']['total_formated']){
							button.closest('.product-item').find('.item-total').html(json['colour_price_total']['total_formated']);
						}
						
						button.closest('.size-entry').slideUp(function(){
							button.closest('.size-entry').remove();
							obj.checkSizes();
						});
						
						obj.parent.find(obj.total).html( json['summary']['total_formated'] );
						obj.parent.find(obj.count).html( json['summary']['bag'] );
					}
				}
			});
			return false;
		});
	},
	
	removeItemInit: function( element ){
		element.closest('.product-item').css({ height: element.closest('.product-item').height()+'px' });
		element.closest('.product-item').animate({ opacity: 0.7 }, 300);
	},
	
	removeItem: function( element ){
		element.closest('.product-item').animate({ width: 0, opacity: 0 }, 400, function(){
			element.closest('.product-item').remove();
		});
	},
	
	checkSizes: function(){
		var obj = this;
		this.parent.find('.product-item').each(function(){
			var sizeCont = $(this).find('.size-container');
			var items = sizeCont.find('.size-entry').length;
			if(items == 0){
				obj.removeItemInit( sizeCont );
				obj.removeItem( sizeCont );
			}
		});
	},
	
	quantity: function( qty, item_data, button, call_type ){
		var obj = this;
		
		button.addClass('processing');
		
		$.ajax({
			type: 'POST',
			url: '/basket/manage-basket?ajax',
			data: $.param({ quantity: qty, colorid: item_data }),
			success: function(data) {
				var json = $.parseJSON(data);
				button.removeClass('processing');
				
				if(json['conf'] == 'true'){
					button.removeClass('disabled');
					button.closest(obj.actions).find(obj.qty).html( qty );
					obj.parent.find(obj.total).html( json['summary']['total_formated'] );
					obj.parent.find(obj.count).html( json['summary']['bag'] );
					if(call_type == 'subtract'){
						button.closest(obj.actions).find(obj.increase).removeClass('disabled');
					}
					if(json['colour_price_total']['total_formated']){
						button.closest('.product-item').find('.item-total').html(json['colour_price_total']['total_formated']);
					}
				}else{
					if(qty == 0){
						button.closest(obj.actions).find(obj.qty).html( 0 );
						obj.parent.find(obj.total).html( json['summary']['total_formated'] );
						obj.parent.find(obj.count).html( json['summary']['bag'] );
						if(json['colour_price_total']['total_formated']){
							button.closest('.product-item').find('.item-total').html(json['colour_price_total']['total_formated']);
						}
					}else{
						button.addClass('disabled');
						tooltip(button);
					}
				}
				
			}
		
		});
	}
	
});

jQuery.fn.helicopter = function (elements,speed,delay) {
	var element = this;
	
	if( elements.length > 1 ){
		var counter = 0;
		$(elements).hide();
		$(elements[0]).show();
		setInterval(function() {
			$(elements[counter]).fadeOut('slow');
			 counter++;
			 if (counter == elements.length) {
				 counter = 0;
			 }
			$(elements[counter]).fadeIn(speed);
		}, delay);
	}
	
	return this;
}

var slideInterval;
function slide(el, end, time, direction){
	var existing_margin = parseInt( el.css('margin-left') );
	var future_margin = existing_margin + ( direction * end );
	var margin_step = Math.max( 1, parseInt( end / time) );
	var time_step = parseInt( Math.max( 1, margin_step * (time/end) ) );

	slideInterval = setInterval ( function(){
		var margin = parseInt( el.css('margin-left') );
		var next_margin = margin + ( direction * margin_step );

		if( next_margin <= future_margin && direction === -1 ){
			next_margin = future_margin;
			clearInterval( slideInterval );
			el.removeClass('animating');

			setTimeout( function(){
				if( !el.hasClass('stopped') ){
					$('.food-wine-page .food-wine-slide-show .right-arrow a').trigger('click');
				}
			}, 4000 );

			$('.food-wine-page .food-wine-slide-show .image:first').appendTo('.food-wine-page .food-wine-slide-show .slide-wrapper .slide-show');
			next_margin += end;
		}
		if( next_margin >= future_margin && direction === 1 ){
			next_margin = future_margin;
			clearInterval( slideInterval );
			el.removeClass('animating');

			setTimeout( function(){
				if( !el.hasClass('stopped') ){
					$('.food-wine-page .food-wine-slide-show .left-arrow a').trigger('click');
				}
			}, 4000 );
		}

		el.css({
			'margin-left' : next_margin+'px'
		});

	}, time_step );
}


$().ready(function() {
	
	$('.custom-pricing').customPricing();
	
	// home page rotating image
	$('.main-banner').rotatingImages();
	
	var $cart = $('#mini-cart');
	if ($cart.length > 0) {
		var basket_container = $('.basket-container').position();
		
		$cart.data('limit', $cart.position().top);

		if (!($.browser.msie && $.browser.version < 7)) $cart.css('position', 'fixed');
	  
		$(window).scroll(function() {
			var $offset;
			var $scroll;

			$offset = $cart.data('limit');
			$offset = basket_container.top;

			$scroll = $(window).scrollTop();
			if ($cart.css('position') == 'fixed') {
				$cart.css('top', Math.max(15, (-$scroll + $offset)) + 'px');
			}
			else {
				$cart.css('margin-top', Math.max(15, ($scroll - $offset)) + 'px');
			}
		}).trigger('scroll');
	}
	
	$('.basket-container').promocode();
	$('.basket-container').promohelper();
	
	$('.tooltip-button').live('click', function(){
		tooltip($(this)); 
	});
	
	$('.helper-info').mouseover(function() {
		$(this).unbind('mouseover');
		$('.helper-popup, .helper-info, .helper-popup2').delay(500).fadeOut(function() { $(this).hide(); });
  	});
	
	$('body').click(function(event){
		if($(event.target).closest('.helper-info').length == 0 && $('.helper-popup, .helper-info, .helper-popup2').is(':visible') && !$(event.target).is('a')){
			$('.helper-popup, .helper-info, .helper-popup2').delay(500).fadeOut(function() { $(this).hide(); });
		}
	});
	
	$('.remove-saved-item').click( function( e ) {	
		if( ! confirm( 'Warning: This item will be permanently removed from this saved basket.\n\nIf you want to remove it before purchase you can add all items to your basket and click remove on the basket page' ) ) {
			return false;
		} else {
			var id = '#' + $(this).closest('.saved-item').attr('id');
			
			$.ajax({
				type: 'POST',
				url: '/basket/_deleteSavedItem?ajax',
				data: $(this).closest('form').serialize(),
				success: function(data) {
					var json = $.parseJSON(data);
					
					if( json['redirect'] ) {
						window.location = json['redirect'];
					} else {
						$(id).slideUp('slow');
						
						$('#subtotal-value').html( json['new_subtotal'] );
					}
				}
			});
		}
		
		return false;
	} );

	$('#member-reg-form').submit( function() {
		$(this).find('input').each( function() {
			if( $(this).val() == $(this).attr('title') ) {
				$(this).val('');
			}
		});
	});
	
	// on hover gets the second product image (preloads it with .load())
	$('.double-image-load').categoryPage();
	
	//$('.product-box').productScroller();
	$('.recently-viewd-container').recentlyViewed();
	$('.recently-viewd-container .box').productScroller();
	
	$(".tab-container").tabs();
	$(".featured-prdct ").tabs();
	
	$('.basket-container').basketPageAction();
	$('#delivery-total').deliveryupdate();
	
	$('.popup-register .close-button a').click(function() {
		$button = $(this);
		$button.parents('.popup-register').find('.register-popup').fadeOut(300);
		$button.parents('.popup-register').find('#overlay').fadeOut(600, function(){
			$button.parents('.popup-register').hide();
		});
		
	});
	
	$('.payment-information .submit-secure-payment').click(function() {
		$('.payment-form').validation({validate : 'validate'});
		if($('.payment-form').hasClass('validated')){
			$('.popup-processing').center();
			$('.popup-processing').show();
		}
	});
	
	var wallpaper = getCookie('wallpaper');
	if(wallpaper.length > 0){
		$('body').css('background-image', wallpaper);
		$('body').css('background-repeat', 'repeat');
	}

	$('.customer-nav .wallpaper').wallpapers();
	
	var $signup_form = $('.confirmation-page .one-third');
	var $payment_page = $('.payment-page .one-third');
	
	if ($payment_page.length > 0 && $payment_page.length == 0) {
		$payment_page.data('limit', $payment_page.position().top);

		if (!($.browser.msie && $.browser.version < 7)) $payment_page.css('position', 'fixed');
	  
		$(window).scroll(function() {
			var $offset;
			var $scroll;
			
			var errorHeight = $('.error-text').height();
			
			$offset = $payment_page.data('limit');
			if(errorHeight > 0){
				$offset = 158+errorHeight+10;
			}else{
				$offset = 148;
			}
		 
			$scroll = $(window).scrollTop();
			if ($payment_page.css('position') == 'fixed') {
				$payment_page.css('top', Math.max(15, (-$scroll + $offset)) + 'px');
			}else {
				$payment_page.css('margin-top', Math.max(15, ($scroll - $offset)) + 'px');
			}
		}).trigger('scroll');
	}
	
	
	if ($signup_form.length > 0) {
		$signup_form.data('limit', $signup_form.position().top);

		if (!($.browser.msie && $.browser.version < 7)) $signup_form.css('position', 'fixed');
	  
		$(window).scroll(function() {
			var $offset;
			var $scroll;

			$offset = $signup_form.data('limit');
			$offset = 175;
			
			$scroll = $(window).scrollTop();
			if ($signup_form.css('position') == 'fixed') {
				$signup_form.css('top', Math.max(15, (-$scroll + $offset)) + 'px');
			}else {
				$signup_form.css('margin-top', Math.max(15, ($scroll - $offset)) + 'px');
			}
		}).trigger('scroll');
	}

	$('.payment-form .csv-example').csvtooltip();
	
	$('#rename-basket-form').validation();
	$('#rename-basket-form').ajaxform({
		reqclass:'validated', 
		change: function(data){
			var json = $.parseJSON(data);
			if(json['conf'] == 'success'){
				$('#rename-field').html(json['new_name']);
				$('#basket-mini-name-' + json['basket_id']).html(json['new_name'].substring(0,20) + '&hellip;');
				$('#basket-mini-name-' + json['basket_id']).attr( 'title', json['new_name'] );
			}
			
			$('.email-basket-form form input[type="text"]').val('');
			$('.email-basket-form form textarea').val('');
			
			if(!$.browser.msie){
				$('.popup-rename-basket').fadeOut();
			}else{
				$('.popup-rename-basket').show().delay(2000).hide();
			}
		}
	});
	
	$('.popup-button').popup();
	$('.free-downloads-style-page').downloadpopup();
	$('.request-pass').popup({ closebutton: '.retrieve-btn .cancel'});
	$('.email-basket').validation();
	$('.send-basket-email-form').validation();
	$('.email-basket .send').click(function(){
		$('.email-basket').submit();
	});
	
	
	$('.content-pad-small').sliderwidget({ container: '.category-scroller', item: '.item', handler: '.scroll-handler', itemcount: 4 });
	
	$('.login-form form').validation();
	$('.login-form form').submit(function(){
		
		if($(this).hasClass('validated')){
			var formdata = $(this).serialize();
			var form = $(this);
			
			$.ajax({
				type: 'POST',
				url: '/account/user-login?ajax',
				data: formdata,
				success: function(data) {
					var json = $.parseJSON(data);
					switch(json['conf']){
						case 'success':
							if( json['path'] ) {
								window.location = json['path'];
							} else {
								window.location = "/account";
							}
							break;
						case 'basket':
							var html = "<a title=\"My Account\" href=\"/account\">My Account</a><a href=\"/account/logout\" class=\"logout-link\">&nbsp;(Logout)</a>";
							$('.customer-nav').find('.account-section').html(html);
							$('.basket-container .promo-code').fadeOut(200, function(){
								$('.basket-container .promo-code-cont').fadeIn();
							});
							$(form).parents('.popup-login').fadeOut(400);
							break;
						case 'custom-hand-bag':
							window.location.reload();
							break;
						default:
							$('.popup-login').find('.error-msg').stop(true,true).fadeIn();
							break;
					}
				}
			
			});
		
		}
		
		return false;
	});
	
	$('.pwd-retrieve-popup .retrieve-submit').click(function() {
		var formcont = $(this).parents('form');
		var formdata = $(formcont).serialize();
		formcont.validation({validate: 'validate'});
		
		if(formcont.hasClass('validated')){
			$.ajax({
				type: 'POST',
				url: '/reset/email?ajax',
				data: formdata,
				success: function(data) {
					$('.pwd-retrieve-popup .valmsg:hidden').slideDown();
					$('.pwd-retrieve-popup .pwd-content').stop(true,true).fadeOut(function(){
						$('.pwd-retrieve-popup .close-button').fadeIn();
					});
				}
			
			});
		}
	});
	$('.pwd-retrieve-popup form').submit(function() {
		$('.pwd-retrieve-popup .retrieve-submit').click();
		return false;
	});
	
	$('.confirmation-page .payment-page .register-form .create-acc-btn a').click(function() {
		var validform = $(this);
		$(validform).parents('.register-form').find('form').validation({validate : 'validate'});
		if($(validform).parents('.register-form').find('form').hasClass('validated')){
			var formdata = $(validform).parents('.register-form').find('form').serialize();
			
			$.ajax({
				type: 'POST',
				url: '/account/order-account-create?ajax',
				data: formdata,
				success: function(data) {
					var json = $.parseJSON(data);
					
					switch(json['conf']){
						case 'success':
							$('.confirmation-page .register-left').fadeOut(400, function() {
								var html = "<div class=\"created-acc-success\"><h1 class=\"account-success\" title=\"Account Created Successfully\">Account Created Successfully</h1></div><div class=\"info\">We have sent you an email confirming your account details. You can also manage  your account using the link below.</div><div class=\"register-form\"><ul><li class=\"my-acc-btn\"><a title=\"My Account\" href=\"/account\">My Account</a></li></ul></div>";
								$('.confirmation-page .register-left').html(html);
							});
							$('.confirmation-page .register-left').fadeIn(400);
							
							break;
						case 'fail1':
							alert('Sorry your Passwords don\'t match');
							break;
						case 'fail2':
							alert('Password has to be at least 6 characters long');
							break;
						case 'fail3':
							alert('Account already exists');
							break;
					}
				}
				
			});
		}
		return false;
	});
	
	// this woz matiss 2011
	/* $('.new-acc-form form .sign-me-up').click(function(){
		$('.new-acc-form form').submit();
	}); */
	
	$('.new-acc-form form').validation();
    $('.new-acc-form form').submit(function(){
		if($(this).hasClass('validated')){
			var formdata = $(this).serialize();
			var email = $(this).find('input[name="email"]').val();
			var pass = $(this).find('input[name="pass1"]').val();
			$.ajax({
				type: 'POST',
				url: '/account/user-register?ajax',
				data: formdata,
				success: function(data) {
					var json = $.parseJSON(data);
					if(json['conf'] == 'success'){
						window.location = "/account";
					}else{
						$('.new-acc-popup .popup-error-message').remove();
						$('.new-acc-form').before('<div class="popup-error-message">This email has already been used to register an account or your passwords do not match. Please check and try again.</div>');
						$('.new-acc-popup .popup-error-message').fadeIn(3000, function(){
							$(this).delay(2000).fadeOut(3000,function(){
								$(this).remove();
							});
						});
					}
				}
			
			});
		}
		return false;
	});	
	
	$('.new-trade-form form .sign-me-up').click(function(){
		$('.new-trade-form form').submit();
		return false;
	});
	
	
	$('.new-trade-form form').submit(function(){
		if($(this).hasClass('validated')){
			var formdata = $(this).serialize();
			var email = $(this).find('input[name="email"]').val();
			var pass = $(this).find('input[name="pass1"]').val();
			
			$.ajax({
				type: 'POST',
				url: '/account/trade-register?ajax',
				data: formdata,
				success: function(data) {
					var json = $.parseJSON(data);
					if(json['conf'] == 'success'){
					
						$('.popup-trade-acc').fadeOut('slow');
						$('.popup-trade-acc-thanks').center();
						$('.popup-trade-acc-thanks').fadeIn();
						
						$('.popup-trade-acc-thanks a, .popup-trade-acc-thanks .overlay').live('click', function() {
							window.location = window.location;
						} );
						
					}else{
						$('.new-trade-popup .popup-error-message').remove();
						$('.new-trade-form').before('<div class="popup-error-message">'+json['conf']+'</div>');
						$('.new-trade-popup .popup-error-message').fadeIn(3000, function(){
							$(this).delay(2000).fadeOut(3000,function(){
								$(this).remove();
							});
						});
					}
				}
			
			});
			return false;
		}
		return false;
	});
	
	$('.popup-trade-acc-thanks').find('.close-button a, .overlay').click(function(){
		$('.popup-trade-acc-thanks').fadeOut();
	});
	
	
	
	$('.product .sizng-chart').live('click', function(){
		if($('.sizing-chart-box').find('.chart-image img').attr('src').length == 0){
			$('.sizing-chart-box').find('.chart-preloader').show();
			
			var image = $(this).next().attr('rel');
			$('.sizing-chart-box').find('.chart-image img').attr('src', image);
			$('<img />').attr('src', image).load(function(){
				$('.sizing-chart-box').find('.chart-preloader').fadeOut(400);
			});
		}
	});
	
});
