$(function(){
	$('#nav_login').loadPanel();
	$('#gallery').gallerify();
	$(".colorbox").colorbox();
	$('#client_list').clientList();
	$('#drawer').slideOpenMap();
	$('#how').howTheyWork();
	
	$("#tweet").tweet({
	            username: "subscantech",
	            join_text: "auto",
	            avatar_size: 0,
	            count: 2,
	            auto_join_text_default: "",
	            auto_join_text_ed: "",
	            auto_join_text_ing: "",
	            auto_join_text_reply: "",
	            auto_join_text_url: "",
	            loading_text: "loading tweets..."
	        });
});

$.fn.loadPanel = function(options){
	return this.each(function(){
		options = options || {};
		var Panel = {
			top: options.top || false,
			show: options.show || false
		}
		var body = $('body');
		var link = $(this).children();

		link.click(function(e){
			e.preventDefault();
			var offset = link.offset();
			var currentPanels = $('.panel');
			if (currentPanels.length) {
				currentPanels.remove();
			} else {
				$.get(link.attr('href'),function(data){
					var panel = $('<div class="panel'+(Panel.top?' top':'')+'"><div class="panel_sleeve"></div></div>');

					var hidePanel = function(e){
						e.preventDefault();
						panel.fadeOut('fast',function(){
							panel.remove();
						});
					}

					panel.children().append(data);
					panel.appendTo('body');
					panel.css({
						top: offset.top+(Panel.top ? 0-panel.outerHeight() : link.parent().height()),
						left: offset.left+link.parent().width()-panel.width()
					});
					$('<p class="close"><a href="#">Close</a></p>').appendTo(panel).children().click(hidePanel);
					body.bind('click.bodyclick',function(e){
						e.stopImmediatePropagation();
						if ($(e.target).closest('.panel').length==0) {
							hidePanel(e);
							body.unbind('click.bodyclick');
						}
					//	return false;
					});
				});
				if (Panel.show) link.click();
			}
		});
	});
}

$.fn.gallerify = function(){
	return this.each(function(){
		var gallery = $(this);
		var slides = gallery.find('li');
		
		var slide = function(e){
			var current = slides.filter('.front'), next, direction;

			if (e.data.direction=='prev') {
				next = current.is(':first-child') ? slides.last() : current.prev();
				direction = '-';
			} else {
				next = current.is(':last-child') ? slides.first() : current.next();
				direction = '+';
			}
			
			next.addClass('back').css({left:0});
			current.animate({
				left: direction+'960px'
			},{
				duration: 500,
				queue: true,
				easing: 'easeInOutExpo',
				complete: function(){
					current.removeClass('front');
					next.removeClass('back').addClass('front');
				}
			});
		}
		
		$('<button class="button_prev"><img src="/images/button_prev.png" alt="Previous slide" /></button>').bind('click',{direction:'prev'},slide).appendTo(gallery);
		$('<button class="button_next"><img src="/images/button_next.png" alt="Next slide" /></button>').bind('click',{direction:'next'},slide).appendTo(gallery);
		
	});
}

$.fn.clientList = function(){
	return this.each(function(){
		var SCROLL_SPEED = 500;
		var container = $(this).css('overflow','hidden');
		var slides = container.children();
		var ul = slides.children();
		var scrollAmount = 850;
		var items = ul.children();
		var itemsWidth = items.outerWidth(true) * items.length;
		
		items.clone().appendTo(ul);
		
		var slide = function(e){
			if(!slides.is(':animated')) {
				var currentScroll = slides.scrollLeft();

				if (e.data.direction == 'next') {
					slides.animate({scrollLeft: currentScroll+scrollAmount},{duration: SCROLL_SPEED, complete:function(){
						if (slides.scrollLeft()>=itemsWidth) slides.scrollLeft(slides.scrollLeft()-itemsWidth);
					}});
				} else {
					slides.animate({scrollLeft: currentScroll-scrollAmount},{duration: SCROLL_SPEED, complete:function(){
						if (slides.scrollLeft()<=0) slides.scrollLeft(itemsWidth);
					}});
				}
			}
		}
		
		// initialise slideshow
		slides.css({
			height: items.first().outerHeight(),
			overflow: 'hidden'
		}).scrollLeft(0);
		ul.css({width: itemsWidth * 2 +'px'});
		
		$('<button class="button_prev"><img src="/images/button_prev_small.png" alt="Previous" /></button>').bind('click',{direction:'prev'},slide).appendTo(container);
		$('<button class="button_next"><img src="/images/button_next_small.png" alt="Next" /></button>').bind('click',{direction:'next'},slide).appendTo(container);

	});
}


$.fn.slideOpenMap = function(){
	return this.each(function(){
		if (GBrowserIsCompatible()) {
			$('#drawing_widget_controls').drawingMap();
		} else {
			$(this).hide();
		}
	});
}

$.fn.drawingMap = function(){
	return this.each(function(){
		
		var map, poly, poly_input = $('#polyline'), postcodeSearch, postcodeValue, geocoder = new GClientGeocoder(), updateHandler, endHandler, polyComplete = false, polylineEncoder = new PolylineEncoder();
		
		var search = function(e){
			e.preventDefault();
			var val = postcodeSearch.children('input.text').val();
			if (val!='') {
				geocoder.getLatLng(val,function(point){
					if (point) {
						map.setCenter(point,15);
					}
				});
			}
		}
		
		/* initialise map */
		map = new GMap2(this);
		map.setCenter(new GLatLng(53.800651, -4.064941),6);
		map.setMapType(G_HYBRID_MAP);
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl3D());
		map.addControl(new GMapTypeControl());

		var postcodeSearch = $('<div id="postcode_search"><input type="text" class="text" placeholder="Enter postcode" title="Enter postcode" /> <input type="image" class="submit" alt="Search" src="/images/button_search.png" id="map_search" /></div>').insertBefore(this);
		postcodeSearch.children('input.text').keypress(function(e){
			if (e.keyCode == 13) {
				search(e);
			}
		}).next('input.submit').click(search);

	
		$('<button id="draw_control"><img src="/images/button_begin_drawing.png" alt="Begin drawing" /></button>').insertBefore(this).click(function(e){
			e.preventDefault();
			var button = $(this);
			var currentPanels = $('.panel');
			if (currentPanels.length==0) {
				if (button.is('.reset')) {
					map.clearOverlays();
					poly_input.val('');
					polyComplete = false;
					GEvent.removeListener(updateHandler);
					GEvent.removeListener(endHandler);
					button.removeClass('reset').html('<img src="/images/button_begin_drawing.png" alt="Begin drawing" />');
				} else {
					poly = new GPolygon([], '#0000ff', 2, 0.7, '#0000ff', 0);
					map.addOverlay(poly);
					poly.enableDrawing({});
					poly.enableEditing({onEvent: "mouseover"});
					poly.disableEditing({onEvent: "mouseout"});
					endHandler = GEvent.addListener(poly, "endline", function() {
						poly.setStrokeStyle({
							color:'#26e000',
							weight:4,
							opacity:1
						});
						poly.setFillStyle({
							color:'#26e000',
							opacity:.3
						});
						updateHandler = GEvent.addListener(poly, "lineupdated", function() {
							var vertices = [], latlngs,imageRequest;
							for (i=0;i<poly.getVertexCount();i++) {
								vertices.push(poly.getVertex(i));
							}
							latlngs = $.map(vertices,function(e){
								return [e.lat(),e.lng()]
							});

							/* If we upgrade to v3 we can use google.maps.geometry.encoding to do this and remove PolylineEncoder.min.js */
							poly_input.val(polylineEncoder.dpEncode(vertices).encodedPoints);
						});
					});
					button.addClass('reset').html('<img src="/images/button_reset.png" alt="Reset map" />');
				}
			}
		});
		
	});
}

$.fn.howTheyWork = function(){
	return this.each(function(){
		var container = $(this);
		var levels = container.find('li');
		var height = levels.eq(0).outerHeight();
		
		levels.children('.img').each(function(){
			var image = $(this).children();
			$(this).css({
				marginTop: -(image.height()-height)/2+'px'
			});
		});
		
		levels.click(function(){
			var level = $(this);
			var image = level.children('.img');
			if (level.is('.on')) {
				level.removeClass('on');
				image.animate({
					height: 0
				},500);
			} else {
				level.addClass('on');
				image.animate({
					height: image.children().height()
				});
			}
		});
		
		levels.first().click();
	});
}
