// ================================================================================================
var tabs = {
  
  // =========================================================================
  init: function()
  {
    // init vars
    var boxes = $('.tabs ul li > a');
    var boxes_length = boxes.length;
    
    // loop through the tabs
    for (var i = 0; i < boxes_length; i ++)
    {
      $(boxes[i]).click(function() {tabs.change(this); return false;});
    }
  },
  
  // =========================================================================
  change: function(element)
  {
    // remove the class
    $('.tabs ul li.proper_tab').addClass('off');
    $(element).parent().removeClass('off');
    
    // loop through the tabs and hide them all
    $('.latest_news_home div.dynamic_tab').hide();
    
    // show the element
    var pos = element.href.match(/#(\w+)$/);
    $('#' + pos[1]).show();
  }
};

// ================================================================================================
function set_main_menu() {
  // set up those buttons that need dropdowns to have them
  $(" #nav div:first").css({display: "none"});
  $(" #nav li").hover(function() {
  		$(this).find('div:first').css({visibility: "visible",display: "none"}).show(400);
  	},
    function() {
  		$(this).find('div:first').css({visibility: "hidden"});
    });
  
  // set up the menu buttons to not respond
  $('#menu_products, #menu_about').click(function() {return false;});
}

// ================================================================================================
function set_dropdown() {
  // hide the basic dropdown and replace with the js version
  $('.country span').hide();
  $('.country_wrapper, .country_wrapper_bottom').addClass('js_on');
  $('.country_wrapper_bottom').removeClass('country_wrapper_bottom');
  
  // init the actual dropdowns
  MSDropDown.init('#country, #country_bottom', 171, 50);
  MSDropDown.showIconWithTitle(false);
  
  // store the serach text for later recall
  $('#search_text').attr('storage', $('#search_text').attr('value'));
  
  // remove the default text if showing
  $('#search_text').focus(function() {
    if ($(this).attr('value') == $(this).attr('storage'))
    {
      $(this).attr('value', '');
    }
  });
  
  // show the default text if none showing
  $('#search_text').blur(function() {
    if ($(this).attr('value') == '')
    {
      $(this).attr('value', $(this).attr('storage'));
    }
  });
  
  // set up the dropdowns to submit on change
  $('#country, #country_bottom').change(function() {
    var val = $(this).children('option:selected').attr('value');
    if (val)
    {
      // check for an http as the option
      if (val.match(/^http\:\/\//))
      {
        document.location.href = val;
      }
      else
      {
        $(this).closest('form').submit();
      }
    }
  });
  
  // set up the dropdown for the country on contact page
  MSDropDown.init('#contact_country', 171, 50);
}

function select_text_area(name) {
	n = name.substr(name.length-1, 1);
	$('ul.text li').css('display', 'none');
	$('ul.text li:nth-child('+n+')').css('display', 'block');
	
	i=0;
	$('ul.tabs li.tab').each(function() {
		i++;
		if (i==n) { $(this).attr('class', 'tab selected'); }
		else { $(this).attr('class', 'tab'); };
	});
}

// ================================================================================================
$(document).ready(function() {
  // simple tabs switcher
  tabs.init();
    
  // set up adverts changing
  $('.ctas_home .left_col').cycle({speed: 500, pause:1});
  $('.ctas_home .right_col').cycle({speed: 500, pause:1});
   
  // set up the menu
	set_main_menu();
  
  // set up the dropdown
  set_dropdown();
  
  // open links to another domain in a new window
	$("a[href^=http]").each(
		function(){
			if(this.href.indexOf('http://'+location.hostname) == -1) {
				$(this).attr('target', '_blank');
			}
		}
	)	
	
	// create share links using href and title tags on a links
	$('.share_btn').each(function() { 
		addthis.button('#'+$(this).attr('id'), addthis_config, {url: $(this).attr('href'), title: $(this).attr('title')});
	});	
	
	// init home page textarea tabs
	$('ul.tabs li a').each(function() {
		$(this).attr('href', 'javascript:select_text_area(\''+$(this).attr('href')+'\')');
	});
	
	// initiate Google Maps api if in the locator page
	if ($("#map_canvas").length > 0) {
		maps.init();
	}	
	
});

var maps = {
	map:null,
	marker_array:Array(),
	init_location_lat:'',
	init_location_lon:'',
	init_town:'',
	zoom:11,
	selected:'',
	active_marker_type:'',
	t:-1,
	init: function() {
		// remove JS fallback
		$('#map_canvas').html('Map Loading...');
		
		if (GBrowserIsCompatible()) {
			maps.map = new GMap2(document.getElementById("map_canvas"));
			maps.map.addControl(new GLargeMapControl3D() );
			maps.map.enableScrollWheelZoom();
			
			// scroll to initial location
			if (maps.init_location_lat!='' && maps.init_location_lon!='') {
				lat = maps.init_location_lat;
				lon = maps.init_location_lon;
				var myGeographicCoordinates = new GLatLng(lat, lon);
				maps.map.setCenter(myGeographicCoordinates, maps.zoom);						
			}
			// attempt to geolocate by town
			else {
				var geocoder = new GClientGeocoder();
				geocoder.getLatLng(
					maps.init_town,
					function(point) {
						if (!point) {
							$('#map_canvas').after('<p>'+maps.init_town + " not found</p>");
						} else {
							maps.map.setCenter(point, maps.zoom);
						};
					}
				);
			};
			
			// add icons to map
			maps.create_icons();
		}
		
		// add unload event to destroy google api and avoid memory leaks
		window.onbeforeunload = function() { 
			GUnload();
		}

	},
	geolocatecallback:function(geoDict) {
		// geolocate success
		if (geoDict.Latitude && geoDict.Longitude) {
			setCookie('lat', geoDict.Latitude);
			setCookie('lon', geoDict.Longitude);
			lat = geoDict.Latitude;
			lon = geoDict.Longitude;	
			maps.zoom = 9;
		}
		
		// geolocate fail - use defaults
		else {
			lat = 53.800651;
			lon = -1.54911;	
			maps.zoom = 6;
		};
		
		var myGeographicCoordinates = new GLatLng(lat, lon);
		maps.map.setCenter(myGeographicCoordinates, maps.zoom);
		maps.create_icons();
		
	},
		
	create_icons:function() {
		// Create our "tiny" marker icon
		var tinyIcon = new GIcon();
		tinyIcon.image = "images/maps/icon.png";
		tinyIcon.shadow = "images/maps/icon_shadow.png";
		tinyIcon.iconSize = new GSize(31, 50);
		tinyIcon.shadowSize = new GSize(56, 50);
		tinyIcon.iconAnchor = new GPoint(15, 50);
		tinyIcon.infoWindowAnchor = new GPoint(45,30);

		// Add markers for each of marker_array (defined inline)
		for (i=0; i<maps.marker_array.length; i++) {
			// Set up our GMarkerOptions object literal
			markerOptions = { icon:tinyIcon, title:maps.marker_array[i].name};
		
			var point = new GLatLng(maps.marker_array[i].lat, maps.marker_array[i].lon);				
		 	var marker = new GMarker(point, markerOptions);
			marker.i=i;
			maps.marker_array[i]['marker_ref'] = marker; 
			
			// small popup on mouseover
			GEvent.addListener(marker, 'click', function(){ 
				var caption = '<b>'+maps.marker_array[this.i].name+"</b><br/>";
				caption += maps.marker_array[this.i].address1+"<br/>";
				if (maps.marker_array[this.i].address2!='') { caption += maps.marker_array[this.i].address2+"<br/>"; }
				if (maps.marker_array[this.i].town!='') { caption += maps.marker_array[this.i].town+"<br/>"; }
				if (maps.marker_array[this.i].postcode!='') { caption += maps.marker_array[this.i].postcode+"<br/><br/>"; }
				if (maps.marker_array[this.i].tel!='') { caption += maps.marker_array[this.i].tel+"<br/>"; }
				if (maps.marker_array[this.i].website!='') { caption += '<a href="'+maps.marker_array[this.i].website+'" target="_blank">Visit Website</a><br/><br/>'; }
				caption += '<i>'+maps.marker_array[this.i].categories+"</i>";
				
				maps.marker_array[this.i]['marker_ref'].openInfoWindowHtml(caption);
			
			});	
						
			
			maps.map.addOverlay(marker);
		}
	}
}

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
 
function setCookie(c_name,value){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+30);
	document.cookie=c_name+ "=" +escape(value)+";expires="+exdate.toGMTString();
}