// Menu on start page / project page
var menu_count=1;

// BLOG
var t; // timeout on blog and contact
var blog_maxh=87; // blog - max height on blog page 
var add_height=25;

// Contact page
var currentview="default";
var currentZ=1;
var fadestarted=false;

// general, history
var firstTimePage=false;

// yikes! do something about this...
document.write('<style type="text/css">#js_projectmenu { top:323px; }</style>')

$(document).ready(function(){
	$("a[@rel*=lightbox]").each(function() {
		var opt = { "overlayopacity" : "0.8" };
		jQuery(this).alrightBox(opt);
		pageTracker._trackPageview(this.href); // google analytics
		pageTracker._trackEvent('JSEvent', 'OpenLightbox', 'a[@rel*=lightbox] href='+this.href);  // google analytics
	});
	// Linux hack for sifr + caret problem
	if ($.browser.mozilla && (navigator.userAgent.indexOf("X11")!=-1 || navigator.userAgent.toLowerCase().indexOf("linux")!=-1)) {
		$("#shadow").css("display","none");
        }
		 	
	// history changes, record to make the back button work 
	$.historyInit(historyChange);
	// project / start page and about page
	if (m=window.location.href.match(/#(.+)$/)) { 
		if (m[1] && typeof pagesarray!="undefined" && pagesarray[m[1]]) {
			var p=m[1];
			fixMenu(p);
			//changePage(p,"#js_content .js_one"); // really simple history framwork handles this now
		} 
	} else {
		$("#projekten li:first").addClass("current");
		firstTimePage=true;
		//$.historyLoad(defp);
//		$("#js_projectmenu").css("top","323px");    // see document write above :-(
	}
	$("ul#projekten li").css("display","none");
	// every page under /pages/ (start/about)
	init_links();
	iePngHack("body");
	// start page menu
	setTimeout("startMenu()",20);
	
	// blog
	if (navigator.userAgent.indexOf("MSIE 6")==-1) { // IE6 gets the simple version
		$(".js_checkheight").each(function() {
			var h=this.offsetHeight + add_height;
			if (h>blog_maxh) {
				$(this).css("height",blog_maxh+"px");
				$(this).css("overflow","hidden");
				$(this).parents(".post").css("position","relative");
				var jq_btnobj=$(this).parents(".post").children(".js_placebtn");
				jq_btnobj.css( { position:"absolute", bottom:"-1px", right:"0px", marginRight:"12px" });
				jq_btnobj.append('<a href="#visatext" onclick="showHideText(this,\''+h+'\');return false;" style="text-align:right;width:100%;display:block;"><img src="../img/bg_blogreadmore_0.png" width="506" height="56" alt="" onmouseover="changePictNo(this,\'1\');" onmouseout="changePictNo(this,\'0\');" /></a>');
 				// alt: (Ie6 problem though)
//				jq_btnobj.children("a").children("img").bind("mouseover", function() { changePictNo(this,"1"); } );
//				jq_btnobj.children("a").children("img").bind("mouseout", function() { changePictNo(this,"0"); });
				jq_btnobj.children("a")[0].onfocus=function() { this.blur() }
			}
		});
	}
				
	// contact page, form
	var defaulmsg=$("#contactPopup .js_form .js_message").html();		
	$("#contactPopup .js_form input.required").add("#contactPopup .js_form 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"); 
			}
		})
	});
	$(".kontaktArea .js_showform").bind("click",function() {
		$("#contactPopup").fadeIn("slow");
		$("#contactPopup .js_form .js_message").html(defaulmsg);
		$("#contactPopup .js_form form").show();
		return false;
	});
	$("#contactPopup input[type=button]").bind("click",function() {
		$("#contactPopup").fadeOut("slow");
	});
	function notValidValue(nm,val) {
		return (
			(nm.indexOf("epost")!=-1 && val.match(/.+@.+\..+/)==null) || 
			(nm.indexOf("telefon")!=-1 && val.match(/[0-9]+/)==null) ||
			val==""
		);
	}
	$("#contactPopup .js_form form").bind("submit",function() { 
		var returnval=true;
		$("#contactPopup .js_form form input.required").add("#contactPopup .js_form form textarea.required").each(function() {
			if (notValidValue(this.name,this.value)) { // not correct
				$(this).addClass("error");
				pageTracker._trackEvent('Forms', 'MissingField', 'Contact');  // google analytics
				returnval=false;
			}
		});
		if (returnval) {
			submitContactForm();
			pageTracker._linkByPost(this);
		}
		return false; // should be returnval if not ajaxed
	}
	);
				
	var submitContactForm=function() {
		pageTracker._trackEvent('Forms', 'Submit', 'Contact');  // google analytics
		$.ajax({
			type: "POST",
			url: "form.php",
			data: { 
				"ajax" : true,
				"namn" : $(".js_form form input[name=namn]").val(),
				"epost" : $(".js_form form input[name=epost]").val(),
				"kvitto" : $(".js_form form input[name=kvitto]").val(),
				"telefon" : $(".js_form form input[name=telefon]").val(),
				"meddelande" : $(".js_form form textarea[name=meddelande]").val() 
			},
			dataType: "html",
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			cache : false,
			success: function(html){
				if (html=="error") {
					$("#contactPopup .js_form .js_message").html("Hoppsan - nåt fel på gång här?");
				} else {
					$("#contactPopup .js_form form").hide();
					$("#contactPopup .js_form .js_message").html(html);
				}
				pageTracker._trackEvent('Forms', 'SubmitReady', 'Contact');  // google analytics
				return false;
			},
			error: function(XMLHttpRequest, textErr, err) {
				$("#contactPopup .js_form .js_message").html("Oh noes! Sumthing went rong! "+textErr+" "+err);
				pageTracker._trackEvent('Forms', 'SubmitError', 'Contact');  // google analytics
				return true;
			}
		});
		//$("#contactPopup").fadeOut("slow");
	}
	
	// lavalamp-effect , start page and global
	$(function() { $("#menu ul").lavaLamp({ fx: "backout", speed: 400 })});
//	if (navigator.userAgent.toLowerCase().indexOf("konqueror")==-1) 
	if ($.browser.msie) 
		$(function() { $("ul#projekten").lavaLamp({ fx: "linear", speed: 100 })});
	else
		$(function() { $("ul#projekten").lavaLamp({ fx: "backout", speed: 400 })});

});
			
// contact page - faces fadein/out
var t;
function contact_fadeIn(nm) { // name
	clearTimeout(t);
	if (nm!=currentview && fadestarted==false) {
		fadestarted=true;
		$("#js_"+nm).css( { "display":"none", "z-index":currentZ } ).fadeIn("slow",function(){
			$("#js_"+currentview).hide();
			currentview=nm;
			currentZ++;
			fadestarted=false;
		});
	}
}
window.onload=function() {
	// contact page, images loaded
	$("#elin").bind("mouseover",function(){
		contact_fadeIn("elin");
	});
	$("#jonas").bind("mouseover",function(){
		contact_fadeIn("jonas");
	});
	$("#jonas").add("#elin").bind("mouseout", function(){
		t=setTimeout('contact_fadeIn("default")',2000);
	});
}
function historyChange(newLocation) {
	if (newLocation && typeof tpl!="undefined") {
		var page=tpl.replace("%p%",newLocation);
		if ($(".aboutArea")[0]) changePage(newLocation,"#js_content .js_one");
		else changePageSlide(page,'up');
		fixMenu(newLocation);
		//pageTracker._trackPageview("/pages/"+newLocation); // google analytics
	}
	firstTimePage=false;
}
function init_links() {
	// internal links with fading
	$("a.internal").bind("click", function() {
		var p=this.href.replace(/^.*p=/,'');
		changePage(p,"#js_content .js_one");
//		dhtmlHistory.add(p,'changePage("'+p+'","#js_content .js_one");');
		$.historyLoad(p);		
		//menuActive(this,".submenu");
		fixMenu(p);
		pageTracker._trackPageview(this.href); // google analytics
		pageTracker._trackEvent('JSEvent', 'Ajaxpage', 'Page fades in: '+p);  // google analytics
		return false;
	});
	// internal links with sliding
	$("a.trans_slide").bind("click", function() {
		var p=this.href.replace(/^.*p=/,'');
		$.historyLoad(p);		
		fixMenu(p);
		if (this.href.match(/^.*p=/)) {
/*			var loc=window.location.href;
			loc=loc.replace(/\?p=([^&]+)$/,"#"+p);
			loc=loc.replace(/#(.+)$/,"#"+p);
			if (!loc.match(/#/)) loc+="#"+p;
			location.href=loc;*/
			// get page location / url
			var page=tpl.replace("%p%",p);
			var notfound=tpl.replace("%p%",nf);
			changePageSlide(page,'up');
			pageTracker._trackEvent('JSEvent', 'Ajaxpage', 'Slides up: '+p);  // google analytics
//			dhtmlHistory.add(p,'changePageSlide("'+page+'","up");');
//			menuActive(this,".submenu");
		} else {
			changePageSlide(this.href,"left");
			pageTracker._trackEvent('JSEvent', 'Ajaxpage', 'Slides left: '+p);  // google analytics
//			dhtmlHistory.add(p,'changePageSlide("'+this.href+'","left");');
		}
		pageTracker._trackPageview(this.href); // google analytics
		return false;
	});
	// show bigger picture from array of smaller thumbnails
	$(".js_showbig").bind("click",function() {
		pageTracker._trackPageview(this.href); // google analytics
		var urlsrc=this.href;
		var thisimgobj=this.getElementsByTagName("img")[0];
		$(".js_showbig img").each(function() {
			$(this).removeClass("current");
			changePictNo(this,"0");
		});
		$(thisimgobj).addClass("current");
		changePictNo(thisimgobj,"1");
		
		if ($.browser.msie && parseInt($.browser.version)==6 && urlsrc.indexOf(".png")!=-1) { // IE6 gets a simple one
			$(".js_showbigtarget").html('<img src="'+urlsrc+'" class="png" />');
			pageTracker._trackEvent('JSEvent', 'ShowbigPic', 'Nothing fancy (IE): '+urlsrc);  // google analytics
		} else { // fancy one for other browsers
			$(".js_showbigtarget").each(function() {
				if (this.tagName.toLowerCase()=="img") {
					this.src=urlsrc;
				} else {
					$(this).append('<img src="'+urlsrc+'" style="opacity:0" class="png new" />')
					$(this).children("img").css( { 
						position: "absolute",
						right: "0",
						top: "0"
					});
					if ($.browser.msie && parseInt($.browser.version)>=7 && urlsrc.indexOf(".png")!=-1) {
						$(this).children("img:first").fadeOut(800,function() { 
							$(this).parents(".js_showbigtarget").children("img:last").each(function() {
								$(this).fadeIn(1000); // IE7 can swallow this, other version gets dark borders
							});
							$(this).remove();
						});
					} else {
						$(this).children("img:first").removeClass("new").addClass("old").fadeOut(800,function() {
							$(this).parents(".js_showbigtarget").children("img.new").each(function() {
								$(this).animate({ opacity:1 },1000); // somehow this works better than fadeIn...
							});
//							$(this).remove(); 
							$(this).parents(".js_showbigtarget").children("img.old").remove();
							while($(this).parents(".js_showbigtarget").children("img.new")[1]) {
								$(this).parents(".js_showbigtarget").children("img.new:last").remove();
							}
						})
					}
				}
				pageTracker._trackEvent('JSEvent', 'ShowbigPic', 'Fancy version: '+urlsrc);  // google analytics
			});
		} 
		this.blur();
		return false;
	});
								
	// close button, use on contact page							
	$(".js_x").bind("click",function() {
		$(this).parent().fadeOut();
		pageTracker._trackEvent('JSEvent', 'CloseLightbox', '.js_x');  // google analytics
	});
	
}

// start / project page, fancy intro for menu
function startMenu() {
	// menu slides up and menu links
	if (navigator.userAgent.toLowerCase().indexOf("konqueror")!=-1) {
		$("#js_projectmenu").animate({ top: "280px" },"fast");
		$("ul#projekten li").fadeIn().css({"position":"absolute","zIndex" : "900","bottom":"0"});
	
	} else {
		$("#js_projectmenu").animate({ top: "280px" },"fast",function() {
			$("ul#projekten li").each(function() {
				setTimeout('fadeInProjects('+(menu_count-1)+')',100*menu_count);
				menu_count++;		
			});			
		});
	}
}
function fadeInProjects(no) {
	$("ul#projekten li").eq(no).fadeIn("slow");
}
// ie png fix on load - this only changes those we haven't put an class=png on ...
function iePngHack(nod) {
	// IE png loading
	if ($.browser.msie && parseInt($.browser.version)==6) {
		$(nod+" *").each(function() {
			if (this.tagName.toLowerCase()=="img" && this.src.indexOf(".png")!=-1 && this.className.indexOf("png")==-1) {
//				alert(this.tagName+"#"+this.id+"."+this.className +" = png-img!")
				this.runtimeStyle.backgroundImage = "none";
				this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='image')";
				this.src = "/x.gif";
				this.className += " png";
			}
			var m=this.currentStyle.backgroundImage.match(/url\("?(.+\.png)"?\)/);
			if (m && m[1]) {
				var src=m[1];
//				alert(this.tagName+"#"+this.id+"."+this.className+ " = png-bakgrund! "+src)
				this.runtimeStyle.backgroundImage = "none";
				this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='image')";
			}
		});
	}
}

// changePict:				
// hover change picture 0->1->0
// set this before loading things...
function testIe6Filter(htmlobj,filtername) {
	return ((typeof htmlobj.filters == 'object') && (typeof htmlobj.filters[filtername] == 'object'));
}
function changePictNo(img,no) {
	if (img.className.indexOf("current")!=-1 && no=="0") {
	} else {
		if (navigator.userAgent.indexOf("MSIE 6")!=-1 && img.src.indexOf("x.gif")!=-1 && testIe6Filter(img,"DXImageTransform.Microsoft.AlphaImageLoader")) { //&& img.filters.item("DXImageTransform.Microsoft.AlphaImageLoader")) { // function rolloverShow(img) {
			var temp=img.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src;
			var src=temp.replace(/_[0-9]\./,"_"+no+".");
	   		img.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='image')";
		} else {
			img.src=img.src.replace(/_[0-9]\./,"_"+no+".");
		}
	}
}
function changePict(imgobj,imgsrc) {
	if (navigator.userAgent.indexOf("MSIE 6")!=-1 && testIe6Filter(imgobj,"DXImageTransform.Microsoft.AlphaImageLoader")) { 
   		imgobj.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgsrc + "', sizingMethod='image')";
	} else {
		imgobj.src=imgsrc;
	}

}

// blog show/hide text
function showHideText(btnobj,h) {
	var jqobj=$(btnobj).parents(".post").children(".postBody").children(".js_checkheight");
	var posttitle=(jqobj.parent(".postBody").children("h2").children(".sIFR-alternate").children("a")[0])?jqobj.parent(".postBody").children("h2").children(".sIFR-alternate").children("a")[0].innerHTML:"";
	if (jqobj[0].offsetHeight==h) {
		jqobj.animate(
			{ height: blog_maxh }, function() {
				var jq_btnobj=$(this).parents(".post").children(".js_placebtn").children("a");
				$(this).css("overflow","hidden");
				changePict(jq_btnobj.children("img")[0],"../img/bg_blogreadmore_0.png");
				pageTracker._trackEvent('Blog', 'ClosePost', 'Blog post: '+posttitle);  // google analytics
			}
		);
	} else {
		jqobj.animate(
			{ height: h }, function(btnobj) {
				var jq_btnobj=$(this).parents(".post").children(".js_placebtn").children("a");
				$(this).css("height",h+"px");
				changePict(jq_btnobj.children("img")[0],"../img/bg_blogreadless_0.png");
				pageTracker._trackEvent('Blog', 'OpenPost', 'Blog post: '+posttitle);  // google analytics
			}
		);
	}
}

// general functions
function addJS(jsfile) {
	var scr = document.createElement('script');
	scr.type = 'text/javascript';
	scr.src = jsfile;
	document.getElementsByTagName('head')[0].appendChild(scr); 
}

/*
JSTarget function by Roger Johansson, www.456bereastreet.com
*/
var JSTarget = {
	init: function(att,val,warning) {
		if (document.getElementById && document.createElement && document.appendChild) {
			var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att;
			var strVal = ((typeof val == 'undefined') || (val == null)) ? 'non-html' : val;
			var strWarning = ((typeof warning == 'undefined') || (warning == null)) ? ' (opens in a new window)' : warning;
			var oWarning;
			var arrLinks = document.getElementsByTagName('a');
			var oLink;
			var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
			for (var i = 0; i < arrLinks.length; i++) {
				oLink = arrLinks[i];
				if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
					oWarning = document.createElement("em");
					oWarning.appendChild(document.createTextNode(strWarning));
					oLink.appendChild(oWarning);
					oLink.onclick = JSTarget.openWin;
				}
			}
			oWarning = null;
		}
	},
	openWin: function(e) {
		var event = (!e) ? window.event : e;
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
		else {
		    var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) oWin.focus();
				return false;
			}
			oWin = null;
			return true;
		}
	},
	/*
	addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	*/
	addEvent: function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() {obj["e"+type+fn]( window.event );}
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};
JSTarget.addEvent(window, 'load', function(){JSTarget.init("rel","external","");});


/*

New pages thingie

see also init_links

*/

// nr 1 med fadein/out
var paging_active=false;
function changePage(p,dom_content) {
	if (!paging_active) {
	 	paging_active=true;
		loc=window.location.href;
		loc=loc.replace(/\?(.+)$/,"#"+p);
		loc=loc.replace(/#(.+)$/,"#"+p);
		if (!loc.match(/#/)) loc+="#"+p;
		location.href=loc;
		page=tpl.replace("%p%",p);
		notfound=tpl.replace("%p%",nf);
		 	
		$(dom_content).fadeOut(500, function(){ 
			$.ajax({
				type: "GET",
				url: page,
				data: { skipnav: true },
				dataType: "html",
				cache : false,
				contentType: "text/html; charset=utf-8",
				success: function(html){
					$(dom_content).empty();
					$(dom_content).append(html);
					$(dom_content).fadeIn(500, function(){ $(this).css("opcaity",".99"); });
				 	paging_active=false;
					init_links(true);
					iePngHack(dom_content);
				},
				error: function() {
					$(dom_content).load(notfound);
					$(dom_content).fadeIn(500);
				 	paging_active=false;
					init_links(true);
				}
			});
		});
	}
}


// version 2 of the change Page function
function changePageSlide(page,direction, filterby) {
	if (!paging_active) {
	 	paging_active=true;
		$.ajax({
			type: "GET",
			contentType: "text/html; charset=utf-8",
			url: page,
			data: { skipnav: true },
			dataType: "html",
			cache : false,
			success: function(html){
				// set some default values for animation
				//$("#content").css("overflow","hidden");
				var w=$("#content").css("width");
				var h=$("#content").css("height");

				var containw=parseInt(w); // container with and height
				var containh=parseInt(h);
				var newleft=0; // after animation done
				var newtop=0;
				var startleft=0; // starting point of anim
				var starttop=0;
				// set startpoint for new content
				// and new left of wrapper
				if (direction=="right") { 
					//var dir=parseInt(w); 
					startleft="-"+w; 
					newleft=parseInt(w)+"px"; 
					containw=parseInt(w)*2+500; // double width needed for slide
				}
				else if (direction=="up") { 
					//var dir=-parseInt(h); 
					newtop="-"+parseInt(h)+"px"; 
					containh=parseInt(h)*2+500; // double width needed for slide
				}
				else { // if (direction=="left") <-- default is to left
					//var dir=-parseInt(w); 
					startleft=w; 
					newleft="-"+parseInt(w)+"px";
					containw=parseInt(w)*2+500; // double width needed for slide
				}

				$("#js_content").css("position","absolute");
				$("#js_content").css("z-index","15");
//				$(".content, #content").css("overflow","hidden"); // for testing
				$("#js_content").css("width",containw+"px"); 
				$("#js_content").css("height",containh+"px"); 
				var jObj=$("#js_content").append('<div class="js_two">'+html+'<div>');

				$("#js_content .js_one, #js_content .js_two").css( { position:"absolute", width:w, height: h, top: 0, left:0 } );
				$("#js_content").css("left",startleft);
				$("#js_content").css("top",starttop);
				if (direction=="right" || direction=="right") {
					$("#js_content .js_two").css( { left:w } );
				} else if (direction=="up" || direction=="down") {
					$("#js_content .js_two").css( { top:h } );
				}

				var ua=navigator.userAgent;
				if (ua.match("(MSIE|Opera|Safari)")) { // sorry Firefox - too slow!
					$("#scene").animate(
						{ opacity:0.4 }, 500, function() {
							$("#scene").animate(
								{ opacity:1 }, 
								1000
							);
						}
					);
				}
				$("#js_content").animate(
					{ left: newleft, top: newtop }, 
					1000, 
					'easeinout', 
					function() {
						$("#js_content .js_one").remove();
						$("#js_content .js_two").addClass("js_one");
						$("#js_content .js_one").removeClass("js_two");
						$("#js_content, #js_content .js_one").css("left","0px");
						$("#js_content").css("width",w);
						$("#js_content").css("height",h);
						$("#js_content").css("z-index","24");
						paging_active=false;
						init_links(true); // still need to initioalize links here...
						iePngHack(filterby);
					}
				);

			},
			error: function() {
				var notfound=tpl.replace("%p%",nf);
				$("#js_content .js_one").load(notfound);
				paging_active=false;
				//$("#content").fadeIn(500);
			},
			complete: function() {
			}
		});
	}
}
					
function fixMenu(p) {
	$("#omsidor li").removeClass("here");
	$("#omsidor li."+p).addClass("here");
	$("#projekten li").removeClass("current");
	$("#projekten ."+p).addClass("current");
}


// sIFR 3
function startSifr() {
	var napoleon = {
	src: '../blog/napoleon.swf'
	};
	
	sIFR.activate(napoleon);

	sIFR.replace(napoleon, {
	selector: '.postBody h2'
	,wmode: 'opaque'
	,css: [
		'.sIFR-root { color: #f46e00; background-color: #ffffff; }'
		,'a { text-decoration: none; }'
		,'a:link { color: #3a3632; }'
		,'a:hover { color: #f25100; }'
		]
	});
}
