/* ########################################################################### *
/* ***** DOCUMENT INFO  ****************************************************** *
/* ########################################################################### *
 * ##### NAME:  global.js
/* ########################################################################### */

/**********************/
/* Init */
/**********************/
$(document).ready(custom_init);

/* Initialisation functions */
function custom_init()
{
	// Collection listing
	custom_collectionListing();

	// Collection listing overlay
	custom_collectionOverlay();
	
	// Collection keylook
	custom_collectionKeylook();
	
	// Modal windows
	custom_modal();
	
	// Contact form
	custom_contactForm();
}



/**********************/
/* Collection listing */
/**********************/
function custom_collectionListing()
{
	if ($(".collectionItemList").length > 0)
	{
		$(".collectionItemList li:nth-child(4n+1)").addClass('firstRowItem');
	}
}

/**********************/
/* Collection overlay */
/**********************/
function custom_collectionOverlay()
{
	if ($(".collectionItemList li a").length > 0)
	{
		$(".collectionItemList li a").tooltip({
			track: true,
			delay: 300,
			showURL: false,
			bodyHandler: function() 
			{
				return '<img src="' + $(this).attr("rel") + '" />';
			},		
			extraClass: "pretty fancy"
		});
	}
}


/**********************/
/* Collection keylook */
/**********************/
function custom_collectionKeylook()
{
	// Process key look
	if ($('.keylook').length > 0)
	{
		// Key look navigation
		var items = $('.nav_keylook_data');
		var prevUrl = '';
		var nextUrl = '';
		var activeItem = 0;
		var totalItems = $(items).find('li').length;
		
		// Check if one of the items is marked as active, if not, set the first to active
		var count = 0;
		$(items).find('li').each(function()
		{
			if ($(this).hasClass('active'))
			{
				activeItem = count;
			}
			count++;
		});
		
		// Show buttons
		$('.nav_keylook').removeClass('hidden');

		
		// Get the current URL
		var currentUrl = $(items).find('li:nth-child(' + (activeItem + 1) + ') .url').html();
		
		// Insert the page number
		var pageNumber = (activeItem + 1) + '&nbsp;of&nbsp;' + totalItems;
		$('.topLinks .pageNumber').html(pageNumber);

		// If active is not the first item then add the previous button
		if (activeItem > 0)
		{
			// Get the URL
			var url = $(items).find('li:nth-child(' + (activeItem) + ') .url').text();
			
			// Assign the URL to the previous button
			$('.nav_keylook .prev a').attr('href', url);
			
			// Show the button
			$('.nav_keylook .prev').hide().removeClass('hidden').fadeIn('slow');
		}
		
		// If active is not the last item then add the next button
		if ((activeItem + 1) < totalItems)
		{
			// Get the URL
			var url = $(items).find('li:nth-child(' + (activeItem + 2) + ') .url').text();
			
			// Assign the URL to the previous button
			$('.nav_keylook .next a').attr('href', url);
			
			// Show the button
			$('.nav_keylook .next').hide().removeClass('hidden').fadeIn('slow');
		}

	}
	
	// Product specifications
	if ($('.productSpecs').length > 0)
	{
		// Hidden fix
		$('.productSpecList .hidden').hide().removeClass('hidden');
		
		// Manage currencies
		$('.productSpecs .currencySelect .currency').each(function () 
		{
			$(this).removeClass('hidden');
			$(this).find('a').click(function () 
			{	
				// Get the currency code / class name
				var currencyCode = $(this).html();
				
				// Set cookie
				$.cookie('sussan_country', currencyCode);
				
				// Hide all prices
				$('.productSpecList .price').hide();
				
				// Show this currency
				$('.productSpecList').find('.' + currencyCode).show();
				
				// Remove active class
				$('.productSpecs .currency a').removeClass('active');
				
				// Add active class to this link
				$(this).addClass('active');
				
				// Prevent click
				return false;
			});	
		});	
		
		// Check if cookie is set
		if ($.cookie('sussan_country') != null)
		{
			// Trigger the click event on the respective currency
			$('.currency a.' + $.cookie('sussan_country')).click();
		}
	}
}

/**********************/
/* Modal window */
/**********************/

function custom_modal()
{
	$('.custom_modal').click(function (e) {
		e.preventDefault();

		// Get the URL for this ajax request
		var url = $(this).attr('href');
				
		// load the modal window using ajax
		$.get(url, function(data)
		{
			// create a modal dialog with the data
			$(data).modal({
				closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
				position: ["15%",],
				overlayId: 'modal-overlay',
				containerId: 'modal-container',
				maxHeight: 488,
				overlayClose: true,
				escClose: true,
				onOpen: modal.open,
				onShow: modal.show,
				onClose: modal.close
			});
		});
	});
	
	var modal = {
		message: null,
		open: function (dialog) {
			// add padding to the buttons in firefox/mozilla
			if ($.browser.mozilla) {
				$('#modal-container .contact-button').css({
					'padding-bottom': '2px'
				});
			}
			// input field font size
			if ($.browser.safari) {
				$('#modal-container .contact-input').css({
					'font-size': '.9em'
				});
			}
	
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200);
				});
			});
		},
		show: function (dialog) {
			$("#modal-container").css("height", "488px");
		},
		close: function (dialog) {
			$('#modal-container .contact-message').fadeOut();
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		}
	};
}


/**********************/
/* Contact form */
/**********************/
/*
 * SimpleModal Contact Form
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2009 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: contact.js 212 2009-09-03 05:33:44Z emartin24 $
 *
 */
var custom_contactFormUrl = '';
function custom_contactForm()
{
	$('#contact-form input.contact, #contact-form a.contact, .custom_sendToAFriend').click(function (e) {
		e.preventDefault();
		
		// Get the URL for this ajax request
		custom_contactFormUrl = $(this).attr('href');
		
		// load the contact form using ajax
		$.get(custom_contactFormUrl, function(data)
		{	
			// Insert the image from the current page
			var imgSrc = $('.keylookImage img').attr('src');
			var imgSrcSmall = $('.keylookImage img.keylookImage_sendToFriend').attr('src');
			
			// Update the retrieved ajax HTML
			var newData = $(data);
			
			// Insert the image
			$(newData).find('.contact-image').html('<img src="' + imgSrc + '" width="260" height="260" style="display:none;" />');
			
			// Add the image source URL reference for use in email post
			$(newData).find('#image_source').val(imgSrcSmall);
			
			// Save back the new changed ajax HTML
			data = newData;
			
			// create a modal dialog with the data
			$(data).modal({
				position: ["15%",],
				overlayId: 'modal-overlay',
				containerId: 'modal-container',
				maxHeight: 450,
				overlayClose: true,
				escClose: true,
				onOpen: contact.open,
				onShow: contact.show,
				onClose: contact.close
			});
		});
	});
	
	var contact = {
		message: null,
		open: function (dialog) {
			// add padding to the buttons in firefox/mozilla
			if ($.browser.mozilla) {
				$('#modal-container .contact-button').css({
					'padding-bottom': '2px'
				});
			}
			// input field font size
			if ($.browser.safari) {
				$('#modal-container .contact-input').css({
					'font-size': '.9em'
				});
			}
	
			// dynamically determine height
			var h = 475;
			if ($('#contact-subject').length) {
				h += 26;
			}
			if ($('#contact-cc').length) {
				h += 22;
			}
	
			var title = $('#modal-container .contact-title').html();
			$('#modal-container .contact-title').html('').hide();
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200, function () {
						$('#modal-container .contact-content').animate({
							height: h
						}, function () {
							$('#modal-container .contact-title').html(title).fadeIn(200);
							$('#modal-container .contact-image img').fadeIn(1000);
							$('#modal-container form').fadeIn(200, function () {
								$('#modal-container #contact-name').focus();
	
								$('#modal-container .contact-cc').click(function () {
									var cc = $('#modal-container #contact-cc');
									cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
								});
	
								// fix png's for IE 6
								if ($.browser.msie && $.browser.version < 7) {
									$('#modal-container .contact-button').each(function () {
										if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
											var src = RegExp.$1;
											$(this).css({
												backgroundImage: 'none',
												filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
											});
										}
									});
								}
							});
						});
					});
				});
			});
		},
		show: function (dialog) {
			$('#modal-container .contact-send').click(function (e) {
				e.preventDefault();
				// validate form
				if (contact.validate()) {
					var msg = $('#modal-container .contact-message');
					msg.fadeOut(function () {
						msg.removeClass('contact-error').empty();
					});
					$('#modal-container .contact-title').html('Sending...');
					$('#modal-container .contact-image').fadeOut(200);
					$('#modal-container form').fadeOut(200);
					$('#modal-container .contact-content').animate({
						height: '80px'
					}, function () {
						$('#modal-container .contact-loading').fadeIn(200, function () {
							$.ajax({
								url: custom_contactFormUrl,
								data: $('#modal-container form').serialize() + '&action=send',
								type: 'post',
								cache: false,
								dataType: 'html',
								success: function (data) {
									$('#modal-container .contact-loading').fadeOut(200, function () {
										$('#modal-container .contact-title').html('Thank you.');
										msg.html(data).fadeIn(1500, function() 
										{
											$.modal.close();	
										});
									});
								},
								error: contact.error
							});
						});
					});
				}
				else {
					if ($('#modal-container .contact-message:visible').length > 0) {
						var msg = $('#modal-container .contact-message div');
						msg.fadeOut(200, function () {
							msg.empty();
							contact.showError();
							msg.fadeIn(200);
						});
					}
					else {
						/*
						$('#modal-container .contact-message').animate({
							height: '30px'
						}, contact.showError);
						*/
					}
					
				}
			});
		},
		close: function (dialog) {
			$('#modal-container .contact-message').fadeOut();
			$('#modal-container .contact-title').fadeOut(200, function () { $(this).html(''); });;
			$('#modal-container .contact-image').fadeOut(200);
			$('#modal-container form').fadeOut(200);
			$('#modal-container .contact-content').animate({
				height: 40
			}, function () {
				dialog.data.fadeOut(200, function () {
					dialog.container.fadeOut(200, function () {
						dialog.overlay.fadeOut(200, function () {
							$.modal.close();
						});
					});
				});
			});
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		validate: function () {
			// Remove previous validation errors
			$('#modal-container .error').removeClass('error');
			
			contact.message = '';
			if (!$('#modal-container #contact-name').val()) {
				contact.message += 'Name is required. ';
				$('#modal-container #contact-name').addClass('error');
			}
	
			var email = $('#modal-container #contact-email').val();
			if (!email) {
				contact.message += 'Email is required. ';
				$('#modal-container #contact-email').addClass('error');
			}
			else {
				if (!contact.validateEmail(email)) {
					contact.message += 'Email is invalid. ';
					$('#modal-container #contact-email').addClass('error');
				}
			}
			
			if (!$('#modal-container #contact-name2').val()) {
				contact.message += 'Name is required. ';
				$('#modal-container #contact-name2').addClass('error');
			}
	
			var email = $('#modal-container #contact-email2').val();
			if (!email) {
				contact.message += 'Email is required. ';
				$('#modal-container #contact-email2').addClass('error');
			}
			else {
				if (!contact.validateEmail(email)) {
					contact.message += 'Email is invalid. ';
					$('#modal-container #contact-email2').addClass('error');
				}
			}
				
			/*
			if (!$('#modal-container #contact-message').val()) {
				contact.message += 'Message is required.';
			}
			*/
	
			// Check if any errors have been found
			if (contact.message.length > 0) {
				return false;
			}
			else {
				return true;
			}
			
		},
		validateEmail: function (email) {
			var at = email.lastIndexOf("@");
	
			// Make sure the at (@) sybmol exists and  
			// it is not the first or last character
			if (at < 1 || (at + 1) === email.length)
				return false;
	
			// Make sure there aren't multiple periods together
			if (/(\.{2,})/.test(email))
				return false;
	
			// Break up the local and domain portions
			var local = email.substring(0, at);
			var domain = email.substring(at + 1);
	
			// Check lengths
			if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
				return false;
	
			// Make sure local and domain don't start with or end with a period
			if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
				return false;
	
			// Check for quoted-string addresses
			// Since almost anything is allowed in a quoted-string address,
			// we're just going to let them go through
			if (!/^"(.+)"$/.test(local)) {
				// It's a dot-string address...check for valid characters
				if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
					return false;
			}
	
			// Make sure domain contains only valid characters and at least one period
			if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
				return false;	
	
			return true;
		},
		showError: function () {
			/*
			$('#modal-container .contact-message')
				.html($('<div class="contact-error"></div>').append(contact.message))
				.fadeIn(200);
			*/
		}
	};
}




/**********************/
/* END */