var LOADING_IMG_HTML = "<img class=\"loading\" alt=\"Loading...\" src=\"" + RESOURCE_URL + "/images/icons/loading.gif\" />";

jQuery(document).ready(function()
{
	// IE 6 and earlier.. we don't support
	if (BrowserDetect.browser == "Explorer" && BrowserDetect.version < 7)
	{
		jQuery("#old-ie-warning").show();
	}
	
	// Onmouseover effects for social network images
	jQuery("div#footer-social-networks img").each(function(i, v)
	{
		var img = jQuery(v);
		var srcNormal = img.attr("src");
		var srcHover = srcNormal.substring(0, srcNormal.lastIndexOf(".png")) + "clean.png";

		// Mouse events
		img.mouseenter(function() { this.src = srcHover; } );
		img.mouseleave(function() { this.src = srcNormal; } );
	});
});

// Determine whether we can show the date labels
jQuery(document).ready(determineShowMixtapeDateLabels);
jQuery(window).resize(determineShowMixtapeDateLabels);
function determineShowMixtapeDateLabels()
{
	// Can we show 'm?
	if (jQuery(window).width() > 1100)
	{
		// Then show the labels
		jQuery("div.mixtape-date-label").show();
		jQuery("div.mixtape-date").each(function(i, v)
		{
			v = jQuery(v);
			if (!v.hasClass("always-visible"))
				v.hide();
		});
	}
	// We need to hide them, not enough space
	else
	{
		jQuery("div.mixtape-date-label").hide();
		jQuery("div.mixtape-date").show();
	}
}

// Toggle the login box
function toggleLoginBox()
{
	var li = jQuery("#signup-login");
	var box = jQuery("#login-box");

	// Currently shown
	if (li.hasClass("active"))
	{
		li.removeClass("active");
		box.hide();
	}
	// Currently hidden --> show
	else
	{
		li.addClass("active");
		box.show();

		// Focus on email
		jQuery("#login-box input[name=username]").focus();
	}
}

function onSubmitFormEncryptPassword(form)
{
	form = jQuery(form);
	var id = form.attr("id");
	
	if (id == "")
	{
		id = "form"+Math.round(Math.random()*100000);
		form.attr("id", id);
	}
	
	// Get the correct fields from the form
	var selectorEncryptedField = "form#"+id+" input[type=\"hidden\"][name=\"encrypted\"]";
	var selectorPasswordField = "form#"+id+" input[type=\"password\"]";
	var encryptedField = jQuery(selectorEncryptedField);
	var passwordField = jQuery(selectorPasswordField);
	
	// Encrypt the password
	var hash = SHA1(passwordField.val());
	encryptedField.val("true");
	passwordField.val(hash);
}

function popup(url, name)
{
	if (typeof(name) == "undefined" || name == null || name == "")
		name = "_impopup";
	
	var width = 800;
	var height = 600;
	
	window.open(url, name, "left=10,top=10,width="+width+",height="+height+",menubar=0,status=0,toolbar=0,scrollbars=1");
}

function like(id)
{
	likeDislike("like/"+id);
}

function dislike(id)
{
	likeDislike("dislike/"+id);
}

function likeDislike(url)
{
	var id = url;
		id = id.replace(/(dis)?like\//gi, "");
		id = id.replace(/\//gi, "");
	
	url = "/like/"+url;
	jQuery.getJSON(
		url,
		function(data)
		{
			// Must be logged in
			if (data.error == 2)
			{
				alert("You have to be logged in to like or dislike something.");
			}
			// Already liked/disliked
			else if (data.error == 3)
			{
				alert("You already liked or disliked this.");
			}
			// Something went wrong!
			else if (data.error > 0)
			{
				alert("Something went wrong while performing the like or dislike action. Error code " + data.error + ".");
			}
			else
			{
				// All good!
				jQuery("#likeResults_"+id).show();
				jQuery("#likeCount_"+id).html(data.likes);
				jQuery("#dislikeCount_"+id).html(data.dislikes);
			}
		}
	);
}

function validateCommentsForm(form)
{
	// Can have an author name
	var authorInput = jQuery(form).find("input[name=author]");
	if (authorInput.length == 1)
	{
		var author = jQuery.trim(authorInput.val());
		if (typeof(author) == "undefined" || author == "" || author.length < 3 || author == "Your name...")
		{
			alert("Please supply a name!");
			return;
		}
	}
	
	var errormsg = jQuery(form).children("div").children("div");
	var textarea = jQuery(form).children("div").children("textarea");
	var val = jQuery.trim(textarea.val());
	
	// Must write something
	if (typeof(val) == "undefined" || val == "")
	{
		errormsg.show((errormsg.is(":visible") ? "highlight" : "blind"), {}, 300);
		return false;
	}
	
	return true;
}

function loadComments(formId, page)
{
	if (typeof(page) != "number" || page < 1)
		page = 1;
	
	// To jQuery object
	var form = jQuery("#"+formId);
	
	// Get required variables
	var divId	= form.find("input[name=divId]").val();
	var type	= form.find("input[name=type]").val();
	var typeId	= form.find("input[name=typeId]").val();
	var hash	= form.find("input[name=hash]").val();
	
	// Loading..
	var div = jQuery("#"+divId);
	
	// On the first page, clear the div
	if (page == 1)
		div.html("");
	
	div.find(".load-more").remove();
	div.append(LOADING_IMG_HTML);
	
	// Construct URL to retrieve comments from
	var url = "/comments/get/type/"+type+"/typeId/"+typeId+"/hash/"+hash+"/page/"+page;
	
	// Retrieve comments from the server
	jQuery.get(url, function(content)
	{
		div.find("img.loading").remove();
		content = jQuery.trim(content);
		
		if (content.length == 0)
		{
			// No more content
			div.append("No more comments available.");
		}
		else
		{
			// Add the content
			div.append(content);
		
			// Add load more button
			var html = "<a class=\"load-more\" href=\"javascript:loadComments('"+formId+"', "+(page+1)+")\">Load more comments &raquo;</a>";
			div.append(html);
		}
	});
}

// On-load, add a submit handler on comment forms
jQuery(document).ready(function()
{
	var forms = jQuery(".comments-form");
	forms.each(function(i, v)
	{
		loadComments(jQuery(v).attr("id"));
	});

	forms.submit(function(event)
	{
		// Don't submit the form the normal way
		event.preventDefault();
		
		if (!validateCommentsForm(this))
			return;
		
		// Get the form and post it
		var form  = jQuery(this);
		var data  = form.serialize();
			data += "&async=true";
		
		// Post it!
		jQuery.post(
			form.attr("action"),
			data,
			function(content)
			{
				content = jQuery.trim(content);
				
				if (content == "9")
				{
					alert("You didn't type the correct letters from the image.");
					return;
				}
				
				// Clear input fields
				var authorInput = form.find("input[type=text]").val("");
				form.find("textarea").val("");
				
				// Update the comments
				loadComments(form.attr("id"), 1);
			}
		);
	});
});

// Encrypt a value with the sha1 hash algorithm
function SHA1(msg)
{
	function rotate_left(n,s) {
		var t4 = ( n<<s ) | (n>>>(32-s));
		return t4;
	};
 
	function lsb_hex(val) {
		var str="";
		var i;
		var vh;
		var vl;
 
		for( i=0; i<=6; i+=2 ) {
			vh = (val>>>(i*4+4))&0x0f;
			vl = (val>>>(i*4))&0x0f;
			str += vh.toString(16) + vl.toString(16);
		}
		return str;
	};
 
	function cvt_hex(val) {
		var str="";
		var i;
		var v;
 
		for( i=7; i>=0; i-- ) {
			v = (val>>>(i*4))&0x0f;
			str += v.toString(16);
		}
		return str;
	};
 
 
	function Utf8Encode(string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	};
 
	var blockstart;
	var i, j;
	var W = new Array(80);
	var H0 = 0x67452301;
	var H1 = 0xEFCDAB89;
	var H2 = 0x98BADCFE;
	var H3 = 0x10325476;
	var H4 = 0xC3D2E1F0;
	var A, B, C, D, E;
	var temp;
 
	msg = Utf8Encode(msg);
 
	var msg_len = msg.length;
 
	var word_array = new Array();
	for( i=0; i<msg_len-3; i+=4 ) {
		j = msg.charCodeAt(i)<<24 | msg.charCodeAt(i+1)<<16 |
		msg.charCodeAt(i+2)<<8 | msg.charCodeAt(i+3);
		word_array.push( j );
	}
 
	switch( msg_len % 4 ) {
		case 0:
			i = 0x080000000;
		break;
		case 1:
			i = msg.charCodeAt(msg_len-1)<<24 | 0x0800000;
		break;
 
		case 2:
			i = msg.charCodeAt(msg_len-2)<<24 | msg.charCodeAt(msg_len-1)<<16 | 0x08000;
		break;
 
		case 3:
			i = msg.charCodeAt(msg_len-3)<<24 | msg.charCodeAt(msg_len-2)<<16 | msg.charCodeAt(msg_len-1)<<8	| 0x80;
		break;
	}
 
	word_array.push( i );
 
	while( (word_array.length % 16) != 14 ) word_array.push( 0 );
 
	word_array.push( msg_len>>>29 );
	word_array.push( (msg_len<<3)&0x0ffffffff );
 
	for ( blockstart=0; blockstart<word_array.length; blockstart+=16 ) {
 
		for( i=0; i<16; i++ ) W[i] = word_array[blockstart+i];
		for( i=16; i<=79; i++ ) W[i] = rotate_left(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
 
		A = H0;
		B = H1;
		C = H2;
		D = H3;
		E = H4;
 
		for( i= 0; i<=19; i++ ) {
			temp = (rotate_left(A,5) + ((B&C) | (~B&D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		for( i=20; i<=39; i++ ) {
			temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		for( i=40; i<=59; i++ ) {
			temp = (rotate_left(A,5) + ((B&C) | (B&D) | (C&D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
 
		for( i=60; i<=79; i++ ) {
			temp = (rotate_left(A,5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
			E = D;
			D = C;
			C = rotate_left(B,30);
			B = A;
			A = temp;
		}
		
		H0 = (H0 + A) & 0x0ffffffff;
		H1 = (H1 + B) & 0x0ffffffff;
		H2 = (H2 + C) & 0x0ffffffff;
		H3 = (H3 + D) & 0x0ffffffff;
		H4 = (H4 + E) & 0x0ffffffff;
	}
	
	var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
	return temp.toLowerCase();
}
