$(function(){
/////////////////////////////////////////////////////
// activities list //
/////////////////////////////////////////////////////
	$('.categories div').hide();
	$('#activities #select-activity').live('click', function() {
		if($('.categories div').is(':hidden')){
			$(this).addClass('hide');
			var activity = $('.categories input').val();
			if(activity=="All Activities"){
				$('.categories div').show().load('/console/activities/ghost-1_'+URIparams);	
			} else {
				$('.categories div').show();	
			}
		} else {
			$(this).removeClass();
			$('.categories div').hide();
			$('.categories div h3').show();
			$('.categories div ul').hide();
		}
		return false;
	});
	// this sets the category filters	
	$('.categories div ul').hide();
	$('.categories div h3 a').live('click', function() {								   
		var h3 = $(this).parent();
		var ul = $(this).parent().next();
		if($(ul).is(':hidden')){
			$('.categories div h3').not(h3).hide();
			$('.categories div ul').hide();	
			$(this).addClass('hide');
			$(ul).show();
			
		} else {
			$(ul).hide();
			$(this).removeClass();
			$('.categories div h3').show();
		}										   
		return false;
	});	
	// this sets the activity filters	
	var activityID_arr = {};
	var activity_arr = {};
	function actID_recal(){
		res = '';
		for (i in activityID_arr){
			if (res !== ''){res += ','+activityID_arr[i];} else {res = activityID_arr[i];}
		}
		$('#activityID').val(res);
	}
	function act_recal(){
		res = '';
			for (i in activity_arr){
				if (res !== ''){res += ', '+activity_arr[i];} else {res = activity_arr[i];}
			}
		if (res === ''){
			res = "All Activities";	
			$('#activities .reset').hide();
		} else {
			$('#activities').append('<a href="#" class="reset"></a>');
		}
		$('.categories input').val(res);
	}
	$('.categories div li a').live('click', function() {           
		var li = $(this).parent();
		var selected = $(this).parent().attr('class');
		var activity = $(this).attr('rel');
		var activityID = $(this).attr('name');
		if(selected=='selected'){
			$(li).removeClass();
			$(this).attr('title','add to filter');
			delete activityID_arr[activityID];
			actID_recal();
			delete activity_arr[activity];
			act_recal();
		} else {
			$(li).addClass('selected');
			$(this).attr('title','remove from filter');
			activityID_arr[activityID] = activityID  ;
			actID_recal();
			activity_arr[activity] = activity  ;
			act_recal();	
		} 
		return false;
	}); 
	$('#activities .reset').live('click', function() {
		$('.categories li').removeClass();
		for (i in activity_arr){
			delete activity_arr[i];
		}
		for (i in activityID_arr){
			delete activityID_arr[i];
		}
		actID_recal();
		act_recal();
		return false;
	});
/////////////////////////////////////////////////////
// recent venues //
/////////////////////////////////////////////////////
	$('#recent_venues b').live('click', function() {
		var el = $(this);
		var node = $(this).next();
		if($(node).is(':hidden')){
		$(node).show('', function(){$(el).addClass('on'); }) ;}
		else
		{$(node).hide('', function(){$(el).removeClass('on'); }) ;}
		return false;
	});
/////////////////////////////////////////////////////
// advanced search //
/////////////////////////////////////////////////////
	$('#advanced-search').hide(0);
	$('.advanced-search').click(function(){
		var el = $(this);

		if($('#advanced-search').is(':hidden')){
		$('#advanced-search').show('', function(){$(el).addClass('on'); }) ;}
		else
		{$('#advanced-search').hide('', function(){$(el).removeClass('on'); }) ;}
		return false;
	});	
/////////////////////////////////////////////////////
// innerfade //
/////////////////////////////////////////////////////
	$('.list-banner #list').innerfade({ speed: 'slow', timeout: 7000, type: 'sequence', containerheight: 'auto' });
	$('.list-gallery #list').innerfade({ speed: 'slow', timeout: 7000, type: 'sequence', containerheight: 'auto' });	
});
/////////////////////////////////////////////////////
// populate list //
/////////////////////////////////////////////////////
function populate_list(p){
	$('#list_view .loading').show(0);
var list = '';
var i = 1;
$.each(p.venues, function(){
if(i<=p.town.listNr){
  list = list + this.listlink.replace('\"','"');
i=i+1;
}
});
$("#list").html(list);
$('#list_view .loading').hide(0);
}
/////////////////////////////////////////////////////
//populate map //
/////////////////////////////////////////////////////
function createMarker(point,html) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "mouseover", function() {
    venuemap.checkResize();
    marker.openInfoWindowHtml(html);
  });
  return marker;
}

function populate_map(p){
venuemap.setCenter(new GLatLng(p.town.lat, p.town.lon), 10);
venuemap.clearOverlays();
// initiate bounds and at the search point to it so that venues are alwasy visible
var bounds = new GLatLngBounds();
var point = new GLatLng(p.town.lat, p.town.lon);
  bounds.extend(point);
var ibounds = 0;
// set map center co-ords for recentering map
centerLat =p.town.lat;
centerLon =p.town.lon; 
var i = 1;
$.each(p.venues, function(){
if(i<=p.town.mapNr){
  var point = new GLatLng(this.lat,this.lon);
  // attempt to make it so map can zoom out to contain minimum of 5 venues
  if (ibounds<5){
    bounds.extend(point);
  }
  ibounds=ibounds+1;
  var markerprice='';
  if (this.price!==""){
    markerprice = '<span class="map-price">From &pound;'+this.price+'</span>';
  }
  var marker = createMarker(point,this.maplink.replace('\"','"'));
  venuemap.addOverlay(marker);
i=i+1;}
 }); 
venuemap.setZoom(venuemap.getBoundsZoomLevel(bounds));
}
/////////////////////////////////////////////////////
// load venue //
/////////////////////////////////////////////////////
function recents(href,name,title){
// append recent viewed venues with new venue - but ensure no duplicates appear in list
			var recentlist = $('#recent_venues ul').html();
			var current = '<li><a href="'+href+'" title="'+title+'" name="'+name+'">'+title+'</a></li>';
			//tags are returned in caps and in a different order in some browsers decapitalise for consistency
      var currentIE = '<LI><A title="'+title+'" href="'+href+'" name='+name+'>'+title+'</A></LI>';
      var currentOP = '<LI><A href="'+href+'" title="'+title+'" name="'+name+'">'+title+'</A></LI>';
      recentlist = recentlist.replace('http://'+window.location.hostname,'');
      recentlist = recentlist.replace(current, '');
      recentlist = recentlist.replace(currentIE, '');
      recentlist = recentlist.replace(currentOP, '');
      
			recentlist = current+recentlist;
			$('#recent_venues ul').html(recentlist);
}

function load_venue(href,name,title){
	if (recentV !='0'){
    $('#recent_venues').show(0);
  	$('#recent_venues ul').hide(0);}
	$('#list').css("height","433px");
	// this sets the activity filter to default
	$('.categories div').hide();
	$('.categories div h3').show();
	$('#select-activity').removeClass();
	$('.categories div ul').hide();	
	if(name=="tab"){
    	$('.tabs-container').hide(0);
      	if (recentV !='0'){
        	recents(href,name,title);}
      		$('.tabs-menu li').removeClass('tab-selected');
			$('#search-results #venue-tab').empty().addClass('tab-selected').append('<a href="#venue_view"><span>'+title+'</span></a>');
			$('#venue_view').show();
      		$('#venue_view').html('<span class="loading">venue loading</span>');
      		$('#venue_view').load(href);
			$('#venueloading').hide();
			$('#venue_view .venue-container').hide(0);
			$('#venue_view .tabs-selected').show(0);
      		return false;
		} else if (name=="popup"){
    		if (recentV !='0'){
        		recents(href,name,title);}
				$('#gb-popup').fadeIn('slow');
      			$('#gb-popup div').load(href);
				return false;
			}
		}

$(function(){
// from list
	$('#list a').live('click', function() {   
    var href = $(this).attr('href');
		var name = $(this).attr('name');	
	  var title = $(this).attr('title');
    //if it needs to open in new page don't proceed with js allow link to just open
    if (name=='popup' || name=='tab'){  
      load_venue(href,name,title);
      return false;
	  }
  });
	
	$('#recent_venues a').live('click', function() {   
    	var href = $(this).attr('href');
		var name = $(this).attr('name');	
	  	var title = $(this).attr('title');
	  	//if it needs to open in new page don't proceed with js allow link to just open
    	if (name=='popup' || name=='tab'){  
      	load_venue(href,name,title);
      	return false;
	  }
  });
 
 // from map
	$('.gmnoprint a').live('click', function() {   
    var href = $(this).attr('href');
		var name = $(this).attr('name');	
	  var title = $(this).attr('title');
	  //if it needs to open in new page don't proceed with js allow link to just open
    if (name=='popup' || name=='tab'){  
      load_venue(href,name,title);
      return false;
    }
	});
  	
	$('a.close').live('click', function() {
		$('#gb-popup').fadeOut().hide();	
		return false;
	});	
});
/////////////////////////////////////////////////////
// first load with no map //
/////////////////////////////////////////////////////
function firstload_nomap(tabfocus, listloaded){
  // tab focus which tab to focus on
  // listloaded whether list is already loaded and loading graphic needs to be hidden
  // venueloaded whether venue is already loaded and loading graphic needs to be hidden
  $('.tabs-container').hide();
  $('.tabs-menu li').removeClass();
  $('.tabs-menu li#'+tabfocus+'-tab').addClass('tab-selected');
  $('#'+tabfocus+'_view').show();
  if (listloaded=='1'){
  $('#list_view .loading').hide(0);}
}

/////////////////////////////////////////////////////
// apply filters //
/////////////////////////////////////////////////////
function apply_filters(firstload, prepop){
	// this sets the activity filter to default
	$('.categories div').hide();
	$('.categories div h3').show();
	$('#select-activity').removeClass();
	$('.categories div ul').hide();	
	//
  // firstload variable dictates whether this is the onload search and amongst other things decides whether it uses the form values of parameter values
  if (firstload === undefined)
  {firstload='0';}
  var townID;
  if (firstload =='0'){
  townID=lookupTown();}
  var href;
  var title;
  var name;

  // check that town is valid
  if ($('#townsearch').val()==='' || $('#townsearch').val()=='undefined'){
    townID = 'geolocate';
    }else{
    if (townID===0){
    if (previoustownID=="undefined"){
    alert ('Please select a town from the list as you type');return false;}
    else{
      townID= previoustownID;
    }}
    }
// check current parameters with previously used if identical do nothing
if (previoustownID ==townID && 
    previousactivityID==$("[name=activity_combo]").val() &&
    previousage==$("select[name='age']").val() &&
    previousbudget==$("select[name='budget']").val()&&
    previousclosest==$("#closest:checked").val())
    {
    // alert ('Search already done please change filters or view results on list or map tab');
    return false;
    }
    else {
    if (prepop!='1'){// if the list isn't already prepoulated add loading message
      $('#list').html('<div class="loading"></div>');
    }
 $('.map .loading').show();
  // get venue list info in json format
    $.ajax({
    type: "POST", 
    // the ghost parameter is a none important parameter it ensures that calls are made correctly when no params exist and it is hosted on aws
 url: [
          "http://",
          window.location.hostname,
          "/console/ajax_search/ghost-1_",
          params
         ].join(''),
    data: [
            "townID=",
            townID,
            "&activityID=",
            $("[name=activity_combo]").val(),
            "&age=",
            $("select[name='age']").val(),
            "&budget=",
            $("select[name='budget']").val(),
            "&closest=",
            $("#closest:checked").val(),
            "&firstload=",
            firstload
          ].join(''),
    dataType: "json",
    success: function(data){
    var p = data;
    // focus on appropriate tab if first load

    if (firstload=='1'){
        var tabfocus;
        if (p.town.focus=='V'){tabfocus='venue';}
        if (p.town.focus=='M'){tabfocus='map';}
        if (p.town.focus=='L'){tabfocus='list';}
        // also establish whether recent venues list should be populated
        recentV = p.town.recents;
       $('.tabs-container').hide();
        $('.tabs-menu li').removeClass();
        $('.tabs-menu li#'+tabfocus+'-tab').addClass('tab-selected');
        $('#'+tabfocus+'_view').show();
    
    }
    
    if(p.town.listNr!='0' && prepop!='1'){
    // if list is prepopulated when this is firstload don't redo it
    populate_list(p);}
    else
    {$('#list_view .loading').hide(0);}
    // rewrite page title
    if (p.town.hTitle!=""){
    $("#ajax_search_title").html(p.town.hTitle);
    }else{
    $("#ajax_search_title").html("Activities in "+p.town.name);
    }
    $("#townsearch").val(p.town.name);
    $('.map .loading').hide();
    if(p.town.mapNr!='0'){
      populate_map(p);}
    // preload a venue if required
    if ((p.town.oVenue=='closest' || (p.town.oVenue!='closest' && p.town.oVenue!='0' && firstload=='1'))){
      if (p.town.oVenue=='closest'){
        href = '/console/get_venue/webID-'+p.town.websiteID+'_oVenue-'+p.venues[0].locationID+'_oVenAct-'+p.venues[0].activityID+'_venue-'+p.town.link_type;
        title = p.venues[0].title;
        
      } else {
        href = '/console/get_venue/webID-'+p.town.websiteID+'_oVenue-'+p.town.oVenue+'_oVenAct-'+p.town.oVenAct+'_venue-'+p.town.link_type;
        title = p.town.venTitle;}
        name = p.town.link_type;
        if (firstload!='1'){
        load_venue(href,name,title);
        }
    }
    //rewrite venue tab title and add to recent venues and focus required - if it hasn't been loaded by ajax
    if(p.town.oVenue!='closest' && p.town.oVenue!='0' && firstload=='1' && p.town.link_type=='tab'){
			  href = '/console/get_venue/webID-'+p.town.websiteID+'_oVenue-'+p.town.oVenue+'_oVenAct-'+p.town.oVenAct;
        title = p.town.venTitle;
        name = p.town.link_type;
			  $('#search-results #venue-tab').empty().append('<a href="#venue_view"><span>'+title+'</span></a>');    
        recents(href,name,title);
    }
    
    //record search parameters to avoid immediate repeats of same search
    previoustownID =townID; 
    previousactivityID=$("[name=activity_combo]").val();
    previousage=$("select[name='age']").val();
    previousbudget=$("select[name='budget']").val();
    previousclosest=$("#closest:checked").val();
    }
  });
  }
}
/////////////////////////////////////////////////////
// map controls //
/////////////////////////////////////////////////////
function moveN(){
  venuemap.checkResize();
  var C = venuemap.getCenter();
  var X = C.lng();
	var Y = C.lat();
	venuemap.setCenter(new GLatLng(Y+((3*(12-venuemap.getZoom()))+1)*0.02,X));}

function moveS(){
  venuemap.checkResize();
  var C = venuemap.getCenter();
  var X = C.lng();
	var Y = C.lat();
	venuemap.setCenter(new GLatLng(Y+((3*(12-venuemap.getZoom()))+1)*-1*0.02,X));}

function moveE(){
  venuemap.checkResize();
	var C = venuemap.getCenter();
	var X = C.lng();
	var Y = C.lat();
	venuemap.setCenter(new GLatLng(Y,X+((3*(12-venuemap.getZoom()))+1)*0.02));}

function moveW(){
  venuemap.checkResize();
	var C = venuemap.getCenter();
	var X = C.lng();
	var Y = C.lat();
	venuemap.setCenter(new GLatLng(Y,X+((3*(12-venuemap.getZoom()))+1)*-1*0.02));}

function reCenter(){
  venuemap.checkResize();
  venuemap.setCenter(new GLatLng(centerLat, centerLon), 10);}

function zoomOut(){
	venuemap.checkResize();
  venuemap.setZoom(venuemap.getZoom() - 1);}

function zoomIn(){
  venuemap.checkResize();
	venuemap.setZoom(venuemap.getZoom() + 1);}
