markers = new Array();

if (typeof(Number.prototype.toRad) === "undefined") {
  Number.prototype.toRad = function() {
    return this * Math.PI / 180;
  }
}

(function($){$.fn.ghostText=function(){return this.each(function(){var text=$(this).attr("title");if(text!=""&&($(this).val()==""||$(this).val()==text)){$(this).addClass("disabled");$(this).val(text);$(this).focus(function(){$(this).removeClass("disabled");if($(this).val()==text){$(this).val("")}});$(this).blur(function(){if($(this).val()==""){$(this).val(text);$(this).addClass("disabled")}})}})}})(jQuery)


function store_locator() {
var myLatlng = new google.maps.LatLng(54.155572,-2.24121);
var myOptions = {zoom:7, center:myLatlng, mapTypeId:google.maps.MapTypeId.ROADMAP};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
addMarkers();

// Centre the map if a searchhas been passed
	if (window.location.hash.length)
	{
		if(window.location.hash.indexOf("#dosearch")==0)
		{
			// Get the postcode
			var postcode = GetParameterValue("postcode");
						
			CentreMap(postcode,10,true);
		}
	}
}

function popup_map() {
// Geocode the postcode/town
geocoder = new google.maps.Geocoder();

postcode = unescape(GetParameterValue("town_postcode"));

geocoder.geocode( { 'address': postcode}, function(results, status) 
	{
      if (status == google.maps.GeocoderStatus.OK) 
      {
        myLatlng = results[0].geometry.location;
        $("#lat").val(myLatlng.lat());
        $("#long").val(myLatlng.lng());
        $("#address").val(results[0].formatted_address);
        
        var myOptions = {zoom:16, center:myLatlng, mapTypeId:google.maps.MapTypeId.ROADMAP};
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		var marker = new google.maps.Marker({position:myLatlng,map:map,title:"Drag me to the perfect spot...",draggable:true});
		google.maps.event.addListener(marker, 'dragend', function() {dragEnd(marker);});
      }
	});
}

function dragEnd(theMarker)
{
	$("#lat").val(theMarker.position.lat());
    $("#long").val(theMarker.position.lng());   
}



$(document).ready( function(){ 
var zIndexNumber = 10000;
	$('div:not(.leavez)').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
	
	$('div.zeroz').css('zIndex', 0);
	$('div.zhigh').css('zIndex', 9961);
	$('div.zhigh2').css('zIndex', 9962);
	
// Cufon Replace Time!
Cufon.set('fontFamily', 'Bureau');
Cufon.replace('h1,h2,h3');

$(".ghost_text").ghostText();

//Boxy implementation
//I have attached the event handler to the .live function. This is so that if any boxy links are
//implemented via ajax (once the DOM has loaded) the boxy popups will still trigger.

$('a[rel=boxy]').live("click", function (e) {
var $url = $(this).attr('href');
var $height = "280px";
var $width = "690px";

if($(this).attr('boxywidth'))
{
	$width = $(this).attr('boxywidth');
}

// If body had a id of:history set the iframe height to 415px, otherwise default to 280px.
// This is becuase we are loading different bg images and content heights into the iframe.

if ($("body#history").length > 0 ){
$height = "415px"	
}
new Boxy("<iframe src='"+$url+"' height='"+$height+"' width='"+$width+"' scrolling='no' frameborder='0' allowTransparency='true'></iframe>", {modal: true, afterShow: function() {}});
e.preventDefault();
});


// Product page tabs
if ($("body#drinks").length > 0 )
{
	$(".tab_content").hide(); //Hide all content
	$("ul#paper_tabs li:first").addClass("on").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content
	
	//On Click Event
	$("ul#paper_tabs li").click(function() 
	{
		$("ul#paper_tabs li").removeClass("on"); //Remove any "on" class
		$(this).addClass("on"); //Add "on" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});
}


// Product page animations
$(".drink_container").mouseenter(function() {
   $(this).find(".product").animate({
	left: '0',
	top: '20',
	width: '250',
	height: '380'
	}, 500, 'easeOutCubic', function() {
	// Animation complete.
	});
	$(this).find(".btn").fadeIn();
  }).mouseleave(function(){
    $(this).find(".product").animate({
	left: '33',
	top: '60',
	width: '184',
	height: '279'
	}, 500, 'easeOutCubic', function() {
	// Animation complete.
	});
	$(this).find(".btn").fadeOut();
  });

// Search form submission
$("#site_search_button").click(function() {$('#site_search').submit();});

// Opening history modal windows via a hash
if (window.location.hash.length)
{
	if(window.location.hash.indexOf("#history")==0)
	{
		// Get the hash
		var mySelector = window.location.hash;
					
		// Open the modal
		$(mySelector).click();
	}
}

//############################################################
//Feature panel clicking
//############################################################
$("#homepage_feature_panels ul li div, #drink_feature_panels ul li div, #side_panels div#feat_panel_history, #side_panels div#feat_panel_blog, #side_panels  #feat_panel_events, #side_panels #feat_panel_drinks").click(function(ev) {
  document.location = $(this).find("a.btn").attr("href");
});
$("#side_panels div#memories").click(function(ev) {
  document.location = $(this).find("a").attr("href");
});


//############################################################
// Ingredient toggle
//############################################################
$("#ingredientsToggle a").click(function(ev) {
  ev.preventDefault();
  $("#ingredientsContent").toggle();
});


//############################################################
// Store locator stuff - main buttons througout site
//############################################################
$("#store_locator_container #store_locator_button").click(function(ev) {
  ev.preventDefault();
  document.location = "http://www.benshawsdrinks.co.uk/ben-shaws-stockists/#dosearch&postcode=" + $("#store_locator_input").val();
});


//############################################################
// Store locator stuff - on stockist page
//############################################################
$("#small_store_locator_container #store_locator_button").click(function(ev) {
  ev.preventDefault();
  CentreMap($("#store_locator_input").val(),10,true);
});

// Stockist submission process - stage 1
$("#stockist-next-1").click(function(ev) {

	ev.preventDefault();
	var $inputs = $("form").find(":input");
	var $variableString = "";
	
	$inputs.each(function() {
		if($(this).is(':checkbox'))
		{
			if($(this).is(':checked'))
			{
				$variableString = $variableString + this.name + "=" + $(this).val() + "&";
			}
		}
		else
		{
			$variableString = $variableString + this.name + "=" + $(this).val() + "&";
		}
	});	
	
	document.location = "http://www.benshawsdrinks.co.uk/ben-shaws-stockists/add-stage-2/?data=" + $variableString;
});

// Stockist stage two hidden field population
$("#shop_name").val(GetParameterValue("shop_name"));
$("#town_postcode").val(GetParameterValue("town_postcode"));
$("#your_name").val(GetParameterValue("your_name"));
$("#your_email").val(GetParameterValue("your_email"));
$("#flavours_spotted").val(GetParameterValue("flavour1")+","+GetParameterValue("flavour2")+","+GetParameterValue("flavour3")+","+GetParameterValue("flavour4"));

// Stockist submission process - stage 2
$("#stockist-next-2").click(function(ev) {

	ev.preventDefault();
	var $inputs = $("form").find(":input");
	var $variableString = "";
	
	$inputs.each(function() {
		if($(this).is(':checkbox'))
		{
			$variableString = $variableString + this.name + "=" + $(this).is(':checked') + "&";
		}
		else
		{
			$variableString = $variableString + this.name + "=" + $(this).val() + "&";
		}
	});	
	
	// AJAX post
	$.ajax(
		{
			type: "POST",
			url: "http://www.benshawsdrinks.co.uk/ben-shaws-stockists/add-form/",
			dataType:"html",
			data:$variableString,
			success: function(msg)
			{
				document.location = "http://www.benshawsdrinks.co.uk/ben-shaws-stockists/add-stage-3/";
			}
     	})
	
});

// Memory submission process
$("#memoryAdd").click(function(ev) {

	ev.preventDefault();
	var $inputs = $("#memoryForm").find(":input");
	var $variableString = "";
	
	$inputs.each(function() {
		if($(this).is(':checkbox'))
		{
			$variableString = $variableString + this.name + "=" + $(this).is(':checked') + "&";
		}
		else
		{
			$variableString = $variableString + this.name + "=" + $(this).val() + "&";
		}
	});	
	
	// AJAX post
	$.ajax(
		{
			type: "POST",
			url: "http://www.benshawsdrinks.co.uk/memories/add-form/",
			dataType:"html",
			data:$variableString,
			success: function(msg)
			{
				$("#memoryForm").replaceWith("<p>Thank you. We've received your memory and will review it shortly before adding it to our website.</p>");
			}
     	})
	
});

	// Drop down nav
	$('#jsddm > li').bind('mouseover', jsddm_open);
	$('#jsddm > li').bind('mouseout',  jsddm_timer);

});


function CentreMap(postcode,zoom,search)
{  
	postcode = unescape(postcode);
    geocoder.geocode( { 'address': postcode}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        map.setZoom(zoom);
      }
  	});
  	
  	google.maps.event.addListenerOnce(map, 'idle', function(){ShowMapSearchResults();});
}

function ShowMapSearchResults()
{
	// Find the markers on display
	var visibleMarkers = new Array();
	for ( var i=0, len=markers.length; i<len; ++i )
	{
		if(map.getBounds().contains(markers[i].getPosition()))
		{visibleMarkers.push(markers[i]);}
	}
	
	// Sort the visible markers by their distance from the map center
	visibleMarkers.sort(sortMarkers);
	
	
	// We only show 5 items at any time
	var foundMarkers = 5;
	
	if(visibleMarkers.length<5)
	{
		foundMarkers = visibleMarkers.length;
	}
	
	var htmlString = "";
	
	for ( var i=0, len=foundMarkers; i<len; ++i )
	{
		var currentMarker = visibleMarkers[i];
		htmlString+=currentMarker.customHtml;
	}
	
	if(visibleMarkers.length == 0)
	{
		htmlString = "Sorry, there were no stockists found near this area.";
	}
	
	$(".post-it-entry").html(htmlString);
	$("#post_it").show();
	//SetHeights(foundMarkers);
	
	
}

function addMarker(lat, lon, stockist, town, flavours)
{
	if(lat)
	{
		flavours = flavours.toLowerCase();
		var flavoursHTML = "";
		if(flavours.indexOf("shandy")!=-1){flavoursHTML=flavoursHTML + "<li class='thumb_bitter_shandy'></li>"};
		if(flavours.indexOf("burdock")!=-1){flavoursHTML=flavoursHTML + "<li class='thumb_dandelion_burdock'></li>"};
		if(flavours.indexOf("cream")!=-1){flavoursHTML=flavoursHTML + "<li class='thumb_cream_soda'></li>"};
		if(flavours.indexOf("lemonade")!=-1){flavoursHTML=flavoursHTML + "<li class='thumb_cloudy_lemonade'></li>"};
	
	
		var htmlString = '<div><p style="font-size:14px"><strong>' + stockist + '</strong></p><p>' + town + '</p><p><strong>Flavours Spotted</strong></p><div class="thumb_drinks"><ul>' + flavoursHTML + '</ul></div></div>';
	
		var myLatlng = new google.maps.LatLng(lat,lon);
		var marker = new google.maps.Marker();
		var contentString = '<h1>' + stockist + '</h1>';
		var infowindow = new google.maps.InfoWindow({content: contentString});
		marker = new google.maps.Marker({map: map, position: myLatlng,title: stockist});
		marker.customHtml = htmlString;
		google.maps.event.addListener(marker, 'click', function() {markerClicked(htmlString);});
		markers.push(marker); 
	}  
}

function markerClicked(content)
{
	$(".post-it-entry").html(content);
	$("#post_it").show();
	//SetHeights(1);
}

function SetHeights(numberOfItems)
{
	var basePostItBG = 0;
	var contentHeader = 720;
	var sidePanels = -716;
	var multiplier = 130;
	
	if(numberOfItems > 1)
	{
		var additional = multiplier * numberOfItems;
	}
	else
	{
		additional = 0;
	}
	
	$("#post-it-bg").height(basePostItBG + additional);
	$("#content_header").height(contentHeader + additional);
	$("#side_panels").css("top",sidePanels - additional);
}

function GetParameterValue(parameterName)
{
	url = document.URL;
	
	var start = url.indexOf(parameterName + '=');
	
	if (start == -1)
	{return("");}
	
	start += parameterName.length + 1;
	
	var end = url.indexOf('&',start);
	
	if (end == -1)
	{
		end = url.length;
	}
	
	var toReturn = url.substring(start,end);
	return(toReturn);
}

// Drop down nav

var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;

function jsddm_open()
{	jsddm_canceltimer();
	jsddm_close();
	ddmenuitem = $(this).find('ul').eq(0).css('display', 'block');}

function jsddm_close()
{	if(ddmenuitem) ddmenuitem.css('display', 'none');}

function jsddm_timer()
{	closetimer = window.setTimeout(jsddm_close, timeout);}

function jsddm_canceltimer()
{	if(closetimer)
	{	window.clearTimeout(closetimer);
		closetimer = null;}}

document.onclick = jsddm_close;

// Custom array sort method to sort an array of map markers 
// by distance from the map centre point
function sortMarkers(a, b) {
return DistanceToMarker(a) - DistanceToMarker(b);
}

// Calculates the distance between the map centre and a marker
function DistanceToMarker(marker)
{
	var lat1 = map.getCenter().lat();
	var lon1 = map.getCenter().lng();
	var lat2 = marker.getPosition().lat();
	var lon2 =  marker.getPosition().lng();
	var R = 6371; // Radius of the earth in km
	var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
	var dLon = (lon2-lon1).toRad(); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
	        Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c; // Distance in km
	return d;
}
