var scroller_scrolldelay = 3000;
var scroller_scrollspeed = 2000;
var scroller_timer;
var hint_timer;
var scroller_classname;
var scroller_current;
var scroller_target;
var scroller_moveby;
var showRatingOption = true;

// Message Ace-ness
var showmessage = function(title, text) {
	$.ui.dialog.defaults.bgiframe = true;
	$(".musicplayer").css( { position:"relative", top:"-500px" } );
	$("#dialog").attr("title", title).html("<div style=\"float: left; padding-top: 16px;\"><img src=\"graphics/info.png\" alt=\"Info\"></div><div style=\"width: auto; margin-left: 50px;\"><p>" + text + "</p></div>");
	$("#dialog").dialog({
		beforeclose: function(event, ui) {
			$(".musicplayer").css( { position:"absolute", top:"-500px" } );
			$("#dialog").dialog("destroy");
			$(".musicplayer").css( { position:"static" } );
		}
	});
};

// Player Magnificence
var player = null;

var eventplayertrack = function(obj) {

    if (showRatingOption) {
        var tracksong = player.getPlaylist()[obj.index].title;
        var trackartist = player.getPlaylist()[obj.index].author;
        var trackfile = player.getPlaylist()[obj.index].file;
        var pos = trackfile.lastIndexOf("/");
        if (pos > -1) {
            trackfile = trackfile.substring(pos + 1);
        }
        var baseurl = $("base").attr("href");
        $(".playerinfo").html('<p><span>Now Playing "' + tracksong + '" by ' + trackartist + ' Rate It: </span>' +
            '<a class="inlinerate" href="' + baseurl + '?Section=Rate&Item=Song&Rating=1&Track=' + trackfile + '"><img src="graphics/minirate5.png" title="1 out of 5"></a>' +
            '<a class="inlinerate" href="' + baseurl + '?Section=Rate&Item=Song&Rating=2&Track=' + trackfile + '"><img src="graphics/minirate5.png" title="1 out of 5"></a>' +
            '<a class="inlinerate" href="' + baseurl + '?Section=Rate&Item=Song&Rating=3&Track=' + trackfile + '"><img src="graphics/minirate5.png" title="1 out of 5"></a>' +
            '<a class="inlinerate" href="' + baseurl + '?Section=Rate&Item=Song&Rating=4&Track=' + trackfile + '"><img src="graphics/minirate5.png" title="1 out of 5"></a>' +
            '<a class="inlinerate" href="' + baseurl + '?Section=Rate&Item=Song&Rating=5&Track=' + trackfile + '"><img src="graphics/minirate5.png" title="1 out of 5"></a>' +
            '</p>');

        $(".inlinerate").click(function() {
            var destination = $(this).attr("href");
            $.get(destination, function(data) {
                if (data.indexOf('Thank you for rating') > -1) {
                    showmessage("Rating", "Thank you for telling us what you think! Your rating has been saved.");
                } else {
                    showmessage("Rating", "You need to be <a href=\"" + masterloginurl + "\">logged in</a> to save a rating.");
                }
            });
            return false;
        });
    }
};

var addPlayerListeners = function() {
	var playlistfound = false;
	try {
		player.getPlaylist();
		playlistfound = true;
	}
	catch(err) {}
	if(playlistfound) {
		player.addControllerListener('ITEM', 'eventplayertrack');
	} else {
		window.setTimeout("addPlayerListeners();", 100);
	}
};

var playerReady = function(obj) {
	$(".musicplayer").after("<div class=\"playerinfo\"></div>");
	player = document.getElementById(obj.id);
	window.setTimeout("addPlayerListeners();", 100);
};

var scrolleraction = function() {
	window.clearTimeout(scroller_timer);
	var moveto = scroller_current - scroller_moveby;
	if (moveto <= scroller_target) {
		moveto = 0;
	}
	scroller_current = moveto;
	$(scroller_classname).animate( { top:(moveto)+"px" }, scroller_scrollspeed );

	scroller_timer = window.setTimeout("scrolleraction();", scroller_scrollspeed + scroller_scrolldelay);
};

var urlify = function (text) {
	text = text.replace(/-/g, "");
	text = text.replace(/  /g, " ");
	return text;
};

var checkform = function(pop) {
    if (pop == null) {
        pop = false;
    }
	var mandatory = $(".mandatory");
	var failed = false;
	for (i = 0; i < mandatory.length; i++) {
		elem = $(mandatory[i]);
		if (elem.attr("value").length === 0) {
			failed = true;
			elem.css( { backgroundColor:"#FFCCCC" } );
		} else {
			elem.css( { backgroundColor:"#FFFFFF" } );
		}
	}
	if (failed) {
		showmessage("Form - Problem", "Please complete all required fields before you continue. We've highlighted the problem fields for you.");
		return false;
	} else {
        $("form input[type='submit']").disabled = "true";
        if (pop) {
            popandcheckform();
        }
    }
	return true;
};

var winHandle;
var popandcheckform = function() {
    winHandle = window.open("Loading.html", winHandle, "width=500, height=400");
};

var destroypop = function() {
   winHandle = window.open("Loading.html", winHandle, "width=500, height=400");
   winHandle.close();
};

var checkgigform = function() {
	var mandatory = $(".mandatory");
	var failed = false;
	for (i = 0; i < mandatory.length; i++) {
		elem = $(mandatory[i]);
		if (elem.attr("value").length === 0) {
			failed = true;
			elem.css( { backgroundColor:"#FFCCCC" } );
		} else {
			elem.css( { backgroundColor:"#FFFFFF" } );
		}
	}
	if (!failed) {
		if (document.eventform.gig_GigInfo.value.indexOf("+") < 0) {
			failed = !confirm("You've not put any plus (+) signs in there... are you sure you've separated the bands with ' + '?");
			if (failed) {
				document.eventform.gig_GigInfo.style.backgroundColor = "#FFCCCC";
			}
		}
	}
	if (failed) {
		showmessage("Form - Problem", "Please complete all required fields before you continue. We've highlighted the problem fields for you.");
		return false;
	}
	return true;
};

var checkform2 = function(form) {
	var ok = checkform();
	if (ok && form.password.value.length < 30) {
		form.password.value = hex_md5(hex_md5(form.password.value));
	}
	return ok;
};

var searching = function(term) {
	if (term.length > 0) {
		var location = mastersearchurl;
		term = term.replace(/ /g, "-");
		location = location.replace(/insertterm/g, term);
		document.location = location;
	}
	return false;
};

var searchingtype = function(term, type) {
	if (term.length > 0) {
		var location = mastertypesearchurl;
		term = term.replace(/ /g, "-");
		location = location.replace(/insertterm/g, term);
		location = location.replace(/inserttype/g, type);
		document.location = location;
	}
	return false;
};

var gigsearching = function(term, type) {
	if (term.length > 0) {
		var location = mastergigsearchurl;
		term = term.replace(/ /g, "-");
		location = location.replace(/insertterm/g, term);
		location = location.replace(/inserttype/g, type);
		document.location = location;
	}
	return false;
};

var managehints = function() {
	var hints = $("div.hint");
	for (i = 0; i < hints.length; i++) {
		$(hints[i]).hide("slow");
	}
};

var hintcountdown = function(seconds) {
	if (seconds < 0) {
		managehints();
	} else {
		$(".hintcounter").html("This hint will close in " + seconds + " seconds. <a href=\"#\">Leave It!</a>");
		$(".hintcounter a").click(function() {
			window.clearTimeout(hint_timer);
			$(".hintcounter").html("Click on the green arrow to close this hint");
			return false;
		});
	}
	hint_timer = window.setTimeout("hintcountdown(" + (seconds - 1) + ");", 1000);
};

$(document).ready(function() {

	// Logo Sparklement
	var logo = new Image();
	var logotimer;
	logo.src = "graphics/logo_blue.png";
	$("#logo img").bind("mouseenter", function() {
		window.clearTimeout(logotimer);
		$(this).attr("src", logo.src);
		logotimer = window.setTimeout('$("#logo img").attr("src", "graphics/logo.png");', 1000);
	});

	// Contact Form Goodness
	$("#contactform").hide("fast");
	$("#contactconfirm").css( { cursor:"pointer", color:"#339966" } ).show();
	$("#contactconfirm").click(function() {
		$("#contactconfirm").hide("slow");
		$("#contactform").show("slow");
	});

	// Datepicker Wonderment
	$(".datepicker").datepicker({ dateFormat: 'yymmdd' });

	// Breadcrumb Shimmerings
	var elems2 = $(".breadcrumb a");
	var width2;
	var textsize2;
	var allowchars2;

	for(i = 0; i < elems2.length; i++) {
		if (i === 0) {
			width2 = 350;
			textsize2 = (parseFloat($(elems2[i]).css("font-size"), 10)) - 7;
			allowchars2 = parseInt(width2 / textsize2, 10);
		}
		var chars2 = $(elems2[i]).text().length;
		if (chars2 > allowchars2) {
			var text2 = $(elems2[i]).text().substring(0, allowchars2) + "...";
			$(elems2[i]).html(text2);
		}
	}

	// Ajax Facination
	$("#label_select").click(function() {
		var filter = prompt("Please enter a filter...");
		var cachebust = new Date();
		$.get("service.php?list=label_select&filter="+filter+"&c="+cachebust.getTime(), function(data) {
			$("#label_select").unbind("click");
			$("#label_select").html(data);
		});
	});
	$("#venue_select").click(function() {
		var filter = prompt("Please enter a filter...");
		var cachebust = new Date();
		$.get("service.php?list=venue_select&filter="+filter+"&c="+cachebust.getTime(), function(data) {
			$("#venue_select").unbind("click");
			$("#venue_select").html(data);
		});
	});

	// Slinding Brilliance
	var displayheight = $(".list").eq(0).height();
	var sliders = $(".slider");
	$(".slidingcolumn").css( { width:"100%", height:displayheight+"px", overflow:"hidden", border:"1px solid #EAEBE3", position:"relative" } );
	$(".slidingcolumn").after("<div class=\"playpause\">" +
		"<div class=\"playbutton\"><img src=\"graphics/site_sprite.png\" class=\"playslide\" alt=\"Play\"></div>" +
		"<div class=\"pausebutton\"><img src=\"graphics/site_sprite.png\" class=\"pauseslide\" alt=\"Pause\"></div>" +
		"<div class=\"forwardbutton\"><img src=\"graphics/site_sprite.png\" class=\"forewardslide\" alt=\"Forward\"></div>" +
		"</div>");
	$(".playslide").click(function () {
		scrolleraction();
		$(".playslide").fadeTo("fast", 0.5);
		$(".pauseslide").fadeTo("fast", 1);
	});
	$(".playslide").css( { cursor:"pointer" });
	$(".playslide").fadeTo("fast", 0.5);
	$(".pauseslide").click(function () {
		window.clearTimeout(scroller_timer);
		$(".playslide").fadeTo("fast", 1);
		$(".pauseslide").fadeTo("fast", 0.5);
	});
	$(".pauseslide").css( { cursor:"pointer" });
	$(".forewardslide").click(function () {
		scrolleraction();
		window.clearTimeout(scroller_timer);
		$(".playslide").fadeTo("fast", 1);
		$(".pauseslide").fadeTo("fast", 0.5);
	});
	$(".forewardslide").css( { cursor:"pointer" });
	for (i = 0; i < sliders.length; i++) {
		$(sliders[i]).css( { position:"absolute" } );
	}
	var listitems = $(sliders[0]).children(".list");

	scroller_classname = ".slider";
	scroller_current = 0;
	scroller_target = ((listitems.length / 2) * displayheight) * -1;
	scroller_moveby = displayheight + 2;
	scroller_timer = window.setTimeout("scrolleraction();", scroller_scrolldelay);

	// Form Astonishment
	$("#faqreply").click(function() {
		document.replyform.Comment.value = document.replyform.Comment.value.replace(/#/, "Thank you for getting in touch with The Mag - sadly we cannot send a personal reply to your message, but the answer can be found using the links on the contact form. Click here to take a look: http://www.the-mag.me.uk/Music/Contact/");
		$("#faqreply").hide("fast");
	});

	// Rating Anchor Remakables
	$(".rate").click(function() {
		var destination = $(this).attr("href");
		$.get(destination, function(data) {
			if (data.indexOf('Thank you for rating') > -1) {
				showmessage("Rating", "Thank you for telling us what you think! Your rating has been saved.");
			} else {
				showmessage("Rating", "You need to be <a href=\"" + masterloginurl + "\">logged in</a> to save a rating.");
			}
		});
		return false;
	});

	// External Anchor Intelligencia
	var anchors = $("a");
	for (i = 0; i < anchors.length; i++) {
		var ahref = $(anchors[i]).attr("href");
		if (ahref.indexOf('http://') > -1 && ahref.indexOf('the-mag.me.uk') < 0 && $(anchors[i]).attr("class") != "external") {
			$(anchors[i]).attr("class", "externallink");
			$(anchors[i]).click(function() {
				document.location =  checkredirecturl.replace(/\*/g, escape($(this).attr("href")).replace(/\//g, "%2F"));
				return false;
			});
		}
	}

	// Autocomplete Automagical
	$("#mainsitesearch").autocomplete(masterbaseurl+"service.php", {
		width: 220,
		selectFirst: false,
		scroll: false,
		extraParams: { list:"bands" }
	});

	// List Item Significance
	var listitems2 = $(".list");
	for (i = 0; i < listitems2.length; i++) {
		if ($(listitems2[i]).text().indexOf(masterdate) > -1) {
			$(listitems2[i]).css({ backgroundColor:"#EAEBE3" }).attr("class", "list listtoday");
		}
	}

	// Word Cloud Sortery
	var sortabc = $('<a href="javascript:void(0)" class="btn">A-Z</a>').toggle(
		function() { $(".wordcloud ul li").tsort({order:"asc"}); },
		function() { $(".wordcloud ul li").tsort({order:"desc"}); }
	);
 	$(".wordcloudicons").append(sortabc);
	$(".wordcloudicons").append(" . ");
	var sortstrength = $(' <a href="javascript:void(0)" class="btn">0-9</a> ').toggle(
		function() { $(".wordcloud ul li").tsort({order:"desc",attr:"class"}); },
		function() { $(".wordcloud ul li").tsort({order:"asc",attr:"class"}); }
	);
 	$(".wordcloudicons").append(sortstrength);

	// Hint Disguisement
	var hints = $("div.hint");
	if (hints.length > 0) {

		$("div.hint").prepend("<div class=\"hidehint\"><a href=\"#\"><img src=\"graphics/back.png\" alt=\"Collapse\"></a></div>");
		$("div.hint").append("<p class=\"hintcounter\">...</p>");

		$(".hidehint a").click(function() {
			window.clearTimeout(hint_timer);
			$("div.hint").hide("slow");
			return false;
		});
	}
	hint_timer = window.setTimeout("hintcountdown(10);", 1000);

	// Admin Stunners
	$("#htmlise").click(function() {
		var htmltarget = document.getElementById("htmltarget").value;
		document.getElementById("htmltarget").value = "<p>" + htmltarget.replace(/\n\n/g, "</p>\n<p>") + "</p>";
	});

	// List Slidenificance
	if (document.getElementById("funklist")) {
		var listitems = $("#funklist .list");
		var funkcontent = "";
		var classswap;
		for (i = 0; i < listitems.length; i++) {
			if (i % 2 == 0) {
				classswap = "";
			} else {
				classswap = " class=\"alternate\"";
			}
			funkcontent += "<li" + classswap + ">" + $(listitems[i]).html().replace('width="90"', 'width="131"').replace('height="90"', '') + "</li>";
		}
		funkcontent = "<div id=\"slider\"><ul>" + funkcontent + "</ul></div>";
		$("#funklist").before(funkcontent);

		$("#slider").after("<div class=\"pages\">" + $(".pages:first").html() + "</div>");

		$("#slider").easySlider({
			controlsBefore:	'<p id="controls">',
			controlsAfter:	'</p>',
			auto: true,
			continuous: true,
			pause: 5000
		});

	}

	// Heading Fantisticals
	//var elems = $(".list h3 a");
	//var width;
	//var textsize;
	//var allowchars;
	//var i;

	//for(i = 0; i < elems.length; i++) {
	//	if (i === 0) {
	//		width = $(elems[i]).parent().width();
	//		textsize = (parseFloat($(elems[i]).css("font-size"), 10)) - 7;
	//		allowchars = parseInt(width / textsize, 10);
	//	}
	//	var chars = $(elems[i]).text().length;
	//	if (chars > allowchars) {
	//		var text = $(elems[i]).text().substring(0, allowchars) + "...";
	//		$(elems[i]).html(text);
	//	}
	//}

});