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) {
                    $(".playerinfo").html("Thank you for telling us what you think! Your rating has been saved.");
                } else {
                    $(".playerinfo").html("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;
};

$(document).ready(function() {

	$.ajaxSetup ({  
		cache: false  
	}); 

	// Logo Sparklement
	var logo2 = new Image();
	logo2.src = "graphics/logo_blue.png";
	$("#logo img").bind("mouseenter", function() {
		$(this).attr("src", logo2.src);
	});
	var logo = new Image();
	logo.src = "graphics/logo.png";
	$("#logo img").bind("mouseleave", function() {
		$(this).attr("src", logo.src);
	});

	// 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);
		});
	});
	
	// Uninterrupted Bliss
	$("#uninterrupted a").live("click", function() {
		var url = this.href + " #uninterrupted";
		$("#uninterrupted tfoot td").eq(0).html("<p><img src=\"/graphics/Loading.gif\" alt=\"Loading\"></p>");
		$("#uninterrupted").load(url);
		if (this.className == "inform") {
			var silent = alert("Because you might already be playing some music on this page, we will queue this request and add the song next time you refresh the page!\r\n\r\nThis means you can listen to music without interruptions.");
		}
		return false;
	});
	$("#uninterrupted form").live("submit", function() {
		var term = escape($("#SongSearch").val());
		var url = masterplayerurl.replace("*", term) + " #uninterrupted";
		$("#uninterrupted tfoot td").eq(0).html("<p><img src=\"/graphics/Loading.gif\" alt=\"Loading\"></p>");
		$("#uninterrupted").load(url);
		return false;
	});

	// 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);

	// 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>";
	});

	// Mapping Flickerings
	var postcode = $("#map_postcode").text();

	if (postcode.length > 0) {
		var mapdescription = $("#map_description").html();
		$(".break").prepend("<div id=\"showmap\" style=\"width: 575px; height: 300px; clear: both; \"></div>");
		$("#showmap").simplemap({ search: postcode, description: mapdescription });
	}

});
