/*global $ */
/*jslint newcap: true, undef: true, devel: true, white: true, onevar: true, nomen: true, bitwise: true, strict: true, browser: true, maxerr: 50, indent: 4 */
/*
 * Cubeworks website plugin code 2011
 * Copyright 2011 Cubeworks Ltd
 */
(function($){
	'use strict';
	function ease(initial, incBy, type, duration, setter){
		var easer = new Easing.Easer({
				type: type
			}),
			start = new Date().getTime(), 
			end = start + duration, 
			interval = setInterval(function(){
			var inc, now = new Date().getTime();
			if(now > end){
				now = end;
				$(window).scroll();
				clearInterval(interval);
			}
			inc = easer.ease(now - start, 0, incBy, end - start);
			setter(initial + inc);
		}, 20);
	}
	
	$.fn.imageSwapper = function(){
		$(this).each(function(ind, div){
			var el, imgs, i, a;
			div = $(div).css('position', 'relative');
			el = $('img', div).css('position', 'relative');
			el.wrap('<a href="" style="outline:none"/>');
			
			imgs = [];
			i = 1;
			while(el.data('src' + i)){
				imgs[imgs.length] = {src: el.data('src' + i), alt: el.data('alt' + i)};
				i++;
			}
			i = 1;
			a = el.parent();
			a.click(function(e){
				e.preventDefault();
				var img = imgs[i++];
				if(!img){
					img = imgs[0];
					i = 1;
				}
				el.animate({width: 0, height: 0, top:div.height()/2, left:div.width()/2}, function(){
					el.attr('src', img.src);	// Fires load event
					el.attr('alt', img.alt);
				});
			});
			el.load(function(){
				el.animate({width: div.width(), height: div.height(), top:0, left:0});
			});
		});
	};
	
	$.fn.imageSwapperSlide = function(){
		$(this).each(function(ind, div){
			var el, imgs, i, a;
			div = $(div).css('position', 'relative');
			el = $('img', div).css('position', 'relative');
			el.wrap('<a href="" style="outline:none"/>');
			
			imgs = [];
			i = 1;
			while(el.data('src' + i)){
				imgs[imgs.length] = {src: el.data('src' + i), alt: el.data('alt' + i)};
				i++;
			}
			i = 1;
			a = el.parent();
			a.click(function(e){
				e.preventDefault();
				var img = imgs[i++];
				if(!img){
					img = imgs[0];
					i = 1;
				}
				el.animate({width: 0, height: 0, top:div.height()/2, left:div.width()/2}, function(){
					el.attr('src', img.src);	// Fires load event
					el.attr('alt', img.alt);
				});
			});
			el.load(function(){
				el.animate({width: div.width(), height: div.height(), top:0, left:0});
			});
		});
	};
	
	$.fn.whatWeDo = function(){
		$(this).each(function(i, el){
			var pointer, pointerWidth, links, sections, left, container, scroller;
			el = $(el).css('position', 'relative');
			pointer = $('<div class=pointer style="position:absolute;bottom:0;left:0"/>');
			el.find('section:first').append(pointer);
			pointerWidth = pointer.width();

			links = $('a[href^=#]', el);
			
			// Setup carousel
			sections = [];
			left = 0;
			links.each(function(i, el){
				var section = $($(el).attr('href'));
				if(section.data('processed')) return;
				sections[sections.length] = section.get(0);

				section.data('moveLeft', left)
					.data('processed', true)
					.css({position: 'absolute', left: left});
				left += section.outerWidth();
			});
			sections = $(sections);
			container = $('<div/>').css({position: 'relative', height: sections.outerHeight(), overflow: 'hidden'});
			scroller = $(sections).wrapAll(container).wrapAll('<div/>').parent();
			scroller.css({position: 'absolute', left: 0});
			
			// Setup click handlers
			links.click(function(e){
				e.preventDefault();
				var newLeft, nav, left,
					selector = $(this).attr('href');
				links.removeClass('current');
				$('a[href=' + selector + ']', el).addClass('current');

				newLeft = $(selector).data('moveLeft');
				scroller.animate({left:-newLeft});

				nav = $('nav li a[href=' + selector + ']', el);
				left = nav.position().left + (nav.width() / 2) - (pointerWidth / 2) + 15;
				
				pointer.animate({left: left});
			});
			links.filter(':first').click();
		});
	};

	$.fn.carousel = function(){
		$(this).each(function(i, el){
			var that = $(el);
			var figures = that.find('.figure');
			var wrapper = $('<div>').css({position: 'relative', overflow: 'hidden'}).appendTo(that);
			var scroller = $('<div>').css({position: 'absolute', top: 0, left: 0}).append(figures).appendTo(wrapper);
			var captions = figures.find('.figcaption');
			var indicator = $('<div class="indicator">').appendTo(that);
			var pager = $('<div class="pager">')
				.html('<a href="" class="prev">&lt;</a><div class=figcaption/><a href="" class="next">&gt;</a>');
			var imgs = wrapper.find('img');
			
			function processImage(img){
				var el = $(img);
				var width = el.parent().width();
				var height = el.parent().height();
				if(wrapper.height() < height) wrapper.height(height);
				if(wrapper.width() < width) wrapper.width(width);
				
				if(imgs.filter('[complete]').length == imgs.length){
					var pos = 0;
					figures.each(function(i, el){
						$(el).css('left', pos).data('left', pos);
						pos += $(el).width();
					});
				}
			}
			
			imgs.each(function(i, el){
				el.onload = function(){
					processImage(el);
				}
				if(el.complete || el.readyState === 4){// If image is already loaded onload event won't fire
					processImage(el);
				}
			});

			function go(btn, dir){
				var current = figures.filter('.current').removeClass('current');
				var show = current[dir]('.figure').addClass('current');
				if(show.length){
					var moveFrom = current.data('left');
					var moveTo = show.data('left');

					scroller.animate({left: -moveTo});

					indicator.find('.current').removeClass('current')[dir]().addClass('current');
					pager.find('.figcaption').html(show.find('.figcaption').html());
					pager.find(dir == 'prev' ? '.next' : '.prev').show();
					if(show[dir]('.figure').length === 0){
						$(btn).hide();
					}
				}
			}

			figures.show().css('position', 'absolute').css('top', 0);
			figures.filter(':first').addClass('current');
			figures.each(function(i, el){
				indicator.append('<span>&bull;</span>');
			});
			indicator.find('span:first').addClass('current');
			that.append(pager);
			pager.find('.figcaption').html(captions.first().html()).show();
			pager.find('.prev').click(function(){
				go(this, 'prev');
				return false;
			}).hide();
			pager.find('.next').click(function(){
				go(this, 'next');
				return false;
			});
			if(imgs.length < 2){
				indicator.find('span').hide();
				pager.find('.prev,.next').hide();
			}
		});
	};

	$.fn.scrollFixed = function(){
		$(this).each(function(i, el){
			var that = $(el);
			var top = 0, headerEnds = 0, left = 0;
			var original = {
				top: that.css('top'),
				left: that.css('left'),
				right: that.css('right'),
				bottom: that.css('bottom'),
				position: that.css('position')
			};
			function setTopAndLeft(){
				var pos = that.css('position');
				that.css('position', '');
				top = that.offset().top;
				headerEnds = $('header').height() + parseFloat($('header').css('top').replace(/auto/, 0)) + 5;
				left = that.offset().left - parseFloat(that.css('marginLeft').replace(/auto/, 0));
				that.css('position', pos);
			}
			$('a[href^=#]').click(function(){
				var a = $(this);
				var div = $(a.attr('href'));

				if(div.length == 0) return true;

				var scrollStart = $(window).scrollTop();
				var scrollBy = div.offset().top - headerEnds - scrollStart + 1;

				ease(scrollStart, scrollBy, 'exp', 250, function(val){$(window).scrollTop(val)});
				return false;
			});
			$(window).resize(function(){
				setTopAndLeft();
				$(window).scroll();
			});
			$(window).scroll(function(){
				var y = $(this).scrollTop() + headerEnds;

				if (y >= top) {
					that.css('position', 'fixed');
					that.css('top', headerEnds + 'px');
					that.css('left', left + 'px');
				} else {
					that.css('position', original.position);
					that.css('top', original.top);
					that.css('left', original.left);
					that.css('right', original.right);
					that.css('bottom', original.bottom);
				}
				that.find('a').each(function(i, el){
					var div = $(el.href.substring(el.href.lastIndexOf('#')));

					if(div.length == 0) return;

					var top = div.offset().top;
					var scrollTop = $(window).scrollTop() + headerEnds;

					// div is on screen if its top is off the top & the bottom is in or below the viewport
					if(top < scrollTop && scrollTop < (top + div.height())){
						$(el).addClass('current');
					}else{
						$(el).removeClass('current');
					}
				});
			});
			setTopAndLeft();
			$(window).scroll();
		});
	};

	$.fn.googleMap = function(){
		$(this).each(function(i, el){
			el = $(el);
			//http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=BN1+1EF&aq=&sll=53.800651,-4.064941&sspn=18.252022,57.084961&ie=UTF8&hq=&hnear=Brighton,+East+Sussex+BN1+1EF,+United+Kingdom&z=16
			var lat = parseFloat(el.data('lat')),
				lon = parseFloat(el.data('long')),
				zoom = parseFloat(el.data('zoom') || 16),
				latlng = new google.maps.LatLng(lat, lon),
				options = {
					zoom: zoom,
					center: latlng,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				},
				map = new google.maps.Map(el[0], options),
				marker = new google.maps.Marker({
						position: latlng, 
						map: map, 
						title:"Cubeworks HQ"
				});
		});
	};

	$.fn.order = function(selector){
		var elements = [],
			that = $(this);
		that.each(function(i, el){
			var con = $(selector, el);
			var num = parseInt(con.text(), 10);
			if(num == 1) con.text(con.text().substring(0, con.text().length - 1));
			elements[elements.length] = { el: $(el), i: num };
		});
		elements.sort(function(a, b){
			if(a.i === b.i) return 0;
			return a.i < b.i ? 1 : -1;
		});
		$.each(elements, function(i, obj){
			obj.el.remove();
			obj.el.appendTo(that.parent());
		});
	};

	$.fn.ajaxSubmit = function(){
		function requiresShim(attr){
			return !(attr in document.createElement('input'));
		}
		function setPlaceHolders(form){
			if(!requiresShim('placeholder')) return;
			$(form).find('input[placeholder],select[placeholder],textarea[placeholder]').each(function(i, el){
				el = $(el);
				var placeholder = el.attr('placeholder');
				el.val(placeholder);
				el.focus(function(){
					if(el.val() === placeholder)
						el.val('');
				});
				el.blur(function(){
					if(el.val() === '')
						el.val(placeholder);
				});
			});
		}
		function validate(form){
			if(!requiresShim('required')) return true;
			var validation = true;
			$(form).find('input[required],select[required],textarea[required]').each(function(i, el){
				el = $(el);
				el.removeClass('invalid');
				if(!el.val() || el.val() === el.attr('placeholder')){
					el.addClass('invalid');
					validation = false;
				}
			});
			return validation;
		}
		$(this).each(function(i, el){
			setPlaceHolders(el);
			$(el).submit(function(){
				if(!validate(el))
					return false;
				
				var oldHtml = $(el).html();
				$(el).html('<div class="waiting">Please wait...</div>');
				
				$[el.method || 'post'](el.action, $.param($(el).serializeArray()), function(data){
					setTimeout(function(){
						$(el).html(data);
						var resume = $('<p class="again"><a href="">Go again?</a></p>')
							.click(function(){
								$(el).html(oldHtml);
								return false;
							});
						resume.appendTo(el);
					}, 1000);
				});
				return false;
			});
		});
	};
})(this.jQuery);

window.log = function(){
	'use strict';
	log.history = log.history || [];
	log.history.push(arguments);
	if(window.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};
(function(doc){
	'use strict';
	var write = doc.write;
	doc.write = function(q){ 
		if (/maps\.gstatic\./.test(q)){
			write.apply(doc,arguments);
			return;
		}
		log('document.write(): ',arguments); 
	};
})(document);
