$(document).ready(function() {
    //function pageLoad(sender, args) {
    // IE?
    var IE = /*@cc_on!@*/false;
    if (navigator.userAgent.indexOf('Opera') > -1) { // Opera needs the same fancybox-script as IE.
        IE = true;
    }


    // Call inputDefaults
    inputDefaults();

    /* Style for checkboxes */
    $('input[type=checkbox]').prettyCheckboxes();

    // Print page
    $(".printit").click(function() {
        window.print();
        return false;
    });

    $("table.tablesorter").tablesorter();


    /*
    // Login
    $("#login .button a").click(function() {
    var url = "/Templates/Environdec/Pages/Login.aspx/ValidateUser";
    alert(url);
    //send form
    $.ajax({
    type: "POST",
    url: url,
    data: $("#login-window :input").serialize(),
    success: function(msg) {
    alert("msg från servern: " + msg);
    $("#login-window .login-content").html(msg);
    }
    });
    });
    */
    $("#login-window input.text").keydown(function(e) {
        if (e.keyCode == 13) {
            document.location = $("#login-window div.button a").attr("href");
            return false;
        }
    });

    // Submit user registration
    /*$("a.submit-user-registration").click(function() {
    var form = $("body").children("form");
    alert("Here");
    if (validate($("#user-register-form"))) {
    alert("validerade true");
    form.submit();
    } else {
    alert("validerade false" + form);
    form.submit();
    }
    });*/

    // Mouseover popup for EPD list
    $("#latest-list.compact li a")
	.mouseover(function(e) {
	    var posY = $(this).position().top - 70;
	    var posX = $(this).position().left - 70;

	    $(this).next(".hover-popup").css({
	        top: posY + 20,
	        left: posX + 20
	    });
	    $(this).next(".hover-popup").show();
	})
	.mouseout(function() { $(this).next(".hover-popup").hide(); })


    // Mouseover popup for included products list
    $("#included-products-list li a")
	.mouseover(function(e) {
	    var posY = $(this).position().top - 60;
	    var posX = $(this).position().left - 80;

	    $(this).next(".hover-popup").css({
	        top: posY + 20,
	        left: posX + 20
	    });
	    $(this).next(".hover-popup").show();
	})
	.mouseout(function() { $(this).next(".hover-popup").hide(); })

    /*
    * All search-boxes requires three elements:
    *  div.search-box (container)
    *  input.search-query
    *  a.search-button
    */
    // Submit searches on mouse-clicks
    $("a.search-button").click(function() {
        submitSearch($(this).closest("div.search-box"));
        return false;
    });
    // Submit searches on ENTER-key
    $(".search-query").keydown(function(e) {
        if (e.keyCode == 13) {
            submitSearch($(this).closest("div.search-box"));
            return false;
        }
    });

    /* == EPD Advanced search ============================================ */
    // Submit searches on mouse-clicks
    $("a.epd-advanced-search-button").click(function() {
        submitEPDAdvSearch($(this).closest("div.advanced-search-holder"));
        return false;
    });
    // Submit searches on ENTER-key
    $(".search-query").keydown(function(e) {
        if (e.keyCode == 13) {
            submitEPDAdvSearch($(this).closest("div.advanced-search-holder"));
            return false;
        }
    });

    //
    // Submits a search query
    //
    function submitEPDAdvSearch(searchBox) {
        var query = searchBox.find("input.search-query").val();
        if (!validate(searchBox.find("input.search-query")) || query == "") {
            query = "";
        }
        var country = $("#search-epd-country").val();

        var category = $("#search-epd-cat").val(); //$("#search-epd-cat option:selected").text();

        var onlyEPD = $("#only-with-climate-declarations").attr("checked");

        var url = searchBox.find("a.epd-advanced-search-button").attr("href");
        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "query=" + encodeURIComponent(query);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "country=" + encodeURIComponent(country);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "category=" + encodeURIComponent(category);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "certEpd=" + encodeURIComponent(onlyEPD);

        document.location = url;
    }
    /* ===================================================================== */

    /* == PCR Advanced search ============================================ */
    // Submit searches on mouse-clicks
    $("a.pcr-advanced-search-button").click(function() {
        submitPCRAdvSearch($(this).closest("div.advanced-search-holder"));
        return false;
    });
    // Submit searches on ENTER-key
    $(".search-query").keydown(function(e) {
        if (e.keyCode == 13) {
            submitPCRAdvSearch($(this).closest("div.advanced-search-holder"));
            return false;
        }
    });

    //
    // Submits a search query
    //
    function submitPCRAdvSearch(searchBox) {

        var query = searchBox.find("input.search-query").val();
        if (!validate(searchBox.find("input.search-query")) || query == "") {
            query = "";
        }

        var cpc = searchBox.find("input.cpcHidden").val();
        
        if (cpc == "") {
            cpc = searchBox.find("input.search-cpc").val();
        }
        
        if (!validate(searchBox.find("input.search-cpc"))) {
            cpc = "";
        }
       

        var cpcLong = searchBox.find("input.search-cpc").val();
        if (!validate(searchBox.find("input.search-cpc"))) {
            cpcLong = "";
        }

        var category = $("#search-pcr-cat").val(); //$("#search-epd-cat option:selected").text();

        var onlyPcrMod = $("#only-pcr-modules").attr("checked");

        var onlyPcrDev = $("#only-pcr-under-development").attr("checked");

        var url = searchBox.find("a.pcr-advanced-search-button").attr("href");

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "query=" + encodeURIComponent(query);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "cpc=" + encodeURIComponent(cpc);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "cpcLong=" + encodeURIComponent(cpcLong);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "category=" + encodeURIComponent(category);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "onlyPcrMod=" + encodeURIComponent(onlyPcrMod);

        url += url.indexOf("?") > -1 ? "&" : "?";
        url += "onlyPcrDev=" + encodeURIComponent(onlyPcrDev);

        document.location = url;
    }
    /* ===================================================================== */

    /* === Advanced search CPC START =============================================*/
    // Temp to show ajax-results.
    var searchAjaxHover = false;
    var ajaxRequest;
    $(".ajax-field .text")
		.focus(function() {
		    if ($(this).val().length >= 1) {
		        this.select();
		        $(this).parent().children("div.search-ajax").show();
		    }

		})
		.blur(function() {
		    if (!searchAjaxHover) {
		        $(this).parent().children("div.search-ajax").hide();
		    }
		})
		.keyup(function() {
		    if ($(this).val().length >= 1) {
		        if (ajaxRequest != undefined) {
		            ajaxRequest.abort();
		        }

		        ajaxHolder = $(this).parent().children("div.search-ajax");
		        mode = $(this).parent().children("#ajax-search-mode").val();
		        langID = $(this).parent().children("#ajax-search-lang-id").val();

		        $(this).parent().children("#cpcHidden").attr("value", "");
		        //query = $(this).parent().children("#cpcHidden").val();
		        //if (query == "") {
		            query = $(this).val();
		        //}

		        var url = "/Templates/Environdec/Pages/SearchAutocomplete.aspx?query=" + query + "&mode=" + mode + "&l=" + langID;
		        ajaxRequest = jQuery.ajax({
		            type: "GET",
		            url: url,
		            cache: false,
		            success: function(data) {
		                ajaxHolder.html(data);
		                ajaxHolder.show();
		            }
		        });
		    }
		});
    $(".search-ajax").mouseover(function() {
        searchAjaxHover = true;
    });
    $(".search-ajax").mouseleave(function() {
        searchAjaxHover = false;
        if (!$(".ajax-field .text").is(":focus")) {
            $(this).hide();
        }
    });

    $(".backResult").live("click", function(e) {
        var code = $(this).parent().children("input").val();
        var text = $(this).text();
        $(".ajax-field .text").attr("value", text);
        $(".ajax-field .cpcHidden").attr("value", code);

        $(".search-ajax").hide();
    });

    /* === Advanced search CPC END ============================================*/

    // Clear graphical error on required fields when correcting it
    $("input.required, textarea.required")
	.keydown(function() {
	    if ($(this).val())
	        $(this).removeClass("has-error");
	});

    /*
    * Collapse/expand functions
    */
    $("a.collapsible").click(function() {
        var contentHolder = $(this).parent().parent().children(".collapsible-block-content");

        if ($(this).hasClass("expanded")) {
            $(this).removeClass("expanded");
            $(this).addClass("collapsed");
            contentHolder.slideToggle(500);
            $(this).parent().addClass("no-bottom-border");
            return false;
        } else {
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
            contentHolder.slideToggle(500);
            $(this).parent().removeClass("no-bottom-border");
            return false;
        }
    });

    $("a.toggle").click(function() {
        var classes = $(this).attr("class").split(" ");
        var id = "q";
        $.each(classes, function(i, value) {
            var t = value.split("_");
            if (t[0] == "exp") {
                $("ul#" + value).slideToggle();
                return;
            }
        });
    });

    /*
    * jcarousel
    */
    jQuery('#epd-carousel').jcarousel({
        wrap: 'circular',
        scroll: 1,
        initCallback: initEpdCarousel,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    // Add buttons for epd-slideshow, and IDs for li.	
    var tmpID = 1;
    $('ul#epd-slideshow-ul').children("li").each(function() {
        $(this).attr("id", "id-" + tmpID);

        var link = '<a href="#" id="epd-slideshow-control-' + tmpID + '"></a>';
        $("#epd-slideshow-controls").append($(link));
        tmpID++;
    });

    // Setup epd-slideshow carousel
    jQuery('#epd-slideshow-ul').jcarousel({
        wrap: 'circular',
        scroll: 1,
        initCallback: initEpdSlideshow,
        itemFirstInCallback: initEpdSlideshow_itemFirstInCallback,
        itemFirstOutCallback: initEpdSlideshow_itemFirstOutCallback,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });

    // Fancybox	
    // IE kräver att padding endast är angiven med en siffra. Firefox kräver att det är citattecken runt.
    if (IE) {
        $("a.fancybox").fancybox({
            'hideOnContentClick': false,
            'padding': 0,
            onComplete: function(e, a, b) { // sIFR doesn't render fonts for hidden divs. You must call the replacement function again when the login-window is shown.
                inputDefaults();
            }
        });
    } else {
        $("a.fancybox").fancybox({
            'hideOnContentClick': false,
            'padding': "0",
            onComplete: function() { // sIFR doesn't render fonts for hidden divs. You must call the replacement function again when the login-window is shown.
                inputDefaults();
            }
        });
    }
    // Load the login-fancybox if dictated so by the query-string
    if ($.getUrlVar('show_login')) {
        //setTimeout('$(".fancybox").trigger("click")', 0);
        $(".fancybox").trigger('click');
    }


    $("input.password-clear").each(function() {
        $(this).show();
        $(this).next("input.password").hide();
    });
    //$('input.password-clear').show();
    //$('input.password').hide();

    $('input.password-clear').focus(function() {
        $(this).hide();
        $(this).next("input.password").show();
        $(this).next("input.password").focus();
        $(this).next("input.password").blur(function() {
            if ($(this).val() == "" || $(this).val() == $(this).next(".defaultvalue").val()) {
                $(this).prev("input.password-clear").show();
                $(this).hide();
            }
        });
    });
});


// All input fields assigned with the class 'default' will
	// get their default values hidden when clicked, and reset again
	// if the user leaves the field empty or hasnt changed anything
	// The searchfields needs an accompanying hidden input with the
	// same id but suffixed "-default" that contains the default value.
	function inputDefaults(){
		$("input.default").each(function() {
			var defaultVal = $(this).next(".defaultvalue").val();
			if (!$(this).val())
				$(this).val(defaultVal);
			$(this).focus(function() {
				if ($(this).val() == defaultVal)
					$(this).val("");
			});
			$(this).blur(function() {
				if ($(this).val() == "")
					$(this).val(defaultVal);
			});
		});
		$("textarea.default").each(function() {
			var defaultVal = $(this).next(".defaultvalue").val();
			if (!$(this).val())
				$(this).text(defaultVal);
			$(this).focus(function() {
				if ($(this).text() == defaultVal)
					$(this).text("");
			});
			$(this).blur(function() {
				if ($(this).val() == "") {
					$(this).text(defaultVal);
				}
			});
		});
	}



/*
 * Jcarousel init
 */
function initEpdCarousel(carousel) {
	if($('#epd-carousel').children().length > 7) {
		jQuery('#epd-carousel-next').bind('click', function() {
			carousel.next();
			return false;
		});
		jQuery('#epd-carousel-prev').bind('click', function() {
			carousel.prev();
			return false;
		});	
	} else {
		$('#epd-carousel-next').hide();
		$('#epd-carousel-prev').hide();
	}
}

function initEpdSlideshow(carousel) {
	jQuery('#epd-slideshow-next').bind('click', function() {
        carousel.next();
        return false;
    });
	jQuery('#epd-slideshow-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
	
	jQuery('#epd-slideshow-controls a').bind('click', function() {
		id = $(this).attr('id');
		id = id.substr(22);
        carousel.scroll(jQuery.jcarousel.intval(id));
        return false;
    });

}

function initEpdSlideshow_itemFirstInCallback(carousel, item, idx, state) {
	id = item.id.substr(3);
	$("#epd-slideshow-control-"+id).addClass("selected");
};

function initEpdSlideshow_itemFirstOutCallback(carousel, item, idx, state) {
	id = item.id.substr(3);
	$("#epd-slideshow-control-"+id).removeClass("selected");
};





//
// Validates all input and textarea children of the passed object.
// Adds a yellow background on required input/textareas that are not correctly filled.
//
function validate(obj) {
	var validated = true;
	var parentObj = $(obj).parent();
	
	// Dont send anything if one of the fields are equal to the default vaule
	$(parentObj).find("input, textarea").each(function() {
		if($(this).val() == $(this).next(".defaultvalue").val()) {
			validated = false;
		}
	});
	
	$(parentObj).find(".required").each(function() {
		if($(this).val() == "" || $(this).val() == $(this).next(".defaultvalue").val()) {
			$(this).addClass("has-error");	
			//$('label[for="'+$(this).attr("id")+"']);
			$("label[for='"+$(this).attr('id')+"']").addClass("has-error");
			validated = false;
		} else {
			$(this).removeClass("has-error");
			$("label[for='"+$(this).attr('id')+"']").removeClass("has-error");
		}
	});
	
	if($(parentObj).find(".password1").val() != $(parentObj).find(".password2").val()){
		$("label[for='"+$(parentObj).find(".password1").attr("id")+"']").addClass("has-error");
		$("label[for='"+$(parentObj).find(".password2").attr("id")+"']").addClass("has-error");
		validated = false;
	} else {
		$("label[for='"+$(parentObj).find(".password1").attr("id")+"']").removeClass("has-error");
		$("label[for='"+$(parentObj).find(".password2").attr("id")+"']").removeClass("has-error");
    }

	if (!validated)
		return false;
	else 
		return true;
}

//
// Submits a search query
//
function submitSearch(searchBox) {
    var query = "*";
    if (validate(searchBox))
	    query = searchBox.find("input.search-query").val();
//	if (!query)
//		return;
	var url = searchBox.find("a.search-button").attr("href");
	url += url.indexOf("?") > -1 ? "&" : "?";
	url += "query=" + encodeURIComponent(query);
	document.location = url;
}

//
// Hooks up the image gallery on the startpage
//
$(function() {
	var index = 0;
	var numImages = $(".gallery li").length;
	if(numImages == 1)
		$("#portraits #nav").hide();
	$("#portraits #nav li")
	.click(function() { 
		index = $(this).html() - 1;	
		switchImage(index);
	});	
});

function switchImage(index) {
	// Find and activate image	
	$("#portraits #nav li.active").removeClass("active");
	$("#portraits #nav li:eq(" + index + ")").addClass("active");
	
	$(".gallery li.active").hide().removeClass("active");
	var imageToView = $(".gallery li:eq(" + index + ")");
	imageToView.fadeIn(500).addClass("active");
}

//
// Hook up tabs
//
$(function() {
	$(".tabs .tab")
	.click(function() {
		var id = $(this).attr("id");
		if($("#"+id+"-content").length) {
			$(".tabs .active").removeClass("active");
			$(".tabs .tab-area").hide();
			$("#"+id+"-content").show().addClass("active");
			$(this).addClass("active");
		}
		return false;
	});

});

//
// Hook up buttons for epd list switching
//
$(function() {
	
	// A fix for the comboboxes which werent working properly when hidden in IE6
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) {
		$("#advanced-area").show().addClass("active");
	}
	
	$("#search-results .button a.expandable")
	.click(function() {
		var button = $(this).parent();
		var expand = $("#"+button.attr("id")+"-area");
		button.siblings(".button").removeClass("active");
		button.toggleClass("active");
		$(".expand-area").removeClass("expanded");
		
		if (button.hasClass("active")) 
			expand.addClass("expanded").show();
		else 
			expand.removeClass("expanded").hide();

		return false;
	});

});


$.extend({
    getUrlVars: function() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name) {
        return $.getUrlVars()[name];
    }
});

$.extend(jQuery.expr[':'], {
    focus: function(element) { 
        return element == document.activeElement; 
    }
});

