/*@cc_on 
	@if (@_win32)
		try {document.execCommand('BackgroundImageCache', false, true);}catch(e){}
	@end
@*/

/**
 * 
 * 
 */

function moveMPU() {
	
	// var mpu_html = $(".mpu-loader *:not(script)").html();	
	// $(".mpu-holder").html(mpu_html);
	
	$(".mpu-loader script, .mpu-loader noscript, .mpu-loader noembed").remove();
	var mpu_html = $(".mpu-loader").html();
	$(".mpu-holder").html(mpu_html);
	
}


$(document).ready( function() {
	
	// confirmation box appears when button is clicked
	$('.confirm').submit(function()
	{
		message = $(this).attr('title');
		var answer = confirm(message);
		return answer // answer is a boolean
	});
	
	/* Add loading code */

	/* filmmker school option */
	
	if($('.filmmaker-school-which').length) {
		
		$('.filmmaker-school-which').hide();
	
		$('#film-school-yes').click(function(){
			$('.filmmaker-school-which').show();
		});
		
	}
	
	if ($('#track-player').length) {
		
		setTimeout(function() {
			
			var id = $('span.track-id').text();
			var ip = $('span.ip').text();
			
			$.ajax({
			   type: "POST",
			   url: "/artists/",
			   data: "fields[track]="+id+"&fields[ip]="+ip+"&fields[fan]=140&action[update-track-data]=1",
			   success: function(msg){
			     //alert( "Data Saved: " + msg );
			   }
			 });
		}, 3000);	
		
	}
	
	/* Rating */
    if(typeof setupRatings == "function")
        setupRatings();


	/* Map Header */
	$("#google-loc-what-H").each(function() {
		var input = $(this);
		if(input.val() == '') {
			input.val("What eg: business");
			input.data("placeholder", true);
            input.addClass("greyed-out");
			
			input.focus(function() {
				var element = $(this);
				if(element.data("placeholder") == true) {
					element.val("");
					element.removeClass("greyed-out");
					element.data("placeholder", false);
				}
			});
		}
	});
	
	$("#google-loc-where-H").each(function() {
		var input = $(this);
		if(input.val() == '') {
			input.val("Where town or postcode");
			input.data("placeholder", true);
            input.addClass("greyed-out");
			
			input.focus(function() {
				var element = $(this);
				if(element.data("placeholder") == true) {
					element.val("");
					element.removeClass("greyed-out");
					element.data("placeholder", false);
				}
			});
		}
	});
	
	/**
	 * General
     */
	var url = window.location.href;
	var anchor = parseUri(url).anchor;
	
	if (anchor) { $.scrollTo( $('#'+anchor), 800 ); }
	
	$("body").addClass("js");
	
	/**
	 * Home Page
     */
	
	/**
	 * Bands Page
     */
	var jcarousel_scroll = 1;	
	
	if ($(".carousel-thumbnails").length > 0) {
		jcarousel_scroll = 3;
	}
	
	jQuery('#carousel').jcarousel({
		scroll : jcarousel_scroll,
		animation : 1000		
	});
		
	$('.tracklist li:nth-child(even)').addClass("alt");
		
	$('.replies-link').click(function() {	
		var id = $(this).attr('rel');
		var ul = $('ul#replies-'+id);
					
		if($('li', ul).length > 1) {
		
			$('li', ul).show();
			$(this).unbind("click");
		
		}

		return false;
    });
		
	/**
	 * Register
     */
	$('#band-members label').after('<ul id="members-list" class="hidden"></ul>');		
	$('#band-members-non-js').hide();
				
	/**
	 * Band Members
     */	
	$('.add-member').click(function(){
		var member = $('#band-member-field');
		var position = $('#band-position-field');
		
		if ($(member).val() == '') {
			$('#band-member-field').focus();
			return false;
		}
		
		if ($(position).val() == '') {
			$('#band-position-field').focus();
			return false;
		}
		
		var text = $(member).val() + ' (' + $(position).val() + ')';
		
		if(text != '') {		
			$('#members-list').show();
			$('#members-list').append('<li>'+text+' <a href="#" class="delete">remove</a><input type="text" style="display:none" name="bands[members]['+text+']" value="'+text+'" /></li>');
		}
		
		$('#band-member-field').val('');
		$('#band-position-field').val('');
		
		return false;
	});
		
	/**
	 * Band maintenance version
     */
	$('.add-member-post').click(function()
	{
		if (!$('#add-name').val())
			return false;
			
		$('#band-members').append('<div class="band-member"><input type="text" class="text name" value="'+$('#add-name').val()+'" /> + <input type="text" class="text position" value="'+$('#add-position').val()+'" /><input type="" value="" class="minus remove-member-post"/></div>');
		$('#band-members .band-member:last .remove-member-post').click(function(){ $(this.parentNode).remove(); });
		
		$('#add-name, #add-position').val('');
		
		return false;
	});
		
	$('.remove-member-post').click(function()
	{
		$(this.parentNode).remove();
		return false;
	});		
	
	$('.pre-submit').click(function()
	{
		var final_output = '';
		
		if ($("#add-name").val() != '' && $("#add-name").val() != '') {
			final_output = $("#add-name").val() + " (" + $("#add-position").val() + ")";
		}			
		
		var len = $('.band-member').length - 1;
		
		$('.band-member').each(function(i){
			
			if ($('input.name', this).val() != '' && $("#add-name").val() != '' && $("#add-name").val() != '') {
				final_output += ', ';
			}
			
			final_output += $('input.name', this).val() + " (" + $('input.position', this).val() + ")";
			
			if (i < len)
				final_output += ", ";
		});
		
		//alert(final_output)
		
		$('#final-members').val(final_output);			
	});
				
	$('#band-register').submit(function(){
		$('input[name="users[screen-name]"]').val($('input#register-name').val());
		
		var memberslist = '';
		
		$('#members-list li').each(function(){
			memberslist += $(this).text();
			memberslist += ',';
		})
		
		memberslist += $('#band-member-field').val();
		$('#band-members-non-js input').val(memberslist);
	})
		
	$('#fan-register').submit(function(){		
		$('input[name="users[screen-name]"]').val($('input#register-name').val());
	})
		
	/**
	 * General
     */
	$("#band-table").tablesorter({ 
		// sort on the first column and third column, order asc 
		sortList: [[0,0],[0,0],[0,0],[0,0]] 
	});
		
	var reply_form = $('.reply-form');
		
	/**
	 * Comments
     */	 	
	// show reply comment blocks 
	//$('ul.comment-replies').hide();
	$('p.replies > a.show, p.replies > a.reply').click(function() {
		if ($(this).hasClass("nojs")) return;
		//$('ul.comment-replies:visible').hide("fast");
		$(this).parents('.comment').next('ul.comment-replies').show("slow");
		return false;
 	}); 
	
	$('a.reply').click(function() {
		if ($(this).hasClass("nojs")) return;
		$('.reply-form').hide();
		var id = $(this).attr('rel');
		$('#replies-' + id + ' li').show();		
		return false;
    });

	// Show error message blocks
	$('.comment-replies.error').each(function() {
		$(this).show("slow");
	});


	/**
	 * Band Search
     */	
	var query = parseUri(url).query;
			
	if (query.indexOf('genre') > -1) {
		$('input.genre').attr('checked', '');
	}
	
	$('input.genre').each(function() {
		if(query.indexOf($(this).attr('name')) > -1) {
			$(this).attr('checked', 'checked');
		};
	})
		
			
	$('#refine-bands').click(function() {
		var string = '?genre=';
		
		$('input.genre').each(function() {
			if ($(this).attr('checked')) {
				string += $(this).attr('name') + ',';
			};
		})
		
		try {
			var query = parseUri(url).queryKey.query;
			if (query.length > 0) {
				string += '&query=' + parseUri(url).queryKey.query;
			}
		} catch(error) { }
		
		window.location.href = string;
		
	});
		
	$('#select-none').click(function() {
		$('input.genre').attr('checked', '');
		return false;
	});
	
	
	// Text Area Character Limiting
	$(function()
	{
		$('.character-limit').keydown(function()
		{
			limitChars($(this), ($(this).attr('title')));
		})
		$('.character-limit').keyup(function()
		{
			limitChars($(this), ($(this).attr('title')));
		})
	});
	
	// Uniquity checking
	$('#user-username').blur(function()
	{
		var element = this;		 		

		$.post("/register/check-uniquity/username/", { value: this.value },
		function(data){
			if ($('result', data).text() == 'success') {
				$('#checking-username').hide();
			}
			else {
				$('#checking-username').text("Username " + element.value + " has been taken.");
				$('#checking-username').fadeIn("fast");
				element.value = '';
				$(element).addClass('invalid');
			}
		});		 	
	});		 	
		 	
	$('#user-email').blur(function()
	{		 		
		var element = this;

		$.post("/register/check-uniquity/email/", { value: this.value },
		function(data){
			if ($('result',data).text() == 'success')
				$('#checking-email').hide();
			else
			{						
				$('#checking-email').text("There is already an account with this email address!");
				$('#checking-email').fadeIn("fast");
				$(element).addClass('invalid');
			}
		});		 	
	});
	
	if(!$.browser.msie)
		Cufon.replace('.cufon-notie');
		
	$('#user-bandname').blur(function()
	{		 		
		var element = this;

		$.post("/register/check-uniquity/bandname/", { value: this.value },
			function(data){
				if ($('result', data).text() == 'success') {
					$('#checking-bandname').hide();
				}
				else {
					$('#checking-bandname').text("There is already an account with this band name!");
					$('#checking-bandname').fadeIn("fast");
					$(element).addClass('invalid');
				}
			});		 	
	});	
		
	$("input[name='action[update-fan-profile]']").click(function() {
		var upload = $("input[name='fields[profile-image]']");
		if (upload.length == 1) {
			if (upload.val() == "") {
				$("p#profile-image-error").html("Please select a profile image.");
				return false;
			}
		}
	});

	$("a#edit-profile-image").click(function(e) {
		e.preventDefault();
		$(".profile-pic").html("<h2>profile pic</h2><input name=\"fields[profile-image]\" type=\"file\" style=\"font-size:11px;\" /><p id='profile-image-error'></p>");
	});

	// About page move image to second paragraph
	var contentimage = $("div#content-image").html();
	$("div#content-image").text('');
	$("div#aboutcontent").children("p:nth-child(2)").after(contentimage);
	
	$("#faq .questions li a, a#comelink").click(function(e) {
			e.preventDefault();
		var location = $(this).attr('href');
		$.scrollTo(location, 2000);
		return false;
	});
		
	$("div.optin label a, .cb-container label a, div.register div.links ul a, div#competition form a, a[rel='external']").click(function(e) {
		e.preventDefault();
		window.open($(this).attr("href"));
	});
	
	$("input[name='action[update-critic]']").click(function() {
		var upload = $("input[name='fields[profile-image]']");
		if (upload.length == 1) {
			if (upload.val() == "") {
				$("p#profile-image-error").html("Please select a profile image.").show();
				return false;
			}
		}
	});
	$("a.edit-profile-image").click(function(e) {
		e.preventDefault();
		
		var event_name = "update-critic";
		if ($(this).hasClass("filmmaker")) event_name = "update-filmmaker";
		
		$(".profile-pic").html("<input name=\"fields[profile-image]\" type=\"file\" style=\"font-size:11px;margin:20px 0 10px 0;width:100px;\" /><p id='profile-image-error' style='display:none;color:#FFE600;'></p><input name=\"action[" + event_name + "]\" type=\"submit\" class=\"submit strip\" value=\"Upload image\"/>");
	});
		
	// DD_belatedPNG applied before the header is written in, therefore
	// home link on logo doesn't work
	$("#virgin-header h2:first").click(function(e) {
		e.preventDefault();
		window.location.href = "/";
	});
		
	if ($("div#upload").length != 0) {
		
		bindVideoEvents('video-contributors', 'contributors');
		bindVideoEvents('video-locations', 'locations');
		bindVideoEvents('video-music', 'music');
		
		// remove default text on first use
		$("div#contributors input, div#locations input, div#music input").focus(function() {
			var element = $(this);
			if(element.data("placeholder") == true) {
				$(this).val("");
				$(this).unbind("focus");				
				$(this).data("placeholder", false);
                $(this).removeClass("greyed-out");
			}
		});
		
		// add default text on first use
		$("div#contributors input.vc-name").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. John Smith");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});
		
		// add default text on first use
		$("div#contributors input.vc-charname").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("Fred");
				input.data("placeholder", true);
                input.addClass("greyed-out");
            }
		});
		
		// add default text on first use
		$("div#contributors input.vc-description").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. blue jeans, white shirt, dark hair");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});
		
		// add default text on first use
		$("div#contributors input.vc-name").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. John Smith");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});
		
		// add default text on first use
		$("div#locations input.vl-name").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. John Smith");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});
		// add default text on first use
		$("div#locations input.vl-description").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. Used for bedroom scene and kitchens");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});

		// add default text on first use
		$("div#music input.vm-name").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. John Smith");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});
		
		// add default text on first use
		$("div#music input.vm-artist").each(function() {
			var input = $(this);
			if(input.val() == '') {
				input.val("E.g. Used for bedroom scene and kitchens");
				input.data("placeholder", true);
                input.addClass("greyed-out");
			}
		});
		
		
		// Clear placeholders before submission
		$("#edit-film").submit(function() {
			$("input", this).each(function() {
				var element = $(this);
				if(element.data("placeholder") == true) {
					element.val("");
				}
			});
		});
	
	}
	
	if ($(".carousel-thumbnails").length > 0) {
		updateCarouselImage($(".carousel-thumbnails li a:first"));
		$(".carousel-thumbnails li a").click(function(e) {
			e.preventDefault();
			updateCarouselImage(this);
		});
	}
	
	if ($("#essentials").length > 0) {
		
		$("a.row-heading").click(function(e) {
			
			if ($(this).attr("href") == "/faq/") return; 
			
			e.preventDefault();
			if ($(this).parent().hasClass("collapse")) {
				$(this).parent().removeClass("collapse");
			} else {
				$(this).parent().addClass("collapse");
			}
		});
	}
	
});

function updateCarouselImage(a) {
	
	var img_container = $(".carousel-image");
	var total  = $(".carousel-thumbnails li").length;
	
	img_container.find("img").attr("src", $(a).attr("href"));
	img_container.find("span.caption").html($(a).find("img").attr("alt"));
	img_container.find("span.count").html( ($("a", ".carousel-thumbnails ul").index(a) + 1) + "/" + total );
}


function bindVideoEvents(section, div) {	
	
	var category = $("div#" + div);
	
	// Show last plus icon and remove any existing click handlers
	$("a.plus:last", category).show();
	$("a.plus, a.minus", category).unbind("click");
	
	
	// Handle deleteing of an item
	$("a.minus", category).click(function(e) {
		e.preventDefault();
	
		// Unset as a hidden field
		var additional = $(this).parents("div.additional");
		var id = $('input[name*="system:id"]', additional).val();
		if((id != undefined) && (id != "")) {
			$('form#edit-film').append('<input type="hidden" name="' + section + '['+id+'][system:id]" value="'+id+'"/>');
			$('form#edit-film').append('<input type="hidden" name="' + section + '['+id+'][video]" value="1"/>');
		}
		
		additional.remove();
		$("a.plus:last", category).show();
	});
	
	var html_third = $("div.third:last", category).clone();
	var html_two_thirds = $("div.two-thirds:last", category).clone();
	
	$("div.additional", category).find("a.minus").show();
	
	$("a.plus", category).click(function(e) {
		e.preventDefault();
		
		$(this).hide();
		var parent = $(this).parent("div.additional");
		parent.find("a.minus").show();
		
		var position = $("div.additional", category).length + 2;
		
		category.append("<div class='additional'></div>");
		category
			.find("div.additional:last").append(html_third).append(html_two_thirds)
			.find("a.right").show().end()
			.find("input").each(function(i) {
				var element = $(this);
				
				// Focuse and empty
				if (i==0) $(this).focus();
				element.val("");
                
                
                if(this.checked == true)
                    this.checked = false;
                if(element.attr("checked") == "checked")
                    element.atrr("checked", "");
				
				// If a tabindex exists
				if(element.attr("tabindex") != undefined) {
					
					// Update tab index
					var tabindex = (Number( element.attr("tabindex") ) + 10);
					element.attr("tabindex", tabindex);
	
				}
				
				// Rename the name attribute
				var name = element.attr("name");
				element.attr("name", name.replace(/[\d+]/, position));
				if (element.attr('name').indexOf('system:id') != -1) {
					element.remove();
				}
			});
            
        category
			.find("div.additional:last .error").removeClass('error');
		
		bindVideoEvents(section, div);
	});	
};

function showLogin() {
	$("div#main-nav form a:first").click();
}

function limitChars(block, limit)
{
	var text = block.find("textarea").val(); 
	var textlength = text.length;
	if(textlength > limit)
	{
		block.find(".display").html('You cannot write more then '+limit+' characters!');
		block.find(".display").html('0');
		block.find("textarea").val(text.substr(0,limit));
		return false;
	}
	else
	{
		block.find(".display").html('You have ' + (limit - textlength) + ' characters left');
		return true;
	}
}

var parseUri = function (source) {
	var o = parseUri.options,
		value = o.parser[o.strictMode ? "strict" : "loose"].exec(source);
	
	for (var i = 0, uri = {}; i < 14; i++) {
		uri[o.key[i]] = value[i] || "";
	}
	
	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});
	
	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q: {
		name: "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function voteFormSubmit(votesRemaining) {
	var voteString = votesRemaining;
	if(votesRemaining > 1)
		voteString += " votes";
	else
		voteString += " vote";
		
	var voteText = "Your vote really does count. Thanks for voting!\n\nTo make sure Virgin Media Shorts is the real deal, we're watching the votes and making sure that only legit votes are being counted.\n\nAre you sure you want to use your vote now?";
	if(confirm(voteText)) {
		$("#voter").submit();	
	}
}
