var savethis="";
$(document).ready(function(){
	if ($(".js_tooltip").tooltip) {
		$(".js_tooltip").tooltip({
			showURL: false,
			showBody: "\n"
		});
	}
	// show/hide category checkboxes
	$('.js_opencatinfo').bind("click",function() {
		if (this.checked) $(this).parents(".ctg").children(".ctgfold").slideDown();
		else $(this).parents(".ctg").children(".ctgfold").slideUp().children('p').children('.chk').each(function(){ this.checked=false; });
		return true;
	});
	$('.ctgfold').each(function(){
		if (!$(this).parents(".ctg").children("h4").children(".chk")[0].checked) $(this).hide();
	});
	$('.js_selallcats').click(function() {
		$(this).parents(".ctgfold").children("p").children(".chk").each(function(){ this.checked=true; });
		return false;
	});
	$('.js_az_names').hide();	 
	$('.js_az_letters').css("cursor","pointer").click(function() {
		var header=this;
		$(this).next('.js_az_names').slideToggle(function(){
			if ($(this).is(":visible")) {
				$(header).addClass('current');
			} else {
				$(header).removeClass('current');
			}	
		});
	})	 
	 
	$(".js_print").click(function(){
		window.print();
	});
	if (navigator.userAgent.indexOf("MSIE 6")!=-1) {
		jQuery("img").each(function() {
			var reg=/\.png$/;
			if (this.src.match(reg)) {
				var imgsrc=this.src;
				this.style.width=this.width+"px";
				this.style.height=this.height+"px";
				this.src = "/x.gif";
				this.runtimeStyle.backgroundImage = "none";
				this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgsrc + "', sizingMethod='scale')";
			}
		});
	}
	$("a[rel=external]").click(function(){
		var winprefs="";
		var s=this.search;
		if (s) {
			var m=s.match(/[\?&]w=([0-9]+)&?/);
			var w=(m[1])?m[1]:"auto";
			m=s.match(/[\?&]h=([0-9]+)&?/);
			var h=(m[1])?m[1]:"auto";
			winprefs=(w||h)?"toolbar=0,location=1,status=1,scrollbars=1,width="+w+",height="+h:"";
		}
		window.open(this.href,s,winprefs);
		return false;
	});
	$('.js_openstatus').bind("click",function() {
		if (jQuery("#js_status:hidden")[0]) jQuery("#js_status").fadeIn();
		else jQuery("#js_status").fadeOut();
		return false;
	});
	
	$(".js_form input.required").add(".js_form textarea.required").each(function() {
		$(this).bind("blur",function() { 
			testFormInput(this);
		})
	});
	$(".js_form select.required").each(function() {
		$(this).bind("blur",function() { 
			testFormInput(this);
		})
	});
	// profile page selectbox for links on logged in
	$("#linktype").bind("change",function(){
		if (this.options[this.options.selectedIndex].value=="other") {
			$("#js_linkdescr").show();
			$("#title").val("Website");
		} else {
			$("#js_linkdescr").hide();
			$("#title").val(this.options[this.options.selectedIndex].innerHTML);
		}
	});
	
	$(".js_form").bind("submit",function() {
		var valid=true;
		$(".js_form input.required").add(".js_form textarea.required").each(function() {
			if (!testFormInput(this)) valid=false;
		});
		$(".js_form select.required").each(function() {
			if (!testFormInput(this)) valid=false;
		});
		return valid;
	});
	function testFormInput(obj) {
		var valid=true;
		if ((obj.tagName.toUpperCase()=="INPUT" || obj.tagName.toUpperCase()=="TEXTAREA") && notValidValue(obj.name,obj.value)) {
			valid=false;
		} else if (obj.tagName.toUpperCase()=="SELECT" && obj.selectedIndex==0) {
			valid=false;
		}
		setFormElementStyle(obj,valid);
		return valid;
	}
	function notValidValue(nm,val) {
		return (
			(nm.indexOf("email")!=-1 && val.match(/.+@.+\..+/)==null) || 
			(nm.indexOf("phone")!=-1 && val.match(/[0-9]+/)==null) ||
			val==""
		);
	}
	function setFormElementStyle(obj,valid) {
		if (!valid) {
			$(obj).removeClass("valid"); 
			$(obj).addClass("error"); 
		} else {
			$(obj).removeClass("error"); 
			$(obj).addClass("valid"); 
		}
	}
	// login box, start page	
	$("#js_loginbox").hide("slow");
	$(".js_openloginbox").click(function() {
		$("#js_loginbox").toggle();
		return false;
	});
	// edit profile - boxes when editable
	$(".js_editprofile .js_edit").add("#js_editproject").hide();
	//$(".js_editprofile .js_saved").hide(); // används detta ännu?
	$(".js_editprofile .js_openedit").click(editProfileEntry);
	$(".js_editprofile .js_view").bind("dblclick",editProfileEntry);
	
	function editProfileEntry() {
		if ($(this).parents(".js_editprofile").children(".js_edit:visible")[0]) {
			$(this).parents(".js_editprofile").children(".js_view").removeClass("error").removeClass("saved").show();
			$(this).parents(".js_editprofile").children(".js_edit").hide();
		} else {
			$(this).parents(".js_editprofile").children(".js_view,.js_saved").removeClass("error").removeClass("saved").hide();
			$(this).parents(".js_editprofile").children(".js_edit").show();
		}
		return false;
	}
	
	$(".js_opencategories").click(function() {
		$("#js_categories .js_edit").toggle();
		return false;
	});
// 	$(".js_openaddproject").click(function() {
// 		$("#js_editproject").toggle();
// 		return false;
// 	});
	
	$("#js_profileform").bind("submit",function() {
		if (savethis=="logo") return true;
		else if (savethis=="password") {
			if (document.getElementById("old_password").value==document.getElementById("new_password").value || document.getElementById("new_password").value=="") return false;
			else return true;
		} else if (savethis=="email") {
			if (document.getElementById("loginemail").value==document.getElementById("email").value || document.getElementById("email").value=="") return false;
			else return true;
		} else return false;
	});
	function startUnobtrusive() {
		// when clicking a removelink on profilepage:
		$(".js_removelink").click(function(){
			var linkobj=this;
			var goto=linkobj.href.replace(linkobj.search,"");
			var d=linkobj.search.replace("&fallback=1","").replace(/^\?/,"");
			$.ajax({                                  
				type: "GET",
				url: goto,
				data : d,
				success: function(msg) {
					if (msg=="ok") {
						$(linkobj).parent("span").hide();
					} else {  
						alert("Problem deleting this link...sorry!");
					}
				}
			});
			return false;
		});
	}
	startUnobtrusive();
	// when saving profile page, small parts //ajax_saveprofile.php
	$("#js_profileform input[type=submit]").click(function() {
		savethis=this.name.replace("save_","");
		if (savethis=="logo" || savethis=="password" || savethis=="email") {
			return;
		} else {
			var senddata="";
			if (savethis=="categories") {
				var categorylist="";
				senddata="categories=1";
				$("input[type=checkbox]").each(function(){
					if (this.checked) {
						senddata+="&"+this.name+"="+this.value;
						categorylist+=" "+$("label[for=tag_"+this.value+"]").html()+",";
					}
				})
			} else if (savethis=="logo") {
				return;
			} else if (savethis=="password") {
				senddata="save_password=1&old_password="+encodeURIComponent(document.getElementById("old_password").value)+"&new_password="+encodeURIComponent(document.getElementById("new_password").value);
			} else if (savethis=="add_url") {
				var slinktype=document.getElementById("linktype").value;
				var sadd_url=document.getElementById("add_url").value;
				var stitle=document.getElementById("title").value;
				senddata="add_url="+encodeURIComponent(sadd_url)+"&title="+encodeURIComponent(stitle)+"&linktype="+encodeURIComponent(slinktype);
				var newlink=linktypetpl.replace("%url%",sadd_url).replace("%title%",stitle).replace("%linktype%",slinktype);
			} else {
				senddata=savethis+"="+encodeURIComponent(document.getElementById(savethis).value);
			}
			if (senddata) {
				senddata+="&id_no="+encodeURIComponent(document.getElementById("id_no").value);
				senddata+="&loginemail="+encodeURIComponent(document.getElementById("loginemail").value);
				$.ajax({                                  
					type: "GET",
					url: "ajax_saveprofile.php",
					data: senddata,
					contentType : "application/x-www-form-urlencoded; charset=utf-8",
					success: function(msg) {
						$("#js_"+savethis+" .js_view").show();
						$("#js_"+savethis+" .js_edit").hide();
						if (linkid=msg.match(/ok (\d+)/)) linkid=linkid[1]*1;
						if (msg=="ok" || (typeof(linkid)=="number" && linkid>0)) {
							if (savethis=="categories") {
								$("#js_categorylist").html(categorylist).addClass("saved");
							} else if (savethis=="password") {
								$("#js_password .js_msg").html("saved new password").removeClass("error").addClass("saved");
							} else if ((savethis=="add_url") && (typeof(linkid)=="number") && (linkid>0)) {
								newlink=newlink.replace("%linkid%",""+linkid)
								$("#js_add_url .js_showlinks").append(newlink);
								$("#add_url").val("http://");
								$("#title").val("");
								startUnobtrusive();
							} else {
								var s=document.getElementById(savethis).value;
								$("#js_"+savethis+" .js_view").html(s.replace(/\n/,"<br />"));
							}
							$("#js_"+savethis+" .js_view").addClass("saved");
							
						} else {  
							if (savethis=="password") $("#js_password .js_msg").html("ERROR! password not saved!").addClass("error");
							else $("#js_"+savethis+" .js_view").removeClass("saved").addClass("error");
							if (msg!="") alert(msg)
						}
					}
				});
				return true;
			} else {
				return false;
			}
		}
	});
	$(".js_deleteproject").click(function() {
		var m=this.href.match(/id=([0-9]+)/)
		var id=m[1];
		$.ajax({                                  
			type: "GET",
			url: this.href+"&ajax=true",
			success: function(msg) {
				if (msg=="ok") {
					$("#project_"+id).fadeOut("slow");
				} else {  
					if (msg!="") alert(msg)
				}
			}
		});
		return false;
	});
	// startpage random projects...
	$(".js_shuffleprojects").click(function() {
		var url=this.href;
		$("#js_randomprojects").fadeOut(function(){ 
			$("#js_randomprojects").load(url,function(){ 
				$(this).children("li").hide();
				$(this).show();
				var t=10;
				$(this).children("li").each(function() {
					$(this).fadeIn(t);
					t*=2; 
				});
			});
		});
		return false;
	});
	if ($('#oembed_service_id')[0]) {
		$(".js_videosite").hide();
		$("#js_videosite_"+$('#oembed_service_id')[0].options[$('#oembed_service_id')[0].selectedIndex].value).show();		
		$('#oembed_service_id').bind("change",function(){
			$(".js_videosite").hide();
			$("#js_videosite_"+this.options[this.selectedIndex].value).show();		
		});
	}
	startNewsSignupIfThere();
	
	$('textarea.statusupd[maxlength]').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}
		$(this).parent().find('.chars').html((max - $(this).val().length));
	});
/*	$('.statusticker').css({
			"position":"absolute",
			"display":"none"
		}).filter(":first").css("display","block");
	$('.statusticker').each(function(){
		$(this);	
	});*/
	if (jQuery('.statusticker').marquee) {
		jQuery('.statusticker').attr("direction","up").attr("scrollamount",1).marquee('pointer').hover(function(){
			$(this).trigger('stop');
		},function(){
			$(this).trigger('start');
		});
	}
	if (jQuery('.fa_event_box').length>1)
		jQuery('.fa_event_box').children("div").css("display","none");
	
	jQuery('.fa_event_box h3').bind("click",function(){
		jQuery(this).next("div").slideToggle();
	});


});
function startNewsSignupIfThere() {
        if (jQuery('.js_frm_newsletter')[0]) {
		jQuery(".js_newsletterpop").hide();
		jQuery('.js_opensignup').click(function() {
			if (jQuery(".js_newsletterpop:hidden")[0]) jQuery(".js_newsletterpop").fadeIn();
			else jQuery(".js_newsletterpop").fadeOut();
			return false;
		})
		//var defaulmsg=$("#contactPopup .js_form .js_message").html();		
		$(".js_frm_newsletter input.required").add(".js_frm_newsletter textarea.required").each(function() {
			$(this).bind("blur",function() { 
				if (notValidValue(this.name,this.value)) { // not correct
					$(this).removeClass("valid"); 
					$(this).addClass("error"); 
				} else {
					//$(this).removeClass("error2"); 
					$(this).removeClass("error"); 
					$(this).addClass("valid"); 
				}
			})
		});
		function notValidValue(nm,val) {
			return (
				(nm.indexOf("email")!=-1 && val.match(/.+@.+\..+/)==null) || 
				(nm.indexOf("phone")!=-1 && val.match(/[0-9]+/)==null) ||
				val==""
			);
		}
		$("form.js_frm_newsletter").bind("submit",function() { 
			var returnval=true;
			$("form.js_frm_newsletter input.required").add("form.js_frm_newsletter textarea.required").each(function() {
				if (notValidValue(this.name,this.value)) { // not correct
					$(this).addClass("error");
					returnval=false;
				}
			});
			if (returnval) {
				submitContactForm();
			}
			return false; // should be returnval if not ajaxed
		}
		);
					//$(".js_frm_newsletter input[name=prefix]").val()+"newslettersignup.php"
		var submitContactForm=function() {
			//pageTracker._trackEvent('Forms', 'Submit', 'Contact');  // google analytics
			$.ajax({
				type: "POST",
				url: $(".js_frm_newsletter").attr("action"),
				data: { 
					"ajax" : true,
					"email" : encodeURIComponent($(".js_frm_newsletter input[name=email]").val()),
					"sign" : encodeURIComponent($(".js_frm_newsletter input[name=sign]:checked").val())
				},
				dataType: "html",
				contentType: "application/x-www-form-urlencoded; charset=utf-8",
				cache : false,
				success: function(html){
					if (html=="error") {
						//$(".js_message").html("Ooops - something went wrong!");
						$("#js_newsletteremail").addClass("error")
					} else {
						$(".js_message").html(html);
						setTimeout('jQuery(".js_newsletterpop").fadeOut()',2000);
					}
					//pageTracker._trackEvent('Forms', 'SubmitReady', 'Contact');  // google analytics
					return false;
				},
				error: function(XMLHttpRequest, textErr, err) {
					$(".js_message").html("Oh noes! Sumthing went rong! "+textErr+" "+err);
					//pageTracker._trackEvent('Forms', 'SubmitError', 'Contact');  // google analytics
					return true;
				}
			});
			//$("#contactPopup").fadeOut("slow");
		}
	}
}
function deleteUploadThing(htmldelete,htmlname,filenm) {
	$("#js_uploadname_"+htmldelete).hide("slow");
	$("#"+htmlname).show("slow");
	$("form#js_projectform").append('<input type="hidden" name="'+htmldelete+'" value="'+filenm+'" />'); 
}

