/**
 * Vive JS
 *
 * The custom JavaScript used for the added functionality for vivebags.com
 *
 * @author Dan Hensby <dan@betterbrief.co.uk>
 * @author Josh Holloway <josh@betterbrief.co.uk>
 * @version 0.4
 * @copyright 2010, Better Brief LLP
 */

google.load("jquery", "1.4");

// Email Validator
function echeck(str) {

	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false
	 }

	 return true					
}
	
function xss_ajax(url) {
	var script_id = null;
	var script = document.createElement('script');
	script.setAttribute('type', 'text/javascript');
	script.setAttribute('src', url);
	script.setAttribute('id', 'script_id');

	script_id = document.getElementById('script_id');
	if(script_id) {
		document.getElementsByTagName('head')[0].removeChild(script_id);
	}
	return document.getElementsByTagName('head')[0].appendChild(script);
}


function inArray(array,val,col) {
	for (var i in array) {
		if (col != undefined){
			if (array[i][col] == val){
				return true;
			}
		}
		else {
			if (array[i] == val) {
				return true;
			}
		}
	}
	return false;
}

google.setOnLoadCallback(function() {
	var J = jQuery.noConflict();
	J(function($) {

		function startOverlay(overlayLink,altText,position) {
			$('body').append(
				'<div class="overlay"></div><div class="overlayContainer"><div class="contents"><p><a href="#">Close</a> or press esc</p></div><img src="'+overlayLink+'" alt="'+altText+'" /></div>'
			).children('.overlay').css({
				'height':$('body').outerHeight(),
				'min-height': '100%'
			}).animate({
				'opacity':'0.6'},200,'linear'
			).click(function() {
				var $this = $('.overlayContainer, .overlay');
				$this.stop().animate({
					'opacity':'0'
				},200,'linear', function() {
					$this.remove();
				});
				return false;
			}).siblings('.overlayContainer').css({
				"left":       position.left,
				"top":        position.top
			}).animate({"opacity":"1"}, 200, "linear").children('.contents').children('p').children('a').click(function() {
				$('.overlay').click();
				return false;
			});
			
			$(document).keyup(function(event) {
				if (event.keyCode == 27 && $('.overlay').length) {
					$('.overlay').click();
				}
			});
		}
		
		$('body').fadeIn('fast');
		
		/**
		 * Fixing inline submit button issues for different browsers
		 */
		if ($.browser.firefox() && $.browser.version.number() < 3.6) {
			$('#NewsletterSubmit').css('top','3px');
		 }
		else if ($.browser.firefox() || $.browser.mozilla() || ($.browser.safari() && $.browser.win())) {
			$('#NewsletterSubmit').css('top','1px');
		}
		
		/**
		 * Inline Labels
		 *
		 * Moves the labels from a form into the input box.
		 */
		jQuery('label').each(function() {
			var label = jQuery(this);
			var labelText = label.text();
			var input = jQuery('#' + label.attr('for'));
			if (input.attr('type') == 'text' || input.attr('type') == 'textarea' || input.attr('type') == 'password' || input.attr('rel') == 'hide') {
				label.hide();
				if (input.val() == '') {
					input.val(labelText);
				}
				input.focus(function() {
					if (input.val() == labelText) {
						input.val('');
					}
				}).blur(function() {
					if (input.val() == '') {
						input.val(labelText);
					}
				});
			}
		});
		
		/**
		 * Accordion Code
		 *
		 * Creates an accordion from an unordered list
		 *
		 */
		var $accordItems = jQuery('#Accord li');
		$accordItems.each(function() {
			var $this = $(this);
			var liHeight = $this.height();
			$this.removeClass('on').css('height', '16px').children('h2').click(function() {
				if ($this.is('.on')) {
					$this.stop().animate({'height':'16px'},'slow',null,$this.removeClass('on'));
				}
				else {
					$this.stop().animate({'height':liHeight + 'px'},'slow',null,$this.addClass('on'));
				}
			});
		});
		if ($accordItems.length == 1) {
			$accordItems.children('h2').click();
		}
		
		/**
		 * Site Menu
		 *
		 * Collapsing nested lists in the side menu
		 *
		 */
		jQuery('#Menu li').each(function() {
			var $this = $(this);
			var $kids = $this.children('ul');
			if ($kids.length && !($this.is('.section') || $this.is('.current'))) {
				var liHeight = $this.height();
				$kids.hide();
				var liCollapsedHeight = $this.height();
				$this.css({
					'height': liCollapsedHeight + 'px',
					'overflow': 'hidden'
				});
				$kids.show();
				$this.hover(function() {
					$this.stop(true,false).animate({
						'height': liHeight + 'px'
					},'700');
				}, function() {
					$this.stop(true,false).animate({
						'height': liCollapsedHeight + 'px'
					},'700');
				});
			}
		});
		
		/**
		 * Footer Links
		 *
		 * Open external links in a new window...
		 *
		 */
		jQuery('#Credits a, #Social a').attr('target','_blank');
		
		/**
		 * Homepage news items slider
		 *
		 * Slides the news items along when
		 *
		 * @todo have an interupt so animations don't que for so long
		 * 
		 */
		if ($('#HomePage').length) {
			
			$('#Items li:not(:first-child)').hide();
			
			var paginatorHTML = '<ul id="Pagnator">';
			$Items = $('#Items');
			
			$Items.children().each(function() {
				var $this = $(this);
				$this.hover(function(){
					$this.addClass('hover');
					$this.children().children('img.off').fadeOut('400');
					$this.children().children('img.on').fadeIn('fast');
				},
				function() {
					$this.removeClass('hover');
					$this.children().children('img.on').fadeOut('400');
					$this.children().children('img.off').fadeIn('fast');
				});
				paginatorHTML += '<li';
				if (!$this.index()) {
					paginatorHTML += ' class="current"';
				}
				paginatorHTML += '><a href="#" rel="' + $this.attr('id') + '">Item ' + ($this.index() + 1) + '</a></li>';
			}).parent().parent().append(paginatorHTML + '</ul>');
			
			$('#Pagnator a').click(function() {
				var $this = $(this);
				$('#' + $this.attr('rel')).show().siblings().hide();
				$this.parent().addClass('current').siblings().removeClass('current');
				return false;
			});
			
			setInterval(function() {
				if (!$('#Items .hover').length) {
					var $Pagnator = $('#Pagnator');
					var currentItemNum = $Pagnator.children('li.current').index() + 1;
					var numItems = $Pagnator.children().length;
					var nextItem = 1;
					if (currentItemNum != numItems) {
						nextItem = currentItemNum + 1;
					}
					$Pagnator.children('li:nth-child(' + nextItem + ')').children().click();
				}
			}, 5000)
			
		}
		
		/**
		 * Stockist Page
		 *
		 * @todo optimise code!
		 */
		if ($('#StockistsPage').length) {
			/* Stockists AJAX */
			
			//Set elements we need
			var $Stockists = $("#Stockists");
			var $Loading = $("#Loading");
			var $Form = $('#StockistsForm');
			var $action = $Form.attr("action") + '/getMyStockists?ajax';
			var $Country = $Form.children().children("#Country");
			var $Region = $Form.children().children("#Region");
			var $City = $Form.children().children("#City");
			var kids = new Array();
			var $init = $('#InitialContent');
			
			$init.show();
			$('#StockSubmit').hide();
			$Stockists.hide();
			
			$Country.children().each(function() {
				var $this = $(this);
				if ($this.val() > 0) {
					kids.push(new Array($this.val(),$this.attr('rel'),$this.html()));
				}
			}).parent().each(function() {
				jQuery.data($Country,'countries',kids);
			}).change(function(obj,ajax){
				$init.remove();
				if (ajax == undefined) {
					ajax = true;
				}
				var regions = jQuery.data($Region,'regions');
				var cities = jQuery.data($City,'cities');
				var string = '<option value="0">choose a region</option>';
				var validRegions = new Array();
				$Region.html('<option value="0">please wait...</option>');
				for (var i in regions) {
					if ($Country.val() == 0){
						string += '<option rel="' + regions[i][1] + '" value="' + regions[i][0] + '">' + regions[i][2] + '</option>';
					}
					else if (regions[i][1] == $Country.val()) {
						validRegions.push(regions[i][0]);
						string += '<option rel="' + regions[i][1] + '" value="' + regions[i][0] + '">' + regions[i][2] + '</option>';
					}
				}
				$Region.html(string);
				var string = '<option value="0">choose a city</option>';
				for (var i in cities) {
					if ($Country.val() == 0 && $Region.val() == 0){
						string += '<option rel="' + cities[i][1] + '" value="' + cities[i][0] + '">' + cities[i][2] + '</option>';
					}
					else if (inArray(validRegions,cities[i][1])) {
						string += '<option rel="' + cities[i][1] + '" value="' + cities[i][0] + '">' + cities[i][2] + '</option>';
					}
				}
				$City.html(string);
				if (ajax) {
					var hashLink = '';
					if ($Country.val() > 0) {
						hashLink += '&country=' + $Country.val();
					}
					if ($Region.val() > 0) {
						hashLink += '&region=' + $Region.val();
					}
					if ($City.val() > 0) {
						hashLink += '&city=' + $City.val();
					}
					window.location.hash = '#' + hashLink; //write hash
					$Stockists.load($action + hashLink);
				}
			});
			var kids = new Array();
			
			$Region.children().each(function() {
				var $this = $(this);
				if ($this.val() > 0) {
					kids.push(new Array($this.val(),$this.attr('rel'),$this.html()));
				}
			}).parent().each(function() {
				jQuery.data($Region,'regions',kids);
			}).change(function(obj,ajax){
				$init.remove();
				if (ajax == undefined) {
					ajax = true;
				}
				var cities = jQuery.data($City,'cities');
				var string = '<option value="0">choose a city</option>';
				var validCities = new Array();
				$City.html('<option value="0">please wait...</option>');
				for (var i in cities) {
					if ($Region.val() == 0){
						string += '<option rel="' + cities[i][1] + '" value="' + cities[i][0] + '">' + cities[i][2] + '</option>';
					}
					else if (cities[i][1] == $Region.val()) {
						validCities.push(cities[i][0]);
						string += '<option rel="' + cities[i][1] + '" value="' + cities[i][0] + '">' + cities[i][2] + '</option>';
					}
				}
				$City.html(string);
				$Country.val($Region.children('[value=' + $Region.val() + ']').attr('rel'));
				if (ajax) {
					var hashLink = '';
					if ($Country.val() > 0) {
						hashLink += '&country=' + $Country.val();
					}
					if ($Region.val() > 0) {
						hashLink += '&region=' + $Region.val();
					}
					if ($City.val() > 0) {
						hashLink += '&city=' + $City.val();
					}
					window.location.hash = '#' + hashLink; //write hash
					$Stockists.load($action + hashLink);
				}
			});
			var kids = new Array();
			
			$City.children().each(function() {
				var $this = $(this);
				if ($this.val() > 0) {
					kids.push(new Array($this.val(),$this.attr('rel'),$this.html()));
				}
			}).parent().each(function() {
				jQuery.data($City,'cities',kids);
			}).change(function(obj,ajax){
				$init.remove();
				if (ajax == undefined) {
					ajax = true;
				}
				$Region.val($City.children('[value=' + $City.val() + ']').attr('rel'));
				$Country.val($Region.children('[value=' + $Region.val() + ']').attr('rel'));
				if (ajax) {
					var hashLink = '';
					if ($Country.val() > 0) {
						hashLink += '&country=' + $Country.val();
					}
					if ($Region.val() > 0) {
						hashLink += '&region=' + $Region.val();
					}
					if ($City.val() > 0) {
						hashLink += '&city=' + $City.val();
					}
					window.location.hash = '#' + hashLink; //write hash
					$Stockists.load($action + hashLink);
				}
			});
			
			if (window.location.hash) {
				//$Loading.ajaxStart();
				$init.remove();
				//$Stockists.hide();
				var hashLink = window.location.hash.replace('#','');
				var tempArray = new Array();
				$Stockists.load($action + hashLink);
				hashArray = window.location.hash.replace('#&','').replace('#').split('&').reverse();
				var tempArray = hashArray[0].split('=');
				if (tempArray[0] == 'city') {
					$City.val(tempArray[1]).change({},false);
				}
				else if (tempArray[0] == 'region') {
					$Region.val(tempArray[1]).change({},false);
				}
				else if (tempArray[0] == 'country') {
					$Country.val(tempArray[1]).change({},false);
				}
			}
			
			$Loading.ajaxStart(function(){
				//When the ajax call is started...
				var $Content = $('#Content'); //get the Content div
				$Content.css('height', $Content.height()); //fix its height
				$Stockists.hide(); //hide the stockists
				$Loading.show(); //show the loading image
			}).ajaxStop(function(){
				//when the ajax is complete
				$Loading.hide(); //hide the loading image
				$Stockists.fadeIn('slow'); //fade in the results
				//Calculate the hieght of the content div and then slide it up/down
				//We need to know how tall to make the Content div, thus we need
				//the height of all the elements inside it + the new #Stockits' height
				var offset = 0; //this is the height of all the other elements
				var minHeight = $('#Sidebar').height(); //the smallest the content can be is the height of the sidebar (this makes animation much smoother)
				var stockistHeight = $('#Stockists').height(); //height of the new Stockists result
				if (stockistHeight < minHeight) { //if the new height of stockists is less than the sidebar, we set the real height to it.
					var realHeight = minHeight;
				}
				$('#Content').stop().children(':not(#Stockists)').each(function() { //get the heights of all the children of content (that aren't the stockists, obv)
					//var $this = $(this);
					offset += $(this).outerHeight(); //get the full height
					if ((stockistHeight + offset) > minHeight) { //if the new 'real height' is greater than the min, we need to set it.
						realHeight = stockistHeight + offset;
					}
				}).parent().animate({height: realHeight + 'px'},Math.abs(stockistHeight - realHeight)*10); //animate :)
			});
		}
		
		/**
		 * Item Page
		 *
		 */
		if($('#ItemPage').length) {
			//Lightbox!
			var position = $('#Content').position();
			jQuery('a.lightbox').click(function() {
				if (!$('.overlay').length){
					$this = $(this);
					startOverlay($this.attr('href'),$this.attr('title'),position);
				}
				return false;
			});
			//colours code NB: Obsolete
			var $Colours = $('#Bag .colours a');
			var $Details = $('#Bag .details');
			jQuery.data($Details,'html',$Details.html());
			$Colours.each(function() {
				var $this = $(this);
				$this.mouseout(function() {
					if ($Details.html() == '') {
						$Details.stop().fadeOut('slow',function(){
							$Details.css({'background':'','opacity':1}).html(jQuery.data($Details,'html')).fadeIn('slow');
						});
					}
				}).click(function() {
					var largeColour = $this.attr('href');
					$Details.fadeOut('slow',function() {
						$Details.html('').css({'background':'url(' + largeColour + ') repeat','opacity':1}).fadeIn('slow');
					});
					return false;
				});
			});
		}
		
		var $NewsletterSubmit = $('#NewsletterSubmit');
		$NewsletterSubmit.click(function() {
			var $FieldSet = $NewsletterSubmit.parent();
			var $Form = $FieldSet.parent();
			//var formMethod = $Form.attr('method');
			var formAction = $Form.attr('action');
			var data = '';
			var success = true;
			$FieldSet.children('input:not([type=submit])').each(function() {
				var $this = $(this);
				var label = $FieldSet.children('label[for=' + $this.attr('id') +']').html();
				if ($this.val() && $this.val() != label) {
					if (label == 'Email'){
						if (echeck($this.val()) == false) {
							$this.css({'background-color':'#FED0D0','color':'#DC1313'});
							success = false;
							if (!$('#EmailError').length) {
								$FieldSet.append('<div id="EmailError"><p>Please enter a valid e-mail address</p></div>');
							}
						}
						else {
							$('#EmailError').remove();
							$this.css({'background-color':'','color':''});
						}
					}
					if (success) {
						$('#' + label + 'Error').remove();
					}
				}
				else {
					success = false;
					if (!$('#' + label + 'Error').length) {
						$FieldSet.append('<div id="' + label + 'Error"><p>Please enter a valid ' + label + '</p></div>');
					}
				}
			});
			data = $Form.serialize();
			if (success){
				xss_ajax(formAction + '?' + data);
				$FieldSet.fadeOut('slow',function() {
					$(this).parent().append('<div id="NewsletterThanks" style="margin-top: 1.1em;display:none"><p>' + _newsletterThanks + '</p></div>').children('#NewsletterThanks').fadeIn('slow');
				});
			}
			return false;
		});
		
		/*$('#Social a').hover(function() {
			var $this = $(this);
			return false;
		});*/
		
	});
});
