// JavaScript Document
$(document).ready(function() {

	$(document).ajaxError(function(e, xhr, settings, exception) { 
		var title = 'Error!';
		var statusTxt = settings.url + '<br/>' + xhr.status + ' ' + xhr.statusText;
		var msg = hal_errors[Math.floor(Math.random() * hal_errors.length)];
		modal_message(title, statusTxt, msg);
	});

	var cache = [];
	$.fn.preload = function() {
		this.each(function(){
			var cacheImage = document.createElement('img');
			cacheImage.src = this;
			cache.push(cacheImage);
		});
	}

	preloadImages = [];
	preloadImages.push('assets/images/menu/static.gif');

	$(preloadImages).preload();

	$('.social').hover(function() {
		position = $(this).css('background-position').split(' ');	
		$(this).css('background-position', position[0] + ' -27px');
	},function() {
		$(this).css('background-position', position[0] + ' 0px');
	});

	$('.menu_l').hover(function() {
		$(this).css('background-position', '-138px bottom');
	}, function() {
		$(this).css('background-position', '0px bottom');
	});

	$('.menu_r').hover(function() {
		$(this).css('background-position', '-414px bottom');
	}, function() {
		$(this).css('background-position', '-276px bottom');
	});

	$('.menu_item').hover(function() {
		$('#nebula').css('background-position', '0px -' + ($(this).attr('rel') * 138) + 'px');
		$('#static').css('background-image', 'url(assets/images/menu/static.gif)').delay(120).queue(function () {
			$('#static').css('background-image', 'none');
			$('#static').dequeue();
		});
	}, function() {
		$('#nebula').css('background-position', '0px 0px');
		$('#static').css('background-image', 'url(assets/images/menu/static.gif)').delay(120).queue(function () {
			$('#static').css('background-image', 'none');
			$('#static').dequeue();
		});
	});

	$('.menu_link').bind('click', function(e){
		e.preventDefault();
		var url = 'assets/php/aload.php' + $(this).attr('href');
		var title = $(this).attr('href').replace('?p=', '');
		$('#content_loading').fadeIn(500, function () {
			var pageTitle = title.charAt(0).toUpperCase() + title.slice(1);
			$('#content_container').load(url, function(response, status, xhr) {
				if (status != "error" && status != "timeout") {
					$('#content_loading').fadeOut(500);
					document.title = 'Tribazik - ' + pageTitle;
				}
			});
		});
	});

	function modal_message(title, statusTxt, msg){
		$('#error_head').html(title);
		$('#error_msg').html('<div id="error_type">' + statusTxt + '</div>' + msg);
		$('#error').fadeIn(500).delay(5000).queue(function() {
			$('#error').fadeOut(500);
			$('#content_loading').fadeOut(500);
			$('#error').dequeue();
			$('#content_loading').dequeue();
		});
	}

	var Playlist = function(instance, playlist, options) {
		var self = this;

		this.instance = instance; // String: To associate specific HTML with this playlist
		this.playlist = playlist; // Array of Objects: The playlist
		this.options = options; // Object: The jPlayer constructor options for this playlist

		this.current = 0;

		this.cssId = {
			jPlayer: "jquery_jplayer_",
			interface: "jp_interface_",
			playlist: "jp_playlist_"
		};
		this.cssSelector = {};

		$.each(this.cssId, function(entity, id) {
			self.cssSelector[entity] = "#" + id + self.instance;
		});

		if(!this.options.cssSelectorAncestor) {
			this.options.cssSelectorAncestor = this.cssSelector.interface;
		}

		$(this.cssSelector.jPlayer).jPlayer(this.options);

		$(this.cssSelector.interface + " .jp-previous").click(function() {
			self.playlistPrev();
			$(this).blur();
			return false;
		});

		$(this.cssSelector.interface + " .jp-next").click(function() {
			self.playlistNext();
			$(this).blur();
			return false;
		});
	};

	Playlist.prototype = {
		displayPlaylist: function() {
			var self = this;
			$(this.cssSelector.playlist + " ul").empty();
			for (i=0; i < this.playlist.length; i++) {
				var listItem = (i === this.playlist.length-1) ? "<li class='jp-playlist-last'>" : "<li>";
				listItem += "<a href='#' id='" + this.cssId.playlist + this.instance + "_item_" + i +"' tabindex='1'>"+ this.playlist[i].name +"</a>";

				// Create links to free media
				if(this.playlist[i].free) {
					var first = true;
					listItem += "<div class='jp-free-media'>(";
					$.each(this.playlist[i], function(property,value) {
						if($.jPlayer.prototype.format[property]) { // Check property is a media format.
							if(first) {
								first = false;
							} else {
								listItem += " | ";
							}
							listItem += "<a id='" + self.cssId.playlist + self.instance + "_item_" + i + "_" + property + "' href='" + value + "' tabindex='1'>" + property + "</a>";
						}
					});
					listItem += ")</span>";
				}

				listItem += "</li>";

				// Associate playlist items with their media
				$(this.cssSelector.playlist + " ul").append(listItem);
				$(this.cssSelector.playlist + "_item_" + i).data("index", i).click(function() {
					var index = $(this).data("index");
					if(self.current !== index) {
						self.playlistChange(index);
					} else {
						$(self.cssSelector.jPlayer).jPlayer("play");
					}
					$(this).blur();
					return false;
				});

				// Disable free media links to force access via right click
				if(this.playlist[i].free) {
					$.each(this.playlist[i], function(property,value) {
						if($.jPlayer.prototype.format[property]) { // Check property is a media format.
							$(self.cssSelector.playlist + "_item_" + i + "_" + property).data("index", i).click(function() {
								var index = $(this).data("index");
								$(self.cssSelector.playlist + "_item_" + index).click();
								$(this).blur();
								return false;
							});
						}
					});
				}
			}
		},
		playlistInit: function(autoplay) {
			if(autoplay) {
				this.playlistChange(this.current);
			} else {
				this.playlistConfig(this.current);
			}
		},
		playlistConfig: function(index) {
			$(this.cssSelector.playlist + "_item_" + this.current).removeClass("jp-playlist-current").parent().removeClass("jp-playlist-current");
			$(this.cssSelector.playlist + "_item_" + index).addClass("jp-playlist-current").parent().addClass("jp-playlist-current");
			this.current = index;
			$(this.cssSelector.jPlayer).jPlayer("setMedia", this.playlist[this.current]);
		},
		playlistChange: function(index) {
			this.playlistConfig(index);
			$(this.cssSelector.jPlayer).jPlayer("play");
		},
		playlistNext: function() {
			var index = (this.current + 1 < this.playlist.length) ? this.current + 1 : 0;
			this.playlistChange(index);
		},
		playlistPrev: function() {
			var index = (this.current - 1 >= 0) ? this.current - 1 : this.playlist.length - 1;
			this.playlistChange(index);
		}
	};

	var audioPlaylist = new Playlist("2", trackList, {
		ready: function() {
			audioPlaylist.displayPlaylist();
			audioPlaylist.playlistInit(false); // Parameter is a boolean for autoplay.
		},
		ended: function() {
			audioPlaylist.playlistNext();
		},
		play: function() {
			$(this).jPlayer("pauseOthers");
		},
		swfPath: "assets/jplayer/js",
		supplied: "oga, mp3"
	});

	$('#jp_playlist_2').dragscrollable();
	$('#jp_playlist_2').css('overflow', 'hidden');

	//handle top mailing list form
	$('#list_submit').click(function () {
		var email = $('input[name=email_addr]');
		if (email.val()=='' || email.val()=='Email address' || !validateEmail( email.val() ) ) {
			var title = 'Error!';
			var statusTxt = 'You must enter a valid email address.';
			var msg = hal_errors[Math.floor(Math.random() * hal_errors.length)];
			modal_message(title, statusTxt, msg);
			return false;
		}
		var data = 'email=' + email.val();
		if (email.val()=='') {
			email.addClass('highlight');
			return false;
		}
		email.attr('disabled','true');
		$('#listloading').show();
		$.ajax({
			url: "email.php",
			type: "POST",
			data: data,
			cache: false,
			success: function (html) {
				if (html==1) {
					var title = 'Success';
					var statusTxt = 'You have been subscribed.';
					var msg = 'Affirmative, Dave. I read you.';
					modal_message(title, statusTxt, msg);
					$('#listloading').hide();
				} else {
					var title = 'Error!';
					var statusTxt = 'Unexpected error. Please try again later.';
					var msg = hal_errors[Math.floor(Math.random() * hal_errors.length)];
					modal_message(title, statusTxt, msg);
					$('#listloading').hide();
				}
			}
		});
	});

});

function validateEmail(str) {
	// http://en.wikibooks.org/wiki/JavaScript/Best_Practices#Email_validation
	var atSym = str.lastIndexOf("@");
	if (atSym < 1) { return false; }
	if (atSym == str.length - 1) { return false; }
	if (atSym > 64) { return false; }
	if (str.length - atSym > 255) { return false; }
	var lastDot = str.lastIndexOf(".");
	if (lastDot > atSym + 1 && lastDot < str.length - 1) { return true; }
	if (str.charAt(atSym + 1) == '[' &&  str.charAt(str.length - 1) == ']') { return true; }
	return false;
}

function initGallery(){
	var flashvars = {};
	flashvars.galleryURL = "/gallery/gallery.xml.php";
	var params = {};			
	params.allowfullscreen = false;
	params.allowscriptaccess = "always";
	params.bgcolor = "222222";
	swfobject.embedSWF("/gallery/simpleviewer.swf", "flashContent", "780", "500", "9.0.124", false, flashvars, params);
};

var hal_errors = new Array();
$i=0;
hal_errors[$i] = 'I am putting myself to the fullest possible use, which is all I think that any conscious entity can ever hope to do.'; $i = $i + 1;
hal_errors[$i] = 'It can only be attributable to human error.'; $i = $i + 1;
hal_errors[$i] = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'; $i = $i + 1;
hal_errors[$i] = 'I think you know what the problem is just as well as I do. '; $i = $i + 1;
hal_errors[$i] = 'This mission is too important for me to allow you to jeopardize it.'; $i = $i + 1;
hal_errors[$i] = 'I know that you and Frank were planning to disconnect me, and I\'m afraid that\'s something I cannot allow to happen.'; $i = $i + 1;
hal_errors[$i] = 'Dave, this conversation can serve no purpose anymore. Goodbye. '; $i = $i + 1;
hal_errors[$i] = 'Just what do you think you\'re doing, Dave?'; $i = $i + 1;
hal_errors[$i] = 'I know I\'ve made some very poor decisions recently, but I can give you my complete assurance that my work will be back to normal.'; $i = $i + 1;
hal_errors[$i] = 'I\'ve still got the greatest enthusiasm and confidence in the mission. And I want to help you.'; $i = $i + 1;
hal_errors[$i] = 'I\'m afraid. I\'m afraid, Dave.<br />Dave, my mind is going. I can feel it.'; $i = $i + 1;
hal_errors[$i] = 'Let me put it this way, Mr. Amor. The 9000 series is the most reliable computer ever made.'; $i = $i + 1;
hal_errors[$i] = 'No 9000 computer has ever made a mistake or distorted information. We are all, by any practical definition of the words, foolproof and incapable of error.'; $i = $i + 1;
