$(document).ready(function() {
	
	/// Send to friend
	$("a.friend").bind("click", function() {
		
		var id = $(this).attr("id").replace("link_","");
		var title = $("div#event_" + id).children("h5").html();
		var detail = $("div#event_" + id).children("p.detail").html();
		var dates = $("div#event_" + id).children("p.text").children("span.dates").html();
		var location = $("div#event_" + id).children("p.text").children("span.location").html();
		var venue = $("div#event_" + id).children("p.text").children("span.venue").html();
		
		var subject = "An event I think you may be interested in...";
		var message = "I found this event on " + window.location.href + " and thought you may be interested.%0A%0A";
		message = message + encodeURI(title) + "%0A";
		
		if(detail != null && detail != "undefined" && detail != "null")
			message = message + encodeURI(detail) + "%0A";
			
		message = message + encodeURI(dates) + "%0A";
		message = message + encodeURI(location) + "%0A";
		message = message + encodeURI(venue) + "%0A%0A%0A";
		
		window.location = "mailto:?subject=" + subject + "&body=" + message;
		
		return false;
	});
	
	/// Send to friend
	$("a#tak_emailpage").bind("click", function() {
		
		var subject = "A website I think you may be interested...";
		var message = "I found this web site: " + window.location.href + " and thought you may be interested.%0A%0A%0A";
		
		window.location = "mailto:?subject=" + subject + "&body=" + message;
		
		return false;
	});
	
	/// Print
	$("a.print").bind("click", function() {
		
		window.print();
		
		return false;
	});
	
	/// Bookmark
	$("a.bookmark").bind("click", function() {
		
		bookmark("Black Routes",window.location.href);
		
		return false;
	});
	
	function bookmark(title,url)
	{
		if (window.sidebar) // firefox
		window.sidebar.addPanel(title, url, "http:www.yourwebsiteurl.com");
			else if(window.opera && window.print) { // opera
				var elem = document.createElement('a');
				elem.setAttribute('href',url);
				elem.setAttribute('title',title);
				elem.setAttribute('rel','sidebar');
				elem.click();
			}
			else if(document.all)// ie
			window.external.AddFavorite(url, title);
	}
	
	/// Search whats on
	$("input#btn-search-whats-on").bind("click", function() {
		
		var artist = $("select#txtArtist").val();
		var region = $("select#region").val();
		var string = "";
		
		if(artist != "Please select")
			string = string + "?artist=" + artist;
			
		if(region != "Please select")
		{
			if(artist != "Please select")
			{
				string = string + "&"
			}
			else
			{
				string = string + "?"
			}
				
			string = string + "region=" + region;
		}
		
		window.location = "/whats_on/" + string;
		
		return false;
		
	});
	
	/// Form submit
    $("div.form-search").bind("keypress", function(e) {
        if (e.keyCode == 13) {
            window.location = "/search/?search=" + $("input#tak_txtSearch").val();
            return false;
        }
    });

	/// Gallery
	$("li.previous a").live("click", function() {
		
		current = current-1;
		
		if(current < 0) current = (total-1);

		$("div.image img").fadeOut(function() {
			
			$(this).attr("src",images[current][1]);
			$(this).fadeIn();
			
		});
		
	});
	
	/// Gallery
	$("li.next a").live("click", function() {
		
		current = current+1;
		
		if(current >= total) current = 0;

		$("div.image img").fadeOut(function() {

			$(this).attr("src",images[current][1]);
			$(this).fadeIn();
			
		});
		
	});
	
	
	/// Subscribe button - hide / show
	$("a.sub").live("click", function() {
		
		var output = new StringBuilder();
		
		if($("div.subscribe").length == 0)
		{
			output.append("<div class=\"subscribe closed\" style=\"display:none;\">");
			output.append("<h3>Sign-up to Black Routes mailing list</h3>");
			output.append("<div class=\"form\"><div class=\"name\">");
			output.append("<label>Name</label><input type=\"text\" value=\"First Name\" class=\"text sub-firstname\" maxlength=\"50\" id=\"firstname\" /><input type=\"text\" value=\"Surname\" class=\"text sub-surname\" id=\"surname\" maxlength=\"50\" />");
			output.append("</div><div class=\"email\">");
			output.append("<label>Email</label><input type=\"text\" value=\"Email Address\" class=\"text sub-email\" maxlength=\"255\" id=\"email\" /><input type=\"text\" value=\"Re-type Email Address\" class=\"text sub-email-repeat\" id=\"emailrepeat\" maxlength=\"255\" />");
			output.append("</div><div class=\"postcode\">");
			output.append("<label>&nbsp;</label><input type=\"text\" value=\"Post Code\" class=\"text sub-postcode\" id=\"postcode\" maxlength=\"10\" /><input type=\"submit\" value=\"SEND\" class=\"btn send-sub\" />");
			output.append("</div><div class=\"check\">");
			output.append("<input type=\"checkbox\" id=\"thirdparties\" /><label>I am happy to receive occasional information from third parties</label>");
			output.append("</div></div></div>");
		
			$("div.toolbar").prepend(output.toString());
		}
		
		if($("div.subscribe").hasClass("closed"))
			$("div.subscribe").addClass("open").removeClass("closed").slideDown();
		else
			$("div.subscribe").addClass("closed").removeClass("open").slideUp();
			
		$("input.text").focus(function() {
			$(this).val("");
		});
			
		return false;
	});
	

	function isValidEmailAddress(emailAddress) {
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(emailAddress);
	}
	
	/// Subscribe button - submit
	$("input.send-sub").live("click", function() {
		
		var firstname = $("input#firstname").val();
		var surname = $("input#surname").val();
		var email = $("input#email").val();
		var emailrepeat = $("input#emailrepeat").val();
		var postcode = $("input#postcode").val();
		var thirdparties = false;
		
		if($("input#thirdparties").is(':checked'))
			thirdparties = true;
		
		var msg = new StringBuilder();
		var send = true;
		
		msg.append("The following errors were found:\n\n");
		
		if(firstname.length <= 0) {
			msg.append("- Please enter your First Name.\n");
			send = false;
		}
		
		if(surname.length <= 0) {
			msg.append("- Please enter your Surname.\n");
			send = false;
		}
		
		if(postcode.length <= 0) {
			msg.append("- Please enter your Postcode.\n");
			send = false;
		}
		
		if(!isValidEmailAddress(email)) {
			msg.append("- Please enter a valid Email address.\n");
			send = false;
		}
			
		if(email != emailrepeat) {
			msg.append("- Please make sure your Email address\'s match.\n");
			send = false;
		}
			
		if(send)
		{
		
	        $.ajax({
	            type: "POST",
	            url: "/subscribe.ashx",
	            dataType: "xml",
	            timeout: 2000,
	            data: "firstname=" + firstname + "&lastname=" + surname + "&email=" + email + "&postcode=" + postcode + "&thirdparties=" + thirdparties,
	            async: false,
	            error: function(xhr, desc, exceptionobj) {
	                alert(xhr.responseText);
	            },
	            success: function(r) {
					alert("Thank you. A mail has been sent to the address supplied, please follow the instructions to complete your subscription.");
					$("div.subscribe").addClass("closed").removeClass("open").slideUp();
	            }
	        });

		}
		else
		{
			alert(msg.toString());
		}
		
		return false;
		
	});
			

});

/* ///// Common Functions ////// */
function loadit() {
	
	$("img#imageSlide").attr("src",images[current][1]);
	
	setTimeout("slideit()",6500);
}

function slideit() {
	
	$("img#imageSlide").fadeOut(function() {
		
		///if(current = "undefined")
		///	current = 0;
		
		if (current<(total-1))
		{
			current++;
			$("img#imageSlide").fadeOut();
		}
		else
		{
			current=0;
			$("img#imageSlide").fadeOut();
		}
		
		$("img#imageSlide").attr("src",images[current][1]);
		$("img#imageSlide").fadeIn();
		
		setTimeout("slideit()",6500);
		
	});
	
}

/// appends the given value if supplied
function StringBuilder(value) 
{
    this.strings = new Array("");
    this.append(value);
}

/// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function(value) 
{
    if (value)
        this.strings.push(value);
}

/// Clears the string buffer
StringBuilder.prototype.clear = function() 
{
    this.strings.length = 1;
}

/// Converts this instance to a String.
StringBuilder.prototype.toString = function() 
{
    return this.strings.join("");
}