﻿
//Användning: log(parametrar), logga vad som helst var som helst i koden.
window.log = this.log = function() {
    window.log.history = window.log.history || [];
    window.log.history.push(arguments);
    if (window.console) {
        console.log(Array.prototype.slice.call(arguments));
    }
};

window.fakeQuery = function(id) { return document.getElementById(id); };
window.fq = window.fakeQuery;
(function($) {
    myrender = function(p) {
        RenderChannel(p, $('numberofobjects').value);
    }

    getElementsByClassName = function(className, tag, elm) {
        var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
        var tag = tag || "*";
        var elm = elm || document;
        var elements = (tag == "*" && elm.all) ? elm.all : elm.getElementsByTagName(tag);
        var returnElements = [];
        var current;
        var length = elements.length;
        for (var i = 0; i < length; i++) {
            current = elements[i];
            if (testClass.test(current.className)) {
                returnElements.push(current);
            }
        }
        return returnElements;
    };
    toggleClass = function(cssClass, elem) {
        var reg = new RegExp("(^|\\s)" + cssClass + "(\\s|$)");
        if (reg.test(elem.className)) {
            elem.className = elem.className.replace(reg, " ");
        } else {
            elem.className += " " + cssClass;
        }
    }
    removeClass = function(cssClass, elem) {
        var reg = new RegExp("(^|\\s)" + cssClass + "(\\s|$)");
        if (reg.test(elem.className)) {
            elem.className = elem.className.replace(reg, " ");
        }
    }
    var rx = /^[._\w\d-]+@[.\w\d-]+[.]{1}[\w]{2,4}$/;
    ValidEmail = function(email) {
        return rx.test(email);
    }
    isArray = function(obj) { if (obj == null) return false; return obj.constructor == Array; }
    Array.prototype.add = function(e) { this[this.length] = e; }
    Array.prototype.insert = function(pos, e) {
        for (var i = this.length; i > pos; i--) {
            this[i] = this[i - 1];
        }
        this[pos] = e;
    }
    Array.prototype.remove = function(pos) {
        for (var i = pos; i < this.length; i++) {
            this[i] = this[i + 1];
        }
        this.length--;
    }
    Array.prototype.find = function(func) {
        var ret = this.findPos(func);
        return (ret >= 0) ? this[ret] : null;
    }
    Array.prototype.findPos = function(func) {
        for (var i = 0; i < this.length; i++) {
            if (func(this[i]) == true) { return i; }
        }
        return -1;
    }
    Array.prototype.findAll = function(func) {
        var a = new Array();
        for (var i = 0; i < this.length; i++) {
            if (func(this[i]) == true) { a[a.length] = this[i]; }
        }
        return a;
    }
    Array.prototype.action = function(func) { for (var i = 0; i < this.length; i++) { func(this[i]); } }
    Array.prototype.filter = function(func) {
        var a = new Array();
        for (var i = 0; i < this.length; i++) {
            var ret = func(this[i]);
            if (ret != null)
                a.add(ret);
        }
        return a;
    }
    Array.prototype.contains = function(v) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == v) return true;
        }
        return false;
    }
    Stats = function(path, url) {
        var img = new Image(1, 1);
        url = (url != undefined) ? ("?" + escape(url)) : "";
        img.src = "http://stats.bovision.se/" + path + url;
    }
    StatsLink = function(path, url) {
        url = (url) ? ("?" + escape(url)) : "";
        window.location = "http://stats.bovision.se/" + path + url;
    }
    getPosition = function(e) {
        var left = 0;
        var top = 0;
        while (e.offsetParent) {
            left += e.offsetLeft;
            top += e.offsetTop;
            e = e.offsetParent;
        }
        left += e.offsetLeft;
        top += e.offsetTop;

        return { x: left, y: top };
    }
    getBounds = function(e) {
        var offset = getPosition(e);
        return { x: offset.x, y: offset.y, w: e.offsetWidth, h: e.offsetHeight };
    }
    setPosition = function(e, x, y) {
        e.style.position = 'absolute';
        e.style.left = x + "px";
        e.style.top = y + "px";
    }
    setBounds = function(ele, rect) {
        if (rect.x && rect.y) {
            setPosition(ele, rect);
        }
        ele.style.width = rect.w + "px";
        ele.style.height = rect.h + "px";
        return rect;
    }
    movement = function(start, stop, speed) {
        this.start = this.current = start;
        this.stop = stop;
        this.speed = speed;
        this.move = function() {
            if (this.speed > 1)
                this.speed--;
            this.current += ((this.stop - this.current) / this.speed) | 0;
            return this.current;
        }
        this.home = function() {
            return this.current == this.stop;
        }
    }
    /**************************************
    ** Moving queue
    ***************************************/
    Queue = function() {
        window.Q = new Array();
        window.Q.add = function(e) {
            if (e.init)
                e.init();
            for (var i = 0; i < Q.length; i++) {
                if (Q[i] != null)
                    continue;
                Q[i] = e;
                return;
            }
            Q[Q.length] = e;
        }
        window.Q.remove = function(e) {
            for (var i = 0; i < Q.length; i++) {
                if (Q[i] != null && Q[i].id == e.id) {
                    if (Q[i].end)
                        Q[i].end();
                    Q[i] = null;
                }
            }
        }
        window.Q.watch = function() {
            for (var i = 0; i < Q.length; i++)
                if (Q[i] != null && Q[i].move != null)
                Q[i].move();
        }
        setInterval("Q.watch()", 20);
    }
    Queue();

    makeCollapsable = function(id) {
        var item = $(id);
        item.init = function() {
            if (!this.height)
                this.height = this.h = GetRealHeight(item);
            this.movement = (this.h == 1) ? new movement(1, this.height, 10) : new movement(this.height, 1, 10);
        }
        item.move = function() {
            if (this.movement.home())
                Q.remove(this);
            this.h = this.movement.move();
            this.style.height = this.h + "px";
        }
        return item;
    }
    /************************************
    ** Controls
    *************************************/
    TextControl = function(div, txt, type) {
        this.Div = div;
        this.Txt = txt;
        this.Type = type;
        this.Value = "";
        this.Child = null;
        this.SetValue = function(v) {
            //if( v != "" )
            this.Value = this.Div.childNodes[0].value = v;
        }
        this.Draw = function() {
            this.Div.innerHTML = '<input type="' + this.Type + '" />';
            this.Child = this.Div.childNodes[0];
            this.Child.onkeyup = this.Changed;
            this.Child.onfocus = this.Changed;
            this.Child.value = this.Txt;
            this.Child.Parent = this;
        }
        this.Changed = function() {
            if (this.value == this.Parent.Txt)
                return this.value = "";
            this.Parent.Value = this.value;
            Update();
        }
        this.Draw();
    }
    Reset = function(node) { node.checked = false; if (node.Childs) node.Childs.action(Reset); }
    CheckControl = function(data, div, have_all, Callback) {
        this.Data = data;
        this.Div = div;
        this.Values = [];
        this.HaveAllOption = have_all;
        this.Data.action(Reset);
        this.Div.Control = this;
        this.Callbacks = new Array();

        this.Draw = function() {
            this.Div.innerHTML = this._Draw(this.Data, '', '');
            if (this.Values.length == 0)
                this._Changed({ value: '' + this.Data[0].Id, checked: true });
        }
        this._Draw = function(data, pre, post) {
            var id = this.Div.id;
            var s = ["<table class='checkListTable'>"];
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                s.add('<tr><td style="width:10px"><input type="checkbox" onclick="$(\'' + id + '\').Control.Changed(this);" value="' + item.Id + '" ' + (item.checked ? ' checked="checked"' : '') + '/></td><td>' + pre + item.Name + post + '</td></tr>');
                if (item.checked == true && item.Childs && item.Childs.length > 0) {
                    s.add('<tr><td colspan="2">');
                    s.add(this._Draw(item.Childs, '<span> &nbsp;-', '</span>'));
                    s.add('</td></tr>');
                }
            }
            s.add("</table>");
            return s.join("");
        }
        this._Changed = function(e) {
            var item;
            (item = this._FindById(this.Data, e.value)).checked = e.checked;
            if (e.checked == true) {
                this.Values.add(e.value);
            }
            else {
                this.Values.remove(this.Values.findPos(function(v) { return v == e.value; }));
                var pos;
                for (var i = 0; item.Childs && i < item.Childs.length; i++) {
                    item.Childs[i].checked = false;
                    if ((pos = this.Values.findPos(function(v) { return v == item.Childs[i].Id; })) >= 0)
                        this.Values.remove(pos);
                }
                if (item.Childs && item.Childs.length > 0)
                    item.Childs.action(function(i) { i.checked = false; });
            }
            if (this.HaveAllOption) {
                if (this.Values.length > 1 && item.Id == this.Data[0].Id && item.checked == true) {
                    this.Data.action(Reset);
                    this.Values = [];
                }
                if (this.Values.length > 1 && this.Values[0] == this.Data[0].Id && this.Data[0].checked)
                    this._Changed({ value: '' + this.Data[0].Id, checked: false });
            }
            this.Draw();
        }
        this.Changed = function(e) {
            this._Changed(e);
            for (var i = 0; i < this.Callbacks.length; i++)
                this.Callbacks[i](this);
        }
        this.SetValues = function(arr) {
            var item;
            this.Values = [];
            this.Data.action(Reset);
            for (var i = 0; i < arr.length; i++) {
                item = this._FindById(this.Data, arr[i]);
                this.Values.add(item.Id);
                item.checked = true;
            }
            this.Draw();
        }
        this._FindById = function(data, id) {
            var item;
            for (var i = 0; i < data.length; i++) {
                if (data[i].Id == id)
                    return data[i];
                if (data[i].Childs && data[i].Childs.length > 0 && (item = this._FindById(data[i].Childs, id)) != null)
                    return item;
            }
            return null;
        }
        this.Draw();
        if (Callback)
            this.Callbacks.add(Callback);
    }
    SelectControl = function(data, div, size, Callback) {
        this.Data = data;
        this.Div = div;
        this.Value = 0;
        this.Index = 0;
        this.Child = null;
        this.Callbacks = new Array();
        this.Draw = function() {
            var data = this.Data.Values;
            var s = '<select ' + size + ' onchange="this.Control.Changed();">';
            for (var i = 0; i < data.length; i++)
                s += '<option value="' + i + '" ' + ((i == this.Index) ? 'selected="selected"' : '') + '>' + data[i].Name + '</option>';
            s += "</select>";
            this.Div.innerHTML = s;
            (this.Child = this.Div.childNodes[0]).Control = this;
        }
        this.SetValue = function(val) {
            var i = this.Data.Values.findPos(function(c) { return c.Id == val; });
            i = (i < 0) ? 0 : i;
            this.Index = this.Child.selectedIndex = i;
            this.Value = this.Data.Values[this.Index].Id;
        }
        this.Changed = function() {
            this.Child.selectedIndex = (this.Child.selectedIndex < 0) ? 0 : this.Child.selectedIndex;
            this.Value = this.Data.Values[this.Index = this.Child.selectedIndex].Id;
            //this.Data.Values[this.Index].checked = true;
            for (var i = 0; i < this.Callbacks.length; i++)
                this.Callbacks[i](this);
        }
        this.Draw();
        if (Callback)
            this.Callbacks.add(Callback);
    }
    MMControl = function(data, div, Callback) {
        this.Data = data;
        this.Div = div;
        this.Value = { Min: 0, Max: 0 };
        this.Childs = new Array();
        this.Callbacks = new Array();
        this.Draw = function() {
            this.Div.innerHTML = this.CreateSelect(this.Value.Min) + this.CreateSelect(this.Value.Max);
            (this.Childs[0] = this.Div.childNodes[0]).Control = this;
            (this.Childs[1] = this.Div.childNodes[1]).Control = this;
        }
        this.SetValue = function(val) {
            if (val) {
                this.Value.Min = val.Min;
                this.Value.Max = val.Max;
            }
            this.Draw();
        }
        this.CreateSelect = function(value) {
            var s = '<select onchange="this.Control.Changed();">';
            s += '<option value="0">' + this.Data.Name + '</option>';
            for (var i = 0; i < this.Data.Values.length - 1; i++)
                s += '<option value="' + this.Data.Values[i] + '" ' + ((this.Data.Values[i] > 0 && this.Data.Values[i] == value) ? 'selected="selected"' : '') + '>' + this.Data.Values[i] + '</option>';
            i = this.Data.Values.length - 1;
            s += '<option value="' + this.Data.Values[i] + '" ' + ((this.Data.Values[i] == value) ? 'selected="selected"' : '') + '>&gt; ' + this.Data.Values[i - 1] + '</option></select>';
            return s;
        }
        this.Changed = function() {
            this.Value.Min = this.Childs[0].value;
            this.Value.Max = this.Childs[1].value;
            for (var i = 0; i < this.Callbacks.length; i++)
                this.Callbacks[i](this);
        }
        this.Draw();
        if (Callback)
            this.Callbacks.add(Callback);
    }
    MenuControl = function(Div, Options) {
        this.Div = Div;
        this.Div.Control = this;
        this.Options = Options;
        this.Options[0].Selected = true;
        this.Draw = function() {
            var s = "<ul class=\"sokflikar\">";
            for (var i = 0; i < this.Options.length; i++) {
                var cl = this.Options[i].Selected ? "current" : "";
                s += "<li class=\"" + cl + "\"><a class=\"" + cl + "\" onclick=\"$('" + this.Div.id + "').Control.Callback(" + i + ")\">" + this.Options[i].Name + "</a></li>";
            }
            s += "</ul>";
            this.Div.innerHTML = s;
        }
        this.Callback = function(c) {
            for (var i = 0; i < this.Options.length; i++) {
                this.Options[i].Selected = false;
                if (c == i) {
                    this.Options[i].Selected = true;
                    this.Options[i].Callback();
                }
            }
            this.Draw();
        }
    }
    SubmitControl = function(Div, Callback, Value) {
        this.Div = Div;
        this.Div.Control = this;
        this.Callback = Callback;
        this.Value = (Value) ? Value : "Skicka";

        this.Div.appendChild(this.Button = document.createElement('span'));
        this.Div.appendChild(this.Message = document.createElement('span'));
        this.Div.appendChild(this.ErrorMsg = document.createElement('span'));
        this.Div.appendChild(this.Working = document.createElement('span'));
        this.Working.style.display = "none";
        this.Working.innerHTML = '<img src="/graphics/wait.gif"/>';

        this.SetMessage = function(Message) {
            this.Working.style.display = "none";
            this.ErrorMsg.innerHTML = "";
            this.Message.innerHTML = Message;
        }
        this.SetError = function(Error) {
            this.Working.style.display = "none";
            this.Message.innerHTML = "";
            this.ErrorMsg.innerHTML = '<span style="color:Red">' + Error + '</span>';
            this.Button.style.display = "";
        }
        this.ShowButton = function() {
            this.Working.style.display = "none";
            this.Button.style.display = "";
        }
        this.Draw = function() {
            this.Button.innerHTML = '<input type = "button" value="' + this.Value + '" onclick="this.Control.Click()"/>';
            this.Button.childNodes[0].Control = this;
        }
        this.Click = function() {
            this.Button.style.display = "none";
            this.Working.style.display = "";
            fq(this.Div.id).Control.Callback($(this.Div.id).Control);
            /*setTimeout((function(b) {
            fq(b.Div.id).Control.Callback($(b.Div.id).Control);
            } (this)), 1);*/
        }
        this.Draw();
    }

    qparser = function(qs, delim) {
        this.params = {};
        this.delim = (delim == undefined) ? '&' : delim;
        if (qs == undefined || qs == null) qs = location.search.substring(1, location.search.length);
        qs = qs.replace(/\+/g, ' ');
        var args = qs.split(this.delim);
        for (var i = 0; i < args.length; i++) {
            var pair = args[i].split('=');
            var name = decodeURIComponent(pair[0]);
            var value = (pair.length == 2) ? decodeURIComponent(pair[1]) : name;
            this.params[name] = value;
        }
        this.get = function(key, default_) {
            var value = this.params[key];
            return (value != null) ? value : default_;
        }
        this.set = function(key, value) {
            this.params[key] = value;
        }
        this.contains = function(key) {
            var value = this.params[key];
            return (value != null);
        }
        this.toString = function() {
            var res = new Array();
            for (var k in this.params)
                res.add(k + '=' + escape(this.params[k]));
            return res.join(this.delim);
        }
    }



    /*Form handling */
    LoadObjectFromForm = function(base) {
        for (prop in base) {
            if (prop.charAt(0) != '_' && (e = $(prop)) != null)
                base[prop] = e.value; ;
        }
        return base;
    }

    LoadFormFromObject = function(base) {
        for (prop in base) {
            if (prop.charAt(0) != '_' && (e = $(prop)) != null)
                e.value = base[prop];
        }
        return base;
    }

    setDivVis = function(name, visibility) {
        var div = $(name);
        if (div != null)
            div.style.display = visibility ? "block" : "none";
    }

    showHideContent = function(id, hidediv) {
        if (hidediv) {
            hidearray = hidediv.split(";");
            for (i = 0; i < hidearray.length; i++) {
                var hide = $(hidearray[i]);
                hide.style.display = 'none';
            }
        }
        var elem = $(id);
        if (elem) {
            if (elem.style.display == 'none') {
                elem.style.display = 'block';
            }
            else {
                elem.style.display = 'none';
            }
        }
    }
    /*Channels */
    function RenderChannel(p, ipp, SkipSetState) {
        if (!p)
            p = Request.Query.Keys.getValue('p');
        if (!ipp)
            ipp = Request.Query.Keys.getValue('ipp');
        var page = (p) ? p : 1;
        Request.Query = (window.ToQuery) ? ToQuery() : Request.Query;
        var keys = Request.Query.Keys;
        keys.setValue('ipp', '' + ipp);
        keys.setValue('p', '' + page);
        if (!SkipSetState)
            __setAjaxState(p, ipp);
        var res = Bv.ChannelResult(Request).value;
        $('ctl00_MainContent_channelcontent').innerHTML = res.RenderedResult;
    }
    function __getq() {
        return window.G ? window.G.Query : Request.Query;
    }
    function __setAjaxState(p, ipp) {
        var q = __getq();
        //var q = Request.Query;
        var hash = "__state__" + p + "_" + q.SortName + "_" + q.SortDirection + "_" + ipp;
        var divname = "anchorcontainer";
        if ($(divname) == null) {
            var d = document.createElement("div");
            d.setAttribute("id", divname);
            var a = document.createElement("a");
            d.appendChild(a);
            document.body.appendChild(d);
        }
        $(divname).childNodes[0].name = hash;
        document.location.replace("#" + hash);
    }

    function Sort(field, defSort) {
        var q = __getq();
        if (field == (q.SortName ? q.SortName : defSort))
            q.SortDirection = q.SortDirection == 1 ? -1 : 1;
        else {
            q.SortName = field;
            q.SortDirection = 1;
        }
        RenderChannel(1);
    }

    if (window.onunload == null)
        window.onunload = function() { }
    window.onload = function() {
        var hash = document.location.hash;
        var __ajaxhashstatestring = "__state__";
        if (hash.indexOf(__ajaxhashstatestring) == 1) {
            var arr = hash.replace("#" + __ajaxhashstatestring, "").split("_");
            if (arr[1].length > 0 || arr[2] == "-1") {
                var q = G.Query;
                q.SortDirection = arr[2];
                q.SortName = arr[1];
            }
            RenderChannel(arr[0], arr[3], true);
        }
    }
} (window.fakeQuery));
