/* Volley

*/

(function($){

	SIGNUP_CONFIGURATION = {
		"input": {
			"formclass": "signup",
			"message": "Enter your email address..."
		}
	}

	STOCKISTS_CONFIGURATION = {
		"input": {
			"formclass": "search",
			"message": "Enter a suburb, city, state or postcode..."
		},
		"filter": {
			"formclass": "filter",
			"message": "Filter results..."
		}
	}

	var Volley = {

		/**
		* Initialize the application
		*/
		initialize: function() {
			
			if($('#ie-container').length > 0) Volley.ieWarning();
			if($('ul#rangeList').length > 0) Volley.setupSubNavigation();
			if($('div#siteMap').length > 0) Volley.setupFooter();
			
			//Setup stockists
			if($('div#s-map').length > 0) Stockists.initialize();
			
			//Input Forms
			if($('input.signup').length > 0) Volley.setupAddForm(SIGNUP_CONFIGURATION);
			if($('input.search').length > 0) Volley.setupAddForm(STOCKISTS_CONFIGURATION);
			
			//Sliders
			if($('#heritageSlider').length > 0) Volley.divSlider('heritage');
			if($('#homeCarousel').length > 0) Volley.divSlider('home');
			
			//Gallery Page
			if($('div.thumbstrip').length > 0) Volley.setupGallery();
			
		},
		
		setupGallery: function() {
			
			$(".gallery .thumbstrip").show();
			$(".gallery .image_wrap").hide();
			
			var first = true;
			
			$(".scrollable").scrollable();
			$(".scrollable a").click(function() {
				return false;
			});

			$(".items a").click(function() {

				var clicked = this;
				if ($(this).hasClass("active")) { return; }

				$(".image_wrap:visible").hide();
				$($(".image_wrap").get($(clicked).index(".items a"))).show();

				// activate item
				$(".items a").removeClass("active");
				$(".items span.active").remove();
				$(this).addClass("active").append("<span class='active'></span>");		

			}).filter(":first").click();
			
			
		},
		
		ieWarning: function() {
			var ieContainer = $('#ie-container');
			ieContainer.slideDown(2000);
			ieContainer.find('a.close').click(function() {
				ieContainer.slideUp(100);
				return false;
			});
		},
		
		setupShoes: function(list) {
			$(list).find('li').click(function() {
				window.location.href = $(this).find('a').attr('href');
			}).css('cursor', 'pointer');
		},
		
		setupFooter: function() {
			$('a.size-chart-link').fancybox({
				'easingIn'      : 'easeOutBack',
				'easingOut'     : 'easeInBack',
				'speedIn'		: 800,
				'autoDimensions': false,
				'overlayColor'	: '#000',
				'overlayOpacity': 0.5,
				'centerOnScroll': true,
				'titleShow'		: false,
				'scrolling'		: 'no'
			});
			$('a.let-us-know').fancybox({
				'easingIn'      : 'easeOutBack',
				'easingOut'     : 'easeInBack',
				'speedIn'		: 800,
				'autoDimensions': true,
				'overlayColor'	: '#000',
				'overlayOpacity': 0.5,
				'centerOnScroll': true,
				'titleShow'		: false,
				'scrolling'		: 'no'
			});
		},

		setupSubNavigation: function() {
			
			$("ul#rangeList ul").hide().parent().find("a.current").siblings("ul").show();
			
		},
		
		setupAddForm: function(CONFIGURATION) {	
			
			$.each(CONFIGURATION, function(key, value){
				$("." + value.formclass).addClass('fallback').val(value.message).focusin(function(){
					if($(this).val() == value.message) $(this).removeClass('fallback').val("");
				}).focusout(function(){
					if($(this).val() == "") $(this).addClass('fallback').val(value.message);
				});
			});
			
			if(CONFIGURATION['input']['class'] == 'signup') {
				$('form#SignupAddForm').submit(function() {
					var signup = $(this).find('input.signup');
					switch(signup.val()) {
						case CONFIGURATION['input']['message']:
						case "":
							signup.focus();
							return false;
							break;
					}
				});
			}
			
		},
		
		divSlider: function(val) {
			
			//Set jQuery easing default value
			jQuery.easing.def = "easeOutQuad";	
			
			if (val == 'home') {
				$('#homeCarousel').slides({
					next: "#carouselNav a.right", 
					prev: "#carouselNav a.left",
					generatePagination: false
				});
			} else if (val == 'heritage') {
				var startValue = 1;
				
				if(window.location.hash) {
					switch(window.location.hash) {
						case '#mark':
							startValue = 1;
							break;
						case '#evonne':
							startValue = 2;
							break;
					}
				}
				
				$('#heritageSlider').slides({
					start: startValue,
					next: "#heritageNavs a.right", 
					prev: "#heritageNavs a.left",
					generatePagination: false,
					
					animationStart: function() {
						$('a.heritageNav').fadeOut();
					},
					animationComplete: function() {
						updateSlideNavigation();
					}
				});
				
				function updateSlideNavigation() {
					var slideId = $('div.slide:visible').find('h2').text().split(' ')[0].toLowerCase();
					window.location.hash = slideId;

					switch(slideId) {
					  case "mark":
						$('#heritageNavs a.right').text('Evonne Goolagong');
						$('#heritageNavs a.right').fadeIn();
						break;
					  case "evonne":
						$('#heritageNavs a.left').text('Mark Edmondson');
						$('#heritageNavs a.left').fadeIn();
						break;
					}		
				}
				
				updateSlideNavigation();
			}
		},
		
		displayModalWindow:function(content) {
			$.fancybox(content, {
				'width'			: 500,
				'height'		: 150,
				'transitionIn'	: 'elastic',
				'transitionOut'	: 'elastic',
				'easingIn'      : 'easeOutBack',
				'easingOut'     : 'easeInBack',
				'speedIn'		: 800,
				'autoDimensions': false,
				'overlayColor'	: '#000',
				'overlayOpacity': 0.5,
				'centerOnScroll': true,
				'titleShow'		: false,
				'scrolling'		: 'no'
			});
		},
		
		setupGalleryHover:function() {
			
			$("ul#gallery li a").prepend("<img class='hoverImg' src='images/gallery/rollOver_landscape.png' alt='' />");
			$("ul#gallery li.portrait a img.hoverImg").remove();
			$("ul#gallery li.portrait a").prepend("<img class='hoverImg' src='images/gallery/rollOver_portait.png' alt='' />");
			
			$("ul#gallery li a").hover(
			  function () {
				$(this).find("img.hoverImg").show();
			  }, 
			  function () {
				$(this).find("img.hoverImg").hide();
			  }
			);
			
		},
		
		lightbox:function() {
		
			$("body").addClass("gallery");		
			
			$("ul#gallery li a").fancybox({
				'speedIn'		:	600, 
				'speedOut'		:	200, 
				'overlayShow'	:	true,
				'showNavArrows' : 	true,
				'cyclic'		: 	true
			});
		}
		
	}

	var Stockists = {
		
		initialize: function() {
			
			$('div.noscript').hide();
			$('div.sidebar').show();
			
			//Set & update width for google maps window on browser resize
			$(window).bind("resize", resizeWindow);				  
			resizeWindow();
			
			function resizeWindow() {
				var fullWidth = $("#content div.stockists").width();
				var sidebarWidth = $("#content div.stockists div.sidebar").innerWidth();
				var mapDiv = $("#s-map");
			
				mapDiv.width(fullWidth - sidebarWidth);
			}

			// Define global markers and stockists array
			markersArray = [];
			stockistsObject = {};
			
			// Set up geocoder
			geocoder = new google.maps.Geocoder();
			
			var initialLocation = new google.maps.LatLng(-29.24469, 145.19531);
			
			// Set up map options
			var options = {
				zoom: 4,
				center: initialLocation,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				scrollwheel: false,
				mapTypeControl: false
			};
			
			// Initialize map
			map = new google.maps.Map(document.getElementById("s-map"), options);
			infowindow = new google.maps.InfoWindow({
				maxWidth: 400
			});
			
			google.maps.event.addListener(infowindow, 'closeclick', function() {
				$('div.stockist').removeClass('selected');
			});

			Stockists.setupSearchForm();
			Stockists.getStockists();
			
		},
			
		setupSearchForm: function() {
			
			var countrybounds = new google.maps.LatLngBounds(new google.maps.LatLng('-50', '-168'), new google.maps.LatLng('-5', '108'));
			
			$("input#search").autocomplete({
				source: function(request, response) {
					geocoder.geocode({
						'bounds': countrybounds,
						'region': 'au',
						'address': request.term
					}, function(results, status) {
						
						$.each(results, function(index, value) {
							if(value) {
								var autopoint = new google.maps.LatLng(value.geometry.location.lat(), value.geometry.location.lng());
								if(countrybounds.contains(autopoint) == true) {
									results.splice(index, 1);
								}
							}
						});
						
						response($.map(results, function(item) {						
							return {
								label: item.formatted_address,
								value: item.formatted_address,
								latitude: item.geometry.location.lat(),
								longitude: item.geometry.location.lng(),
								bounds: item.geometry.bounds
							}
						}));
					})
				},
				
				//This bit is executed upon selection of an address
				select: function(event, ui) {
					var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
					map.setCenter(location);
					if(ui.item.bounds) {
						map.fitBounds(ui.item.bounds);
					} else {
						map.setZoom(14);
					}
					
				}
			});
			
			$('form.search').submit(function() {
				var search = $(this).find('input.search');
				
				switch(search.val()) {
					case STOCKISTS_CONFIGURATION['input']['message']:
					case "":
						search.focus();
						return false;
						break;
				}
				
				Stockists.searchStockists($(this).find('input').val());
				return false;
			});
			
		},
		
		searchStockists: function(search) {
			
			geocoder.geocode( {
				'address': search,
				'bounds': new google.maps.LatLngBounds(new google.maps.LatLng('-50', '-168'), new google.maps.LatLng('-5', '108')),
				'region': 'au'
				}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
					
					if(results[0].geometry.bounds) {
						map.fitBounds(results[0].geometry.bounds);
					} else {
						map.setZoom(14);
					}
				} else {
					
					var result  = '<div id="content">';
							
					switch(status) {
						case google.maps.GeocoderStatus.ZERO_RESULTS:
							result += '<h1>Location not found</h1>';
							result += '<p>Please enter a suburb, city, state or postcode.</p>';
							break;
						case google.maps.GeocoderStatus.OVER_QUERY_LIMIT:
							result += '<h1>Service temporarily unavailable.</h1>';
							result += '<p>Please wait before searching again.</p>';
							break;
						case google.maps.GeocoderStatus.REQUEST_DENIED:
							result += '<h1>Service temporarily unavailble.</h1>';
							result += '<p>Please contact us or try again later.</p>';
							break;
						case google.maps.GeocoderStatus.INVALID_REQUEST:
							result += '<h1>Location not found</h1>';
							result += '<p>Please enter a suburb, city, state or postcode.</p>';
							break;
					}
							
					result += '</div>';
					
					Volley.displayModalWindow(result);
				}
			})
			
		},
		
		zoomToResults: function() {
			
			var latLng = [];
			$.each(markersArray, function(i, value) {
				if(markersArray[i].getVisible()) latLng.push(markersArray[i].getPosition());
			});
			
			var latLngBounds = new google.maps.LatLngBounds();
			$.each(latLng, function(i, value){
			   latLngBounds.extend(value);
			});
			
			map.setCenter(latLngBounds.getCenter());
			map.fitBounds(latLngBounds);
		},
		
		getStockists: function() {

			$.ajax({
				type: 'GET',
				url: location.href + Utilities.getDirectorySlash() + 'search/?is_ajax=true',
				dataType: 'json',
				success: function(data, textStatus){
					if($(data).length > 0)
					{
						Stockists.storeAllStockists(data);
					} else {
						var result  = '<div id="content">';
							result += '<h1>Stockists not found</h1>';
							result += '<p>Stockists not found - please try again later, or contact us.</p>';
						result += '</div>';

						Volley.displayModalWindow(result);
					}
				},
				error: function(XMLHttpRequest){
					var result  = '<div id="content">';
						result += '<h1>Stockists not found</h1>';
						result += '<p>An error has occured while retrieving the stockists - please try again later, or contact us.</p>';
					result += '</div>';
					
					Volley.displayModalWindow(result);	
				}
			});
			
		},
		
		storeAllStockists: function(data) {
			
			stockistsObject = data;
			
			$.each(stockistsObject, function(index, value){
				Stockists.addMarker(index, new google.maps.LatLng(value['Stockist']['latitude'], value['Stockist']['longitude']), value['Stockist']);
			});
			
			var clusterStyles = [{
				url: location.href + Utilities.getDirectorySlash() + '../images/stockists/map-cluster-small.png',
				height: 35,
				width: 35,
				textColor: '#ffffff',
				textSize: 11,
				textFont: '"RockwellRegular",serif'
			}, {
				url: location.href + Utilities.getDirectorySlash() + '../images/stockists/map-cluster-medium.png',
				height: 45,
				width: 45,
				textColor: '#ffffff',
				textSize: 12,
				textFont: '"RockwellRegular",serif'
			}, {
				url: location.href + Utilities.getDirectorySlash() + '../images/stockists/map-cluster-large.png',
				height: 55,
				width: 55,
				textColor: '#ffffff',
				textSize: 14,
				textFont: '"RockwellRegular",serif'
			}];
			
			var markerCluster = new MarkerClusterer(map, markersArray, {
				maxZoom: 9,
				styles: clusterStyles
			});
			
			Stockists.addStockistsToSidebar();
			
			var initialised = false;
			var boundsChanged = google.maps.event.addListener(map, 'bounds_changed', function() {
				if(!initialised) {
					google.maps.event.removeListener(boundsChanged);
					setInterval(Stockists.checkStock, 1000);
				}
			})
			
			google.maps.event.addListener(map, 'dragend', function() {
				setTimeout(Stockists.updateStockist, 500);
			});
			google.maps.event.addListener(map, 'zoom_changed', function() {
				setTimeout(Stockists.updateStockist, 500);
			});
			
			// Try W3C Geolocation (Preferred)
			if(navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(function(position) {
					map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
					map.setZoom(14);
				}, function() {});
			}
			
		},
		
		updateStockist: function() {
			
			$('div.stockist').hide();
			
			if(map.getZoom() >= 10) {
			
				$.each(markersArray, function(i, value){
				
					if(map.getBounds().contains(markersArray[i].getPosition())) {
						$('div#sid-' + $(markersArray[i]).data('id')).show();		
					}
				
				});
			
				Stockists.checkStock();
				$('div.results').scrollTop(0);
			
			}

		},
		
		checkStock: function() {
			
			checked = [];
			
			$.each($('div.ranges input:checkbox:checked'), function(i, value) {
				checked[i] = $(value).attr('name');
			});
			
			$.each($('div.stockist'), function(i, value) {
				if(Stockists.checkStockistHasStock(checked, value) && map.getBounds().contains($(value).data('marker').getPosition()) && map.getZoom() >= 10) {
					$(value).show();
					$(value).data('marker').setVisible(true);
				} else {
					$(value).hide();
					$(value).data('marker').setVisible(false);
				}
			});
		},
		
		checkStockistHasStock: function(checked, value) {
			
			var hasStock = false;
			
			$.each($(value).find('div.swatches img'), function(j, subvalue){
				if($.inArray($(subvalue).attr('id'), checked) != -1) {
					hasStock = true;
				}
			});
			
			return hasStock;

		},
		
		addStockistsToSidebar: function() {
			
			$('div.ranges input:checkbox').attr('checked', true)
			$('div.ranges input:checkbox').change(function(e) {
				$('div.stockist').removeClass('selected');
				infowindow.close();
				Stockists.updateStockist();
			});
			
			var stockists = "";
			
			$.each(markersArray, function(i, value){
				var marker = $(markersArray[i]).data('data');
				
				var stockist = "<div class='stockist clearfix' id='" + "sid-" + $(markersArray[i]).data('id') + "'>";
					stockist += "<span class='marker'>Marker</span>";
					stockist += "<h3><a class='anchor' href='javascript:;'>" + marker['title'] + "</a></h3>";
					stockist += "<div class='clearfix'></div>";
					stockist += "<ul>";
						if(marker['trading']) stockist += "<li>" + marker['trading'] + "</li>";
						if(marker['address']) stockist += "<li>" + marker['address'] + "</li>";
						if(marker['city']) stockist += "<li>" + marker['city'] + "</li>";
						if(marker['state']) stockist += "<li>" + marker['state'];
						if(marker['country']) stockist += ", " + marker['country'];
						if(marker['postcode']) stockist += ", " + marker['postcode'] + "</li>";
						if(marker['phone']) stockist += "<li class='phone'>" + marker['phone'] + "</li>";
						if(marker['fax']) stockist += "<li class='fax'>" + marker['fax'] + "</li>";
					stockist += "</ul>";
					var meta = "width='7' height='7' src='" + location.href + Utilities.getDirectorySlash() + "../images/stockists/swatch-";
					stockist += "<div class='colours'>";
						stockist += "<div class='swatches'>";
							if(marker['stockist_oc'] == true) stockist += "<img id='volleyoc' alt='Volley OC' " + meta + "oc.gif' />";
							if(marker['stockist_ss'] == true) stockist += "<img id='volleyss' alt='Volley SS' " + meta + "ss.gif' />";
							if(marker['stockist_international'] == true) stockist += "<img id='volleyinternational' alt='Volley International' " + meta + "international.gif' />";
						stockist += "</div>";
						stockist += "<div class='clearfix'></div>";
						stockist += "<a href='javascript:;' class='colourchart' title=' '>What is this?</a>"
					stockist += "</div>";

				stockist += "</div>";			
				stockists += stockist;
			});
			
			$('div.results').html(stockists);
			
			$.each($('div.stockist'), function(i, value) {
				$(this).data('marker', markersArray[$(this).attr('id').split('-')[1]]);
			});
			
			$('div.stockist').hide();
			
			var tooltip = "<div><img src='" + location.href + Utilities.getDirectorySlash() + "../images/stockists/tooltip-colours.png' width='326' height='153' title='What do these colours mean?' /></div>";
			
			$('div.stockist a.colourchart').tooltip({
				layout:tooltip,
				predelay: 300,
				delay: 0,
				effect: 'slide',
				offset: [5, -85]
			}).dynamic();
			
			$('div.stockist').hover(function() {
				$(this).addClass('hover');
				$(this).data('marker').setAnimation(google.maps.Animation.BOUNCE);
				$(this).data('marker').setAnimation(null);
			}, function() {
				$(this).removeClass('hover');
				$(this).data('marker').setAnimation(null);
			});
			
			$('div.stockist a.anchor').click(function() {
				var marker = $(this).closest('div.stockist').data('marker');
				marker.setAnimation(google.maps.Animation.BOUNCE);
				Stockists.clickMarker(marker);
			});
			
		},
		
		clickMarker: function(marker) {
			
			map.setCenter(marker.getPosition());
			
			var contentString = '';
				contentString += '<div id="infowindow" style="height:150px;">';
					contentString += '<h4>' + $(marker).data('data')['title'] + '</h4>';
					contentString += '<ul>';
						if($(marker).data('data')['trading']) contentString += "<li>" + $(marker).data('data')['trading'] + "</li>";
						if($(marker).data('data')['address']) contentString += "<li>" + $(marker).data('data')['address'] + "</li>";
						if($(marker).data('data')['city']) contentString += "<li>" + $(marker).data('data')['city'] + "</li>";
						if($(marker).data('data')['state']) contentString += "<li>" + $(marker).data('data')['state'];
						if($(marker).data('data')['country']) contentString += ", " + $(marker).data('data')['country'];
						if($(marker).data('data')['postcode']) contentString += ", " + $(marker).data('data')['postcode'] + "</li>";
						if($(marker).data('data')['phone']) contentString += "<li class='phone'>" + $(marker).data('data')['phone'] + "</li>";
						if($(marker).data('data')['fax']) contentString += "<li class='fax'>" + $(marker).data('data')['fax'] + "</li>";
					contentString += '</ul>';
				contentString += '</div>';
			
			infowindow.setContent(contentString);
			infowindow.open(map, marker);
			if(map.getZoom() < 10) map.setZoom(10);
			
			$('div.stockist').removeClass('selected');
			$('div#sid-' + $(marker).data('id')).addClass('selected');
			
			$.each(markersArray, function(i, value) {
				markersArray[i].setAnimation(null);
			});
		},
		
		addMarker: function(id, loc, data) {
			marker = new google.maps.Marker({
				position: loc,
				map: map,
				icon: new google.maps.MarkerImage(location.href + Utilities.getDirectorySlash() + '../images/stockists/map-marker-icon.png', new google.maps.Size(16, 21), new google.maps.Point(0,0), new google.maps.Point(13, 21)),
				shadow: new google.maps.MarkerImage(location.href + Utilities.getDirectorySlash() + '../images/stockists/map-marker-shadow.png', new google.maps.Size(20, 15), new google.maps.Point(0,0), new google.maps.Point(8, 15)),
				visible: false
			});
			
			$(marker).data('id', id);
			$(marker).data('data', data);
			
			google.maps.event.addListener(marker, 'click', function(){
				Stockists.clickMarker(this);
			});
			
			markersArray.push(marker);
		}
		
	}

	Utilities = {
		
		getDirectorySlash:function () {
			return location.href.charAt(location.href.length - 1) == "/" ? "" : "/";
		}
		
	}
	
	ND = {
		expandable:function() {
			$('.expand-target').hide();
			$('.expand-trigger').click(function(e) {
				$($(this).attr('rel')).slideToggle('fast');
				e.preventDefault();
			});
		},		
		floatbox:function() {
			if ($('.checkout-onepage-index #aside').length > 0){
				$('.checkout-onepage-index #aside').stickyfloat({duration: 400, startOffset:124, offsetY: -124});
			}
		}
	}

	$(document).ready(function() {
		Volley.initialize();
		ND.expandable();
		ND.floatbox();
	});
	
})(jQuery);

