﻿(function($)
{
    $.GenerateUUID = function()
    {
        var i,
            c = "89ab",
            u = [];
        for (i = 0; i < 36; i += 1)
        {
            u[i] = (Math.random() * 16 | 0).toString(16);
        }
            u[8] = u[13] = u[18] = u[23] = "-";
        u[14] = "4";
        u[19] = c.charAt(Math.random() * 4 | 0);
        return u.join("");
    };
})(jQuery);

(function($)
{
    $.fn.AnimatOutIn = function(className)
    {
        var t = this;
        t.addClass(className);
        window.setTimeout(function()
        {
            t.fadeOut('slow',
                function()
                {
                    t.fadeIn('slow', function() { t.removeClass(className); });
                });
        }, 200);
        return this;
    }
})(jQuery);


(function($)
{
    $.fn.log = function(msg)
    {
        if (typeof (console) != "undefined")
        {
            if (!!msg)
                console.log(msg);
            else
                console.log(this);
        }
        return this;
    };

    $.log = function(msg)
    {
        if ( typeof(console) != "undefined" && !!msg)
            console.log(msg);
    };
})(jQuery);

(function($)
{
    var idiv = null;

    jQuery.fn.PrintArea = function()
    {
        if (idiv != null)
            idiv.remove();

        var divID = $.GenerateUUID();
        var framename = $.GenerateUUID();
        var target = framename;
        if( $.browser.msie )
            target = "_blank";

        idiv = $('<div id="' + divID + '"><form method="POST" target="' + target + '" action="/print"><input type="hidden" name="innerhtml" />' 
            + '<iframe name="' + framename + '"></iframe></form></div>');

        idiv.attr('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
        $("body").append(idiv);


        var t = $(this[0]);
        window.setTimeout(function()
        {
            $("#" + divID + " form input").val(t.html());
            $("#" + divID + " form").submit();
        }, 50);

        return this;
    }

})(jQuery);


(function($) {
    $.fn.Resize2Parent = function(callBack, bindTo) {
        return this.each(function(i) {
            var jq = $(this);
            var par = jq.parent();
            par.css("overflow", "hidden");
            if (bindTo == null)
                bindTo = $(window);

            var margins =
                    {
                        vertical: Math.max(0, jq.css("margin-top").cssVal2pixelVal(jq)
                            + jq.css("margin-bottom").cssVal2pixelVal(jq)),

                        horizontal: Math.max(0, jq.css("margin-left").cssVal2pixelVal(jq)
                            + jq.css("margin-right").cssVal2pixelVal(jq))
                    };

            bindTo.bind("resize", { el: jq, margins: margins, callback: callBack }, function(event) {
                var jq = event.data.el;
                var parent = event.data.el.parent();
                var margins = event.data.margins;

                var d = jq.outerWidth() - jq.width();
                try {
                    jq.width(parent.width() - d - margins.horizontal);
                }
                catch (e) { }

                d = jq.outerHeight() - jq.height();
                try
                {
                    jq.height(parent.height() - d - margins.vertical);
                }
                catch (e) { }

                if (event.data.callback != null)
                    event.data.callback();

            });
        });
    };

    $.TriggerResize2Parent = function() {
        $(window).resize();
    };


})(jQuery);



(function($)
{
    $.fn.zap = function()
    {
        this.filter("div, p, span, form, b, i, u, strong, label").each(function()
        {
            $(this.childNodes).insertBefore(this);
        }).remove();
        return this;
    };
})(jQuery);

(function($)
{
    $.fn.disable = function()
    {
        return this.attr("disabled", "disabled");
    };

    $.fn.enable = function()
    {
        return this.removeAttr("disabled");
    };
})(jQuery);

(function($)
{
    $.fn.AddWaitState = function(waitUrl, disable)
    {
        if (!!disable)
        {
            this.filter(":not(body)").attr("disabled", "disabled").each(function()
            {
                $(this).after('<img src="' + waitUrl + '" />');
            });
        }
        else
        {
            this.filter(":not(body)").each(function()
            {
                $(this).after('<img src="' + waitUrl + '" />');
            });
        }
        return this;
    };

    $.fn.RemoveWaitState = function()
    {
        this.filter(":not(body)").removeAttr("disabled").each(function()
        {
            $(this).next("img").remove();
        });
        return this;
    };
})(jQuery);

(function($)
{
    var rawBrowserInfoText = "";
    jQuery.each(jQuery.browser, function(i, val)
    {
        rawBrowserInfoText = rawBrowserInfoText + "<div>" + i + " : <span>" + val + "</span><br /></div>";
    });
    $.browser.toString = function()
    {
        return rawBrowserInfoText;
    };
})(jQuery);

(function($)
{
    $.fn.CaptureKeyUp = function(keyCode, callback)
    {
        var key = keyCode;
        this.keyup(function(e)
        {
            if (e.keyCode == key)
            {
                var returnValue;
                if (!!callback)
                    returnValue = callback.call(this);
                return !!returnValue ? returnValue : false;
            }
        });
        return this;
    };

    $.fn.CaptureKeyDown = function(keyCode, callback)
    {
        var key = keyCode;
        this.keydown(function(e)
        {
            if (e.keyCode == key)
            {
                var returnValue;
                if (!!callback)
                    returnValue = callback.call(this);
                return !!returnValue ? returnValue : false;
            }
        });
        return this;
    };

    $.fn.StopKeyDown = function(keyCode)
    {
        var key = keyCode;
        this.keydown(function(e)
        {
            if (e.keyCode == key)
            {
                event.preventDefault();
                return false;
            }
        });
        return this;
    };
})(jQuery);

/*
The callback recieves an object as parameter with the following properties
event: The keyup event
isCapsLock: Boolean stating wether capslock is turned on
*/
(function($)
{
    $.fn.CapsLockControll = function(callback)
    {
        if (!!callback)
        {
            this.keyup(function(e)
            {
                var res = {};
                res.event = e;
                res.isCapsLock = false;

                var value = $(this).val();

                if (value.length != 0)
                {
                    var c = value.substr(value.length - 1, 1);
                    if ((c != c.toLowerCase() && !e.shiftKey) || (c != c.toUpperCase() && e.shiftKey))
                    {
                        if (e.keyCode != 8 && e.keyCode != 16)
                        {
                            res.isCapsLock = true;
                        }
                    }
                }
                callback.call(this, res);
                return false;
            });
        }
        return this;
    }
})(jQuery);


/*
$.fn.AddPulse:
Adds a timer that's connected to an element through it's ID. Only elements with an ID set can be used.
                    
@Param intervall  (int)  : The intervall in milliseconds that shall have passed before the callback is called.
@Param callback  (function)  : The function to call when the desired intervall has been reaced.
                    
@Returns JQuery set: Returns the JQuery set after operations have been completed on it.
                
$.fn.RemovePulse:
Removes the timer on each element that has their ID connected to a timer.
                    
@Param intervall  (int)  : The intervall in milliseconds that shall have passed before the callback is called.
@Param callback  (function)  : The function to call when the desired intervall has been reaced.
                    
@Returns JQuery set: Returns the JQuery set after operations have been completed on it.
                
$.HeartBeat:
Used to start/stop the timers and remove all added timers
                    
Start:
Starts polling all timers
            
@Param intervall: The intervall to check the timers if they are to have their callbacks executed
                
Stop:
Stops all timers
                    
Clear:
Removes all timers
*/
(function($)
{
    var listeners = {};
    var started = false;
    var key = null;

    $.fn.AddPulse = function(intervall, callback)
    {
        return this.each(function()
        {
            if (this.id != null && this.id != "")
            {
                listeners[this.id] = {
                    element: this,
                    pulse: callback,
                    intervall: intervall,
                    lastCalled: new Date().valueOf()
                };
            }
        });
    };

    $.fn.RemovePulse = function()
    {
        return this.each(function()
        {
            if (this.id != null && this.id != "")
            {
                delete listeners[this.id];
            }
        });
    };

    $.HeartBeat = {
        Start: function(intervall)
        {
            if (started == false)
            {
                started == true;
                key = window.setInterval(function()
                {
                    DoPulse();
                }, intervall);
            }
        },
        Stop: function()
        {
            if (key != null)
            {
                window.clearInterval(key);
                key = null;
                started = false;
            }
        },
        Clear: function()
        {
            listeners = {};
        }
    };

    function DoPulse()
    {
        for (l in listeners)
        {
            if (listeners[l] != null)
            {
                if ($("#" + [l]).length > 0)
                {
                    if (new Date().valueOf() - listeners[l].lastCalled >= listeners[l].intervall)
                    {
                        listeners[l].lastCalled = new Date().valueOf();
                        listeners[l].pulse();
                    }
                }
                else
                {
                    delete listeners[l];
                }
            }
        }
    };
})(jQuery);

/*
JQuery UI is needed for the following extension
            
$.OpenDialog:
Dynamically creates a dialog based on JQuery UI that is removed from the DOM when closed.
                                
@Param options  (object)  : Parameters for the dialog setup.
@Param buttons  (object)  : Button functions.
Buttons will automatically close the dialog.
Return false in the callback to prevent this.
@Param message  (string)  : The contents of the dialog.
@Param header   (string)  : The title of the dialog.
@Param callback (function): Optional callback that is passed the JQuery wrapped dialog element.
If callback is used the dialog will not automatically open.
The returned dialog then exposes open() and close() which allows showing/hiding it.
NOTE: If the dialog is not opened or removed in the callback, it will not be removed from the DOM.

$.CloseAllDialogs:
Closes all open JQuery UI dialogs

$.LoadUrlInDialog:
Wraps $.OpenDialog and loads the contents of a specific url to the dialog before showing it.
                
@Param options  (object)  : Parameters for the dialog setup.
@Param buttons  (object)  : Button functions.
@Param header   (string)  : The title of the dialog.
@Param url      (string)  : The url to load.
@Param data     (string)  : Optional data object to send.
If it is included the request will be sent as POST, otheriwse GET is used.
@Param callback (function): Optional callback that is passed the JQuery wrapped dialog element.
If callback is used the dialog will not automatically open.
The returned dialog then exposes open() and close() which allows showing/hiding it.
NOTE: If the dialog is not opened or removed in the callback, it will not be removed from the DOM.
        
$.LoadUrlInIFrameDialog:
Wraps $.OpenDialog and loads the contents of a specific url to a borderless iFrame that is inserted in to the dialog.
The iFrame will resize and automatically fit the dialog.

@Param options  (object)  : Parameters for the dialog setup.
@Param buttons  (object)  : Button functions.
@Param header   (string)  : The title of the dialog.
@Param url      (string)  : The url to load.
If it is included the request will be sent as POST, otheriwse GET is used.
@Param callback (function): Optional callback that is passed the JQuery wrapped dialog element.
If callback is used the dialog will not automatically open.
The returned dialog then exposes open() and close() which allows showing/hiding it.
NOTE: If the dialog is not opened or removed in the callback, it will not be removed from the DOM.

*/
(function($)
{
    $.OpenDialog = function(options, buttons, message, header, callback)
    {
        if (!header)
            header = " ";
            
//        It's possible to use the following logic to always display a dialog in the root parent
//      
//        var theParent = window.parent;
//        while (theParent.parent != theParent)
//            theParent = theParent.parent;
//        var dialog = theParent.$('<div title=""></div>');

        var dialog = $('<div title=""></div>');
        dialog.insertAfter("body:last-child");
        var standardoptions = {
            title: header,
            bgiframe: true,
            autoOpen: false,
            height: 200,
            width: 300,
            resizable: "se",
            modal: true
        };
        if (options != null)
        {
            standardoptions = $.extend(standardoptions, options);
        }
        var windowHeight = $(window).height();
        if (windowHeight <= standardoptions.height)
        {
            standardoptions.height = windowHeight - 5;
        }
        var windowWidth = $(window).width();
        if (windowWidth <= standardoptions.width)
        {
            standardoptions.width = windowWidth - 5;
        }

        dialog.dialog(standardoptions);
        dialog.html(message);
        dialog.open = function() { dialog.dialog('open'); };
        dialog.close = function() { dialog.dialog('close'); };

        dialog.dialog('option', 'close', function(event, ui)
        {
            if (options != null && !!options['close'])
                options['close'].call();
            dialog.remove();
        });
        var butts = {};
        for (b in buttons)
        {
            butts[b] = SetFunction(dialog, buttons[b]);
        }
        dialog.dialog('option', 'buttons', butts);

        if (!!callback)
        {
            callback.call(null, dialog);
        }
        else
        {
            dialog.open();
        }
    }

    $.CloseAllDialogs = function()
    {
        $(".ui-dialog-content").dialog('close');
    };

    $.LoadUrlInDialog = function(options, buttons, header, url, data, callback)
    {
        $.OpenDialog(options, buttons, "", header, function(dialog)
        {
            var funct = function(responseText, textStatus, XMLHttpRequest)
            {
                switch (XMLHttpRequest.status)
                {
                    case 200:
                        if (!!callback)
                        {
                            callback.call(null, dialog);
                        }
                        else
                        {
                            dialog.open();
                        }
                        break;

                    default:
                        dialog.close();
                        break;
                }
            };
            if (!!data)
                dialog.load(url, data, funct);
            else
                dialog.load(url, funct);
        });
    };

    $.LoadUrlInIFrameDialog = function(options, buttons, header, url, callback)
    {
        var iFrame = $('<iframe id="' + $.GenerateUUID() + '" frameborder="0" src="' + url + '" ></iframe>');
        $.OpenDialog(options, buttons, "", header, function(dialog)
        {
            dialog.append(iFrame);
            iFrame.Resize2Parent();

            if (!!callback)
            {
                var openFunct = dialog.open;
                dialog.open = function()
                {
                    openFunct();
                    
                }
                callback.call(dialog);
            }
            else
            {
                dialog.open();
                window.setTimeout($.TriggerResize2Parent, 50);
            }
        });
    };

    function SetFunction(dialog, funct)
    {
        return function()
        {
            var res = funct.call();
            if (res == null || res == true)
                dialog.close();
        };
    };
})(jQuery);

(function($)
{
    $.fn.FileInputStyleAgain = function()
    {
        this.filter("input:file").each(function()
        {
            var t = $(this);
            $("#" + this.id + "_fake")
                .css("width", t.outerWidth() - $("#" + this.id + "_fakebutton").outerWidth());

            t.css("margin-left", -t.width() + "px");
                
                
        });
        return this;
    }

    $.fn.FileInputStyler = function(options)
    {
        this.filter("input:file").each(function()
        {


            fileInput = $(this).css({
                "text-align": "right",
                "-moz-opacity": "0",
                "filter": "alpha(opacity: 0)",
                "filter": "progid:DXImageTransform.Microsoft.Alpha(opacity=0)",
                "opacity": "0",
                "z-index": "2"
            });


            var fakeText = $('<input type="text" />').attr("id", this.id + "_fake");
            var fakeBrowseButton = $('<input type="button"  value="' + options.browseText + '" />').attr("id", this.id + "_fakebutton").css("z-index", "1");
            var fakeBrowseButton = $('<input type="button"  value="' + options.browseText + '" />').attr("id", this.id + "_fakebutton").css("z-index", "1");
            var clearButton = $('<input type="button" value="' + options.clearText + '" />').attr("id", this.id + "_clear")
                .css("z-index", "1")
                .css("margin-left", "20px");
            
            fileInput.before(fakeText);
            fileInput.before(fakeBrowseButton);

            fileInput.after(clearButton);

            window.setTimeout(function()
            {
                fakeText.css("width", fileInput.outerWidth() - fakeBrowseButton.outerWidth());
                fileInput.css("margin-left", -fileInput.width() + "px" );
            }, 50);

            fileInput[0].fakeTextBox = fakeText[0];
            clearButton[0].realInput = fileInput[0];
            clearButton.click(function()
            {
                this.realInput.fakeTextBox.value = "";
                this.realInput.value = "";
                var inp = $(this.realInput);
                window.setTimeout(function()
                {
                    inp.change();
                }, 20);
            });

            var funct = function()
            {
                if (this.value != "")
                {
                    var filePath = this.value.split('\\');
                    this.fakeTextBox.value = filePath[filePath.length - 1];
                }
                else
                    this.fakeTextBox.value = "";

                var t = $(this.fakeTextBox);
                window.setTimeout(function()
                {
                    t.trigger("change");
                }, 50);
            };
            fileInput.change(funct);

            if ($.browser.msie == false)
            {
                fileInput.focus(function()
                {
                    fakeBrowseButton.trigger("focus");
                });
                fileInput.blur(function()
                {
                    fakeBrowseButton.trigger("blur");
                });
            }
            fileInput.hover(function()
            {
                fakeBrowseButton.trigger("mouseover");
            }, function()
            {
                fakeBrowseButton.trigger("mouseout");
            });
        });
        return this;
    };
})(jQuery);




/*-------------------------------------------------------------------- 
* javascript method: "pxToEm"
* by:
Scott Jehl (scott@filamentgroup.com) 
Maggie Wachs (maggie@filamentgroup.com)
http://www.filamentgroup.com
*
* Copyright (c) 2008 Filament Group
* Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
*
* Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
* Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
* Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
*							
* Options:  	 								
scope: string or jQuery selector for font-size scoping
reverse: Boolean, true reverses the conversion to em-px
* Dependencies: jQuery library						  
* Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
*
* Version: 2.0, 08.01.2008 
* Changelog:
*		08.02.2007 initial Version 1.0
*		08.01.2008 - fixed font-size calculation for IE

*       2010 02 01 - changed to auto mode (px/em) by inpecting. Returning no "px" or "em" at end  /Staffan S

--------------------------------------------------------------------*/
(function($)
{
    String.prototype.cssVal2pixelVal = function(settings)
    {
            var value = parseFloat(this);
        if (this.toLowerCase().indexOf("px") > -1)
            return value;

        if (isNaN(value) == true)
            return 0;

        settings.reverse = false;
        return  this.pxToEm(settings);
    }


    Number.prototype.pxToEm = String.prototype.pxToEm = function(settings)
    {
        //set defaults
        settings = jQuery.extend({
            scope: 'body',
            reverse: false
        }, settings);


        var pxVal = (this == '') ? 0 : parseFloat(this);
        var scopeVal;
        var getWindowWidth = function()
        {
            var de = document.documentElement;
            return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
        };

        /* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
        For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
        When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
        to get an accurate em value. */

        if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0)
        {
            var calcFontSize = function()
            {
                return (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(3) * 16;
            };
            scopeVal = calcFontSize();
        }
        else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };

        var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) : (pxVal / scopeVal).toFixed(2);


        return result;
    };

})(jQuery);
