//- Author: Aaron Lord
(function(){
	//- Feature Slider
	var feature = {
		init : function(options){
			this.options = $.extend({
				elem : $('#feature'),
				controls_elem : $('#f_controls'),
				auto_slide : true,
				pause : 5000,
				speed : 500
			}, options);

			feature.setup();
		},

		setup : function(){
			var that = feature.options;
			//- Set everything up here, It's backed up with the stylesheet changes for the initial load
			that.elem.children().not('li:first-child').css({
				'left' : '960px',
				'opacity' : '0'
			});
			setTimeout("feature.slide()", that.pause);
		},
		//- The actual slide animation itself. next_item = false if controls not been used
		slide : function(){
			var that = feature.options;
			//- Fade out the first item
			that.elem.find('li:first-child').stop(true, true).animate({
				'opacity' : '0'
			}, that.speed, function(){
				//- Push it tot he right
				$(this).css('left', '960px').appendTo(that.elem);
				//- Move the next item in and fade it in
				that.elem.find('li:first-child').css('left', '0').stop(true, true).animate({
					'opacity' : '1'
				}, that.speed);
			});	
			//- Should we attempt another slide after x seconds?
			setTimeout("feature.slide()", that.pause)
		}
	};

	//- Company Counter
	//- Notes: Improve by adding Co2 increments & miliseconds
	var company_counter = {
		init : function(options){
			this.options = $.extend({
				url : '../includes/energy-counter.php'
			}, options);
			company_counter.setup();
		},
		setup : function(){
			$.ajax({
				type : 'GET',
				url : company_counter.options.url,
				dataType : 'json',
				success : function(results){
					company_counter.value = results.value;
					company_counter.increment = results.increment;

					if(results.run === 'daylight_run'){
						setInterval(function(){
							$('#elec_gen').html(company_counter.format(company_counter.value.toFixed(2)) + ' <small>kWh</smll>');
							company_counter.value += company_counter.increment;
						}, 1000);
					}
					else {
						$('#elec_gen').html(company_counter.format(company_counter.value) + ' <small>kWh</small>');
					}

					$('#installs_counter').html(results.installs);
					$('#co2_saved').html(company_counter.format(results.co2) + ' <small>tonnes</small>');
					$('#elephants_count').html(company_counter.format(results.elephants));
				}
			});
		},
		format : function(nStr){
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}
	};


	//- Social Feed
	//- Notes: Get Facebook updates working
	var social_feed = {
		init : function(options){
			this.options = $.extend({
				elem : $('#social_feed'),
			}, options);
			this.options.elem.find('li:first-child').css('opacity', 1);
			this.twitter();
			//this.facebook();
			this.slide();
		},
		twitter : function(){
			$.ajax({
				type : 'GET',
				url : 'http://twitter.com/statuses/user_timeline/ashadegreener.json?callback=?&count=5',
				dataType : 'json',
				success : function(results){
					// console.log(results);
					var list_item = '';
					$.each(results, function(index, values){
						var message = values.text.substr(0, 140); // Max len
							message = message.substr(0, Math.min(message.length, message.lastIndexOf(' ')));
							list_item += '<li style="opacity: 0;">' + message + '</li>';
					});
					$('#social_feed').append(list_item);
				}
			});
		},
		facebook : function(){
			$.ajax({
				type : 'GET',
				url : 'https://graph.facebook.com/ashadegreener/statuses?callback=?&fields=message&limit=5&access_token=AAADOF0uRgEUBAMTktwrS0OCBmSGYb0ljoLg7f7dOftskriSWKJZAvLUv4PUbw9pZBPZBf1KUlVcBr204BvJWftJUAOZBx7012uYjR9B4pnHVZAQk9cO8D',
				dataType : 'json',
				success : function(results){
					var list_item = '';
					$.each(results.data, function(index, values){
						var message = values.message.substr(0, 140); // Max Length
							message = message.substr(0, Math.min(message.length, message.lastIndexOf(' ')));
							list_item += '<li>' + message + '</li>';
					});
					$('#social_feed').append(list_item);
				}
			});
		},
		slide : function(){
			var that = this.options;
			(function loopsiloopsiloo(){
				that.elem.find('li:first-child').appendTo(that.elem).animate({
					'opacity' : 0
				}, 500, function(){
					that.elem.find('li:first-child').prependTo(that.elem).animate({
						'opacity' : 1
					}, 500);
				});
				setTimeout(loopsiloopsiloo, 3000);
			})();
		}
	};

	//- Tooltips
	//- Notes: could possibly use the same function for hover and click
	var tooltips = {
		init : function(options){
			this.options = $.extend({
				hover_elem : $('.htip'),
				click_elem : $('.ctip'),
				speed_in : 100,
				speed_out : 100
			}, options);
			this.hover();
			this.click();
		},
		hover : function(){
			$(tooltips.options.hover_elem).bind({
				mouseenter : function(){
					$('<div style="' + $(this).attr('data-tooltip-style') + '" class="tooltip">' + $(this).attr('data-tooltip') + '<div class="tooltip_pointer_down"></div></div>').stop(true, true).fadeIn(tooltips.options.speed_in).appendTo(this);
				},
				mouseleave : function(){
					$('.tooltip').stop(true, true).fadeOut(tooltips.options.speed_out, function(){
						$(this).remove();
					});
				}
			});
		},
		click : function(){
			$(tooltips.options.click_elem).click(function(){
				if($('.ctooltip').css('display') === undefined){
					$('<div style="' + $(this).attr('data-tooltip-style') + '" class="ctooltip">' + $(this).attr('data-tooltip') + '<div class="tooltip_pointer_up"></div></div>').fadeIn(tooltips.options.speed_in).appendTo($(this).parent());
				}
				else {
					$('.ctooltip').stop(true, true).fadeOut(tooltips.options.speed_out, function(){
						$(this).remove();
					});
				}
			});
		}
	};

	//- Scrollable
	//- Notes: Could possibly improve
	var scrollable = {
		init : function(options){
			this.options=$.extend({
				elem : $('.scrollable')
			}, options);
			this.setup();
		},
		setup : function(){
			//- Find all scrollable elements and prepare them with scrollbars.
			this.options.elem.bind('find_scrollable', function(){
				var that = this;
				sb_id=$(that).attr('id')+'_scrollbar';
				$(that).wrap('<div class="scroll_wrapper"/>');
				$(that).children('ul').wrap('<div class="scroll_area" />');
				$(that).parent().append('<div class="scroll_bg"><div id="'+sb_id+'" class="scroll_bar" /></div>');
			}).trigger('find_scrollable');

			$('.scroll_bar').parent().mouseenter(function(){
				highlight.disable(document);
			});
			this.mousedown();
		},
		mousedown : function(){
			$('.scroll_bar').mousedown(function(e){
				//- Scroll IDs
				sb_id=$(this).attr('id');
				s_id=sb_id.substr(0, sb_id.length-10); //- Minus off '_scrollbar'
				//- Work out how far max scroll is
				s_size=parseInt($('#'+s_id+' li:last-child').css('left'))+parseInt($('#'+s_id+' li:last-child').css('width'))
				s_size+=(parseInt($('#'+s_id+' li:last-child').css('borderLeftWidth'))*2)*(parseInt($('#'+s_id+' ul li').size()));
				s_size-=parseInt($('#'+s_id).css('width'));
				//- Scroll bar width
				s_width=parseInt(($('#'+sb_id).parent().css('width')))-100; //- e.g 300px;
				//- Scale movement
				s_divide=0.001;
				while(s_size/s_divide>=s_width){
					s_divide=s_divide+0.001;
				}
				//- Mouse Start Position
				scrollable.m_down=true;
				scrollable.m_start=e.pageX;
				//- Items Start Point
				scrollable.sb_start=parseInt($('#'+sb_id).css('left'));

				scrollable.mousemove();
			});
		},
		mousemove : function(){
			$(document).mousemove(function(e){
				if(scrollable.m_down===true){
					//- Mouse End Position
					m_end=e.pageX;
					m_moved=parseInt(scrollable.m_start)-parseInt(m_end);
					sb_move=parseInt(scrollable.sb_start)-parseInt(m_moved);
					if(sb_move<0){
						sb_move=0;
					}
					if(sb_move>s_width){
						sb_move=s_width;
					}
					$('#'+sb_id).css('left', sb_move+'px');
					s_move=sb_move*s_divide;
					$('#'+s_id+' ul').css('left', '-'+s_move+'px');
					scrollable.mouseup();
				}
			});	
		},
		mouseup : function(){
			$(document).mouseup(function(e){
				scrollable.m_down=false;
				highlight.enable(document);
			});
		}
	};

	//- textToggle
	//- Notes: Could possibly improve
	var textToggle = {
		init : function(options){
			this.options=$.extend({
				elem : $('.slide_item'),
				show : 'h3, .slide_toggle, .show',
				click : 'h3, .slide_toggle'
			}, options);
			this.toggle();
		},
		toggle : function(){
			this.options.elem.children().not(this.options.show).hide();
			$(this.options.click).click(function(e){
				$(this).parents('.slide_item').children('h3').children().toggle();
				$(this).parents('.slide_item').children().not(textToggle.options.show).stop(true, true).slideToggle();
			});
		}
	};

	//- Highlight
	//- Notes: Enables and Disables text highlighting. Useful for other functions
	var highlight = {
		disable : function(elem){
			if(elem.attachEvent){
				elem.attachEvent("onselectstart",highlight.disabler);
			}
			else {
				elem.addEventListener("mousedown",highlight.disabler,"false");
			}
		},
		enable : function(elem){
			if(elem.attachEvent){
				elem.detachEvent("onselectstart",highlight.disabler);
			}
			else {
				elem.removeEventListener("mousedown",highlight.disabler,"false");
			}
		},
		disabler : function(e){
			if(e.preventDefault){
				e.preventDefault(); 
			}
			return false;
		}
	};

	var gMap = {
		init : function(options){
			this.options = $.extend({
				device : 'computer',
				canvas : 'map_canvas',
				search_box : $('#search_query'),
				search_btn : $('#search_btn')
			}, options);

			gMap.loadMap();
		},

		loadMap : function(){
			var latlng = new google.maps.LatLng(53.488212,-1.49575);

			var double_click_zoom = false;
			if(gMap.options.device == 'iOS'){
				double_click_zoom = true;
			}

			var myOptions = {
				zoom : 18,
				center : latlng,
				mapTypeId : google.maps.MapTypeId.HYBRID,
				disableDoubleClickZoom : double_click_zoom,
				panControl : true,
				zoomControl : true,
				mapTypeControl : false,
				scaleControl : false,
				streetViewControl : false,
				overviewMapControl : false,
				panControl : true
			};

			map = new google.maps.Map(document.getElementById(this.options.canvas), myOptions);

			var markerImage = new google.maps.MarkerImage(
				'http://ashadegreener.co.uk/img/map_pin.png',
				new google.maps.Size(60, 62),
				new google.maps.Point(-22, 0)
			);

			var marker = new google.maps.Marker({
				icon: markerImage,
				map: map,
				draggable: true,
				animation: google.maps.Animation.DROP
			});

			if(gMap.options.device == 'iOS'){
				google.maps.event.addListener(map, 'dblclick', function(evt) {
					marker.setPosition(evt.latLng);
					position = evt.latLng;
					//- Add to hidden field
					$('#latlng').val(position);
					gMap.pin_placed();
				});
			}
			else {	
				google.maps.event.addListener(map, 'rightclick', function(evt) {
					marker.setPosition(evt.latLng);
					position = evt.latLng;
					//- Add to hidden field
					$('#latlng').val(position);
					gMap.pin_placed();
				});
			}

			google.maps.event.addListener(marker, 'dragend', function(evt) {
				position = evt.latLng;
				$('#latlng').val(position);
			});
		},
		geocode : function(){
			var geocoder = new google.maps.Geocoder();
			var address = $('#search_query').val();
			geocoder.geocode({ 
				'address': address
			}, function(results, status) {
				if(status === google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
					map.setZoom(18);
				}
			});

			if($('#step1').is(':visible')){	
				$('#step1').fadeOut(100);
				$('#step2').fadeIn(100);
			}
		},
		pin_placed : function(){
			$('#map_wrapper').removeClass('pin_invalid');
			if($('#step2').is(':visible')){
				$('#step2').fadeOut(100);
				$('#step3').fadeIn(100);
			}
		}
	};

	var installMap = {
		init : function(options){
			this.options = $.extend({
				canvas : 'map_canvas'
			}, options);

			installMap.loadMap();
		},

		loadMap : function(){
			var latlng = new google.maps.LatLng(52.456009,-1.428223);

			var myOptions = {
				zoom : 7,
				center : latlng,
				mapTypeId : google.maps.MapTypeId.HYBRID,
				panControl : true,
				zoomControl : true,
				mapTypeControl : false,
				scaleControl : false,
				streetViewControl : false,
				overviewMapControl : false,
				panControl : true
			};

			map = new google.maps.Map(document.getElementById(this.options.canvas), myOptions);

			var leftCoords = [	
								new google.maps.LatLng(64.75539,-31.201172),
								new google.maps.LatLng(64.848937,-4.833984),


								new google.maps.LatLng(54.120602,-2.798767),
								new google.maps.LatLng(53.821733,-2.601013),
								new google.maps.LatLng(53.545204,-2.658691),
								new google.maps.LatLng(53.306262,-2.622986),
								new google.maps.LatLng(52.704683,-2.927856),
								new google.maps.LatLng(52.229482,-2.743835),
								new google.maps.LatLng(51.628248,-2.70813),
								new google.maps.LatLng(51.169011,-3.47168),
								new google.maps.LatLng(50.513427,-2.460937),

								new google.maps.LatLng(39.368279,-3.164062),
								new google.maps.LatLng(39.808536,-30.146484)
							];

			var rightCoords = [
								new google.maps.LatLng(64.848937,-4.833984),
								new google.maps.LatLng(64.811557,26.762695),
								new google.maps.LatLng(42.585444,27.421875),
								new google.maps.LatLng(39.368279,-3.164062),
								new google.maps.LatLng(50.513427,-2.460937),
								new google.maps.LatLng(50.802463,-1.027222),
								new google.maps.LatLng(50.743408,0.087891),
								new google.maps.LatLng(51.131108,-0.153809),
								new google.maps.LatLng(51.169011,-0.508118),
								new google.maps.LatLng(51.394065,-0.681152),
								new google.maps.LatLng(51.69299,-0.626221),
								new google.maps.LatLng(51.76104,-0.32959),
								new google.maps.LatLng(51.869708,0.373535),
								new google.maps.LatLng(52.315195,0.384521),
								new google.maps.LatLng(52.98503,0.031586),
								new google.maps.LatLng(53.255355,-0.082397),
								new google.maps.LatLng(53.48539,0.177841),
								new google.maps.LatLng(53.797406,-0.137329),
								new google.maps.LatLng(54.497163,-0.914612),
								new google.maps.LatLng(54.214664,-2.28241),
								new google.maps.LatLng(54.120602,-2.798767)

							];

			leftArea = new google.maps.Polygon({
				paths: leftCoords,
				strokeColor: "#0077FF",
				strokeOpacity: 0,
				strokeWeight: 2,
				fillColor: "#f00",
				fillOpacity: 0.3
			});

			rightArea = new google.maps.Polygon({
				paths: rightCoords,
				strokeColor: "#0077FF",
				strokeOpacity: 0,
				strokeWeight: 2,
				fillColor: "#f00",
				fillOpacity: 0.3
			});

			leftArea.setMap(map);
			rightArea.setMap(map);
		}
	};

	partners_slide = {
		init : function(options){
			this.options = $.extend({
				elem : $('#partners_logos'),
			}, options);
			this.options.elem.find('li:first-child').css('opacity', 1);
			this.slide();
		},
		slide : function(){
			var that = this.options;
			(function loopsiloopsiloo(){
				that.elem.find('li:first-child').appendTo(that.elem).animate({
					'opacity' : 0
				}, 500, function(){
					that.elem.find('li:first-child').prependTo(that.elem).animate({
						'opacity' : 1
					}, 500);
				});
				setTimeout(loopsiloopsiloo, 5000);
			})();
		}
	};

	var enquire = {
		init : function(options){
			this.options = $.extend({
				form : $('#enquire_form'),
				map_wrapper : $('#map_wrapper'),
				location : $('#latlng'),
				alnums : $('.alnum'),
				from_box : $('#search_query'),
				to_box : $('#postcode'),
				compare : $('.compare'),
				compare_this : $('#email'),
				compare_to : $('#email_c'),
				find : $('#find'),
				send_warning : $('#nopin')
			}, options);
			//- Prepares the instructions
			enquire.prep_instructions();
			//- Auto completes the to box with the value of the from box
			enquire.autocomplete_search();
			//- Adds a listener to check alnum values
			enquire.alnum_listener();
			//- Email Confirm checker
			enquire.email_listener();
			//- Checkbox complete listener
			enquire.checkbox_listener();
			//- Displays more fields
			enquire.other_fields_listener();
			//- Checks everything on submit
			enquire.submit_checks();
		},
		prep_instructions : function(){
			$('#map_help').click(function(){
				$('#step1').fadeIn(100);
			});

			$('#step1').click(function(){
				$(this).fadeOut(100);
				$('#step2').fadeIn(100);
			});

			$('#step2').click(function(){
				$(this).fadeOut(100);
				$('#step3').fadeIn(100);
			});

			$('#step3').click(function(){
				$(this).fadeOut(100);
			});
		},
		//- Listens for alnum values and checks them
		alnum_listener : function(){
			$(enquire.options.alnums).blur(function(){
				if(enquire.regex_alnum(this) === false){
					$(this).removeClass('input_valid').addClass('input_invalid');
				}
				else {
					$(this).removeClass('input_invalid input_invalider').addClass('input_valid');
				}
			});
		},
		email_listener : function(){
			$(enquire.options.compare).blur(function(){
				enquire.email_checks();
			});
		},
		checkbox_listener : function(){
			$('.custom-radio').click(function(){
				console.log('something');
				$('.checkbox_invalid').css('display', 'none');
			});
		},
		//-	On submit check over everything
		submit_checks : function(){
			var incorrect_items = 0;
			enquire.options.form.submit(function(){
				//- Check the alnum fields are filled in
				$(enquire.options.alnums).each(function(index, item){
					if(enquire.regex_alnum(item) === false){
						$(item).addClass('input_invalider');
						incorrect_items++;
					}
				});
				//- Check the email fields
				if(enquire.email_checks() === false){
					$(enquire.options.compare).addClass('input_invalider');
					incorrect_items++;
				}

				//- Check the location
				if(enquire.options.location.val() == ''){
					enquire.options.map_wrapper.addClass('pin_invalid');
					incorrect_items++;
				}

				//- Check the own / rent checkboxes
				var is_checked = $('input[@name=\'own_rent\']:checked').val();
				if(is_checked != 'own' && is_checked != 'rent'){
					$('.checkbox_invalid').css('display', 'block');
					incorrect_items++;
				}

				if(incorrect_items === 0){
					console.log('Send : true');
				}
				else {
					enquire.options.send_warning.css('display', 'block');
					incorrect_items = 0;
					return false;
				}
			});
		},
		email_checks : function(){
			var return_val = false;
			switch(enquire.options.compare_to.val()){
				case enquire.options.compare_this.val():
					if(enquire.regex_email(enquire.options.compare) === true){
						//- Both are the same, and genuine emails
						$(enquire.options.compare).removeClass('input_invalid input_invalider').addClass('input_valid');
						return_val = true;
					}
					else {
						//- Both the same, but both fakies
						$(enquire.options.compare).removeClass('input_valid').addClass('input_invalid');
					}
					break;
				case '':
					//- Not the same, but user hasn't attempted the confirmation box
					break;
				default:
					// - The user just failed at life
					$('.compare').removeClass('input_valid').addClass('input_invalid');
			}
			return return_val;
		},
		other_fields_listener : function(){
			enquire.options.find.change(function(){
				var value = $(this).val();
				switch(value){
					case 'refered':
						$('.hide_other').css('display', 'none');
						$('#refered_hide').css('display', 'block');
						break;
					case 'wom':
						$('.hide_other').css('display', 'none');
						$('#refered_hide').css('display', 'block');
						break;
					case 'postcard':
						$('.hide_other').css('display', 'none');
						$('#postcard_hide').css('display', 'block');
						break;
					case 'other':
						$('.hide_other').css('display', 'none');
						$('#other_hide').css('display', 'block');
						break;
					default:
						$('.hide_other').css('display', 'none');
				}
			});
		},
		//- Checks the value against regex
		regex_alnum : function(that){
				var value = $(that).val();
				var filter = /^[a-zA-Z0-9'\s_.,-@&()]{3,255}$/;
				if(filter.test(value) === false){
					return false;
				}
				else {
					return true;
				}
		},
		//- Checks the value against regex
		regex_email : function(that){
				var value = $(that).val();
				var filter = /^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$/;
				if(filter.test(value) === false){
					return false;
				}
				else {
					return true;
				}
		},
		//- Auto completes the to box with the value of the from box
		autocomplete_search : function(){
			enquire.options.from_box.keyup(function(){
				enquire.options.to_box.val(enquire.options.from_box.val());
			});
		}
	};
	
	window.enquire = enquire;
	window.partners_slide = partners_slide;
	window.gMap = gMap;
	window.installMap = installMap;
	window.feature = feature;
	window.scrollable = scrollable;			
	window.textToggle = textToggle;
	window.social_feed = social_feed;
	window.tooltips = tooltips;
	window.company_counter = company_counter;
})();
