/**
 * 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 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) {
		 var hideOverlay = false,
			$overlay = $('div.overlay'),
			_attrs = {
			   src: overlayLink,
			   alt: altText
			};
			if (!$overlay.length) {
			   $('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>'
			   );
			   $overlay = $('div.overlay');
			   _attrs = {};
			}
			else {
			   hideOverlay = true;
			}
			$('.overlayContainer img').attr(_attrs).addpowerzoom({
			   magnifiersize:[160, 160],
			   //largeImage is defined in Page.ss <script>
			   largeimage: largeImage
			});
			$overlay.css({
				'height':$('body').outerHeight(),
				'min-height': '100%',
				display: 'block'
			}).animate({
				'opacity':'0.6'
			   },200,'linear'
			).click(function() {
				var $this = $('.overlayContainer, .overlay');
				$this.stop().animate({
					'opacity':'0'
				},200,'linear', function() {
					 if (hideOverlay) {
						$this.css('display','none');
					 }
					 else {
						$this.remove();
					 }
				});
				return false;
			}).siblings('.overlayContainer').css({
				"left":       position.left,
				"top":        position.top+51,
				display: 'block'
			}).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
		 */
		//$.getScript('mysite/javascript/jqbrowser.jquery.compressed.js',function() {
		 if ($.browser.firefox()) {
		  if ($.browser.version.number() < 3.6) {
				$('#NewsletterSubmit').css('top','3px');
			 }
			else {
				$('#NewsletterSubmit').css('top','1px');
			}
			if (document.body.getAttribute('id') == 'ItemPage' && $.browser.mac()) {
			   $('#Bag .related .bag h3 a').css('padding-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);
					}
				});
			}
		});

		jQuery('label[for="Country"]').hide();

		/**
		 * 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();
		}

		/**
		 * Slideshow
		 *
		 * The custom slide show for accordion pages
		 */
		$slideHolder = $('div.slideHolder');
		if ($slideHolder.length) {
		 //make slide object
		 sliderObj = {
			//vars & Objects
			slideHolder: $slideHolder,
			ulWidth: null,
			numSlides: null,
			$nextButton: null,
			$prevButton: null,
			$slides: null,
			$currentSlide: null,
			$nextSlide: null,
			$prevSlide: null,
			$firstSlide: null,
			$lastSlide: null,
			isAnimating: false,

			//Cases
			isValidDir: function(dir) {
			   return dir == 'next' || dir == 'prev';
			},
			positionSlide: function(slide,dir) {
			   //position the slide its width left of the ul
			   //we need to stop the animation when we re-position
			   if (this.isValidDir(dir)) {
				  var width = dir == 'prev' ? -this.ulWidth : this.ulWidth;
				  slide.css({
					 left: width
				  });
			   }
			   return this;
			},
			positionNextSlide: function(slide) {
			   return this.positionSlide(slide,'next');
			},
			positionPrevSlide: function(slide) {
			   return this.positionSlide(slide,'prev');
			},
			/*clickeEvent: function(dir) {
			   if (this.isValidDir(dir)) {
				  var titleCaseDir = dir.charAt(0).toUpperCase() + dir.substring(1), length = this.numSlides, leftRight = dir == 'prev' ? 'Right' : 'Left';
				  if (length > 1) {
					 this['position' + titleCaseDir + 'Slide'](this['$' + dir + 'Slide'])
					 .animateSlideRight([this.$currentSlide,this.$prevSlide])
					 .redefineSlides('prev')
					 .positionPrevSlide(this.$prevSlide);
					 if (length > 2) {
						this.positionNextSlide(this.$nextSlide);
					 }
				  }
			   }
			   return false;
			},*/
			prevClickEvent: function() {
			   if (!this.isAnimating) {
				  this.isAnimating = true;
				  var length = this.numSlides;
				  if (length > 1) {
					 this.positionPrevSlide(this.$prevSlide)
					 .animateSlideRight([this.$currentSlide,this.$prevSlide])
					 .redefineSlides('prev');
				  }
			   }
			   return false;
			},
			nextClickEvent: function() {
			   if (!this.isAnimating) {
				  this.isAnimating = true;
				  var length = this.numSlides;
				  if (length > 1) {
					 this.positionNextSlide(this.$nextSlide)
					 .animateSlideLeft([this.$currentSlide,this.$nextSlide])
					 .redefineSlides('next');
				  }
			   }
			   return false;
			},
			getNextItem: function() {
			   var next = this.$currentSlide.next();
			   if (!next.length) {
				  next = this.$firstSlide;
			   }
			   return next;
			},
			getPrevItem: function() {
			   var prev = this.$currentSlide.prev();
			   if (!prev.length) {
				  prev = this.$lastSlide;
			   }
			   return prev;
			},
			redefineSlides: function(dir) {
			   if (this.isValidDir(dir)) {
				  this.$currentSlide.removeClass('current');
				  this.$currentSlide = this['$' + dir + 'Slide'].addClass('current');
				  this.$nextSlide = this.getNextItem();
				  this.$prevSlide = this.getPrevItem();
			   }
			   return this;
			},
			animateSlide: function(slide,dir) {
			   if (this.isValidDir(dir) && slide instanceof Array) {
				  var operator = dir == 'prev' ? '-=' : '+=';
				  var self = this;
				  for (var i in slide) {
					 slide[i].animate({
						left: operator + this.ulWidth
					 },{
						duration: 'slow',
						complete: function() {
						   self.isAnimating = false;
						}
					 });
				  }
			   }
			   return this;
			},
			animateSlideLeft: function(slide) {
			   return this.animateSlide(slide,'prev');
			},
			animateSlideRight: function(slide) {
			   return this.animateSlide(slide,'next');
			},
			hideButtons: function() {
			   this.slideHolder.addClass('single');
			   return this;
			},
			init: function() {
			   var self = this, i = 0;
			   this.$ul = this.slideHolder.children('ul');
			   this.$slides = this.$ul.children('li');
			   this.numSlides = this.$slides.length;
			   this.$nextButton = this.slideHolder.children('a.next');
			   this.$prevButton = this.slideHolder.children('a.prev');
			   if (this.numSlides > 1) {
				  /*if (this.numSlides == 2) {
					 //duplicate the slides for smoother UX
					 this.$ul.append(this.$slides.clone(true));
					 this.$slides = this.$ul.children('li');
					 this.numSlides = this.$slides.length;
				  }*/
				  //define the vars
				  this.ulWidth = this.$ul.width();
				  this.$firstSlide = this.$slides.first();
				  this.$lastSlide = this.$slides.last();
				  this.$currentSlide = this.$firstSlide;
				  this.$nextSlide = this.getNextItem();
				  this.$prevSlide = this.getPrevItem();

				  //run the init functions
				  //position all but first and last slide
				  this.$slides.slice(1,-1).each(function(index2,value) {
					 self.positionNextSlide($(value));
				  });
				  //postition last slide
				  this.positionPrevSlide(this.$prevSlide);
				  //assign click events
				  this.$nextButton.click(function() {return self.nextClickEvent(); });
				  this.$prevButton.click(function() {return self.prevClickEvent(); });
			   }
			   else if (this.numSlides) {
				  //hide the next and prev and no need to do anything else
				  this.hideButtons();
			   }
			   return this;
			}
		 }
		 sliderObj.init();
		}

		/**
		 * 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!
			//$.getScript('/mysite/javascript/ddpowerzoomer.js',function() {
			   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	$colourHolder = $('div.colours'),
				   $colourSwatches = $('li a',$colourHolder),
				   $bigColour = $('div.bigColour',$colourHolder),
				   $colourH2 = $colourHolder.children('h2').last();
			   $colourSwatches.click(function() {
				  var $img = $(this);
				  $bigColour.css('background-image','url(' + $img.attr('href') + ')');
				  $colourH2.text($img.attr('title'));
				  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){
			   $.post(
				  'Page_Controller/doNewsletterSignup',
				  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;
		});*/

	});
});

