google.setOnLoadCallback(function(){$(document).ready(SalonInit);});

function SalonInit()
{
	var SALON = new Salon();
	
	var mapTarget = false;
	var mapZoom = 12;
	
	if(!ShinobiUtils.isEmpty(document.getElementById('salonInformation')) && ShinobiUtils.isEmpty($('#salonMainImage').html()))
	{
		mapTarget = document.getElementById('salonInformation');
		mapZoom = 12;
	}
	
    if(!ShinobiUtils.isEmpty(document.getElementById('salonLocation')))
    {
    	mapTarget = document.getElementById('salonLocation');
    	mapZoom = 15;
    }
    
    if(!ShinobiUtils.isEmpty(document.getElementById('salonSearchNearestMap')))
    {
    	mapTarget = document.getElementById('salonSearchNearestMap');
    	mapZoom = 13;
    }
    
    if(!ShinobiUtils.isEmpty(document.getElementById('salonPrices')))
    {
    	SALON.initSalonPrices();
    }
    
    if(!ShinobiUtils.isEmpty(document.getElementById('salonPromotions')))
    {
    	SALON.initSalonPromotions();
    }
    
    if(!ShinobiUtils.isEmpty(document.getElementById('salonMeetTheTeam')))
    {
    	SALON.initSalonMeetTheTeam();
    }
    
	if(mapTarget) SALON.initMap(mapTarget, mapZoom);
	if(!ShinobiUtils.isEmpty(document.getElementById('salonsMap'))) SALON.initSalonsMap();
	if(!ShinobiUtils.isEmpty(document.getElementById('salonFinderPanel'))) SALON.initLetters();
	if(!ShinobiUtils.isEmpty(document.getElementById('salonThumbnails'))) SALON.initThumbnails();
	if(!ShinobiUtils.isEmpty(document.getElementById('salonFinderForm'))) SALON.initSalonFinder();
	if(!ShinobiUtils.isEmpty(document.getElementById('showMoreSalons'))) SALON.initShowMoreSalons();
}

function Salon()
{
	var fadeOut = .25;
	var selected = 0;
	
	this.initMap = initMap; function initMap(mapTarget, mapZoom)
	{
		var centerLatLng = new google.maps.LatLng(parseFloat(salonDetails[0]['latitude']), parseFloat(salonDetails[0]['longitude']));
		var tgMarker = new google.maps.MarkerImage(salonDetails[0]['tgMarker'], new google.maps.Size(50,33), new google.maps.Point(0,0), new google.maps.Point(25,33));
		var youMarker = new google.maps.MarkerImage(salonDetails[0]['youMarker'], new google.maps.Size(50,33), new google.maps.Point(0,0), new google.maps.Point(25,33));
		
		var map = new google.maps.Map(mapTarget, {
			zoom:mapZoom,
			center:centerLatLng,
			mapTypeId:google.maps.MapTypeId.ROADMAP,

			mapTypeControl: true,
		    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},

			navigationControl: true,
			navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		    
			scrollwheel: false
		});
		
		if(salonDetails.length > 1)
		{
			var i = salonDetails.length;
			while(i--)
			{
				if(i == 0)
				{
					var marker = new google.maps.Marker({title:'Your position', position:centerLatLng, map:map, icon:youMarker});
				} else {
					var marker = new google.maps.Marker({title:salonDetails[i]['name'].replace('&amp;', '&'), position:new google.maps.LatLng(parseFloat(salonDetails[i]['latitude']), parseFloat(salonDetails[i]['longitude'])), map:map, icon:tgMarker});

					$(marker).data('id', '/salon/information/' + salonDetails[i]['id']);
					google.maps.event.addListener(marker, 'click', function() { window.location.href = $(this).data('id'); });
				}
			}
		} else {
			marker = new google.maps.Marker({position:centerLatLng, map:map, icon:tgMarker});
		}
	};
	
	this.initThumbnails = initThumbnails; function initThumbnails()
	{
		$('#salonThumbnails img').each(
			function(i){
				$(this).data('id', i);
			}
		).hover(
			function(){
				if($(this).data('id') != selected) $(this).stop().fadeTo('fast', .75);
			},
		
			function(){
				if($(this).data('id') != selected) $(this).stop().fadeTo('fast', fadeOut);
			}
		).click(
			function(){
				selected = $(this).data('id');
				$('#salonMainImage img').attr('src', $(this).attr('src').split('/thumb/').join('/full/'));
				
				fadeUnselected();
			}
		);
		
		fadeUnselected();
		
		function fadeUnselected()
		{
			$('#salonThumbnails img').each(
				function(i){
					if(i != selected)
					{
						$(this).fadeTo('fast', fadeOut);
					} else {
						$(this).fadeTo('fast', 1);
					}
				});
		}
	};
	
	this.initLetters = initLetters; function initLetters()
	{
		var salonData = null;
		var letter = null;
		
		var type = $('#salonFinderByLetterForm [name="type"]:checked').val();
		
		$('#salonFinderByLetterForm [name="type"]').change(function(obj){type = $(obj.currentTarget).val(); getList(letter); });
		$('#salonLetters li').click(function(){getList(letter = $(this).html());});
				
		function getList(letter)
		{
			if(letter) $.ajax({url:'/gateway/salon-letter/' + letter + '/' + type, dataType:'json', async:true, success:function(data){updateList(data, letter);}});
		};
		
		function updateList(data, letter)
		{
			if(letter)
			{
				clearSalonFinderPanel();
			
				if(ShinobiUtils.isEmpty(data.length))
				{
					$('#salonFinderPanel ul').append('<li><h2>&bull; No salons found.</h2></li>');
				} else {
					$('#salonImages li img').hide();
					clearTimeout(rotateSalons);
					$('#salonFinderPanel ul').append('<li><h2>&bull; ' + letter + '</h2></li>');
				
					$(data).each(function(i){
							
						var salon = '';
						var city = '';
						var name = '';
						var country = '';
							
						if(!ShinobiUtils.isEmpty(data[i]['type']))
					
						var city = data[i]['city'];
						if(!ShinobiUtils.isEmpty(city)) salon = salon.concat(city);
					
						var name = data[i]['name'];
						if(!ShinobiUtils.isEmpty(name)) salon = salon.concat(', ' +  name);
					
						var country = data[i]['country'];
						if(!ShinobiUtils.isEmpty(country)) salon = salon.concat(', ' + country + '.');
					
						$('#salonFinderPanel ul').append('<li><a href="/salon/information/' + data[i]['id'] + '">&raquo; <strong>' + data[i]['type'] + '</strong> ' + salon + '</a></li>');
				});
			}
			}
		};
		
		//Rotate salon finder page images
		$('#salonImages li.current img').fadeIn('slow');
		var rotateSalons = setInterval(function(){
		  	var $next = $('#salonImages li.current img').fadeOut('slow').parent('li').removeClass().next('li');
		  	
		  	if(!$next.length) $next = $('#salonImages li:first');
		  	
		  	$next.addClass('current').children('img').fadeIn('slow');
		},3000);
	}
	
	this.initSalonFinder = initSalonFinder; function initSalonFinder()
	{
		var flagPost = false;
		var geo = new Array();
		var geoData = false;
		var keywords = '';
		
		$('#salonFinderForm').submit(
				function()
				{
					$('#salonImages').remove();
					
					if(flagPost)
					{
						return true;
					} else {
						keywords = filterKeywords($('#salonFinder [name=keywords]').val().toLowerCase());
						
						queryGoogle();
						return false;
					}
				}
		);
		
		this.filterKeywords = filterKeywords; function filterKeywords(keywords)
		{
			switch (keywords)
			{
				case 'sw1':
					keywords = 'sw1a';
				break;
				
				case 'w1':
					keywords = 'w1a, london';
				break;
				
				case 'soho':
					keywords = 'soho, greater london';
				break;
				
				case 'east london':
					keywords = 'east london, uk';
				break;
				
				case 'chelsea':
					keywords = 'king\'s road, chelsea, london, uk';
				break;
				
				case 'covent garden':
					keywords = 'covent garden, tube station, london, uk';
				break;
				
				case 'newark':
					keywords = 'newark, uk';
				break;
				
				case 'yorkshire':
					keywords = 'yorkshire, uk';
				break;
				
				case 'crouch end':
					keywords = '22 Crouch End Hill';
				break;
				
				case 'st albans':
					keywords = 'St Albans, St Peters St';
				break;
				
				case 'westfield':
					keywords = 'Ariel Way, Hammersmith, Greater London, UK';
				break;
				
				case 'bluewater':
					keywords = 'Bluewater, Dartford, UK';
				break;
			}
			
			return keywords;
		}
		
		this.queryGoogle = queryGoogle; function queryGoogle()
		{
			var geocoder = new google.maps.Geocoder();
			
			if(geocoder) {
				geocoder.geocode({'address':keywords, 'region':'uk', 'language':'en'}, function (results, status) {
					
					geoData = undefined;
					
					switch(status)
					{
						case google.maps.GeocoderStatus.OK:
							geoData = results;
							parseResults();
						break;
						
						case google.maps.GeocoderStatus.ZERO_RESULTS:
							geoData = null;
							parseResults();
						break;
						
						case google.maps.GeocoderStatus.OVER_QUERY_LIMIT:
							queryLocal();
						break;
						
						case google.maps.GeocoderStatus.REQUEST_DENIED:
							queryLocal();
						break;
						
						case google.maps.GeocoderStatus.INVALID_REQUEST:
							queryLocal();
						break;
					}
				});
			}
		}
		
		this.queryLocal = queryLocal; function queryLocal()
		{
		}
		
		this.parseResults = parseResults; function parseResults()
		{
			if(geoData)
			{
				clearSalonFinderPanel();
				
				if(geoData.length > 1)
				{
					$('#salonFinderPanel ul').append('<li><h2>&bull; Did you mean...</h2></li>');
					c = 0;
					i = geoData.length;
					
					while(i--)
					{
						var result = geoData[(geoData.length-1) - i];
						$('#salonFinderPanel ul').append('<li><a href="#">&raquo; ' + result.formatted_address + '</a></li>');
					}
					
					$('#salonFinderPanel ul li').each(function(i){
						$(this).data('id',i - 1);
						$(this).click(function(){
							geo['formatted_address'] = geoData[$(this).data('id')].formatted_address;
							geo['lat'] = geoData[$(this).data('id')].geometry.location.lat();
							geo['lng'] = geoData[$(this).data('id')].geometry.location.lng();
							
							submitSalonFinderForm();
						});
					});
					
				} else {
					geo['formatted_address'] = geoData[0].formatted_address;
					geo['lat'] = geoData[0].geometry.location.lat();
					geo['lng'] = geoData[0].geometry.location.lng();
					
					submitSalonFinderForm();
				}
			} else {
				clearSalonFinderPanel();
				$('#salonFinderPanel ul').append('<li><h2>- Sorry, we couldn\'t find any results matching your search terms...</h2>&nbsp;&nbsp;&nbsp;Please try again.</li>');
			}
		}
		
		this.submitSalonFinderForm = submitSalonFinderForm; function submitSalonFinderForm()
		{
			flagPost = true;
			$('#salonFinder [name=data]').val(geo['formatted_address'] + '|' + geo['lat'] + '|' + geo['lng']);
			$('#salonFinderForm').submit(); 
		}
	}
	
	this.clearSalonFinderPanel = clearSalonFinderPanel; function clearSalonFinderPanel()
	{
		$('#salonFinderPanel ul').remove();
		$('#salonFinderPanel').append('<ul></ul>');
	}
	
	this.initShowMoreSalons = initShowMoreSalons; function initShowMoreSalons()
	{
		$('#showMoreSalons').click( function() { showMoreSalons(); return false; });
		
		function showMoreSalons()
		{
			$('#salonSearchOthers ul li.sfHide').show().animate({'height':'60px'}, 'slow', function() { $(this).css({'height':'100%'}); });
			$('#salonDidntFind').html('<p>Didn\'t find what you were looking for? Try the <a href="/salon/finder"><u>Salon Finder</u></a> again.</p>');
		}
	}
	
	this.initSalonPrices = initSalonPrices; function initSalonPrices()
	{
		$('#salonSideMenu ul.sub li').each( function(i){ $(this).data('idRef', i); } ).click( function(){ showHideSection($(this).data('idRef')); return false;});
		
		showHideSection(0);
		
		function showHideSection(section)
		{
			$('#salonArticle div.services').hide();
			$('#salonSideMenu ul.sub li').removeClass('selected');
			
			$('#salonSideMenu ul.sub li:eq(' + section + ')').addClass('selected');
			$('#salonArticle div.services:eq(' + section +')').show();
		}
	}
	
	this.initSalonPromotions = initSalonPromotions; function initSalonPromotions()
	{
		$('#salonSideMenu ul.sub li').each( function(i){ $(this).data('idRef', i); } ).click( function(){ showHideSection($(this).data('idRef')); return false;});
		
		showHideSection(0);
		
		function showHideSection(section)
		{
			$('#salonArticle div.promotions').hide();
			$('#salonSideMenu ul.sub li').removeClass('selected');
			
			$('#salonSideMenu ul.sub li:eq(' + section + ')').addClass('selected');
			$('#salonArticle div.promotions:eq(' + section +')').show();
		}
	}
	
	this.initSalonMeetTheTeam = initSalonMeetTheTeam; function initSalonMeetTheTeam()
	{
		$('#salonSideMenu ul.sub li').each( function(i){ $(this).data('idRef', i); } ).click( function(){ showHideSection($(this).data('idRef')); return false;});
		
		showHideSection(0);
		
		function showHideSection(section)
		{
			$('#salonArticle div.member').hide();
			$('#salonSideMenu ul.sub li').removeClass('selected');
			
			$('#salonSideMenu ul.sub li:eq(' + section + ')').addClass('selected');
			$('#salonArticle div.member:eq(' + section +')').show();
		}
	}
}
