/*
________________________________________
¤¤¤ Common: Template byBrick™ ¤¤¤
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯
*/
/*
 * runOnLoad.js: portable registration for onload event handlers.
 * 
 * This module defines a single runOnLoad() function for portably registering
 * functions that can be safely invoked only when the document is fully loaded
 * and the DOM is available.
 *
 * Functions registered with runOnLoad() will not be passed any arguments when
 * invoked. They will not be invoked as a method of any meaningful object, and
 * the this keyword should not be used.  Functions registered with runOnLoad()
 * will be invoked in the order in which they were registered.  There is no
 * way to deregister a function once it has been passed to runOnLoad().
 *
 * In old browsers that do not support addEventListener() or attachEvent(),
 * this function relies on the DOM Level 0 window.onload property and will not
 * work correctly when used in documents that set the onload attribute
 * of their <body> or <frameset> tags.
 */
 


function runOnLoad(f) {
    if (runOnLoad.loaded) f();    // If already loaded, just invoke f() now.
    else runOnLoad.funcs.push(f); // Otherwise, store it for later
}

runOnLoad.funcs = []; // The array of functions to call when the document loads
runOnLoad.loaded = false; // The functions have not been run yet.

// Run all registered functions in the order in which they were registered.
// It is safe to call runOnLoad.run() more than once: invocations after the
// first do nothing. It is safe for an initialization function to call
// runOnLoad() to register another function.
runOnLoad.run = function() {
    if (runOnLoad.loaded) return;  // If we've already run, do nothing

    for(var i = 0; i < runOnLoad.funcs.length; i++) {
        try { runOnLoad.funcs[i](); }
        catch(e) { /* An exception in one function shouldn't stop the rest */ }
    }
    
    runOnLoad.loaded = true; // Remember that we've already run once.
    delete runOnLoad.funcs;  // But don't remember the functions themselves.
    delete runOnLoad.run;    // And forget about this function too!
};

// Register runOnLoad.run() as the onload event handler for the window
if (window.addEventListener)
    window.addEventListener("load", runOnLoad.run, false);
else if (window.attachEvent) window.attachEvent("onload", runOnLoad.run);
else window.onload = runOnLoad.run;




runOnLoad(function(){ //fix for FireFox; when <img-tags doesn't have width and height set the "$(document).ready(function(){" will run before the images are loaded
	
	fixHtml();
	
});	


function fixHtml() {

}


var ENABLE_PASSWORD_TITLE_IN_INPUT = true;

$(document).ready(function () {
    fixIE();
    fixFirstLast();
	if(!bIE67) {
		fixContent();
	}
    fixClips();
    fixBoxes();
    fixBrokenImages();

    //header functions
    $(".header-tools .lnk-login").click(function () {
        HideOverlay($("#header-services .box-language"));
        SyncOverlay($(this), $("#header-services .box-login"), $("#header-services"));
        return false;
    });
    $("#header-services .box-login .close-top, #header-services .box-login .close-bottom span").click(function () {
        HideOverlay($("#header-services .box-login"));
        return false;
    });
    $(".header-tools .lnk-language").click(function () {
        HideOverlay($("#header-services .box-login"));
        SyncOverlay($(this), $("#header-services .box-language"), $("#header-services"));
        return false;
    });
    $("#header-services .box-language .close-top, #header-services .box-language .close-bottom span").click(function () {
        HideOverlay($("#header-services .box-language"));
        return false;
    });
    /*$(".header-tools .lnk-login").mouseover(function () {
    SyncOverlay($(this), $("#header-services .box-login"), $("#header-services"));
    });
    $("#header-services .box-login").mouseleave(function () {
    HideOverlay($(this));
    });
    $(".header-tools .lnk-language").mouseover(function () {
    SyncOverlay($(this), $("#header-services .box-language"), $("#header-services"));
    });
    $("#header-services .box-language").mouseleave(function () {
    HideOverlay($(this));
    });*/

    //fancybox popup
    $("a.fancybox").fancybox({
        'titleShow': false,
        'transitionIn': 'fade',
        'transitionOut': 'fade',
        'speedIn': 600,
        'padding': 0
    });

    //init tooltip
    if ($(".tooltip").size() > 0) {
        $('.tooltip').tooltip({
            track: true,
            delay: 0,
            showURL: false,
            showBody: " - ",
            fade: 300
        });
    }


    //password title in input fix
    if (ENABLE_PASSWORD_TITLE_IN_INPUT) {
        InitPasswordFields();
        $(".pwd-tmp").focus(function () {
            ShowPasswordField($(this));
        });
        $(".pwd-org").blur(function () {
            HidePasswordField($(this));
        });
    }

    //go to handler
    $(".goto").click(function () {
        GoTo($(this));
    });


});
/* --- START: goto --- */
var objGotoInterval;
function GoTo($obj) {
    var strClass = $obj.attr("class").replace("  ", " ");
    var aClass = strClass.split(" ");
    for (var i = 0; i < aClass.length; i++) {
        if (aClass[i].toLowerCase().indexOf("goto-") > -1) {
            var id = aClass[i];
            if ($("#" + id).size() > 0) {
                //GoToAlert(id);
                $('html, body').animate({ scrollTop: $("#" + id).offset().top - 5 }, 600, function () {
                    switch (id.toLowerCase()) {
                        case "goto-cart":
                            $("#" + id).find(".item:last").effect("highlight", { color: "#f2ec54" }, 800); //yellow: f2ec54
                            break;
                        default:
                            $("#" + id).effect("highlight", { color: "#f29325" }, 1000); //orange: f29325;
                            break;
                    }

                });
            }
            break;
        }
    }
}
function GoToAlert(id) {
    if ($("#" + id).attr("class").toLowerCase().indexOf("goto-alert") > -1) {
        objGotoInterval = setInterval("GoToHighlight('" + id + "')", 400);
        setTimeout("ClearGoToHighlight('" + id + "')", 3000);
    }
}
var GoToHighlight = function (id) {
    $("#" + id).toggleClass("goto-highlight");
};
var ClearGoToHighlight = function (id) {
    clearInterval(objGotoInterval);
    $("#" + id).removeClass("goto-highlight");
};
/* --- END: goto --- */


/* --- START: password title in input fix --- */
function InitPasswordFields() {
    if ($(".pwd-org").size() > 0) {
        if ($(".pwd-org").val().length > 0) {
            $(".pwd-tmp").hide();
            $(".pwd-org").show();
        }
        else {
            $(".pwd-tmp").show();
            $(".pwd-org").hide();
        }
    }
}
function HidePasswordField($obj) {
    if ($obj.prev(".pwd-tmp").size() > 0 && $obj.val().length < 1) {
        $obj.hide();
        $obj.prev(".pwd-tmp").show();
    }
}
function ShowPasswordField($obj) {
    if ($obj.next(".pwd-org").size() > 0) {
        $obj.hide();
        $obj.next(".pwd-org").show().focus();
    }
}
/* --- END: password title in input fix --- */

var bIE = false;
var bIE6 = false;
var bIE7 = false;
var bLtIE8 = false;
var bIE67 = false;
var bWebkit = false;
var bMoz = false;
function fixIE() {
    if ($.browser.webkit) {
        $("body").addClass("webkit");
        bWebkit = true;
    }
    else if ($.browser.mozilla) {
        $("body").addClass("moz");
        bMoz = true;
    }
    else if ($.browser.msie) {
        bIE = true;
		if($.browser.version.indexOf("6.") == 0 && !window["XMLHttpRequest"]) {
		    bIE6 = bLtIE8 = bIE67 = true;
		    $("body").addClass("ie6 ie67");

			//Add message
			var dtNow = new Date();
			var iIE6YearsOld = dtNow.getFullYear() - 2001; //first release 2001-08-27
			var str = '';
			str += '<h2>Dags att uppgradera!</h2>';
			str += '<p>Om du läser det här så surfar du med Internet Explorer 6, en ' + iIE6YearsOld + ' år gammal webbläsare som inte klarar dagens standarder och gör din dator osäker.<br/>Vi rekommenderar <a href="http://www.getfirefox.com/">Firefox</a>, <a href="http://www.google.com/chrome">Google Chrome</a> eller den senaste versionen av <a href="http://www.microsoft.com/windows/downloads/ie/getitnow.mspx">Internet Explorer</a>.</p>';
			str += '<p>Bästa hälsningar <strong>// Soliditet</strong></p>';

			$("#hd").before('<div id="global-message"><div id="global-message-content">' + str + '</div></div>');
			
		}
		else if($.browser.version.indexOf("7.") == 0) {
		    bIE7 = bLtIE8 = bIE67 = true;
		    $("body").addClass("ie7 ie67");
		}
        /**
        else if ($.browser.version.indexOf("8.") == 0) {
		    bIE7 = bIE67 = true;
		    $("body").addClass("ie7 ie67 ie8");
		}
        else if ($.browser.version.indexOf("9.") == 0) {
		    bIE7 = bIE67 = true;
		    $("body").addClass("ie7 ie67 ie9");
		}
         **/
    }

}

/*function ltIE8() {
	var bLtIE8 = false;
	if($.browser.msie) {
		if($.browser.version.indexOf("6.") == 0 && !window["XMLHttpRequest"]) {
			bLtIE8 = true;
		}
		else if($.browser.version.indexOf("7.") == 0) {
			bLtIE8 = true;
		}
	}
	return bLtIE8;
}*/

function fixContent() {
    if ($("#main-content:visible").size() > 0) {
        var bContentFixed = ($("#main-content").attr("class").toLowerCase().indexOf("main-content-") > -1);
        var bLeftColumnExist = ($("#left-content:visible").size() > 0);
        var bRightColumnExist = ($("#right-content:visible").size() > 0);
        if(!bContentFixed) {
            //add class for main-content
            if (bLeftColumnExist && bRightColumnExist) {
                $("#main-content").addClass("main-content-lrs");
            }
            else if (bLeftColumnExist) {
                $("#main-content").addClass("main-content-ls");
            }
            else if (bRightColumnExist) {
                $("#main-content").addClass("main-content-rs");
            }
        }

        //fix height - if not startpage
        if ($("#page-start").size() < 1) {
            if (bIE7 && !bRightColumnExist) { 
            }
            else {
                if (bLeftColumnExist || bRightColumnExist) {
                    $("#main-content").height($("#page-content").height());
                }
            }
        }

        if (bIE67) {
            $(".main-sub-content").each(function () {
                if ($(this).next(".right-sub-content").size() > 0 && $(".main-sub-content").height() < $(this).next(".right-sub-content").height()) {
                    $(".main-sub-content").height($(this).next(".right-sub-content").height());
                }
            });
        }
    }
}

function fixClips() {
    if (bIE67) {
        $(".clip").each(function () {
            var iWidth = $(this).find(".clip-content-container").width();
            $(this).width(iWidth);
        });
    }
}

function fixBrokenImages() {
    $("img").error(function () { $(this).hide(); });
}

function fixFirstLast() {
    //first / last
    //$(".banner:first").addClass("first");
    $(".banner:visible").each(function () {
        if ($(this).prev(".banner").size() < 1) {
            $(this).addClass("first");
        }
    });

    $(".box-table .content").each(function () {
        $(this).find("a.title:first").addClass("first");
    });
    $(".puff-container").each(function () {
        $(this).find(".puff:last").addClass("last");
    });
    $(".news-list .content").each(function () {
        $(this).find(".item:first").addClass("first");
    });
}

function fixBoxes() {
    if (bIE67) {
        $(".box").each(function () {
            var iWidth = $(this).find(".box-content-container").width();
            $(this).width(iWidth);
        });

    }

    //puffar
    $(".puff-container.horizontal").each(function () {
        var iMaxHeaderHeight = 0;
        var iMaxContentHeight = 0;
        var iMinContentHeight = 0;
        var iMaxContentSyncHeight = 0;
        $(this).find(".puff").each(function () {
            var iHeaderHeight = $(this).find(".header").height();
            if (!bIE) {
                iHeaderHeight -= parseInt($(this).find(".header").css("padding-top"));
            }
            var iContentHeight = $(this).find(".content").height();
            var iContentSyncHeight = $(this).find(".content .content-sync").height();

            var iMaxImgHeight = 0;
            $(this).find(".content img.right, .content img.left").each(function () {
                iMaxImgHeight = ($(this).height() > iMaxImgHeight ? $(this).height() : iMaxImgHeight);
            });
            iMinContentHeight = (iMaxImgHeight > iMinContentHeight ? iMaxImgHeight : iMinContentHeight);

            iMaxHeaderHeight = (iHeaderHeight > iMaxHeaderHeight ? iHeaderHeight : iMaxHeaderHeight);
            iMaxContentHeight = (iContentHeight > iMaxContentHeight ? iContentHeight : iMaxContentHeight);
            iMaxContentSyncHeight = (iContentSyncHeight > iMaxContentSyncHeight ? iContentSyncHeight : iMaxContentSyncHeight);
        });
        if (iMaxHeaderHeight > 0) {
            $(this).find(".puff .header").height(iMaxHeaderHeight);
        }
        if (iMaxContentHeight > 0) {
            $(this).find(".puff .content").height(iMaxContentHeight);
        }
        if (iMinContentHeight > 0) {
            //get image vertical padding
            var iVerticalPaddingImgLeft = parseInt($(this).find(".puff .content img.left:first").css("padding-top")) + parseInt($(this).find(".puff .content img.left:first").css("padding-bottom"));
            var iVerticalPaddingImgRight = parseInt($(this).find(".puff .content img.right:first").css("padding-top")) + parseInt($(this).find(".puff .content img.right:first").css("padding-bottom"));

            iMinContentHeight += (iVerticalPaddingImgLeft > iVerticalPaddingImgRight ? iVerticalPaddingImgLeft : iVerticalPaddingImgRight);

            //alert(parseInt($obj.css("padding-top")) + parseInt($obj.css("padding-bottom")))
            $(this).find(".puff .content").css("min-height", iMinContentHeight + "px");
        }
        if (iMaxContentSyncHeight > 0) {
            $(this).find(".puff .content .content-sync").height(iMaxContentSyncHeight);
        }
    });

    //if image with class="right" in a box; min-height must be set (if the content is less than the image height)
    if($(".content img.right").size() > 0){
        $(".content").each(function () {
            var iMinHeight = 0;
            $(this).find("img.right").each(function () {
                iMinHeight += $(this).height() + parseInt($(this).css("padding-bottom")) + parseInt($(this).css("padding-top"));
            });
            if (iMinHeight > 0) {
                $(this).css("min-height", iMinHeight + "px");
            }
        });
    }

}

function fixBox($box) {
    if (bIE67) {
        var iWidth = $box.find(".box-content-container").width();
        if (iWidth > 0) {
            $box.width(iWidth);
        }
    }
}




function removeTooltip(obj) {
    obj.className = obj.className.replace(/input-tooltip/g, '');
}
function addTooltip(obj) {
    obj.className += ' input-tooltip';
}

/* --- START: Overlay --- */
function SyncOverlay($objSync, $objOverlay, $objReference) {
    $objOverlay.fadeIn("fast");

    if ($objOverlay.find(".sync-pos").size() > 0) {
        var iPosTop = $objSync.offset().top - $objReference.offset().top;
        var iSyncPosTop = $objOverlay.find(".sync-pos").offset().top - $objOverlay.offset().top;
        $objOverlay.css("top", iPosTop - iSyncPosTop + "px");

        var iPosLeft = $objSync.offset().left - $objReference.offset().left + parseInt($objSync.css("padding-left"));
        var iSyncPosLeft = $objOverlay.find(".sync-pos").offset().left - $objOverlay.offset().left
        $objOverlay.css("left", iPosLeft - iSyncPosLeft + "px");
        //alert("top: " + iPosTop + " - " + iSyncPosTop + " = " + (iPosTop - iSyncPosTop) + "\nleft: " + iPosLeft + " - " + iSyncPosLeft + " = " + (iPosLeft - iSyncPosLeft));
    }
    fixBox($objOverlay);
}
function HideOverlay($objOverlay) {
    $objOverlay.fadeOut("fast");
}
/* --- END: Overlay --- */




var newWin;
var previousURL;
var previousWinName
function OpenWindow(URL,Width,Height,scrollbars,winname,resizable){
	if(scrollbars == "yes" || scrollbars == "1"){
	  scrollbars = "yes"
  }
  else{
	  scrollbars = "no"
  }
  if(resizable == "yes" || resizable == "1"){
	  resizable = "yes"
  }
  else{
	  resizable = "no"
  }
  
  if (!newWin || newWin.closed || winname != previousWinName){
		var winParams = 'toolbar=0,scrollbars='+scrollbars+',status=no,resizable='+resizable;
		if(Width.length > 0 && !isNaN(Width) && Height.length > 0 && !isNaN(Height)){
			if(parseInt(Width) > 0 && parseInt(Height) > 0){
				winParams += ',width='+Width+',height='+Height;
			}
		}
		newWin = window.open(URL,winname,winParams);
			
		previousURL = URL;
		if (!newWin.opener){
			newWin.opener = window;
		}
	}
	else if(URL != previousURL){
		newWin.location.href = URL;
		newWin.focus();
		previousURL = URL;
	}
	else {
		newWin.focus();
	}
	
	previousWinName = winname
}

function listProperties(obj, strFind){
  var i = 0;
  var msg = "";
  for(itm in obj){
    if(i > 50){
      alert(msg);
      i = 0;
      msg = "";
    }	
		if(strFind.length > 0){
			if(itm.toLowerCase().indexOf(strFind.toLowerCase()) > -1){	//search for lower case part of item name
				msg += itm + "\n";	
				i++;
			}
		}
		else {
			msg += itm + "\n";	
			i++;
		}

  }
  alert(msg);
}

  $(window).load(function() {
   if (bIE7) {
		fixContent();
	}
  });


