var map;
var mapObj = null;
var addressManager;
var tagManager;
var openingTimeManager;
var graphManager;
var tabDataManager = null;
var directoryManager = null;
var toggled = false;
$(document).ready(function(){
	
	// Search for the google map

	$('#google_map').each(function(){
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("google_map"));
			if($(this).hasClass('business')){
				map.addControl(new GSmallMapControl());
			} else {
				map.addControl(new GLargeMapControl());
			}
			map.addControl(new GMapTypeControl());
		}
	});
	
	$('.toggleMap').click(function(){
		$('#tabular, .toggleMap').fadeOut('slow', function(){
			$('#google_map, .toggleTable').fadeIn();
		});
		return false;
	});
	
	$('.toggleTable').click(function(){
		if(toggled == false){
			$('select[name="sort[limit]"]').val('10');
			$('#tabular table tbody tr:gt(10)').remove();
		}

		$('#google_map, .toggleTable').fadeOut('slow', function(){
			$('#tabular, .toggleMap').fadeIn(null);
		});
		toggled = true;
		return false;
	});
	
	// Initialise tab manager and map manager if one exists
	if($('#google_map').length > 0){	
		mapObj = new MapManager($('#google_map').attr('class'));
	}
	
	if($('#tabular').length > 0){
		tabDataManager = new TabDataManager('#tabular');
	}
	
	if(mapObj || tabDataManager){
		
		// Init the directory manager
		directoryManager = new DirectoryManager();
		
		// Perform a blank search to get all businesses

		if ($('#fuelpoint_search form').length > 0) {
			directoryManager.search($('#fuelpoint_search form, #tabular form').serialize());
		}
		else if(gup('id')){
			directoryManager.search('id=' + gup('id'));
		} else {
			directoryManager.search('fields[price]=false');
		}
		
		$('#fuelpoint_search form :input').change(function(){
			directoryManager.search($('#fuelpoint_search form, #tabular form').serialize());
		});
		
		$('#tabular form#sortForm').submit(function(){
			return false;
		});

		$('#tabular form#sortForm .button').click(function(){
			directoryManager.search($('#fuelpoint_search form, #tabular form').serialize());
		});
		

	}
	
	// Set the rating
	if ($('#rating_1').length > 0) {
	
		$('#rating_1').rating();
		$('#rating_2').rating();
		$('#rating_3').rating();
		$('#rating_4').rating();
		
		var voteHeight = $('#ratingForm').height();
	}
	
	$('#ratingForm').submit(function(){
		
		var ratings = $(this).serialize();
		
		$(':submit', this).fadeOut(null, function(){
			$('.loading', this).fadeIn();
		});
		
		var tmpObj = this;
		
		$.getJSON('/json/?controller=directory&method=rate', ratings, function(data){
			$('.loading', tmpObj).fadeOut();

			if(data.status.message == 'OK'){
				$('.vote').fadeOut(null, function(){
					$(this).text('Your rating has been submitted.');
					$(this).unbind();
					$(this).css('cursor', 'default');
					removeVote();
					$('.vote').fadeIn();
					// Update the stars
					var rating = data.data.rating;
					$('.current-rating span[class!="vote"]').each(function(i){						
						
						if(i < rating){
							$(this).addClass('selected');
						}
						
					});
				});
			} else {
				$('.vote').fadeOut(null, function(){
					$(this).text(data.status.message);
					$(this).unbind();
					$(this).css('cursor', 'default');
					removeVote();
					$(this).fadeIn();
				})
				
			}
		});
		
		return false;
	});
	
	$('.vote').click(function(){
		if($('#ratingForm').css('display') == 'none'){
			showVote();
		} else {
			hideVote();
		}
	});
	
	function showVote(){
		$('#ratingForm').css({height: 0, opacity: 0, display: 'block'});
		$('#ratingForm').animate({height: voteHeight, opacity: 1});
	}
	
	function hideVote(){
		$('#ratingForm').animate({height: 0, opacity: 0}, null, null, function(){
			$('#ratingForm').css({display: 'none'});
		});
	}
	
	function removeVote(){
		$('#ratingForm').animate({height: 0, opacity: 0}, null, null, function(){
			$('#ratingForm').css({display: 'none'});
			$('#ratingForm').remove();
		});
	}
	
	if($('#field_AddressPrimaryCountry').length > 0){
		addressManager = new DropDownAddressManager('#field_AddressPrimaryCountry', '#field_AddressPrimaryCounty', '#field_AddressPrimaryTown');
		
	}
	
	if($('#tagWrapper').length > 0){
		tagManager = new TagManager('#tagWrapper', '.availabletags .tags', '.folders', '.chosentags');
	}
	
	if ($('select.json_country').length > 0) {
		addressManager = new DropDownAddressManager('.json_country', '.json_county', '.json_town');
	}

	
	$('#field_AddressPrimaryPostcode').keyup(function(){
		
		var value = $(this).val();
		
		if (value.length > 0) {
			$('p.conditional, dl.coordinates').fadeOut('slow');
		} else if (value.length == 0) {
			$('p.conditional, dl.coordinates').fadeIn('fast');
		}
		
	});
	
	if($('div#graph').length > 0){
		graphManager = new GraphManager('div#graph');
	}
	
	$('#viewGraph').click(function(){
		
		var windowWidth = $(window).width();
		var windowHeight = $(window).height();
		
		var graphWidth = $('#graph').width();
		var graphHeight = $('#graph').height();
		
		var graphOffset = $('#graph').o
		
		var positionX = ((windowWidth / 2) - (graphWidth / 2));
		var positionY = ((windowHeight / 2) - (graphHeight / 2));
		
		
		$('#graph').prependTo('body');
		
		$('#graph a.close').click(function(){
			$('#graph').fadeOut();
			return false;
		});
		
		$('#graph').css({
			left: positionX,
			top: positionY
		});
		
		$('#graph').fadeIn('slow');
		
	});
	
	if($('p#newsList').length){
		$('p#newsList').text('Loading rss feed...');
		$.get('/blog/?feed=rss2', null, function(data, status){
			
			var html = '';
			
			$('item', data).each(function(i){
				if(i < 2){
					date = new Date($('pubDate', this).text());
					html +=	'<p><strong><a href="' + $('link', this).text() + '">' + $('title', this).text() + '</a> ' + date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear() + '</strong></p>';
					html += '<p>' + $('description', this).text().substr(0, 100) + '...</p>';
				}
			});
			
			$('p#newsList').after(html);
			$('p#newsList').remove();
			
		});
	}
	
	$('div.folders a').click(function(){
		
		var folderId = $(this).attr('id').replace(/folder_/, '');
		var tmpObj = this;
		var tagDiv = $(this).parent('div').next('div');
		var folderDiv = $(this).parent('div');
		$('a[class="tag"]', tagDiv).remove();
		// Get the tags
		$.getJSON('/json/?controller=directory&method=getTags', 'folderId=' + folderId, function(response){
			
			for (var i = 0; i < response.data.length; i++) {
				$(tagDiv).append('<a href="#" id="tag_' + response.data[i].id + '" class="tag" title="' + response.data[i].listings + ' listings" style="font-size: ' + (response.data[i].listingPercentage + 100) + '%;">' + response.data[i].name + '</a>');
			}
			
			bindTags();
			
			$(folderDiv).slideUp();
			$(tagDiv).slideDown();
			
		});
		
		return false;
	});
	
	$('div.tags a[class="back"]').click(function(){
		var tagDiv = $(this).parent('div');
		var folderDiv = $(this).parent('div').prev('div');
		
		$('#field_tagId').val('0');
		var string = $('#fuelpoint_search form, #tabular form').serialize();
			
		directoryManager.search(string);
		
		$(tagDiv).slideUp();
		$(folderDiv).slideDown();
		
		return false;
	});

	function bindTags(){
	
		$('div.tags a[class="tag"]').click(function(){
			
			var id = $(this).attr('id').replace(/tag_/, '');
			$('#field_tagId').val(id);
			var string = $('#fuelpoint_search form, #tabular form').serialize();
			
			directoryManager.search(string);
			
			$('div.tags a[class="tag"]').css('font-weight', 'normal');
			$(this).css('font-weight', 'bold');
			
			return false;
		});
		
	}
	
	// Set up the maximum length script
	$('textarea[class*="maxlength"]').each(function(){
		var className = $(this).attr('class');
		position = className.indexOf('maxlength');
		string = className.substr(position);
		var length = parseInt(string.replace(/maxlength_/, ''));
		
		$(this).after('<br /><span class="counter"><span class="length"><strong>' + (length - $(this).val().length) + '</strong></span> out of <strong>' + length + '</strong> characters remaining.</span><br /><br />');
		
		$(this).keyup(function(){
			var remaining = length - $(this).val().length;
			
			if(remaining <= 0){
				var value = $(this).val().substring(0, length);
				$(this).val(value);
				remaining = length - $(this).val().length;
			}
			
			$(this).next('br').next('span.counter').children('span.length').children('strong').text(remaining);
			
		});
		
	});
	
});

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}