$(function() {
	enhance();
});

var enhance = function() {
	var o = {};
	
	o.adjustLayout = function() {
		// set border (keyline)
		var m = $('#main'), h = $(document).height();
		m.css({ 'border-right-color':'#a9a8a7', 'height':h + 'px' });
		
		// hide body overflow-x on homepage
		if ($('.index').length) {
			var body = $('body');
			if (parseInt(body.width(), 10) >= 985) {
				body.css('overflow-x', 'hidden');
			} else {
				body.css('overflow-x', 'scroll');
			}
			
			if (parseInt(body.height(), 10) >= 540) { // enough height to view nav + footer at normal font size
				body.css('overflow-y', 'hidden');
			} else {
				body.css('overflow-y', 'scroll');
			}
		}
	};
	
	o.languageSelector = {
		createMenu: function() {
			var elems = $('#lang, #lang_submit').hide(),
				options = $('option', $(elems[0])),
				html = $('<ul id="lang_selector">\
							<li class="chosen"><span /></li>\
							<li class="options">\
								<div>\
									<ul />\
								</div>\
							</li>\
						</ul>');
			
			options.each(function() {
				var newOption = $('<li><a href="?lang='+ $(this).val() +'">' + $(this).text() + '</a></li>');
				
				if ($(this).val() == $(elems[0]).val()) {
					$('a', newOption).addClass('selected');
					$('.chosen span', html).text($(this).text());
				}
				
				$('.options ul', html).append(newOption);
			});
			
			elems.remove();
			$('.options', html).css('opacity', '0.95');
			$('#footer form').addClass('upgraded').append(html);
			
			this.addHandler();
		},
		addHandler: function() {
			var el = $('#lang_selector'),
				isSelected = false,
				t;
			
			$('.options a', el).click(function(e) {
				e.preventDefault();
				var elem = $(this);
				
				if (elem.hasClass('selected')) {
					isSelected = true;
				} else {
					isSelected = false;
					$('.selected', el).removeClass('selected');
					elem.addClass('selected');
					
					$('.chosen span', el).text(elem.text());
				}
				
				$('.options', el).slideUp(500, function() {
					$('.chosen', el).removeClass('hovered');
					el.removeClass('active');
					if (! isSelected) window.location = elem.attr('href');
				});
			});
			
			$('.chosen', el).click(function() {
				$('.selected', el).click();
			});
			
			el.hover(function() {
				clearTimeout(t);
				if (el.hasClass('active')) return false;
				el.addClass('active');
				$('.chosen', el).addClass('hovered');
				$('.options', el).slideDown(500);
			}, function() {
				t = setTimeout(function() {
					$('.options', el).slideUp(500, function() {
						$('.chosen', el).removeClass('hovered');
						el.removeClass('active');
					});
				}, 1000);
			});
			
		},
		upgrade: function() {
			$('head').append('<style type="text/css">#lang_selector .hovered { -webkit-border-radius: 4px 4px 0 0; -moz-border-radius: 4px 4px 0 0; border-radius: 4px 4px 0 0; } #lang_selector .options { -webkit-border-radius: 0 0 4px 4px; -moz-border-radius: 0 0 4px 4px; border-radius: 0 0 4px 4px; }</style>');
			this.createMenu();
		}
	};
	
	o.hpCarousel = {
		ix: 0,
		changeBg: function() {
			
			if (this.ix == this.data.length) this.ix = 0;
			var nx = (this.ix == (this.data.length - 1)) ? 0 : this.ix + 1,
				speed,
				duration;
			
			$('.animation:first').remove();
			
			// are we dealing with an image or an animation ?
			if (this.data[this.ix].bg.indexOf('animate') != -1) { // animation
				var sequence = this.data[this.ix].bg.substring(this.data[this.ix].bg.indexOf('[') + 1, this.data[this.ix].bg.indexOf(']'));
				
				speed = animations[sequence].speed;
				
				this.mainMask.append(o.animateImageSet(sequence)).animate({ 'opacity': 1 }, speed, function() {
					duration = speed * (animations[sequence].images.length * animations[sequence].loop);
					transition();
				});
				
				setBodyBg(speed);
				
			} else { // image
				speed = 2000;
				
				this.mainMask.css('background-image', o.hpCarousel.data[o.hpCarousel.ix].bg).animate({ 'opacity': 1 }, speed, function() {
					duration = 5000;
					transition();
				});
				
				setBodyBg(speed);
			}
			
			function setBodyBg (speed) {
				o.hpCarousel.bodyMask.css('background-image', o.hpCarousel.data[o.hpCarousel.ix].rhs).animate({ 'opacity': 1 }, speed);
			}
			
			function transition () {
				$('.preloader').removeClass('preloader');
				
				// animate the visible elements
				window.setTimeout(function() {
					
					o.hpCarousel.mainMask.animate({ 'opacity': 0 }, speed, function() {
						o.hpCarousel.ix++;
						o.hpCarousel.changeBg();
					});
					
					o.hpCarousel.bodyMask.animate({ 'opacity': 0 }, speed);
					
				}, duration);
				
				// set next elements in place
				window.setTimeout(function() {
					if (o.hpCarousel.data[nx].bg.indexOf('animate') != -1) { // next is an animation
						
						var nx_seq = o.hpCarousel.data[nx].bg.substring(o.hpCarousel.data[nx].bg.indexOf('[') + 1, o.hpCarousel.data[nx].bg.indexOf(']'));
						
						$('#main').css({ 'background-image': 'url(' + animations[nx_seq].base_src + animations[nx_seq].images[0] + ')', 'background-color': animations[nx_seq].fill });
						
					} else { // next is an image
						$('#main').css('background-image', o.hpCarousel.data[nx].bg);
					}
					
					$('body').css('background-image', o.hpCarousel.data[nx].rhs);
				}, 2000);
				
			}
			
		},
		setup: function() {
			this.bodyMask = $('<div style="width: 560px; height: 100%; background-repeat: no-repeat; position: absolute; top: 0; left: 978px;" />').css('opacity', 0);
			$('body').append(this.bodyMask);
			
			this.mainMask = $('<div style="width: 100%; height: 100%; background-repeat: no-repeat;" />').css('opacity', 0);
			$('#main').append(this.mainMask);
			
			window.setTimeout(function() {
				o.hpCarousel.changeBg();
			}, 1000);
		},
		loadData: function() {
			// loads data from json rendered by the server
			var that = this;
			
			that.data = (typeof(hpCarouselData) != 'undefined') ? hpCarouselData : [];
			if (that.data.length) {
				
				var newBgImage = true, newRhsImage = true,
					bg_img, rhs_img,
					i = 0, j = 0,
					len = that.data.length;
				
				var cacheBgImage = function() {
					if (that.data[i].bg.indexOf('animate') == -1) { // not an animation
						if (newBgImage) {
							bg_img = new Image();
							bg_img.src = that.data[i].bg;
							that.data[i].bg = 'url(' + that.data[i].bg + ')';
						}
							
						if (! bg_img.complete) {
							newBgImage = false;
							window.setTimeout(function() {
								cacheBgImage();
							}, 200);
						} else {
							newBgImage = true;
							i++;
							if (i < len) {
								cacheBgImage();
							} else {
								that.setup();
							}
						}
					} else {
						i++;
						if (i < len) {
							cacheBgImage();
						} else {
							that.setup();
						}
					}
				};
				
				var cacheRhsImage = function() {
					if (newRhsImage) {
						rhs_img = new Image();
						rhs_img.src = that.data[j].rhs;
						that.data[j].rhs = 'url(' + that.data[j].rhs + ')';
					}
					
					if (! rhs_img.complete) {
						newRhsImage = false;
						window.setTimeout(function() {
							cacheRhsImage();
						}, 200);
					} else {
						newRhsImage = true;
						j++;
						if (j < len) cacheRhsImage();
					}
				};
				
				cacheBgImage();
				cacheRhsImage();
			}
		},
		init: function() {
			if ($('.index').length) {
				$('#main').addClass('preloader');
				this.loadData();
			}
		}
	};
	
	o.gallery = {
		rotate: function(el, dir) {
			var dir = dir || 'right',
				imgWidth = el.data('imgWidth'),
				i = el.data('i'),
				len = el.data('len'),
				reelPos = el.data('reelPos'),
				imageReel = $('.image-reel', el);
			
			if (dir == 'right') {
				reelPos = imgWidth * i;
				imageReel.animate({ 'left': -reelPos+'px' }, 600);
				i = (i == (len - 1)) ? 0 : i + 1;
			} else {
				reelPos -= imgWidth;
				if (reelPos < 0) reelPos = imgWidth * (len - 1);
				imageReel.animate({ 'left': -reelPos+'px' }, 600);
				i = (i == 1) ? len - 1 : i - 1;
			}
			el.data('reelPos', reelPos); //update for next time
			el.data('i', i);
		},
		setHandlers: function(el) {
			$('.trigger span, .trigger a', el).css('opacity', 0);
			
			$('.trigger a', el).hover(
				function() {
					$(this).animate({ 'opacity': 1 }, 500);
					$(this).prev().animate({ 'opacity': 0.5 }, 500);
					clearInterval(el.timer);
				},
				function() {
					$(this).prev().animate({ 'opacity': 0 }, 400);
					$(this).animate({ 'opacity': 0 }, 400);
					o.gallery.startRotation(el);
				}
			).click(function(e) {
				e.preventDefault();
				o.gallery.rotate(el, $(this).attr('class'));
			});
		},
		startRotation: function(el) {
			el.timer = setInterval(function() {
				var canRotate = false;
				if (el.parents('div').hasClass('bellow')) {
					if (el.parents('.bellow:visible').length) canRotate = true;
				} else {
					canRotate = true;
				}
				if (canRotate) o.gallery.rotate(el);
			}, 5000);
		},
		upgrade: function(el) {
			var li = $('li', el),
				len = li.length;
			
			if (len > 1) {
				var accum = 0;
				li.each(function(i) {
					// TODO: Check the completeness of each image before capturing width and incrementing loop count
					var w = $('img', $(this))[0].width;
					accum += w;
					
					if (i == len - 1) {
						
						li.wrapAll('<div class="image-reel" style="width:'+ accum +'px;"></div>');
						el.append('<div class="trigger"><span /><a href="#" class="left" /><span /><a href="#" class="right" /></div>')
							.data('imgWidth', w)
							.data('i', 1)
							.data('len', len)
							.data('reelPos', 0);
						
						o.gallery.startRotation(el);
						o.gallery.setHandlers(el);
					}
				});
			}
		},
		init: function() {
			if ($('.gallery').length) {
				$('.gallery').each(function() {
					o.gallery.upgrade($(this));
				});
			}
		}
	};
	
	o.accordion = {
		setControls: function() {
			$('h3', '#accordion').wrapInner('<a href="#expand" class="bellow-ctrl" />');
			this.setHandlers();
		},
		setHandlers: function() {
			window.setTimeout(function() {
				$('.bellow-ctrl').click(function(e) {
					e.preventDefault();
					var bellow = $('.bellow', $(this).parents('li'));
					
					if (bellow.is(':visible')) {
						o.accordion.hide();
					} else {
						o.accordion.show(bellow, $(this));
					}
				});
			}, 50);
			
			if (!$.browser.msie) { // IE needs to ensure all images are completed before building galleries on the projects page
				window.setTimeout(function() {
					$('.bellow-ctrl:first').click();
				}, 1000);
			}
		},
		hide: function() {
			$('.bellow:visible').slideUp('slow', function() {
				$('.bellow-ctrl', $(this).parents('li')).css('background-image', 'url(images/bellow-down.gif)');
			});
		},
		show: function(el, a) {
			if ($('.bellow:visible').length) this.hide();
			
			el.slideDown('slow', function() {
				a.css('background-image', 'url(images/bellow-up.gif)');
			});
		},
		upgrade: function() {
			if ($('#accordion').length) this.setControls();
		}
	};
	
	o.animateImageSet = function(animation) {
		var data = animations[animation];
		if (typeof data == 'undefined') return false;
		
		var len = data.images.length,
			newImage = true,
			i = 0,
			img,
			sequence = $('<div class="animation" />').css({ 'background-color': data.fill });
		
		var cacheImage = function() {
			if (newImage) {
				img = new Image();
				img.src = data.base_src + data.images[i];
				img.style.zIndex = (len - 1) - i;
				img.width = data.width;
				img.height = data.height;
			}
			
			if (! img.complete) {
				newImage = false;
				window.setTimeout(function() {
					cacheImage();
				}, 200);
			} else {
				sequence.append(img);
				newImage = true;
				i++;
				if (i < len) {
					cacheImage();
				} else {
					data.loaded = true;
					data.frameset = $('img', sequence);
					setAnimation(sequence);
				}
			}
		};
		
		if (! data.loaded) {
			cacheImage();
		} else {
			sequence.append(data.frameset);
			setAnimation(sequence);
		}
		
		
		function setAnimation(sequence) {
			
			if (typeof(this.timer_1 !== 'undefined')) window.clearTimeout(this.timer_1);
			if (typeof(this.timer_2 !== 'undefined')) window.clearTimeout(this.timer_2);
			
			var frames = data.frameset,
				x = 0;
			
			var play = function() {
				
				if (x % 2 === 0) {
					this.timer_1 = window.setTimeout(function() {
						$(frames[x]).animate({ 'opacity' : 0 }, data.speed);
						x++;
						if (x === len - 1) {
							x = 0;
							$(frames[x]).animate({ 'opacity' : 1 }, data.speed, function() {
								frames.css('opacity', 1);
							});
						}
						play();
						
					}, data.speed / 2);
				} else {
					this.timer_2 = window.setTimeout(function() {
						$(frames[x]).animate({ 'opacity' : 0 }, data.speed);
						x++;
						if (x === len - 1) {
							x = 0;
							$(frames[x]).animate({ 'opacity' : 1 }, data.speed / 1.5, function() {
								frames.css('opacity', 1);
							});
						}
						play();
						
					}, data.speed);
				}
			};
			
			play();
		}
		
		return sequence;
	};
	
	o.handleModalLinks = function() {
		var termsLink = $('.terms a'),
			shippingLink = $('.shipping a');
		
		if (termsLink.length) {
			var html = $('<div id="termsModal" style="display: none;"></div>').load(termsLink.attr('href') + ' #content', function() {
				termsLink.after(html);
			});
			
			termsLink.attr({ href: '#termsModal', rel: 'prettyPhoto' });
		}
		
		if (shippingLink.length) {
			var html = $('<div id="shippingModal" style="display: none;"></div>').load(shippingLink.attr('href') + ' #content', function() {
				shippingLink.after(html);
			});
			
			shippingLink.attr({ href: '#shippingModal', rel: 'prettyPhoto' });
		}
	};
	
	o.handleNewsletterSignup = function() {
		var input = $('#newsletter_email');
		
		input.data('inputValue', input.val())
		
		input.focus(function() {
			if ($(this).val() == $(this).data('inputValue')) $(this).val('');
		}).blur(function() {
			if ($(this).val() == '') $(this).val($(this).data('inputValue'));
		});
		
		var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/,
			isEmail = function(s) {
				return String(s).search (isEmail_re) != -1;
			};
		
		var form = $('#newsletter_form');
		
		form.submit(function(e) {
			e.preventDefault();
			
			var userInput = input.val();
			
			if (userInput != input.data('inputValue')) {
				if (isEmail(userInput)) {
					input.val('Thank you... we\'ll be in touch');
				} else {
					input.val('Please enter a valid email');
				}
				input.css('color', '#e11b1e');
			} else {
				return false;
			}
			
			window.setTimeout(function() {
				input.val(input.data('inputValue')).css('color', '#999');
			}, 2500);
			
			//TODO: Make it work!
			//console.log('submitted');
		});
	};
	
	o.upgradeRegionSelector = function() {
		var form = $('#product-region');
		
		$('input', form).hide();
		
		$('select', form).change(function() {
			form.submit();
		});
	};
	
	o.init = function() {
		o.adjustLayout();
		
		//o.languageSelector.upgrade();
		o.hpCarousel.init();
		o.gallery.init();
		o.accordion.upgrade();
		
		o.handleModalLinks();
		
		o.handleNewsletterSignup();
		
		o.upgradeRegionSelector();
		
		$('#main a[rel^="prettyPhoto"]').prettyPhoto({theme:'facebook'});
		
		$(window).bind('scroll resize', o.adjustLayout);
	};
	
	return o.init();
};
