﻿/// <reference path="jQuery/jquery-1.4.2.min.js" />

/* Datumformattering */
Date.prototype.format = function(format) {
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {
        var curChar = format.charAt(i);
        if (replace[curChar])
            returnStr += replace[curChar].call(this);
        else
            returnStr += curChar;
    }
    return returnStr;
};
Date.replaceChars = {
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],

    // Day
    d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
    D: function() { return Date.replace.shortDays[this.getDay()]; },
    j: function() { return this.getDate(); },
    l: function() { return Date.replace.longDays[this.getDay()]; },
    N: function() { return this.getDay() + 1; },
    S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
    w: function() { return this.getDay(); },
    z: function() { return "Not Yet Supported"; },
    // Week
    W: function() { return "Not Yet Supported"; },
    // Month
    F: function() { return Date.replace.longMonths[this.getMonth()]; },
    m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
    M: function() { return Date.replace.shortMonths[this.getMonth()]; },
    n: function() { return this.getMonth() + 1; },
    t: function() { return "Not Yet Supported"; },
    // Year
    L: function() { return "Not Yet Supported"; },
    o: function() { return "Not Supported"; },
    Y: function() { return this.getFullYear(); },
    y: function() { return ('' + this.getFullYear()).substr(2); },
    // Time
    a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
    A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
    B: function() { return "Not Yet Supported"; },
    g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
    G: function() { return this.getHours(); },
    h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
    H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
    i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
    s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
    // Timezone
    e: function() { return "Not Yet Supported"; },
    I: function() { return "Not Supported"; },
    O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
    T: function() { return "Not Yet Supported"; },
    Z: function() { return this.getTimezoneOffset() * 60; },
    // Full Date/Time
    c: function() { return "Not Yet Supported"; },
    r: function() { return this.toString(); },
    U: function() { return this.getTime() / 1000; }
}

/* Sökresultat - Start */

function VK(kapitelLänk, träffPanelId) {
    VippaKapitel(kapitelLänk, träffPanelId);
}

function VippaKapitel(kapitelLänk, träffPanelId) {
    //var kapitelLänk = $get(kapitelLänkId);
    var träffPanel = $("#" + träffPanelId);

    if (träffPanel.is(":visible")) {
        träffPanel.hide("fast");
        kapitelLänk.className = "KapitelLabel";
        kapitelLänk.title = "Visa artiklar";
    }
    else {
        träffPanel.show("fast");
        kapitelLänk.className = "KapitelLabel Vald";
        kapitelLänk.title = "Dölj artiklar";
    }

    return false;
}

/* Sökresultat - Slut */

function trim(s) {
    var l = 0;
    var r = s.length - 1;
    while (l < s.length && s[l] == ' ') {
        l++;
    }

    while (r > l && s[r] == ' ') {
        r -= 1;
    }

    return s.substring(l, r + 1);
}

/// Kort namn för ChangeFocusOnEnter()
function CFOE(event, ref) {
    ChangeFocusOnEnter(event, ref);
}

function ChangeFocusOnEnter(event, ref) {
    if (event.keyCode == 13) {
        var btn = document.getElementById(ref);
        if (btn) {
            btn.focus();
        }
    }
}

var fonster = null;
var x = 0; var y = 0;

if (parseInt(navigator.appVersion) > 3) {
    x = (screen.availWidth - 300) / 2; y = (screen.availHeight - 300) / 2;
}


function ShowPopup(url, winname, features) {
    if (parseInt(navigator.appVersion) > 3 || navigator.appName == "Netscape") {
        if (!fonster || fonster.closed) {
            fonster = window.open(url, winname, features);
            fonster.focus();
        } else {
            fonster.location.href = url;
            fonster.focus();
        }
    } else {
        window.parent.frames.base.location.href = url;
    }
}
function FakturaArkivVisaPopup(Faktnr) {
    var Url = "../Popup/FakturaArkivVisa.aspx?Faktnr=" + Faktnr;
    window.open(Url, "FakturaArkivVisa", "menubar=no,scrollbars=yes,resizable=yes,HEIGHT=600,WIDTH=800,top=120,left=150");
}
/* Client-side access to querystring name=value pairs
Version 1.2.4
30 March 2008
Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
    this.params = {};
    this.get = Querystring_get;

    if (qs == null);
    qs = location.search.substring(1, location.search.length);

    if (qs.length == 0)
        return;

    // Turn <plus> back to <space>
    // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
    qs = qs.replace(/\+/g, ' ');
    var args = qs.split('&'); // parse out name/value pairs separated via &

    // split out each name=value pair
    for (var i = 0; i < args.length; i++) {
        var pair = args[i].split('=');
        var name = unescape(pair[0]);

        var value = (pair.length == 2)
			? unescape(pair[1])
			: name;

        this.params[name] = value;
    }
}

function Querystring_get(key, default_) {
    var value = this.params[key];
    return (value != null) ? value : default_;
}

function ShowStopTimes() {
    myWindow = window.open("Popup/StoppTider.aspx", "alertWindow", 'toolbar=no, width=500, height=440, top=200, left=200, scrollbars=yes')
}

function VippaSynlighet(id) {
    var elRef = $get(id);
    elRef.style.display = elRef.style.display == "none" ? "block" : "none";
}

function unhide(divID) {
    var item = document.getElementById(divID);
    if (item) {
        item.className = item.className == 'hidden' ? 'visible' : 'visible';
    }
}


function openMyPaper(pid) {
    window.open('http://www.mypaper.se/read.asp?pid=' + pid, 'mypaper' + pid, 'width=1020,height=745,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no');
}

var gammalPanelId;

function VisaPanel(panelId) {

    if (gammalPanelId) {
        if (gammalPanelId != panelId) {
            DöljPanel(gammalPanelId);
            gammalPanelId = panelId;
        }
    }
    else {
        gammalPanelId = panelId;
    }

    // Hide elements when showing favourites in IE6 and 7 because of z-index bug
    if (panelId == "FavoritBehållare" && IsIEBelowVersion8())
    {
        if($("#SupersokResultContainer").is(":visible"))
            $("#tabs").hide();

        $("#CatalogCont #RightPane").hide();
    }

    var el;
    el = $get(panelId);
    el.style.display = "block";
    FortSättVisaPanel();

}

var timeOutId;

function StartaDöljPanel(panelId, timeout) {
    timeOutId = setTimeout("DöljPanel('" + panelId + "')", timeout);
}

function DöljPanel(panelId) {
    var el;
    el = $get(panelId);
    el.style.display = "none";

    if (panelId === "SupersokResultContainer")
        $("#SupersokResultContainer").trigger("SokHidden");

    // Searchresults was hidden in VisaPanel() -> Show them again
    if (panelId == "FavoritBehållare" && IsIEBelowVersion8())
    {
        if($("#SupersokResultContainer").is(":visible"))
            $("#tabs").show();

        $("#CatalogCont #RightPane").show();
    }
}

function FortSättVisaPanel() {
    clearTimeout(timeOutId);
}

function BlockeraUI(meddelande) {
    if (typeof meddelande == "undefined") {
        meddelande = "Var god vänta, sidan laddar...";
    }

    try {
        var pageIsValid = Page_ClientValidate('');
        if (!pageIsValid) {
            return;
        }
    }
    catch (e) {

    }

    var vanta = $('#VantaBehallare');
    vanta.show();
    vanta.html("<div><img src='/App_Themes/Standard/Grafik/ActivityIndicator.gif' /> " + meddelande + "</div>");
}

function AvblockeraUI() {
    var vanta = $('#VantaBehallare');
    vanta.hide();
}

/* Skapa en stacktrace i javaScript */
function hamtaStackTrace() {
    var callstack = [];
    var isCallstackPopulated = false;
    try {
        i.dont.exist += 0; //does not exist - that's the point
    } catch (e) {
        if (e.stack) { //Firefox
            var lines = e.stack.split("\n");
            for (var i = 0, len = lines.length; i < len; i++) {
                if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
                    callstack.push(lines[i]);
                }
            }
            //Remove call to printStackTrace()
            callstack.shift();
            isCallstackPopulated = true;
        }
        else if (window.opera && e.message) { //Opera
            var lines = e.message.split("\n");
            for (var i = 0, len = lines.length; i < len; i++) {
                if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
                    var entry = lines[i];
                    //Append next line also since it has the file info
                    if (lines[i + 1]) {
                        entry += " at " + lines[i + 1];
                        i++;
                    }
                    callstack.push(entry);
                }
            }
            //Remove call to printStackTrace()
            callstack.shift();
            isCallstackPopulated = true;
        }
    }
    if (!isCallstackPopulated) { //IE and Safari
        var currentFunction = arguments.callee.caller;
        while (currentFunction) {
            var fn = currentFunction.toString();
            //If we can't get the function name set to "anonymous"
            var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
            callstack.push(fname);
            currentFunction = currentFunction.caller;
        }
    }
    return callstack;
}

/*
* Stoppa exekvering på aktuell tråd i det givna antalet millisekunder
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

function GfkWin(urlen) {
    var fonster = null;
    if (parseInt(navigator.appVersion) > 3 || navigator.appName == "Netscape") {
        if (!fonster || fonster.closed) {
            fonster = window.open("TK Lagerhotell", "subwin", "menubar=no,scrollbars=yes,resizable=yes,HEIGHT=560,WIDTH=796,top=50,left=0");
            fonster.location.href = urlen;
            fonster.focus();
        }
        else {
            fonster.location.href = urlen;
            fonster.focus();
        }
    }
    else {
        location.href = urlen;
    }
}

function MarkeraOchSkrollaTill(sokOrd, cssNamnMarkera, omrade) {
    // Inställningar för SearchHighlight
    var options = { exact: "partial", keys: sokOrd, style_name_suffix: false, style_name: cssNamnMarkera, highlight: omrade };
    var doc = $(document);

    // Markera träff
    doc.SearchHighlight(options);

    // Skrolla till första träffen
    var traffPos = doc.find(omrade + " ." + cssNamnMarkera).offset();
    if (traffPos)
        $('html,body').animate({ scrollTop: traffPos.top - 10 }, 700);
}

function format(str) {
    for (i = 1; i < arguments.length; i++) {
        str = str.replace('{' + (i - 1) + '}', arguments[i]);
    }
    return str;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name, "", -1);
}

function FixHeader(headerContSelector, viewEl) {
    // Wait a litle while so that widths can be found in IE8
    setTimeout(function() {
        FixHeaderDelayed(headerContSelector, viewEl);
    }, 250);
}

/// This function makes table headers visible even if the are scrolled out of view
function FixHeaderDelayed(headerContSelector, viewEl) {

    var headerCont = $(headerContSelector);

    if (!headerCont.length)
        return;

    var header = headerCont.children().length > 1 ? headerCont.children().last() : headerCont.children();
    var view = $(viewEl);

    // Reset bindings because of partial postbacks
    view.unbind("scroll resize", HeaderOnScroll);

    var backgroundIssues = IsIEBelowVersion8();

    // Do not use position:fixed if the view is some sub element or if IE7 or less
    var useFixed = (viewEl == window) && !backgroundIssues;

    // Check if browser supports position:fixed
    var headerCSS = useFixed ? "head-fixed" : "head-absolute";

    this.setHeights = function() {

        var viewScrollTop;
        var viewOffsetTop;

        // Find top of view depending on if the window is the view or a nested element with scroll
        if (view.offset()) {
            viewOffsetTop = view.offset().top;
            viewScrollTop = view.scrollTop();
        } else {
            viewOffsetTop = 0;
            viewScrollTop = 0;
        }

        // Calculate top of header container
        headerCont.data("ViewTop", (headerCont.offset().top + viewScrollTop - viewOffsetTop));

        //header.css("top", viewOffsetTop);
    }

    this.reset = function() {
        setHeights();
        view.trigger("scroll");
    }

    // Hook into search container events since it changes position of things
    var supersokResultContainer = $("#SupersokResultContainer");
    supersokResultContainer.unbind("SokFinished SokHidden", this.reset);
    supersokResultContainer.bind("SokFinished SokHidden", this.reset);

    this.setHeights();


    var headerClone;

    // Width must be specified otherwise the table and headers collapses in FF
    SetWidthForElementAndChildren(header, "th");

    // If position is not fixed (ie scrolling in an inner element) we move the table headers outside the table so that they stay
    if (!useFixed) {

        view.height(view.height() - header.height() - 2);
        view.width(header.width());

        if (view.parent().children().length === 1) {
            view.before(header.parent()).parent().children(":first-child").wrap('<div class="AspNet-GridView" style="overflow:visible;" />').wrap('<table cellpadding="0" cellspacing="0" />');
        }

        return;
    }

    // Create a clone that will maintain space and column widths when scrolling
    headerClone = headerCont.children().length > 1 ? headerCont.children().first() : header.clone().prependTo(headerCont).hide();

    // Bind scroll and resize events
    view.bind(
        "scroll resize",
        {
            view: view,
            useFixed: useFixed,
            header: header,
            headerCSS: headerCSS,
            headerClone: headerClone,
            headerCont: headerCont,
            backgroundIssues: backgroundIssues
        },
        HeaderOnScroll
    );

    // Trigger scroll event so that header is shown even if the view was scrolled before the eventual partial postback
    view.trigger("scroll");
};

function MoveHeader(header, viewTop) {
    header.animate({
        "top": viewTop
    }, 300, 'easeOutCirc');
}

var moveHeaderTimeout;

function HeaderOnScroll(event) {

    var viewTop = event.data.view.scrollTop();
    var headerViewTop = event.data.headerCont.data("ViewTop");
    
    // Only set top when absolute positioning is used
    if (!event.data.useFixed) {
        clearTimeout(moveHeaderTimeout);
        moveHeaderTimeout = setTimeout(function() { MoveHeader(event.data.header, viewTop) }, 100);
    }

    if ((viewTop > headerViewTop) && !event.data.header.hasClass(event.data.headerCSS)) {
        event.data.header.addClass(event.data.headerCSS);
        event.data.headerClone.show();
    } else if ((viewTop <= headerViewTop) && event.data.header.hasClass(event.data.headerCSS)) {
        event.data.headerClone.hide();
        event.data.header.removeClass(event.data.headerCSS);

        // Force header to redraw due to problems i certain browsers
        if (event.data.backgroundIssues) {
            event.data.header.css("display", "none");
            var test = event.data.header.offsetHeight;
            event.data.header.css("display", "block");            
        }

    }
        
}

function SetWidthForElementAndChildren(el, childSel) {
    el.each(function() {
        $this = $(this);
        $this.width($this.width());

        $this.children(childSel).each(function() {
            $(this).width($(this).width());
        });

    });
}

function IsIEBelowVersion8() {
    return $.browser.msie && $.browser.version.substr(0, 1) < 8;
}

//Test av webenkäter
//function VisaPopupQuestion001(siden) {
//    var Urlen = "../EskandiaWebbButik/Popup/FakturaArkivVisa.aspx?Siden="+siden;
//    alert(Urlen);
////    FakturaArkivVisaPopup('ettt');
//    window.open(Urlen, "Webbenkät001", "menubar=no,scrollbars=yes,resizable=yes,HEIGHT=600,WIDTH=800,top=120,left=150");
//}

