
// Slide show utility functions.
function paginate(index, element) {
	var slide = $(element).attr('id');
	return '<li class="inactive"><a href="#" title="' + slideshow_icons[slide].title + '"><img src="' + slideshow_icons[slide].active  + '" alt="' + slideshow_icons[slide].title + '" class="active" /><img src="' + slideshow_icons[slide].inactive  + '" alt="' + slideshow_icons[slide].title + '" class="inactive" /></a></li>';
}

function update_pager(pager, currSlideIndex) { 
    $(pager).find('li').removeClass('active').addClass('inactive').filter('li:eq('+currSlideIndex+')').removeClass('inactive').addClass('active'); 
};


$(document).ready(function() {
	
	// Popups - we're getting the titles from the h2s in the content divs and then removing the h2s
	$('a.zoom, div.box.zoom').each(function() {
		
		// Work out the box title from the H2
		if ($(this).attr('href')) {
			var selector = $(this).attr('href');
		} else {
			var selector = $(this).children('a:first').attr('href');
		}
		
		
		var title = $(selector).find('h2:first');
		
		var options = {
			directory: '/sites/twozero/images/zoom',
			title:     title.html(),
			target:    selector
		};
		
		if (selector.search('gallery') != -1) {
			selector = 'gallery';
		} else if (selector.search('asset') != -1) {
			selector = 'asset';
		}
		
		switch(selector)
		{
			case '#contact_us':
				options.width  = 480;
				options.height = 520;
				break;
			case '#store_locator':
				options.width  = 480;
				options.height = 250;
				options.background = '/sites/twozero/images/backgrounds/storelocator.png';
				options.title  = 'Store Locator';
				break;
			case 'gallery':
				options.width  = 555;
				options.height = 410;
				break;
			case 'asset':
				options.width  = 555;
				options.height = 500;
				break;
				
				case '#indicazioni':
				options.width  = 500;
				options.height = 400;
				break;
				
				case '#informazioni-aziendali':
				options.width  = 400;
				options.height = 400;
				break;

               case '#certificazioni':
				options.width  = 700;
				options.height = 400;
				break;


			default:
				options.width  = 700;
				options.height = 400;
				break;
		}
		
			});
	
	// Remove the titles after adding the zoom event so that duplicate links don't break.
	$('a.zoom, div.box.zoom').each(function() {
		if ($(this).attr('href')) {
			var selector = $(this).attr('href');
		} else {
			var selector = $(this).children('a:first').attr('href');
		}
		var title = $(selector).find('h2:first');
		title.remove();
	});
	
	// Contact Us nav option to make selected when popup opens and reset the form.
	$('a.zoom').click(function() {
		
		if (this.href.substring(this.href.length - 11) == '#contact_us') {
			
			var selected = $('ul#navigation').find('li.active');
			
			$('ul#navigation').data('selected', selected);
			
			$('a#zoom_close').click(function() {
				
				var selected = $('ul#navigation').data('selected');
				$('ul#navigation li').removeClass('active');
				selected.addClass('active');
			});
			
			$('ul#navigation li').removeClass('active');
			$('ul#navigation li#nav-contact_us').addClass('active');
			
			// Reset the form status
			$('div#contact-form-success').hide();
			
			
			$('form#contact-form-retailer')[0].reset();
			$('form#contact-form-consumer')[0].reset();
					
			
			$('div#contact-form').show();
		}
		
	});
	
	
	// Slide show on home page.	
	$('ul#slideshow-nav').empty();
	$('ul#slideshow').cycle({
		fx: 'fade',
		timeout: 7500,
		pager: 'ul#slideshow-nav',
		pagerAnchorBuilder: paginate,
		updateActivePagerLink: update_pager
	});
	
	
	// Contact form
	$('fieldset#contact-select input').change(function() {
		$('form#contact-form-consumer').hide();
		$('form#contact-form-retailer').hide();
		$('form#contact-form-' + this.value).show();
		$('form#contact-form-consumer div.error').hide();
		$('form#contact-form-retailer div.error').hide();
		$('form#contact-form-consumer div.error ul#form-errors').empty();
		$('form#contact-form-retailer div.error ul#form-errors').empty();
	});
	
	$('form#contact-form-consumer, form#contact-form-retailer').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').hide();
		     $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) { 
		
			var response = $form.find('div#form-response');
			response.html(rtn);
			
			if (rtn == "success") {
	  			$('div#contact-form-success').show();
				$('div#contact-form').hide();
			} else {
				$form.find('div.error').show().find('#form-errors').html(response.find('#content ul').html());
				$form.find('button').show();
				$form.find('div.progress').hide();
			}
			
			response.empty();
		}
	});
	
	
	$('form#shop-contact-form').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').hide();
		     $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) { 
		
			var response = $form.find('div#form-response');
			response.html(rtn);
			
			if (rtn == "success") {
	  			$('div#shop-contact-form-success').show();
				$('form#shop-contact-form').hide();
			} else {
				$form.find('div.error').show().find('#form-errors').html(response.find('#content ul').html());
				$form.find('button').show();
				$form.find('div.progress').hide();
			}
			
			response.empty();
		}
	});
	
	// Registration form
	$('form#register_member_form').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').hide();
		     $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) {
			
			// Populate the response div. Target option results in two calls for some reason.
			var response = $form.find('div#form-response');
			response.html(rtn);
			
			var title = response.find('h1:first').html();

			switch (title) {
				case 'Thank You!':
					// Show thanks message
					window.location = 'http://' + window.location.host + '/registration-successful';
					break;
				default:
					$form.find('div.error').show().find('#form-errors').html(response.find('#content ul').html());
					$form.find('button').show();
					$form.find('div.progress').hide();
					break;
			}
			
			response.empty();
		}
	});
	
	// Forgotten password form
	$('form#forgot_password_form').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').hide();
		     $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) {
			
			// Populate the response div. Target option results in two calls for some reason.
			var response = $form.find('div#form-response');
			response.html(rtn);
			
			var title = response.find('h1:first').html();

			switch (title) {
				case 'Thank You!':
					// Show thanks message
					window.location = 'http://' + window.location.host + '/password-reset-email-sent';
					break;
				default:
					$form.find('div.error').show().find('#form-errors').html(response.find('#content ul').html());
					$form.find('button').show();
					$form.find('div.progress').hide();
					break;
			}
			
			response.empty();
		}
	});
	
	// Login form
	$('form[name="login"]').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').hide();
		     $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) {
			
			if (rtn == "success") {
				window.location = 'http://' + window.location.host + '/assets';
				
			} else {
				// Populate the response div. Target option results in two calls for some reason.
				var response = $form.find('div#form-response');
				response.html(rtn);
				$form.find('div.error').show().find('#form-errors').html(response.find('#content ul').html());
				$form.find('button').show();
				$form.find('div.progress').hide();
				response.empty();
			}
		}
	});
	
	// Update account forms
	$('form#update_email, form#update_username_password').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').hide();
		     $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) {
			
			// Populate the response div. Target option results in two calls for some reason.
			var response = $form.find('div#form-response');
			response.html(rtn);
			
			var title = response.find('h1:first').html();

			switch (title) {
				case 'Email Preferences Updated':
					// Show thanks message
					window.location = 'http://' + window.location.host + '/account-updated';
					break;
				case 'Username and Password':
					// Show thanks message
					window.location = 'http://' + window.location.host + '/account-updated';
					break;
				default:
					$form.find('div.error').show().find('#form-errors').html(response.find('#content ul').html());
					$form.find('button').show();
					$form.find('div.progress').hide();
					break;
			}
			
			response.empty();
		}
	});
	
	
	// Store Locator
	$('#storelocator-content select').change(function() {
		
		var value = this.value
		
		if (value == '') {
			$('#storelocator-content ul.stores').fadeOut();
			$('#storelocator-content > p').animate({opacity: '1.0'}).fadeIn();
		} else {
			$('#storelocator-content > p').fadeOut();
			$('#storelocator-content ul.stores').fadeOut();
			$('#storelocator-content ul#stores-' + value).animate({opacity: '1.0'}).fadeIn();
		}
	});
	
	
	// Basket preview
	$('li#basket-preview div').data('clicked', false);
	
	$('li#basket-preview').click(function() {
		
		$('li#basket-preview').addClass('active');
		$('li#basket-preview div').data('clicked', true).fadeIn();		
	});
	
	$('html').click(function() {
		
		if ($('li#basket-preview div').data('clicked') != true) {
			
			$('li#basket-preview').removeClass('active');
			$('li#basket-preview div:visible').hide();
		}
		
		$('li#basket-preview div').data('clicked', false);
	});
	
	// Re-usable function to add delete from basket handler.
	var deleteHandler = function() {
		
		$.ajax({
			url: this.href,
			cache: false,
			success: function(html){
				$('li#basket-preview div').empty().append(html);
				
				// Add the delete handlers to the new basket.
				$('li#basket-preview div table td.delete a').click(deleteHandler);
			}
		});
		
		return false;
	}
	
	// Add delete from basket handler to initial basket.
	$('li#basket-preview div table td.delete a').click(deleteHandler);
	
	$('li#basket-preview form button#checkout').click();
	
	
	// Add to basket form
	$('form.addtobasket').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
		     $form.find('button').attr('value', 'Adding...').html('Adding...').attr('disabled', 'disabled');
		},
	    success: function(rtn, status, xhr, $form) {
			
			var result = jQuery.parseJSON(rtn);
			
			if (result.success == 1) {
			
				$.ajax({
					url: '/basket',
					cache: false,
					success: function(html){
				
						// Replace the basket contents.
						$('li#basket-preview div').empty().append(html).fadeIn();
						$('li#basket-preview').addClass('active');
				
						// Add the delete handlers to the new basket.
						$('li#basket-preview div table td.delete a').click(deleteHandler);
				
						// Re-activate the button.
						$form.find('button').removeAttr('disabled').attr('value', 'Buy Now').html('Buy Now');
					}
				});
				
			} else {
				alert(result.msgs);
				$form.find('button').removeAttr('disabled').attr('value', 'Buy Now').html('Buy Now');
			}
		}
	});
	
	// Shipping address use billing info checkbox.
	$('.checkout input[name="use_billing_info"]').change(function() {
		
		if (this.checked) {
			// Copy the billing address values to the shipping address and disable the fields.
	        $('.checkout fieldset.shipping input:not(input[name="use_billing_info"])').val(function(index, value) {
				//$(this).attr('disabled', 'disabled');
				return $('.checkout fieldset.billing input[name="' + this.name.substr(9) + '"]').val();
			});
			
			$(this).attr('checked', 'checked');

	        return;
	    }
		
		// Clear and enable the fields.
		$('.checkout fieldset.shipping input').removeAttr('disabled');
	});
	
	// Update the shipping address fields if they're disabled.
	$('.checkout fieldset.billing input').bind('textchange', function() {
		if ($('.checkout input[name="use_billing_info"]').attr('checked')) {
			$('.checkout fieldset.shipping input[name="shipping_' + this.name + '"]').val(this.value);
		}
	});
	
	// Add to basket form
	$('form#coupon').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
			$form.find('button').attr('value', 'Adding...').html('Adding...').attr('disabled', 'disabled');
			
			if ($form.find('input#coupon_code').val() == '') {
				$form.find('button').removeAttr('disabled').attr('value', 'Apply').html('Apply');
				alert('Please enter a discount code.');
				return false;
			}
		},
	    success: function(rtn, status, xhr, $form) {

			var result = jQuery.parseJSON(rtn);
					
			if (result.success == 1) {
			
				$.ajax({
					url: '/basket/checkout',
					cache: false,
					success: function(html){
						
						// Replace the basket contents.
						$('div.basket').empty().append(html);
				
						// Re-activate the button.
						$form.find('button').removeAttr('disabled').attr('value', 'Apply').html('Apply');
					}
				});
				
			} else {
				alert(result.msgs);
				$form.find('button').removeAttr('disabled').attr('value', 'Apply').html('Apply');
			}
		}
	});
	
	
	var display_errors = function(form, errors, error_title) {
		form.find('div.error').show().find('#form-errors').html(errors);
		form.find('div.error').find('h3').html(error_title);
		form.find('button').show();
		form.find('div.progress').hide();
		window.location = '#errors';
	}
	
	
	// Checkout form
	$('form#checkout').ajaxForm({
		
		target: false,
		
		beforeSubmit: function(arr, $form, options) {
			
			if ($form.find('input#agree_terms:checked').val() == null) {
				alert('Please check the box to confirm you agree to the Terms & Conditions of sale.');
				return false;
			}
			
			$form.find('button').hide();
		    $form.find('div.progress').show();
		},
	    success: function(rtn, status, xhr, $form) {
			
			var error_title = '';
			var errors = '';
					
			if (rtn == '') {
				
				$.ajax({
					
					url: '/checkout/json-response',
					cache: false,
					success: function(rtn) {
						
						var result = jQuery.parseJSON(rtn);
						
						if (result.authorized) {
							// Show thanks message
							window.location = 'http://' + window.location.host + '/checkout/order';
							return true;
						} else {
							error_title = "We're sorry, but your payment was unsuccessful"
							errors = '<li>' + result.error_message + '</li>';
							display_errors($form, errors, error_title);
						}
					}
				});
				
			} else {
			
				// Populate the response div. Target option results in two calls for some reason.
				var response = $form.find('div#form-response');
				response.html(rtn);
			
				error_title = response.find('h1:first').html();
				errors = response.find('#content ul').html()
				response.empty();
				
				display_errors($form, errors, error_title);
			}
		}
	});
	
	
	$('ul#shop-tabs li a').click(function() {
		
		$('ul#shop-tabs li').removeClass('active');
		$(this).parent().addClass('active');
		
		$('ul.shop-products, div#shop-about, div#shop-contact').hide();
		$('div#shop').removeClass('contact').removeClass('about');
		
		if ($(this).parent().attr('id') == 'shop-tab-featured') {
			$('ul.shop-products').show();
		} else if ($(this).parent().attr('id') == 'shop-tab-about') {
			$('div#shop-about').show();
			$('div#shop').addClass('about');
		} else if ($(this).parent().attr('id') == 'shop-tab-contact') {
			$('div#shop-contact').show();
			$('div#shop').addClass('contact');
		}
		
		return false;
	});
});
