var timers = new Array();

$(document).ready(function initialize_page() {

    if($('#start').length > 0) {
        start_projector();
    }

	//transform flags from png to gif if browser is IE6
	if($.browser.msie && parseInt($.browser.version) == 6)
	{
		if($("a#language_chooser img").length > 0) {
			var flag_src = $("a#language_chooser img").attr("src");
			var new_flag_src = flag_src.replace(".png",".gif");
			$("a#language_chooser img").attr("src",new_flag_src);
		}
	}
	
	//switch icons when hovering the flags
	$("a#language_chooser img").hover(function() {
		$(this).attr("src",$(this).attr("src").replace("_grey",""));
	},function() {
		$(this).attr("src",$(this).attr("src").replace("flag_se.","flag_se_grey.").replace("flag_en.","flag_en_grey."));
	});
	
	//make div.action-button clickable
	$("body#start div.action-button").click(function(){
		window.location = $(this).find("a").attr("href");
	})
	
	//WHAT WE DO-page
    var process_timer = window.setInterval(function() {
        change_process();
    }, 1000);
	function change_process() {
		var current_highlighted = $(".process.highlight");
		if(!current_highlighted.html()) {
			$(".process").addClass("highlight"); clearTimeout(process_timer);}
		else {
			current_highlighted.next(".process").addClass("highlight");
		}
	}
	
	//tag-links on portfolio page
	$("body#projects div.tag-links span").click(function(){
		if($(this).hasClass("active")) {
			$(this).removeClass("active");
		}
		else {
			$(this).addClass("active");
		}
		if($(".tag-links span.active").length < 1) {
			$("#action-bar-content").removeClass("active");
			$(".project").fadeIn();
		} else {
			$(".project").fadeOut();
			$(".tag-links span.active").each(function(){
				$(".project."+$(this).attr("class").replace("active","")).fadeIn();
			})
			$("#action-bar-content").addClass("active");
		}
	})
	
	
	$("a#language_chooser img").click(function(e){
		e.preventDefault();
		//remember the flag and page url clicked
		var clicked_lang = $(this).attr("id").replace("flag_","");
		var url = window.location;
		//start page falling or fading
		$("#wrap").animate({
		    marginTop: '2000px'
		  }, 500, function() {
			//when page is down, load set-language page in a div to set new lang. then load the new page (with new lang) in #wrap
			$("#masthead").load("/set-language/"+clicked_lang, function() {
				if($("body").attr("id") == "notfound") window.location = url;
				else {
					$("#wrap").load(url+" #wrap", function(){
						//reinitialize all event handlers!
						initialize_page();
						//when everything is ready, let's drag the new page up
						$("#wrap").animate({
							marginTop: '0px'
						}, 500);
					});
				}
			});
		  });
	});
	
	$(".project img, span.start_projector_link").not(".noshow img").diaprojector({
		class_name: "project",
		text_prev : $("#lang_prev").html(),
		text_next : $("#lang_next").html(),
		text_turn_off : $("#lang_turnoff").html(),
		image_folder : "/image/css",
		rotation : false,
		slideimages_folder : "/image/portfolio"
	});
	
	//make emails
	$(".email, .contact-email").each(function(){
		var name = $(this).html();
		var email = name+"@monkeyagency.com";
		var new_html = "<a href=\"mailto:"+email+"\">"+email+"</a>";
		$(this).html(new_html);
	});
	
	//CONTACT FORM behaviours
	$("body#contact input.text_field:first").focus();
	$("body#contact textarea, body#contact input").blur(function(){
		var all_filled = true;
		$("body#contact textarea, body#contact input").each(function(){
			if($(this).val() == "") all_filled = false;
		});
		if(all_filled) {$("#form_error").fadeOut();}
	});
	
	$("#send_contact_form").click(function(e){
		e.preventDefault();
		var errors = false;
		$("body#contact textarea, body#contact input").each(function(){
			if($(this).val() == "") {
				$("#form_error").show("highlight");
				errors = true;
			}
		});
		//success?
		if(!errors) {
			$.post("/send_email", $("#contact_form").serialize());
			$("#contact_form").hide("slide", { direction: "down"});
			$("#action-bar").animate({
				height: '80px'
			},500, function(){
				$("#thanks").show("slide", { direction: "down"});
			});
		}
	});
	
	$("input.text_field").autoGrowInput({
	    comfortZone: 20,
	    minWidth: 100,
	    maxWidth: 280
	});
	
	
	//styling av clip-pics
	$("body#blog .entry-content img:not(:.noframe,.wp-smiley), #office-description img").each(function(){
		var img_width = $(this).width();
		var img_height = $(this).height();
		var img_class = $(this).attr("class");
		$(this).wrap('<div style="width: '+(img_width+10)+'px; height: '+(img_height+10)+'px;" class="clip_pic '+img_class+'" />');
		$(this).before("<span></span>");
	});
	
	$.localScroll.defaults.axis = 'y';
	// Scroll initially if there's a hash (#something) in the url 
	$.localScroll.hash({
		duration:1500
	});
	$("body#blog .comments-link").localScroll({
		duration:1000,
		hash:true
	});
	//inserting img via javascript to avoid hacking outside the theme folder
	$("body#blog #comments").prepend("<img src='/wp-content/themes/socialmonkey/images/comments.png' alt='' /> ");
	
});

function start_projector() {
    
    $('#projector-screen').children().first().addClass('active');
    $('#projector-screen').children().next().hide();
    
    $('#introduction').children().first().addClass('active');
    $('#introduction').children().next().hide();
    
    $('#page-ingress-headers').children().first().addClass('active');
    

    var slide_changer = window.setInterval(function() {
        change_slide('introduction', 'page-ingress-headers', 'projector-screen');
    }, 8000);

    $("#page-ingress-headers h2").click(function(e){
		clearTimeout(slide_changer);
		$("#page-ingress-headers h2").removeClass("active");
		$(this).addClass("active");
		$("#projector-screen img").fadeOut(1000);
		$("#introduction p").fadeOut(1000);
		var p_id = $(this).attr("id").replace("button_","");
		$("p#"+p_id).addClass("active").fadeIn(1000);
		$("img#image_"+p_id).addClass("active").fadeIn(1000);
	});
}


function change_slide(text_parent_id, header_parent_id, screen_parent_id) {

    var current_text = $('#'+text_parent_id).children(".active");
    var current_header = $('#'+header_parent_id).children(".active");
    var current_screen = $('#'+screen_parent_id).children(".active");
    
    var text_offset = current_text.offset();
    current_text.fadeOut(1000).removeClass('active').next().fadeIn(1000).addClass('active');
    
    var screen_offset = current_screen.offset();
    current_screen.fadeOut(1000).removeClass('active').next().fadeIn(1000).addClass('active');
    
    current_header.removeClass('active').next().addClass('active');
    
    if(current_header.is(":last-child")) {
        $('#'+screen_parent_id).children().first().fadeIn(1000).addClass('active');
        $('#'+text_parent_id).children().first().fadeIn(1000).addClass('active');
        $('#'+header_parent_id).children().first().addClass('active');
    }

}







(function($){
    $.fn.autoGrowInput = function(o) {
        
        o = $.extend({
            maxWidth: 1000,
            minWidth: 0,
            comfortZone: 70
        }, o);
        
        this.filter('input:text').each(function(){
            
            var minWidth = o.minWidth || $(this).width(),
                val = '',
                input = $(this),
                testSubject = $('<tester/>').css({
                    position: 'absolute',
                    top: -9999,
                    left: -9999,
                    width: 'auto',
                    fontSize: input.css('fontSize'),
                    fontFamily: input.css('fontFamily'),
                    fontWeight: input.css('fontWeight'),
                    letterSpacing: input.css('letterSpacing'),
                    whiteSpace: 'nowrap'
                }),
                check = function() {
                    
                    if (val === (val = input.val())) {return;}
                    
                    // Enter new content into testSubject
                    var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                    testSubject.html(escaped);
                    
                    // Calculate new width + whether to change
                    var testerWidth = testSubject.width(),
                        newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                        currentWidth = input.width(),
                        isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                             || (newWidth > minWidth && newWidth < o.maxWidth);
                    
                    // Animate width
                    if (isValidWidthChange) {
                        input.width(newWidth);
                    }
                    
                };
                
            testSubject.insertAfter(input);
            
            $(this).bind('keyup keydown blur update', check);
            
        });
        
        return this;
    
    };
    
})(jQuery);
