﻿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);
                $(".my-installations-selector ul.subscriptions li").mouseover(ME.base.MyInstSelectorOver);
                $(".my-installations-selector ul.subscriptions li").mouseout(ME.base.MyInstSelectorOut);
                $(".my-installations-selector ul.subscriptions li").click(ME.base.MyInstSelectorClick);
                $(".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);
                $("a.show-info-box").mouseover(ME.base.toggleInfoBox);
                $("a.show-info-box").mouseout(ME.base.toggleInfoBox);
            },
        refresh:
            function() {
                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");
                $("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" });
                    elm.addClass("visible");
                    elm.show();
                }
                else {
                    elm.hide();
                    elm.removeClass("visible");
                }

            },
        MyInstSelectorOver:
            function(evt) {
                $(this).addClass("hover");
            },
        MyInstSelectorOut:
            function(evt) {
                $(this).removeClass("hover");
            },
        MyInstSelectorClick:
            function(evt) {
                var InstallationUrl = $(this).find("a:first").attr("href");
                document.location.href = InstallationUrl;
            },
        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;
                /*if ((broadbandSearchString != "Skriv din adress") && (broadbandSearchString.length > 1)) {
                document.location.href = "/sv/privat/stadsnat/anslutna-adresser/?find=" + broadbandSearchString;
                } else {                    
                return false;
                }*/
            },
        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('ftp:') == -1 && this.href.toLowerCase().indexOf('file:') == -1 && (this.target == '' || this.target == '_self')) {

		    var excludedAnchorClasses = '|show-info-box|script-show print|print|export|show-in-popup|tips|adjust show-in-popup|find show-in-popup|';
			if ((excludedAnchorClasses.indexOf('|' + this.className + '|') == -1) && (this.href.indexOf('#') != 0)) {
				$(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';
}
