jQuery(document).ready(function($) {

    /* TABMENU */

    // make index toolbar tabs
    $("#toolbar").tabs();

    // make body tabs
    $("#product #body").tabs();
    $(".tabbed-page #body").tabs();
    $(".tab-wrap").tabs();


    /* LAYERS */

    $("#tab-help a").click(function(event) {
        $("#layer-help").toggle();
    });

    $("#layer-help .tabsClose").click(function(event) {
        $("#layer-help").hide();
    });

    /* FAQ (DL, DD, DT) */

    $('dl dd').hide();

    $('dl dt').bind("click", function() {
        $(this).next('dd').toggle();
    });

    /* PRODUCT FILTER */

    // filter productlist when entering text
    $("#tableFilter").keyup(function(event) {
        var filter = $(this).val();
        var rg = new RegExp(filter, 'i');
        $("#productList .list ul li, table.list tbody tr").each(function() {
            if ($.trim($(this).html()).search(rg) == -1) {
                $(this).css('display', 'none');
            } else {
                $(this).css('display', '');
            }
        });
    });

    /* PRODUCT TABLE */
    var $product_table = $("#productTable");

    // show product details
    $(".show a", $product_table).click(function() {
        $(".show", $product_table).hide();
        $(".hide", $product_table).show();
        $("tbody", $product_table).show();
        return false;
    });

    // hide product details
    $(".hide a", $product_table).click(function() {
        $(".show", $product_table).show();
        $(".hide", $product_table).hide();
        $("tbody", $product_table).hide();
        return false;
    });

    //trigger hover/click on description
    var $product_fields = $("thead th", $product_table),
	    $href;
    $product_fields.each(function() {
        $href = $("h2 a.lightboxLink", $(this)).attr("href");
        if ($href && $href.replace("#", "") != "") {
            $(this).bind("mouseenter mouseleave click", function(event) {
                if (event.type == "mouseenter") {
                    $(this).addClass("hover");
                } else if (event.type == "mouseleave") {
                    $(this).removeClass("hover");
                } else {
                    $("h2 a.lightboxLink", $(this)).trigger("click");
                }
            });
        }
    });


    $("#productTable a").each(function() {
        var baseObj = $(this);
        var title = $(this).attr("title");
        if (title == "tooltip") {
            //var text = $(this).text().trim().toLowerCase();
            //var text = $(this).text().trim().toLowerCase();
            var str = $(this).text();
            var text = $.trim(str).toLowerCase();
            baseObj.removeAttr('title');
            baseObj.removeAttr('href');
            baseObj.addClass(title);
            var ids = "#" + text;
            baseObj.attr('rel', ids);
            baseObj.attr('href', 'javascript:void(0);');
        }
    });

    //fancybox
    var $fancyboxLinks = $(".lightboxLink");
    $fancyboxLinks.fancybox({
        "padding": 5,
        "overlayOpacity": "0.9",
        "overlayColor": "#f00",
        "autoDimensions": true
    });

    //link to-enabler
    if (window.location.hash && window.location.hash != "#") {
        $fancyboxLinks.filter("[href=" + window.location.hash + "]").trigger("click");
    }

    /* SHARE */
    var $share = $("#share").css("display", "none"),
	    $share_form = $("form", $share),
	    $padding_y;

    $("div.tools li.share a").add(".icon-close", $share).bind('click', function() {
        if ($share.is(":hidden")) {
            $share.show();
            $("html, body").animate({ scrollTop: $share.offset().top }, 500);
        } else {
            $share.hide();
        }
    });

    $share.find("form").bind("submit", function(event) {
        event.preventDefault();
        $padding_y = parseInt($share.css("padding-top").replace("px", ""));

        $share.height($share.height())
              .children().not(".close").hide();

        $share.prepend("<h3 style='text-align: center;'>E-posten er sendt</h3>")
        .animate({
            height: $("> h3", $share).height() + $padding_y
        }, 500, function() {
            setTimeout(
                function() {
                    $share.fadeOut(100).children().delay(100).show(0)
                    .parent().height('auto').find("h3").remove();
                }, 4000
            );
        }
        );
    });

    /* TOOLTIP */
    var $tooltipAnchors = $(".tooltip"),
	    $tooltipContent;
    $tooltipAnchors.bind("click", function(event) {
        event.preventDefault();
    }).each(function() {
        $(this).tooltip({
            bodyHandler: function() {
                //Get the text of the link without special chars
                var text = $(this).text().replace(/[^a-zA-Z 0-9]+/g, '').toLowerCase().replace(/ /g, "");
                //get the body title
								var clonedTitle ="";
								try{
                clonedTitle = $("#" + text + ' dt').clone().html();
                clonedTitle = "<strong>" + clonedTitle + "</strong>"; //modify markup
                //Get just body content
                var clonedBody = $("#" + text + ' dd').clone().html();
                clonedTitle = clonedTitle + "<p>" + clonedBody + "</p>"; 
                }catch(e){}
                return clonedTitle;
            },
            showURL: false,
            fixPNG: true
        });
    });

		//Made it to a function
		appendTooltipLink();
    
    $("#tooltip").append("<div class='tooltip-bg tooltip-n'></div><div class='tooltip-bg tooltip-nw'></div><div class='tooltip-bg tooltip-ne'></div><div class='tooltip-bg tooltip-w'></div><div class='tooltip-bg tooltip-e'></div><div class='tooltip-bg tooltip-sw'></div><div class='tooltip-bg tooltip-se'></div><div class='tooltip-bg tooltip-s'></div>");

    /* CONTENT FORM */
    var $form = $("form").filter(".contentForm");
    $form.find("select:not(.ui-selectmenu-small)").selectmenu({
        style: 'dropdown',
        width: 278
    });
    $form.find("select.ui-selectmenu-small").selectmenu({
        style: 'dropdown',
        width: 90,
        transferClasses: true
    });

    //multi toggle
    $form.find("input.multi-toggle").bind("click", function() {
        var $val = $(this).attr("value");
        window.location.hash = $val;
        $(".toggle-" + $(this).attr("name")).filter(":visible").hide();
        $("#toggle-" + $val).show();
    }).each(function() {
        var $val = $(this).attr("value");
        if (window.location.hash) {
            if (window.location.hash == "#" + $val) {
                $(this).attr("checked", true);
                $("#toggle-" + $val).show();
            } else {
                $(this).removeAttr("checked");
                $("#toggle-" + $val).hide();
            }
        } else {
            if ($(this).is(":checked")) {
                $("#toggle-" + $val).show();
            } else {
                $("#toggle-" + $val).hide();
            }
        }
    });

    //single toggle
    var $toggle_on = $form.find("input.toggle-on"),
	    $toggle_off = $form.find("input.toggle-off");
    $toggle_on.bind("click", function() {
        var $name = $(this).attr("name");
        window.location.hash = $name;
        $("#toggle-" + name).show();
    }).each(function() {
        var $name = $(this).attr("name");
        if (window.location.hash) {
            alert(window.location.hash);
            if (window.location.hash == "#" + $name) {
                $(this).attr("checked", true);
                $("#toggle-" + $name).show();
            } else {
                $(this).removeAttr("checked");
                $("#toggle-" + $name).hide();
            }
        } else {
            if ($(this).is(":checked")) {
                $("#toggle-" + $name).show();
            } else {
                $("#toggle-" + $name).hide();
            }
        }
    });
    $toggle_off.bind("click", function() {
        $("#toggle-" + $(this).attr("name")).hide();
    });

    //toggle next
    $(".toggle-next").bind("click", function() {
        $(this).next().toggle();
    }).next().hide();

    //datepicker
/*
    $form.find("input.datepicker").datepicker();
    $form.find("a.datepicker").bind("click", function() {
        $($(this).attr("rel")).focus();
    });
*/
    $("input.datepicker").datepicker({
  			changeMonth: true,
			changeYear: true   
    });
    $("a.datepicker").bind("click", function() {
        $($(this).attr("rel")).focus();
    });


    /* TABLESORTER */
    $("table.tablesorter:not(.zebra)").tablesorter({
        cssAsc: "asc",
        cssDesc: "desc"
    });
    $("table.tablesorter.zebra").tablesorter({
        cssAsc: "asc",
        cssDesc: "desc",
        widgets: ['zebra']
    });

    /*the new table sorter for scandinavia dates*/
    $.tablesorter.addParser({
        id: 'dd.mm.yyyy',
        is: function(s) {
            return false;
        },
        format: function(s) {
            s = '' + s;
            var hit = s.match(/(\d{1,2})\.(\d{1,2})\.(\d{4})/);
            if (hit && hit.length == 4) {
                return hit[3] + hit[2] + hit[1];
            }
            else {
                return s;
            }
        },
        type: 'text'
    });

    //$('.contentForm input[type="submit"]').click(function() {enableSubmit(false);});
   $('.loading').click(function() { ajaxLoad(true); });

//Can be removed when IE supports CCS3 (proberbly in IE 9) (FF)
    $('.zebra tr:even tr:nth-child(2n+2), .zebra body tr:even body tr:nth-child(2n+2)').addClass('even');

//FF: Append to change height on textarea
        $('.freetext').bind({
            focus: function() {
                $(this).addClass('freetextBig');
            },
            blur: function() {
                $(this).removeClass('freetextBig');
            }
        });  

});


//Custimized by Frank Furnes - Tryg IT (11.feb 2011)
function enableSubmit(enable) { if (enable) { $('#myform input[type="submit"]').removeAttr('disabled'); } else { $('#myform input[type="submit"]').attr('disabled', 'disabled'); } }
function setParentClass(obj, setC) { $(obj).parents('div:eq(0)').addClass(setC); }
function setErrorMessageInParent(obj, message, display) {if (!display)$(obj).parents('div:eq(0)').find('p').remove();else{$(obj).parents('div:eq(0)').find('p').remove();$(obj).parents('div:eq(0)').append('<p class=\'invalid\' generated=\'true\'>' + message + '</p>')}}
function removeAttributeOnParent(obj, attr) { $(obj).parents('div:eq(0)').removeAttr(attr); }
function displayErrorMessage(objID, message, display) {
    if (display) {
        setErrorMessageInParent(objID, message, display);
        setParentClass(objID, 'error');
        enableSubmit(display);
        ajaxLoad(false);
    } else {
        removeAttributeOnParent(objID, 'class');
        setErrorMessageInParent(objID, '', display);
    }
}

// show a text message with class error around it
function showMessage(element,text) {
    $(element).closest(".body").parent("div").addClass("message");
    $(element).text(text);
}

// hide a message by removing the surrounding class and text
function hideMessage(element) {
    $(element).closest(".body").parent("div").removeClass("message");
    $(element).text("");
}

function ajaxLoad(visible) {
	if (visible){
		$('<div id="ajaxwrapp" />').addClass('lightbox_bg').appendTo('body').show();
		$('<div id="ajaxload" />').addClass('modal').appendTo('body').show();
	}else{
			$('#ajaxwrapp').hide();
			$('#ajaxwrapp').remove();
			$('#ajaxload').hide();
			$('#ajaxload').remove();
			
	}
}

function validateContactUsForm() {

        var type = $("input[name='type']:checked", '#contactUsForm').val();
        
         if ("private" == type) {
              var validated = true;
               if (!validateElement($('#isabout'))) {
                    validated = false;
               }
               if ($('#isabout').val() == "2") {
                    if (!validateElement($('#damageabout'))) {
                       validated = false;
                   }
               }

               if (!validateElement($('#firstname'))) {
                    validated = false;
               }
               if (!validateElement($('#lastname'))) {
                      validated = false;
               }
               if (!validateElement($('#email'))) {
                      validated = false;
               }
               if (!validateElement($('#phone'))) {
                      validated = false;
               }
               if (!validateElement($('#inquiry'))) {
                      validated = false;
               }
               return validated;
         } else if ("company" == type) {
                  var validated = true;
               if (!validateElement($('#companyname'))) {
                    validated = false;
               }
               if (!validateElement($('#gjelderCompany'))) {
                    validated = false;
               }


               if (!validateElement($('#orgnr'))) {
                      validated = false;
               }
               if (!validateElement($('#companyemail'))) {
                      validated = false;
               }
               if (!validateElement($('#tocontact'))) {
                      validated = false;
               }
               if (!validateElement($('#daytimephone'))) {
                      validated = false;
               }
               if (!validateElement($('#companyzip'))) {
                      validated = false;
               }
               if (!validateElement($('#employees'))) {
                      validated = false;
               }
               if (!validateElement($('#companyinquiry'))) {
                      validated = false;
               }

               return validated;

         }
         return true;
}

function validateElement(element) {
       var value = element.val();
      if ($.trim(value).length == 0) {
            displayErrorMessage(element, 'Må fylles inn', true);
           return false;
      } else {
           displayErrorMessage(element, '', false);
      }
      return true;
}


function showNext(obj) {
        $('#damageabouts').hide();
        $('#customer').hide(); 
        var selVal =$(obj).val();
        if (selVal == "2") {
            $('#damageabouts').show();
        } else if (selVal == "3") {
            $('#customer').show();     
        }
}
	

   $(document).ready(function() {
       var about = $('#isabout');
       showNext(about);
    });


function appendTooltipLink(){
        $(".tooltipLink").tooltip({
            bodyHandler: function() {
                return $($(this).attr("rel")).html();
            },
            showURL: false,
            fixPNG: true
        });    
}



//SiteCatalyst special tracking kode -  start

//Appended by Frank Furnes - 7 juli
//Tracking document, 3.3. Intern søg 
function trackSearch(){
var searchVal = $("#searchValue").val();
 if(searchVal.length>0){
    s.events ='event1';
    s.evar1= searchVal; 
    s.prop11=searchVal;
    void(s.t());
 }
}

//Appended by Frank Furnes - 8 juli
//Tracking document, 4.8 Custom links
function custlink(obj,strLinkName){
	if(obj!=null){
		var linkname = (strLinkName=="" ? obj.innerHTML : strLinkName);
		s.tl(obj,'o', linkname);
	}
}


//SiteCatalyst special tracking kode -  end
function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}

function trackPageName(strPageName){
	if(s!=null){
		s.pageName = strPageName;
		void(s.t());
	}
	
if (typeof(YWA) != 'undefined') {	
	var YWATracker = YWA.getTracker(yahooID);
		if(YWATracker!=null){
			if(strPageName!=""){
				YWATracker.setDocumentName(strPageName);
				YWATracker.submit();
			}
		}	
	}
}

function trackOmnitureUrl(url){
	if(s!=null){
		s.pro = url
		void(s.t());
	}
}


function myPageviewWrapper(document_name,document_group)
{
if (typeof(YWA) != 'undefined') {	
var YWATracker = YWA.getTracker(yahooID);
	if(YWATracker!=null){
		if(document_name!="")
			YWATracker.setDocumentName(document_name);
		if(document_group!="")
			YWATracker.setDocumentGroup(document_group);
			
		YWATracker.submit();
	}
}
}
function trackUrl(url){
	trackYahooUrl(url);
	trackOmnitureUrl(url);

}
function trackYahooUrl(url){
if (typeof(YWA) != 'undefined') {	
	var YWATracker = YWA.getTracker(yahooID);
		if(YWATracker!=null){
			if(url!=""){
				YWATracker.setUrl(url);
				YWATracker.submit();
			}
		}
}
}

