$(function() {

    $(document).bind('ajaxStart.loader', function() {
        window.clearTimeout($.loaderSettings.hide);
        if (!$.loaderSettings.load) {
            if (!$.loaderSettings.init) {
                if ($('#jg_loader_container').length == 0) $('body').append('<div id="jg_loader_container"><div id="jg_loader"><div></div></div></div>');
                $.loaderSettings.width = $('#jg_loader div').css('width');
                $.loaderSettings.init = true;
            }
            $.loaderSettings.load = true;
            $.loaderSettings.timeout = window.setTimeout(function() {
                $('#jg_loader_container').show();
                _playLoader();
            }, $.loaderSettings.delay);
        }
    }).bind('ajaxStop.loader ajaxError.loader', function() {
        _hideLoader();
    }).ajaxError(function(info, xhr) {
        try {
            if (xhr.status != 200) {
                var err = eval("(" + xhr.responseText + ")");

                // additional error handling.
                if (typeof errorHandle == 'function') {
                    errorHandle(err);
                }
                if (err.Redirect != null) {
                    window.location = err.Redirect;
                } else {
                    $.showError(err.Message);
                }
            }
        }
        catch (e) {
            if (typeof debugHandler == 'function') {
                debugHandler(xhr.responseText);
            }
            $.showError("Er is een FOUT opgetreden (" + e.message + ").");
        }
    });

    var _playLoader = function() {
        if ($.loaderSettings.load) {
            $('#jg_loader div').animate({
                left: $(window).width() + 'px'
            }, $.loaderSettings.animate, function() {
                $('#jg_loader div').css('left', '-' + $.loaderSettings.width);
                _playLoader();
            });
        }
    };

    var _hideLoader = function() {
        window.clearTimeout($.loaderSettings.timeout);
        $.loaderSettings.hide = window.setTimeout(function() {
            if ($.loaderSettings.width) $('#jg_loader div').stop().css('left', '-' + $.loaderSettings.width);
            $.loaderSettings.load = false;
            $('#jg_loader_container').hide();
        }, $.loaderSettings.hideDelay);
    };

    var _showMessage = function(message, type) {
        //no message to show, cancel
        if (message == undefined || message == "") {
            return false;
        }
        if (!$.messageSettings.init) {
            if ($('#jg_message').length == 0) {
                $('body').append(
                    '<div id="jg_message_container">' +
                        '<div id="jg_message">' +
                            '<div id="jg_message_inner">' +
                                '<div id="jg_message_hide"></div>' +
                                '<div id="jg_message_body"></div>' +
                            '</div>' +
                        '</div>' +
                    '</div>');
            }

            // Arrow click hides message almost instantaneously.
            $('#jg_message_hide').click(function(e) {
                _hideMessage(300, 1);
            });

            // Message hover induces "infinite" timeout which prevents the message from disappearing.
            $('#jg_message').mouseover(function(e) {
                _hideMessage(1, 99999999999999999);
            }).mouseout(function() {
                _hideMessage($.messageSettings.animate, 800);
            });

            $.messageSettings.init = true;
        }
        $('#jg_message_body').html(message);
        if (!$('#jg_message').hasClass('jg_expanded')) {
            $('#jg_message').css('top', -$('#jg_message').outerHeight() + 'px');
        }

        if ($('#jg_message.jg_expanded').exists()) {
            var bgColor = $('#jg_message').css('backgroundColor');
            $('#jg_message').css('background', '#fff');
            setTimeout(function() {
                $('#jg_message').css('background', bgColor);
            }, 100);
        }
        $('#jg_message').removeClass().addClass(type).animate(
            { top: 0 },
            $.messageSettings.animate,
            function() {
                $(this).addClass('jg_expanded');
                _hideMessage($.messageSettings.animate, 99999999999999999);
                $(document).bind('mousemove.jg_message', function(e) {
                    _hideMessage($.messageSettings.animate, $.messageSettings.show);
                    $(document).unbind('mousemove.jg_message');
                });
            }
        );
    };

    var _hideMessage = function(animate, delay) {
        clearTimeout($.messageSettings.timeout);
        $.messageSettings.timeout = window.setTimeout(function() {
            $('#jg_message').removeClass('jg_expanded').animate({
                top: -$('#jg_message').outerHeight() + 'px'
            }, animate);
        }, delay);
    };

    $.showMessage = function(message, type) {
        _showMessage(message, type);
    };

    $.showSuccess = function(message) {
        _showMessage(message, 'jg_success');
    };

    $.showWarning = function(message) {
        _showMessage(message, 'jg_warning');
    };

    $.showError = function(message) {
        _showMessage(message, 'jg_error');
    };

    $('a[rel="external"],a.external').click(function() {
        window.open($(this).attr('href'));
        return false;
    });

    if ($.fn.fancybox) {
        $('a.jg_lightbox').fancybox({
            titleShow: false,
            overlayOpacity: 0.5,
            overlayColor: '#000',
            centerOnScroll: true
        });
    }
});

(function($){  
    
    // To totally remove loader from a page, call $(document).unbind('.loader');
    $.loaderSettings = { animate: 1500, delay: 600, hideDelay: 700};
    $.messageSettings = { animate: 500, show: 5000};
    
    // Give focus to first available input.
    $.firstFocus = function(selector) {
        var focusSet = false;
        
        var wrappedSet = (selector) ? $(selector).find(":input") : $(":input");
       
        wrappedSet.not(":button, :image, :hidden").each(function(index) {
            if (!focusSet)
            {
                var $this = $(this);
                var setfocus = false;
                if ($this.is(':radio') && !$this.attr('checked'))
                {
                    setfocus = true;
                } else {
                    var val = $(this).val();
                    if (val != undefined && val.length == 0) {             
                        setfocus = true;
                    }
                }
                if (setfocus) {                
                    $(this).focus();
                    focusSet = true;
                    return true;
                }
            }
        })
        
        if (!focusSet)
        {
            $("input:first").not(':button, :image, :hidden').focus();
        }
    }

    // Post and return JSON.
    $.postJSON = function(url, data, succes) {
        $.post(url, data, succes, "json");
    }
    
    // Post and return JSON in the background
    $.postJSONbackground = function(url, data, succes) {
        //_disableLoader = true;
        $.postJSON(url, data, succes);
    }

    // higlight plugin required.
    $.fn.yellowFade = function() {
        return this.highlightFade({speed:2000});
    };

    $.escapeJs = function(val) {
        if (val)
        {
            return val.replace("\'", "\\'");
        }
        else
        {
            return val;
        }
    }

    $.fn.exists = function() {      
        return $(this).length > 0;
    };    

    $.fn.getClassNames = function() {
        if (name = this.attr("className")) {
            return name.split(" ");
        }
        else {
            return [];
        }
    };
    
    $.fn.reId = function(id) {
        return this.attr({id:id,name:id});
    };

    $.rootinize = function(url, culture) {
        if (url && url.length > 0) {
            // .net root url is tilde.
            if (url.charAt(0) == "~") url = url.substr(1);
            if (url.charAt(0) == "/")
                return (culture ? $.Mvc.url_root + url : $.Mvc.root + url);
            else
                return (culture ? $.Mvc.url_root + "/" + url : $.Mvc.root + "/" + url);         
        }
        else
            return (culture ? $.Mvc.url_root : $.Mvc.root);    
    };   
    
    $.unrootinize = function(url) {
        if (url && url.length > 0) 
            return url.toLowerCase().replace($.Mvc.url_root + '/', '').replace($.Mvc.root + '/', '');
        else
            return url;    
    };         

    $.fn.disableSelect = function(){
        if( $.browser.mozilla ) 
        {
            return $(this).each(function(){ 
                $(this).css('MozUserSelect', 'none'); 
            });
        } 
        else if( $.browser.msie ) 
        {
            return $(this).each(function(){ 
                $(this).bind('selectstart.disableTextSelect', function() { return false; }); 
            });
        } 
        else 
        {
            return $(this).each(function(){ 
                $(this).bind('mousedown.disableTextSelect', function() { return false; }); 
            });
        }  
    };
    
    $.fn.enableSelect = function(){
        if( $.browser.mozilla ) 
        {
            return $(this).each(function(){ 
                $(this).css('MozUserSelect', ''); 
            });
        } 
        else if( $.browser.msie ) 
        {
            return $(this).each(function(){ 
                $(this).unbind('selectstart.disableTextSelect');
            });
        } 
        else 
        {
            return $(this).each(function(){ 
                $(this).unbind('mousedown.disableTextSelect');
            });
        }  
    };
    
    // Calculate window overflow for a given element.
    // x: optional, added to the width overflow calculation.
    // y: optional, added to the height overflow calculation.
    $.fn.overflow = function(x, y){
        var offset = $(this).offset();
        return {
            width : offset.left + $(this).outerWidth() + (x || 0) - $(window).width() - $(window).scrollLeft(),
            height : offset.top + $(this).outerHeight() + (y || 0) - $(window).height() - $(window).scrollTop()
        };
    };

    $.getTimeStamp = function(){
        var newDate = new Date;
        return newDate.getTime();             
    };
        
    $.fn.outerHtml = function(){   
        return $('<div>').append(this.eq(0).clone()).html(); 
    };
    /* Cookie plugin
    Copyright (c) 2006 Klaus Hartl (stilbuero.de)
    Dual licensed under the MIT and GPL licenses:
    http://www.opensource.org/licenses/mit-license.php
    http://www.gnu.org/licenses/gpl.html 
    example: $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); */
    $.cookie = function(name, value, options){
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        }
        else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
})(jQuery);

String.prototype.brToNewLine = function(){ return this.replace(/<[bB][rR]\s*\/?>/g, '\n'); };
String.prototype.ltrim = function () { return this.replace(/^\s+/,""); };
String.prototype.rtrim = function () { return this.replace(/\s+$/,""); }; 
String.prototype.trim = function () { return this.ltrim().rtrim(); };
String.prototype.cur = function () { return this.replace(".", ","); };
String.prototype.uncur = function () { return this.replace(/\./g, ''); };
String.prototype.uncurdot = function () { return this.replace(/\./g, '').replace(",", "."); };
