/**
 * Experiment
 */
try {
    document.execCommand("BackgroundImageCache", false, true);
}
catch(err) {}

/**
 * Calendaring
 */
var Kampus = function() {}
Kampus.calendar = function() {}

Kampus.calendar.selectedDay = '';
Kampus.calendar.onlyMine = 0;
Kampus.calendar.group_id = false; // set this to display the widget with group events

Kampus.calendar.get = function(wrapperId, year, month)
{
    if(Kampus.calendar.group_id)
    {
        var _url = '/calendar/widget_group/' + Kampus.calendar.group_id + '/' + year + '/' + month + '/' + Kampus.calendar.selectedDay;
    }
    else
    {
        var _url = '/calendar/widget_mine/' + year + '/' + month + '/' + Kampus.calendar.selectedDay;
    }
    if ( Kampus.calendar.onlyMine == 1)
    {
        _url += '/1';
    }
    $('#' + wrapperId + '_month').html('<div class="widgetload">loading...</div>');
    $.ajax({
        url: _url,
        success: function(msg){
            $('#' + wrapperId).html(msg);
            Kampus.evenSizes();
       }
    });
}

Kampus.files = {
    get : function(wrapperId, groupId, pictureOffset)
    {
        $('#' + wrapperId).html('<div class="widgetload">loading...</div>');
        $.ajax({
            url: '/file/widget/' + groupId,
            async: true,
            success: function(msg){
                $('#' + wrapperId).html(msg);
                Kampus.evenSizes();
            }
        });
        $('#' + wrapperId).html(msg);
    }
}

Kampus.gallery = {

    'pictureOffset'     : 0,
    'groupId'           : 0,
    'endPic'            : 0,

    get : function(wrapperId, groupId, pictureOffset)
    {
        this.groupId = groupId;
        $('#' + wrapperId).html('<div class="widgetload">loading...</div>');
        $.ajax({
            url: '/gallery/widget/' + groupId + '/' + pictureOffset,
            async: true,
            success: function(msg){
                $('#' + wrapperId).html(msg);
                Kampus.evenSizes();
            }
        });
    },

    nextPicture : function(wrapperId)
    {
        this.pictureOffset = Math.min(this.pictureOffset + 1, this.endPic);
        this.get(wrapperId, this.groupId, this.pictureOffset);
        Kampus.evenSizes();
        return false;
    },

    prevPicture : function(wrapperId)
    {
        this.pictureOffset = Math.max(this.pictureOffset - 1, 0);
        this.get(wrapperId, this.groupId, this.pictureOffset);
        Kampus.evenSizes();
        return false;
    }

}

Kampus.evenSizes = function()
{
    ok = true;
    i = 1;
    while (ok)
    {
        var ok = ( document.getElementById("box_" + 1 + "_" + i) && document.getElementById("box_" + 2 + "_" + i) && document.getElementById("box_" + 3 + "_" + i) );
        if (ok)
        {

            var lft_c = document.getElementById("boxc_" + 1 + "_" + i);
            var ctr_c = document.getElementById("boxc_" + 2 + "_" + i);
            var rgt_c = document.getElementById("boxc_" + 3 + "_" + i);

            var lft_b = document.getElementById("box_" + 1 + "_" + i);
            var ctr_b = document.getElementById("box_" + 2 + "_" + i);
            var rgt_b = document.getElementById("box_" + 3 + "_" + i);

            lft_c.style.height='auto';
            ctr_c.style.height='auto';
            rgt_c.style.height='auto';

            lft_b.style.height='auto';
            ctr_b.style.height='auto';
            rgt_b.style.height='auto';

            var lft_b_h = lft_b.offsetHeight;
            var ctr_b_h = ctr_b.offsetHeight;
            var rgt_b_h = rgt_b.offsetHeight;

            var max_height = Math.max(lft_b_h,
                            Math.max(ctr_b_h, rgt_b_h));

            lft_c.style.height = ( lft_c.offsetHeight + ( max_height - lft_b_h ) ) + "px";
            ctr_c.style.height = ( ctr_c.offsetHeight + ( max_height - ctr_b_h ) ) + "px";
            rgt_c.style.height = ( rgt_c.offsetHeight + ( max_height - rgt_b_h ) ) + "px";

            lft_c.style.height = ( parseInt(lft_c.style.height) - (lft_c.offsetHeight - parseInt(lft_c.style.height))) + "px";
            ctr_c.style.height = ( parseInt(ctr_c.style.height) - (ctr_c.offsetHeight - parseInt(ctr_c.style.height))) + "px";
            rgt_c.style.height = ( parseInt(rgt_c.style.height) - (rgt_c.offsetHeight - parseInt(rgt_c.style.height))) + "px";
        }
        i++;
    }
};

/**
 * News ticker
 */
Kampus.newsticker = {
    news      : null,
    curitem   : -1,
    newsTimer : null,
    newsTime  : 10000,
    wrapperId : '',
    data      : null,

    _display : function ()
    {
        nextitem = this.curitem;
        tmp = '';
        links = '';
        while ( tmp.length < 75 )
        {
            it = this.news[nextitem];
            links += ( nextitem == this.curitem ? '' : ' &diams; ' ) + '<a href="' + it.link + '">' + it.title + '</a>';
            tmp += ( nextitem == this.curitem+1 ? '' : ' * ' ) + it.title;
            nextitem++;
            if ( nextitem >= this.news.length )
            {
                nextitem = 0;
            }
        }
        this.curitem = nextitem;
        $("#"+this.wrapperId).html(links).show();

        $("#"+this.wrapperId+" a").each(function () {
            this.onclick = function () {
                window.open(this.href);
                return false;
            }
        });

        $("#"+this.wrapperId+" a").bind("mouseover", function () {
            clearTimeout(Kampus.newsticker.newsTimer);
        });
        $("#"+this.wrapperId+" a").bind("mouseout", function () {
            clearTimeout(Kampus.newsticker.newsTimer);
            Kampus.newsticker.newsTimer = setTimeout('Kampus.newsticker.displayNext()',Kampus.newsticker.newsTime);
        });

        this.newsTimer = setTimeout("Kampus.newsticker.displayNext()", this.newsTime);
    },

    displayNext : function() {
        if ( ++this.curitem >= this.news.length )
        {
            this.curitem = 0;
        }
        $("#"+this.wrapperId).hide();
        Kampus.newsticker._display();
    },

    run : function(wrapperId)
    {
        this.wrapperId = wrapperId;
        this.displayNext();
    }
};

/* Shoutbox */
Kampus.shoutbox = {
    lastEntry: 0,
    limit: 4,
    interval: 10000,
    groupId: '',
    wrapperId: '',
    highlight: false,
    deleting: false,
    counter: 0,
    b2b: false,
    myid: 0,
    offset: 0,
    dedicated: false,
    pgno: 0,

    renderShouts: function ()
    {
        if (this.deleting)
        {
            $("#" + this.wrapperId).html("");
            this.deleting = false;
        }
        if ( typeof this.data != 'undefined' && typeof this.data.records != null && typeof this.data.records != 'undefined' )
        {
            this.lastEntry = this.data.latest;
            items = this.data.records;
            n = items.length;
            for ( i = 0; i < n; i++ )
            {
				$(".shouty:gt("+ ( this.limit - 2 ) + ")").remove();
                theId = items[i].mi;
                html = shouttemplate.replace(/shouttemplate/,'shout_'+theId).replace(/shouttmpl/,"shouty");
                html = html.replace(/%%NAVN%%/g, items[i].n).replace(/%%POSTED%%/g, items[i].p).replace(/%%USERID%%/g, items[i].ui);
                html = html.replace(/i\/anonymous_32x32\.png/g, items[i].i).replace(/%%MSG%%/g, items[i].m);
                if (this.b2b || items[i].ui == this.myid)
                {
                    html = html.replace(/<a class="shb2b_userid".*?<\/a>/g,'');
                }
                else
                {
                    html = html.replace(/shb2b_userid/g,'shb2b'+items[i].ui);
                }
                moderator = '';
                if (items[i].mo)
                {
                    moderator = shoutdelbut.replace(/shoutdeletebut/,"shoutd_" + theId).replace(/return false/g, "Kampus.shoutbox.del(" + theId + "); return false");
                }
                html = html.replace(/%%MODERATOR%%/g,moderator).replace(/%%MSGID%%/g,theId);

                $("#" + this.wrapperId).prepend(html);

                if ( this.highlight )
                {
                    $("#shout_" + theId).highlightFade();
                }
            }
            Kampus.evenSizes();
        }

        this.highlight = true;
    },

    update : function () {
        add = '';
        if ( this.b2b )
        {
            add = '/' + this.b2b;
        }
        url = "/shoutbox/get_latest/" + this.groupId + "/" + this.lastEntry;
        url += '/' + this.offset + '/' + this.limit + add;
        $.getJSON(
            url,
            function (data)
            {
                k = Kampus.shoutbox;
                k.counter++;
                if ( k.counter < 500 )
                {
                    setTimeout("Kampus.shoutbox.update()", k.interval);
                }
                if ( ( data.length == 0 && !k.deleting ) || data.latest <= k.lastEntry )
                {
                    return;
                }
                k.data = data;
                k.renderShouts();
            }
        );
    },

    del: function(msgId)
    {
        _url = "/shoutbox/delete/"+this.groupId+"/"+msgId+"/";
        $.ajax({
            url: _url,
            async: true,
            success: function (){
                // Hack. We need a complete re-draw, so set timestamp to 0.
                k = Kampus.shoutbox;
                k.highlight = false;
                k.lastEntry = 0;
                k.deleting = true;
                k.update();
            }
        });
    },

    init : function (wrapperId, groupid, lastentry)
    {
        this.wrapperId = wrapperId;
        this.groupId = groupid;
        this.lastEntry = lastentry;
        if ( !this.dedicated ) this.deleting = true;
        this.renderShouts();

        if ( $("#shoutboxcreateform").length > 0 )
        {
            var opts = {
                    url: $("#shoutboxcreateform")[0].action,
                    resetForm: true,
                    beforeSubmit: function () {
                        $('#shoutmit')[0].disabled = true;
                    },
                    success: function () {
                        $('#shoutmit')[0].disabled = false;
                        Kampus.shoutbox.update();
                    }
            };
            $("#shoutboxcreateform").ajaxForm(opts);
        }
        Kampus.evenSizes();
        setTimeout("Kampus.shoutbox.update()", this.interval);
    }
};

/* Forum */
Kampus.forum = {
    lastEntry: 0,
    limit: 4,
    interval: 10000,
    groupId: '',
    wrapperId: '',
    deleting: false,
    highlight: false,
    counter: 0,

    renderPosts: function ()
    {
        if ( this.deleting )
        {
            if ( this.highlight == false && typeof this.data != 'undefined' && typeof this.data.records != 'undefined' && this.data.records.length > 0 )
            {
                $("#" + this.wrapperId).html("");
            }
            this.deleting = false;
        }
        if ( typeof this.data != 'undefined' && typeof this.data.records != 'undefined' )
        {
            this.lastEntry = this.data.latest;
            items = this.data.records;
            n = items.length;
            for ( i = 0; i < n; i++ )
            {
                $(".widget_post:gt("+ ( this.limit - 1 ) + ")").remove();
                theId = items[i].messageid;
                html = ''+$("#forum_widget_template").html();
                html = html.replace(/forum_hidden_one/g,"fpost-"+theId).replace(/%%POSTID%%/g,theId).replace(/%%USERID%%/g,items[i].userid);
                html = html.replace(/%%THREADID%%/g,items[i].threadid).replace(/\/res\/i\/anonymous_32x32\.png/g,items[i].img_url);
                html = html.replace(/%%NAME%%/g,items[i].firstname+" "+items[i].lastname).replace(/%%POSTED%%/g,items[i].posted);
                html = html.replace(/%%TITLE%%/g,items[i].title);
                $("#" + this.wrapperId).prepend(html);
                $("#fpost-"+theId).show();
                if (this.highlight)
                {
                    $("#fpost-"+theId).highlightFade();
                }
            }
            Kampus.evenSizes();
        }
        this.highlight = true;
    },

    update: function ()
    {
        url = "/forum/getLatestPosts/" + this.groupId + "/" + this.lastEntry + '/' + this.limit;
        $.getJSON(
            url,
            function (data)
            {
                k = Kampus.forum;
                if ( data.records && data.records.length > 0 )
                {
                    k.data = data;
                    k.renderPosts();
                }
                k.counter++;
                if ( k.counter < 500 )
                {
                    setTimeout("Kampus.forum.update()", k.interval);
                }
            }
        );
    },

    init: function (wrapperId, groupId)
    {
        this.wrapperId = wrapperId;
        this.groupId = groupId;
        this.highlight = false;
        this.deleting = true;
        this.renderPosts();
        setTimeout("Kampus.forum.update()", this.interval);
    }
};

/**
 * Utilities
 */
Kampus.utils = {
    checkAllCheckboxes : function(caller, className)
    {
        $('.' + className).each(
            function()
            {
                this.checked = (caller.checked ? 1 : 0);
            }
        )
    },
    invertChecksOnCheckboxes : function(className)
    {
        $('.' + className).each(
            function()
            {
                this.checked = (!this.checked);
            }
        )
    },
    moveItemsFromSelect : function (idfrom, idto)
    {
        var frB = $("#" + idfrom)[0];
        var toB = $("#" + idto);
        var i = frB.selectedIndex;
        while ( frB.selectedIndex != -1 )
        {
            toB.append('<option value="' + frB.options[i].value + '">' + frB.options[i].text + '</option>');
            frB.options[i] = null;
        }
        toB[0].selectedIndex = frB.selectedIndex = -1;
    },
    confirmNavigation : function(msg, url)
    {
        if(confirm(msg))
        {
            window.location = url;
        }
        return false;
    },
    wrMail: function(t,d,u,l)
    {
        s = '';
        m = s+u+'@'+s+d+s+'.'+s+t+s;
        if ( typeof l == 'undefined' )
        {
            document.write(m);
        }
        else
        {
            document.write('<a href="mailto:' + m + '">' + m + '</a>');
        }
    },
    ValidEmail: function(mail)
	{
	    return mail.match(/^[a-z0-9_\-\.\+]+@[a-z0-9\-]+\.[a-z0-9\-\.]{2,}$/);
	}
}

Kampus.activity = {
    lastHtml: '',
    wrapperId: null,
    _url: null,
    checkInterval: 10000,
    counter: 0,
    no: 5,

    check: function ()
    {
        $.ajax({
            url: this._url,
            async: true,
            success: function(msg){
                k = Kampus.activity;
                if (k.lastHtml != msg)
                {
                    $('#' + k.wrapperId).html(msg);
                    if (k.lastHtml.length > 0)
                    {
                        $('#' + k.wrapperId + ' ul li .first').highlightFade();
                    }
                    k.lastHtml = msg;
                    Kampus.evenSizes();
                }
                k.counter++;
                if ( k.counter < 500 )
                {
                    setTimeout('Kampus.activity.check()', k.checkInterval);
                }
           }
        });
    },

    init:  function(wrapperId,groupid)
    {
        this._url = '/activity/widget/' + groupid + '/' + this.no;
        this.wrapperId = wrapperId;
        Kampus.activity.lastHtml = $('#' + this.wrapperId).html();
        Kampus.evenSizes();
        setTimeout('Kampus.activity.check()', this.checkInterval);
    }
}
