$(document).ready(function() {
   	init();
});

function limitChars(textid, limit) {
	var text = $('#'+textid).val(); 
	var textlength = text.length;
	if(textlength > limit) {
		$('#'+textid).val(text.substr(0,limit));
		return false;
	} else {
		return true;
	}
}

function validateHead(head) {
	if (head == "(Max 50 tecken)" || head == "") {
		return false;
	} else {
		return true;
	}
}

function validateMessage(message) {
	var messageLength = message.length;
	
	if (message == "" || messageLength > 1900) {
		return false;
	} else {
		return true;	
	}
}

function validateUrl(url) {
	if (url == "L\344nk" || url == "" || $("#url-preview").html() == "Bilden kunde inte läsas in. Kontrollera länken.") {
		return false;
	} else {
		return true;
	}
}

function validateEmail(email) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(email);
}

function validateName(name) {	
	var pattern = new RegExp(/.[a-zA-ZÅÄÖåäöÀÂÄÈÉËÎÏÔŒÙÛÜàâäèéêëîïôœùûüÿÇç]+$/);
	return pattern.test(name);
}

function init() {	

	$("a.back").click(function() {
		history.go(-1);
	
		return false;
	});
	
	/* Index -- voices
	___________________________________________________*/
	
	$(".tpl-voices .main a.avatar img, .tpl-voices .main span.avatar img, .voices .excerpt .voice a.avatar img.avatar-a, .tpl-voices .sidebar a.avatar img.avatar-a").each(function() {
		if ($(this).width() < 73) {
			$(this).attr({ 
    	    	width: 73
   			});
		}
	});
	
	$(".tpl-voices .avatars-section a img.avatar-a, .voices .avatars img.avatar-a").each(function() {
		if ($(this).width() > $(this).height()) {
			$(this).height("46px");
		} else {
			$(this).width("46px");
		}
	});
	

	/* Ajax upload
	___________________________________________________*/
	
	var uploadError;
	
	new Ajax_upload('#upload', {
	  action: 'http://www.antonabele.se/wp-content/themes/anton/script/php/upload.php',
	  name: 'userfile',
	  autoSubmit: true,
	  onSubmit: function(file, extension) {
	  	$('#upload-preview').show();
	    $("#upload-preview").html('<span class="msg">F&ouml;rs&ouml;ker l&auml;sa in bilden...</span>');
	  },
	  onComplete: function(file, response) {	  	
	  	if (response == "Otillåtet filformat." || response == "Bilden är för stor." || response == "Otillåen filändelse." || response == "Filen kunde inte sparas." || response == "") {
	  	    uploadError = "true";
	  	    $("#upload-preview").html(response);	 
	  	} else {
	  	    uploadError = "false";	  	    
	  	    $("#upload-preview").html('<div id="avatar"><img src="http://www.antonabele.se/wp-content/uploads/avatar/' + response + '" alt=""/></div>');	 	
	  		// $("#upload-preview").after('<input type=\'hidden\' name=\'temp_upload\' id=\'temp_upload\' value=\'' + response + '\' />');
	  		$("#temp_upload").val(response);
	  	}
	  }
	});
	
	
	/* Validate voice form
	___________________________________________________*/
	
	/* -- Head -- */
	
	$("#head").keyup(function() {
	   limitChars('head', 50);
	});
	
	$("#voice-form").submit(function() {
	
		var error = "";
		
		/* -- Head --*/
		
		var head = $("#head");		
		if (validateHead(head.val())) {
			$(head).css("border", "1px solid #ccc");
		} else {
			error += "messageError";
			$(head).css("border", "1px solid red");
			$(head).parent().find("label").css("color", "red");
		}
		
		/* -- Text --*/
		
		var message= $("#message");
		if (validateMessage(message.val())) {
			$(message).css("border", "1px solid #ccc");
		} else {
			error += "headError";
			$(message).css("border", "1px solid red");
			$(message).parent().find("label").css("color", "red");
		}
		
		/* -- Avatar -- */
		
		avatarType = $("input[name='avatar']:checked").val();
		
		if (avatarType == "type-upload") {
			if (uploadError == "false") {
				$(".image span").css("color", "#ff51ca");
				$(".image span label").css("color", "#ff51ca");
			} else {
				error += "uploadError";
				$(".image span").css("color", "red");
				$(".image span label").css("color", "red");
			}
		} else if (avatarType == "type-gravatar") {
		    var gravatar = $("#gravatar");
		    if(validateEmail(gravatar.val())) {
		    	$(gravatar).css("border", "1px solid #ccc");
		    	$(".image span").css("color", "#ff51ca");
				$(".image span label").css("color", "#ff51ca");
		    } else {
		    	error += "gravatarError";
		    	$(gravatar).css("border", "1px solid red");
		    	$(".image span").css("color", "red");
				$(".image span label").css("color", "red");
		    }
		} else if (avatarType == "type-url") {
			var urlAvatar = $("#url");
			if (validateUrl(urlAvatar.val())) {
				$(urlAvatar).css("border", "1px solid #ccc");
				$(".image span").css("color", "#ff51ca");
				$(".image span label").css("color", "#ff51ca");
			} else {
				error += "urlError";
				$(urlAvatar).css("border", "1px solid red");
				$(".image span").css("color", "red");
				$(".image span label").css("color", "red");
			}
		}
		
		/* -- Name --*/
		
		var from = $("#from");		
		if(from.val() != 0) {
			if(validateName(from.val())) {
				$(from).css("border", "1px solid #ccc");
			} else {
				error += "nameError";
				$(from).css("border", "1px solid red");
				$(from).parent().find("label").css("color", "red");
			}
		} else {
			error += "nameError";
			$(from).css("border", " 1px solid red");
			$(from).parent().find("label").css("color", "red");
		}
		
		/* -- Email --*/
		
		var email = $("#email");		
		if(email.val() != 0) {
			if(validateEmail(email.val())) {
				$(email).css("border", "1px solid #ccc");
			} else {
				error += "emailError";
				$(email).css("border", "1px solid red");
				$(email).parent().find("label").css("color", "red");
			}
		} else {
			error += "emailError";
			$(email).css("border", "1px solid red");
			$(email).parent().find("label").css("color", "red");
		}
		
		
		/* -- Submit if all is OK -- */
		
		if (error == "") {
			return true;
		} else {
			$("#required").css("color", "red");
			$("#required").css("font-weight", "bold");
			return false;
		}
	});
	

	/* Clear inputs
	___________________________________________________*/
	
	$("input[type=text]").focus(function() { 
		inputValue = $(this).val();
		if (inputValue == "(Max 50 tecken)" || inputValue == "E-postadress" || inputValue == "L\344nk") {
			$(this).val("");
		}
	});


	/* Swap avatar type
	------------------------------------- */

	$("#row-url").hide();
	$("#row-gravatar").hide();
	
	$("input[name='avatar']").click(function() {
	
		activeType = $("input[name='avatar']:checked").val();
	
		if (activeType == "type-upload") {
			$("#row-upload").show();
			$("#row-url").hide();
			$("#row-gravatar").hide();
		} else if (activeType == "type-url") {
			$("#row-upload").hide();
			$("#row-url").show();
			$("#row-gravatar").hide();
			$("#url-preview").html('<span class="msg"><strong>&Auml;r l&auml;nken fr&aring;n Facebook?</strong> <br />Kontrollera att den fungerar &auml;ven när du &auml;r utloggad.</span>');
		} else if (activeType == "type-gravatar") {
			$("#row-upload").hide();
			$("#row-url").hide();
			$("#row-gravatar").show();
		}
		
	});
	

	/* Avatar validation
	------------------------------------- */
	
	/* -- Url -- */
	
   	$('#url').keydown(function() {
   	    var t = this;
   	    clearTimeout(this.timer);
   	    this.timer = setTimeout(function () {
   	        if (t.value == t.current) {
   	            return true;
   	        }
   	
   	        var preview = $('#url-preview').html('<span class="msg">F&ouml;rs&ouml;ker l&auml;sa in bilden...</span>');
   	        var i = new Image();
   	
   	        clearTimeout(t.timeout);
   	
   	        if (t.value == '') {
   	            preview.html('');
   	        } else {
   	            i.src = t.value;
   	            i.height = 73;
   	            i.width = 73;
   	            i.className = 'avatar';
   	
   	            // set a timeout of x seconds to load the image, otherwise, show the fail message
   	            t.timeout = setTimeout(function () {
   	                preview.html('Bilden kunde inte l&auml;sas in. Kontrollera l&auml;nken.');
   	                i = null;
   	            }, 3000);
   	
   	            // if the dummy image holder loads, we'll show the image in the validation space,
   	            // but importantly, we clear the timer set above
   	            i.onload = function () {
   	                clearTimeout(t.timeout);
   	                preview.empty().append(i);
   	                i = null;
   	            };
   	        }
   	        
   	        t.current = t.value;
   	    }, 250);
   	}).change(function () {
   	    $(this).keyup(); // call the keyup function
   	});
   	
   
   	/* -- Gravatar -- */
   	
   	$("#gravatar").keyup(function() {
   		var email = $(this).val();
   		var emailLength = email.length;
   		if (emailLength >= 4) {
   			$("#gravatar-preview").load("http://www.antonabele.se/wp-content/themes/anton/script/php/functions.php", {todo: 'gravatar_preview', email: email});
   		}
   	});
	

	/* Handle video size in post
	_______________________________*/
	
	$("#video .video").each(function() {
		$("#video .video object").attr({ 
    	    width: 202,
    		height: 174
   		});
		$("#video .video embed").attr({ 
    	    width: 202,
    		height: 174
   		});
	});
	

	/* Add first/last class
	___________________________________________________*/
	
	$(".twitter ul li:first-child").addClass("first");
	
	
	/* Display issues
	___________________________________________________*/
	
	var t;
	
	var optContainter = $(".introduction");
	var optDefault = $("#opt-default");
	
	var navContainer = $("#issues");	
	var nav1 = $("#nav-item-1");
	var nav2 = $("#nav-item-2");
	var nav3 = $("#nav-item-3");
	
	var opt1 = $("#opt-1");
	var opt2 = $("#opt-2");
	var opt3 = $("#opt-3");
	
	nav1.click(function() {
		window.location = "http://www.antonabele.se/sakfragor?sakfraga=1";	
		return false;
	});
	nav2.click(function() {
		window.location = "http://www.antonabele.se/sakfragor?sakfraga=2";	
		return false;
	});
	nav3.click(function() {
		window.location = "http://www.antonabele.se/sakfragor?sakfraga=3";	
		return false;
	});
	
	nav1.mouseover(function() {
		optDefault.hide();
		$(this).find("a").addClass("active");
		$(nav2).find("a").removeClass("active");
		$(nav3).find("a").removeClass("active");
		opt1.show();
		opt2.hide();
		opt3.hide();		
		activateSifr();
	});
	
	nav2.mouseover(function() {
		optDefault.hide();
		$(nav1).find("a").removeClass("active");
		$(this).find("a").addClass("active");
		$(nav3).find("a").removeClass("active");
		opt1.hide();
		opt2.show();
		opt3.hide();
		activateSifr();
	});
	
	nav3.mouseover(function() {
		optDefault.hide();
		$(nav1).find("a").removeClass("active");
		$(nav2).find("a").removeClass("active");
		$(this).find("a").addClass("active");
		opt1.hide();
		opt2.hide();
		opt3.show();
		activateSifr();
	});
	
	optContainter.mouseover(function() {
		clearTimeout(t);
	});
	
	optContainter.bind("mouseleave",function() {
		$(nav1).find("a").removeClass("active");
		$(nav2).find("a").removeClass("active");
		$(nav3).find("a").removeClass("active");
		opt1.hide();
		opt2.hide();
		opt3.hide();
		optDefault.show();
	});
	
	navContainer.bind("mouseleave",function() {
		t = setTimeout(function() {
			$(nav1).find("a").removeClass("active");
			$(nav2).find("a").removeClass("active");
			$(nav3).find("a").removeClass("active");
			opt1.hide();
			opt2.hide();
			opt3.hide();
			optDefault.show();
		}, 50);
	});
	
	
	/* Issues
	___________________________________________________*/
	
	/*
	var issueNav_1 = $(".tpl-issues #nav-item-1");
	var issueNav_2 = $(".tpl-issues #nav-item-2");
	var issueNav_3 = $(".tpl-issues #nav-item-3");
	
	var issueTxt_1 = $(".tpl-issues #post-1");
	var issueTxt_2 = $(".tpl-issues #post-2");
	var issueTxt_3 = $(".tpl-issues #post-3");
	
	issueNav_1.click(function() {
		$(this).children().addClass("current");
		issueNav_2.children().removeClass("current");
		issueNav_3.children().removeClass("current");
		issueTxt_1.show();
		issueTxt_2.hide();
		issueTxt_3.hide();
		return false;
	});
	
	issueNav_2.click(function() {
		$(this).children().addClass("current");
		issueNav_1.children().removeClass("current");
		issueNav_3.children().removeClass("current");
		issueTxt_1.hide();
		issueTxt_2.show();
		issueTxt_3.hide();
		return false;
	});
	
	issueNav_3.click(function() {
		$(this).children().addClass("current");
		issueNav_1.children().removeClass("current");
		issueNav_2.children().removeClass("current");
		issueTxt_1.hide();
		issueTxt_2.hide();
		issueTxt_3.show();
		return false;
	});
	*/
	
	
	/* Affect
	___________________________________________________*/
	
	$("#col-2 .thumb").each(function() {
		$("#col-2 .thumb img").attr({ 
    	    width: 51,
    		height: 51
   		});
	});
	
	
	/* Follow
	------------------------------------- */
	
	$("#follow form").submit(function() {
		var followEmail = $("#follow-email");
		var followError = "";
		
		var emailLength = followEmail.val().length;
	
		if (emailLength < 150) {		
			if(validateEmail(followEmail.val())) {
			    $(followEmail).css("border", "1px solid #ccc");
			    $("#reg").html(" ");			
			} else {
			    followError += "emailError";
			    $(followEmail).css("border", "1px solid red");
			    $("#reg").html(" ");
			}
		} else {
			followError += "emailError";
			$(followEmail).css("border", "1px solid red");
			$("#reg").html(" ");
		}
		
		/* Submit if all is OK */
		
		if (followError == "") {
			$("#follow form fieldset").load("http://www.antonabele.se/wp-content/themes/anton/script/php/follow.php", {todo: 'save_email', email: followEmail.val()});
		}
		
		return false;
	});
	
	
}


/* Activate sIFR
___________________________________________________*/

function activateSifr() {
    var lefthand = { src: 'http://www.antonabele.se/wp-content/themes/anton/flash/lefthand.swf' };
    
    sIFR.activate(lefthand);		
    
    sIFR.replace(lefthand, {
      selector: '.introduction h2',
      wmode: 'transparent',
      css: '.sIFR-root { color: #007fbd; }'
    });
}