﻿var ME = {};

ME.base = function () {
    var fadeTimer = 500;
    var ie6 = false;
    var ie = false;
    return {
        init:
			function () {
			    ie6 = document.all && /MSIE\s?6/.test(navigator.userAgent);
			    if (ie6) {
			        $("#main-nav a").mouseover(ME.base.hoverForIE6);
			        $("#main-nav a").mouseout(ME.base.hoverForIE6);
			    }
			    EnableProgressIndicator();
			    hideProgressIndicator();
			    CaptureAnchorClickEvent();
			    $("a.print").click(function () { window.print(); return false; });
			    $(".teaser.clickable").click(ME.base.extendLinkArea);
			    $("table.striped-table tbody tr:nth-child(odd)").addClass("odd");
			    $("table.striped-table tbody tr:nth-child(odd) td").addClass("striped");
			    $("table.striped-table tbody tr td").addClass("striped");
			    $("table.striped-table tbody tr th").addClass("striped");
			    $("table.striped-table").addClass("striped");
			    $("#InitBBSearch").click(ME.base.InitBroadbandSearch);
			    $("#BBSearch").focus(ME.base.FocusBroadbandSearch);
			    $("#BBSearch").keydown(ME.base.EnterInitBroadbandSearch);
			    $(".invoiceListContainer div table tbody tr").mouseover(ME.base.MyInvoiceOver);
			    $(".invoiceListContainer div table tbody tr").mouseout(ME.base.MyInvoiceOut);
			    $(".invoiceListContainer div table tbody tr").click(ME.base.MyInvoiceClick);
			    $(".dataListContainer div table.selectable tbody tr").mouseover(ME.base.MyInvoiceOver);
			    $(".dataListContainer div table.selectable tbody tr").mouseout(ME.base.MyInvoiceOut);
			    $(".dataListContainer div table.selectable tbody tr").click(ME.base.MyInvoiceClick);
			    $("a.show-info-box").mouseover(ME.base.toggleInfoBox);
			    $("a.show-info-box").mouseout(ME.base.toggleInfoBox);
			    $(".cts2010-tab-labels li").click(ME.base.ContractTeaserStartpageClick);
			    $(".cts2010-content-tab1 table tbody tr:first td").css("border-top", "none");
			    $(".cts2010-content-tab1 table tbody tr:last td").css("border-bottom", "none");
			    if ($('#photos').length != 0) //Check if element exists 
			        $('#photos').galleryView({ panel_width: 500, panel_height: 310, frame_width: 100, frame_height: 65, transition_interval: 0, nav_theme: 'me' });
			    if ($('a[rel*=facebox]').length != 0)
			        $('a[rel*=facebox]').facebox();
			    SetupPopups();
			},
        refresh:
			function () {
			    EnableProgressIndicator();
			    hideProgressIndicator();
			    CaptureAnchorClickEvent();
			    initCommonContent();
			    $("a.print").click(function () { window.print(); return false; });
			    $(".teaser.clickable").click(ME.base.extendLinkArea);
			    $("table.striped-table tbody tr:nth-child(odd)").addClass("odd");
			    $("table.striped-table tbody tr:nth-child(odd) td").addClass("striped");
			    $("table.striped-table tbody tr td").addClass("striped");
			    $("table.striped-table tbody tr th").addClass("striped");
			    $("table.striped-table").addClass("striped");
			    $("a.show-info-box").mouseover(ME.base.toggleInfoBox);
			    $("a.show-info-box").mouseout(ME.base.toggleInfoBox);
			},
        submitOnEnterPress:
			function (evt) {
			    if (evt.keyCode == 13) {
			        evt.preventDefault();
			        $(this).parents(".form-container").find("*[type=submit]").trigger("click");
			        return false;
			    }
			},
        openInNewWindow:
			function (evt) {
			    var event = (!evt) ? window.event : evt;
			    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;
			    }
			},
        customFadeIn:
			function (elm, speed) {
			    elm.fadeIn(speed, function () {
			        if (jQuery.browser.msie) {
			            $(this).get(0).style.removeAttribute('filter');
			        }
			    });
			},
        customFadeOut:
			function (elm, speed) {
			    elm.fadeOut(speed, function () {
			        if (jQuery.browser.msie) {
			            $(this).get(0).style.removeAttribute('filter');
			        }
			    });
			},
        extendLinkArea:
			function (evt) {
			    document.location.href = $(this).find("a:eq(0)").attr("href");
			},
        animateTeaser:
			function (evt) {
			    $(this).find(".teaser-inner").css({
			        borderWidth: "1px"
			    });
			    $(this).find(".teaser-inner").animate({
			        backgroundColor: "#edecec"
			    }, 600);
			},
        deAnimateTeaser:
			function (evt) {
			    $(this).find(".teaser-inner").css({
			        borderWidth: "1px"
			    });
			    $(this).find(".teaser-inner").animate({
			        backgroundColor: "#fff"
			    }, 600);
			},
        toggleInfoBox:
			function (evt) {
			    var elmId = "#" + this.className.replace(/.*info-box-id-([\w\_\-]+).*/, "$1");
			    var elm = $(elmId);

			    if (elm.is(":hidden")) {
			        var link = $(this);
			        var pos = link.offset();


			        var width = link.width() + parseInt(link.css("padding-right"), 10) + parseInt(link.css("padding-left"), 10) - 4;
			        var height = elm.height() + parseInt(elm.css("padding-bottom"), 10) + parseInt(elm.css("padding-top"), 10) - 17;
			        elm.css({ "left": (pos.left + width) + "px", "top": (pos.top - height) + "px" });

			        //ÖS 2011-05-17
			        var box = $(this).parents(".ibox-container, .box, .teaser-inner");
			        if (box.size() > 0) {
			            var posBox = box.offset();
			            elm.css({ "left": ((pos.left - posBox.left) + width) + "px", "top": ((pos.top - posBox.top) - height) + "px" });
			        }

			        elm.addClass("visible");
			        elm.show();
			    }
			    else {
			        elm.hide();
			        elm.removeClass("visible");
			    }

			},
        MyInvoiceOver:
			function (evt) {
			    $(this).addClass("hover");
			},
        MyInvoiceOut:
			function (evt) {
			    $(this).removeClass("hover");
			},
        MyInvoiceClick:
			function (evt) {
			    var InvoiceUrl = $(this).find("a.pdf").attr("href");
			    if (InvoiceUrl != null && InvoiceUrl != '') {
			        window.open(InvoiceUrl);
			        return false;
			    }
			    return true;
			},
        InitBroadbandSearch:
			function (evt) {
			    var broadbandSearchString = $("#BBSearch").val();
			    var querystringsupplement;
			    if (broadbandsearchlink.indexOf("?") >= 0)
			        querystringsupplement = "&";
			    else
			        querystringsupplement = "?";
			    document.location.href = broadbandsearchlink + querystringsupplement + "find=" + broadbandSearchString;
			},
        FocusBroadbandSearch:
			function (evt) {
			    $(this).filter(function () {
			        return $(this).val() == "" || $(this).val() == "Skriv din adress";
			    }).removeClass("watermarkOn").val("");
			},
        EnterInitBroadbandSearch:
			function (evt) {
			    if (evt.keyCode == 13) {
			        ME.base.InitBroadbandSearch();
			    }
			},
        hoverForIE6:
			function (evt) {
			    var elm = $(this);
			    if (elm.hasClass("hover")) {
			        elm.removeClass("hover");
			    }
			    else {
			        elm.addClass("hover");
			    }
			}
    };
} ();

$(document).ready(ME.base.init);

// Clear textbox if it's contents is the default value
function ClearTextBox(tb) {
	if (tb.defaultValue == tb.value) {
		tb.value = "";
	}
}

// provides enterfunctionality. e = event, target=the button/linkbutton (href) which you want to execute
// islink=is a link/linkbutton
function KeyDownEnterExecute(e, target, islink) {

	if (window.event) // IE
	{
		keynum = e.keyCode;
	}
	else if (e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}

	if (keynum == 13) {
		var element = document.getElementById(target);
		if (islink) {
		    if (!element.onclick || (element.onclick() != false))
		        location = element.href;
		}
		else {
			target.click();
		}
		return false;

	}

	else {
	    return true;
	};
}


// Repeater fix to enable use of radiobuttons inside a repeater
function SetUniqueRadioButton(nameregex, current) {
	re = new RegExp(nameregex);
	for (i = 0; i < document.forms[0].elements.length; i++) {
		elm = document.forms[0].elements[i]
		if (elm.type == 'radio') {
			if (re.test(elm.name) || re.test(elm.id)) {
				elm.checked = false;
			}
		}
	}
	current.checked = true;
}

// Function to capture the click event of all anchor elements
function CaptureAnchorClickEvent() {
	$('a').each(function () {

	    if (this.href != '' &&
    	    this.href.toLowerCase().indexOf('javascript:') == -1 &&
        	this.href.toLowerCase().indexOf('mailto:') == -1 && 
            this.href.toLowerCase().indexOf('http:') == -1 &&
	        this.href.toLowerCase().indexOf('https:') == -1 &&
	        this.href.toLowerCase().indexOf('ftp:') == -1 &&
    	    this.href.toLowerCase().indexOf('file:') == -1 &&
        	(this.target == '' || this.target == '_self')) 
	    {

	        var excludedAnchorClasses = '|show-info-box|script-show print|print|export|tips|';
	        
			if (
			    (excludedAnchorClasses.indexOf('|' + this.className.toLowerCase() + '|') == -1) &&
    			(this.href.indexOf('#') != 0) &&
        	    (this.href.length > 1 && this.href.substring(this.href.length - 2, this.href.length) != '/#') &&
            	(this.className.toLowerCase().indexOf('popup') == -1)			    
			    ) 
			{
				$(this).click(function () {
					progressIndicatorTimerHandle = window.setTimeout('showProgressIndicator();', ciProgressIndicatorDelayTime);
				});
			}
		}
	});
}

var ciProgressIndicatorDelayTime = 2000; // in milliseconds
var progressIndicatorEnabled = true; // By default the progress indicator is enabled
var progressIndicatorTimerHandle;

function onPanelUpdating() { //Use this if you want to have progressbar in updatePanel. Must be used in conjunction with onUpdated()
	onPanelUpdatingEx(ciProgressIndicatorDelayTime);
}

function onPanelUpdatingEx(time) { //Use this if you want to have progressbar in updatePanel. Must be used in conjunction with onUpdated()
	window.clearTimeout(progressIndicatorTimerHandle);
	progressIndicatorTimerHandle = window.setTimeout('showProgressIndicator()', time);
}

function onPanelUpdated() { //Use this if you want to have progressbar in updatePanel. Must be used in conjunction with onUpdating()
	window.clearTimeout(progressIndicatorTimerHandle);
	hideProgressIndicator();
	DisableProgressIndicator(true);
}

function DisableProgressIndicator(reenabled) {
	window.clearTimeout(progressIndicatorTimerHandle);
	progressIndicatorEnabled = false;
	if (reenabled) {
		window.setTimeout('EnableProgressIndicator();', ciProgressIndicatorDelayTime + 500);
	}
}

function EnableProgressIndicator() {
	//alert('progressIndicatorEnabled: ' + progressIndicatorEnabled);
	progressIndicatorEnabled = true;
}

function showProgressIndicator() {
	//alert('showProgressIndicator: ' + progressIndicatorEnabled);

	if (!progressIndicatorEnabled) {
		return;
	}

	// get the update progress div
	var progressBarContainer = $get('progressBarContainer');

	if (progressBarContainer == null) {
		return;
	}

	// make it visible
	progressBarContainer.style.display = '';

	// get the bounds of both the progress indicator container
	var progressBarContainerBounds = Sys.UI.DomElement.getBounds(progressBarContainer);

	// Get the size of the browser window
	var myWidth = 0, myHeight = 0;
	if (typeof (window.innerWidth) == 'number') {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}

	//  center of divPage
	var x = Math.round(myWidth / 2) - Math.round(progressBarContainerBounds.width / 2);
	if (x <= 200) {
		x = 200;
	}
	var y = Math.round(myHeight / 2) - Math.round(progressBarContainerBounds.height / 2);
	if (y <= 200) {
		y = 200;
	}
	//	set the progress element to this position
	Sys.UI.DomElement.setLocation(progressBarContainer, x, y);
}

function hideProgressIndicator() {
	// get the update progress div
	var progressBarContainer = $get('progressBarContainer');

	if (progressBarContainer == null) {
		return;
	}

	// make it invisible
	progressBarContainer.style.display = 'none';
}

// POPUPS //

function SetupPopups() {
    if ($('a.contentpopup').length != 0)
        $('a.contentpopup').colorbox();
    if ($('a.iframepopup').length != 0)
        $('a.iframepopup').colorbox({ width: "80%", height: "80%", iframe: true });
    if ($('a.largeiframepopup').length != 0)
        $('a.largeiframepopup').colorbox({ width: "864px", height: "600px", iframe: true });
    if ($('a.mediumiframepopup').length != 0)
        $('a.mediumiframepopup').colorbox({ width: "700px", height: "450px", iframe: true });
    if ($('a.smalliframepopup').length != 0)
        $('a.smalliframepopup').colorbox({ width: "400px", height: "220px", iframe: true });

    $(".popupClosePageRefresh").colorbox({
        onClosed:
                function () {
                    location.href = location.href;
                } 
    }
    );
}

function ClosePopupAndRedirect(url) {
	showProgressIndicator();
	location.href = url;
    ClosePopup();
}

function ClosePopup() {
    $.fn.colorbox.close();
}

function ClosePopupAndRefresh() {
    ClosePopupAndRedirect(location.href);
}

