﻿/// <reference path="jquery-1.6.2.js" />

$(document).ready(function() {
    AttachThickbox()
    AttachContainerToggling();
    AttachTruncate();
});


function AttachThickbox() {
    $('a.thickbox, area.thickbox, input.thickbox').unbind("click");
    if (tb_init) {
        tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
        imgLoader = new Image(); // preload image
        imgLoader.src = tb_pathToImage;
    }
}


function AttachCommentsToTarget(target) 
{
    target.each(function () {
        if ($(this).data("qtip")) {
            // already have a qtip.
            return;
        }

        var id = $(this).find("var").html();
        var title = $(this).attr("title");
        var delay = $(this).is(".tooltip2,.tooltip") ? 50 : 1000;

        var opts = {
                show: {
                    solo:true,
                    delay: delay
                },
                content: {
                    text: title
                },
                events: {
                    render: function(event, api) {
                        // Grab the tip element
                        var elem = api.elements.tip;
                    }
                },
                style: {
                    classes: 'ui-tooltip-shadow ui-tooltip-rounded',
                    widget: true
                }
            };

        
        if (id) {
            // <var>id</var> type of data.
            var regExp = /\s+/g;
            id = id.replace(regExp, "");

            opts.content = { 
                text: "Laddar...",
                ajax: {
                    url: "/HttpHandlers/GetTooltip.ashx?TipId=" + id,
                    type: "GET"
                }
            };
        } else {
            //console.log(this);
        }

        var tip = $(this).qtip(opts); // create the qtip.

        if($(this).is("input,button")) {
            $(this).click(function() {
                // clear the show timer if we click a button, to prevent it from showing if we open a ui.dialog.
                clearTimeout($(this).qtip('api').timers.show);
            });
        }
    });
}


function AttachContainerToggling(jExp) {
    
    // Toggle containers
    $("span.toggleContainerLink", jExp).unbind();
    $("span.toggleContainerLink", jExp).toggle(
        function() {
            var textArr = $(this).text().split(' ');
            textArr[0] = "Maximera ";
            $("span", this).text(textArr[0] + textArr[1]);
            $("img", this).attr("src", "/Images/Dp/toggle_max.gif");
            $(this).next().slideUp('fast');
        }, function() {
            var textArr = $(this).text().split(' ');
            textArr[0] = "Minimera ";
            $("span", this).text(textArr[0] + textArr[1]);
            $("img", this).attr("src", "/Images/Dp/toggle_min.gif");
            $(this).next().slideDown('fast');
        });
}


function AttachTruncate(jExp) {
    $(".truncate", jExp).expander();
}


function GetUpdatePanelId(objects, searchPanel) {
    if (objects == null) return;
    objects = objects.replace(/\$/g, '_');

    var arrMatch = objects.match(searchPanel);
    if (arrMatch != null && arrMatch.length > 0)
        objects = objects.match(searchPanel);

    objects = objects.toString();
    l = objects.toString().length;
    if (objects.lastIndexOf("_", l) == l - 1) {
        objects = objects.substr(0, l - 1);
    }
    return objects;
}

function GetInvokedPanel(sender) {
    var isMatch = false;
    
    var allIDs = sender._updatePanelIDs;
    var invokedFrom = sender._postBackSettings.panelsToUpdate[0];
    
    if (invokedFrom && sender._postBackSettings.sourceElement && sender._postBackSettings.async) {
        var pId = invokedFrom.substring(0, invokedFrom.indexOf('|'));
        for (var i = 0; i < allIDs.length; i++) {
            if (pId == allIDs[i]) {
                // We found original panel
                isMatch = true;
                break;
            }
        }
    }

    if (isMatch) { return pId; } else { return ""; }
}


function AttachButtons() {
//    var selector = "input[type=submit],input[type=button],button";
//    $(selector).button();
//    //$(selector).not(".hide").show();
//    $("input.hide").hide(); // fix because buttons that have hide class are not hidden by default.
}

function AttachQTips() {
    $('.qtip:visible').qtip('destroy'); // remove all visible qtips laying around.

    // create qtips for all tooltip2 elements.
    target = $("a.tooltip2"); 
    //target.unbind();
    target.click(function() { return false; });
    AttachCommentsToTarget(target);

    // create qtips for all dom elements with the title attribute.
    var target = $("[title]").filter(function() {
        return $(this).attr("title").length > 0; // remove all elements that have an emtpy title.
    }); 
    AttachCommentsToTarget(target);
}


function KeepAliveTimer() {
    //console.log("KeepAliveTimer");
    var timer = $(window).data("KeepAliveTimer");
    if (timer) {
        timer.stop();
        //console.log("timer.stop();");
    }

    var keepAliveLimit = 3;
    // Every 10 minutes, call a server page to refresh the session
    timer = $.timer(10 * 60 * 1000, function (timer) {

        // Stays alive a certain amount of time
        if (keepAliveLimit == 0) {
            timer.stop();
            return;
        }
        keepAliveLimit--;

        // Shows a message
        $.blockUI({ message: $('#pageRefresh'),
            css: {
                padding: '10px',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px'
            }
        });
        setTimeout(jQuery.unblockUI, 2000);

        // Calls a handler
        $.ajax({
            type: "POST",
            url: "/HttpHandlers/KeepAlive.ashx",
            success: function (msg) {
                $(".keepAliveWarn").show();
            }
        });
    });

    $(window).data("KeepAliveTimer", timer);
    $(".keepAliveWarn").hide();
}

// -----------------------------------------------------------------------------------------------------

// this function runs on every postback, to ensure ensure diffrent skript functions.
function RunOnEveryRequest() {
    $(function () {
        AttachQTips();
        //AttachButtons();
    });
}


function OnInitializeRequest() {
    // Center the update progress image div
//    console.log("TET");
//    $('div#ClamTreeUpdateProgress .UpdatePanelProgress').position({
//        of: $(window),
//        my: "center",
//        at: "center"
//    });
}

function ClamTreeInitialize() 
{
    prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_pageLoaded(RunOnEveryRequest);
    prm.add_initializeRequest(OnInitializeRequest);
}


/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function () {
    var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/;

    // The base Class implementation (does nothing)
    this.Class = function () { };

    // Create a new Class that inherits from this class
    Class.extend = function (prop) {
        var _super = this.prototype;

        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        initializing = true;
        var prototype = new this();
        initializing = false;

        // Copy the properties over onto the new prototype
        for (var name in prop) {
            // Check if we're overwriting an existing function
            prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function (name, fn) {
            return function () {
                var tmp = this._super;

                // Add a new ._super() method that is the same method
                // but on the super-class
                this._super = _super[name];

                // The method only need to be bound temporarily, so we
                // remove it when we're done executing
                var ret = fn.apply(this, arguments);
                this._super = tmp;

                return ret;
            };
        })(name, prop[name]) :
        prop[name];
        }

        // The dummy class constructor
        function Class() {
            // All construction is actually done in the init method
            if (!initializing && this.init)
                this.init.apply(this, arguments);
        }

        // Populate our constructed prototype object
        Class.prototype = prototype;

        // Enforce the constructor to be what we expect
        Class.prototype.constructor = Class;

        // And make this class extendable
        Class.extend = arguments.callee;

        return Class;
    };
})();

