var DOMLoaded = false;
$().ready(function() {
    DOMLoaded = true;

    /*$('.launchPad_dropZoneBar').hover(
        function() {
            $(this).find('.launchPad_dropZoneBarInner, .launchPad__ModuleHandle').slideDown(350);
        },
        function() {
            $(this).find('.launchPad_dropZoneBarInner, .launchPad__ModuleHandle').hide(0);
        }
    );*/

    /* TODO: Tooltips
    $('.launchPad__tip')*/
});

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

var _GLOBAL_LoadingHTML = '<img src="/__resource/LaunchPad.Core/Resources.Images/loading_icon.gif" style="border:0;vertical-align:middle;" alt="" /> Loading...';

function killEvent(e) {
    e.cancelBubble = true;
    e.returnValue = false;
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}

function __mps(text) {
    if (text && text.indexOf) {
        if (text.indexOf('/') > -1) {
            text = text.replace(/\//g, '{{SLASH}}');
        }
        if (text.indexOf('&') > -1) {
            text = text.replace(/\&/g, '{{ANDAMP}}');
        }
        if (text.indexOf('&') > -1) {
            text = text.replace(/\+/g, '{{PLUS}}');
        }
    }
    return text;
}

function __fnMakeUpdateCall(type, method, params, onComplete) {
    __fnMakeCustomUpdateCall('/__service/' + type + '/' + method + '/default.aspx', 'POST', '__ServiceParameters=' + params, onComplete);
}

function __fnMakeCustomUpdateCall(url, verb, body, onComplete) {

    switch (verb.toLowerCase()) {
        case 'get':
            $.get(url, onComplete);
            break;
        case 'post':
            $.post(url, body, onComplete);
            break;
    }
}

function launchPadLogOut(callback) {
    $.postJSON('/__service/LaunchPad.Core.LaunchPadUser/DoLogout', { logout: 1 }, function(logOutResponse) {
        if (typeof callback != 'undefined' && callback) {
            callback(logOutResponse);
        }
    });
}

(function($) {
    $.fn.enterPressed = function(callback) {
        return this.keypress(function(e) {
            var code = e.keyCode || e.which;
            if (code == 13) {
                return callback();
            }
            return true;
        });
    };
})(jQuery);

(function($) {
    $.fn.escapePressed = function(callback) {
        return this.keypress(function(e) {
            var code = e.keyCode || e.which;
            if (code == 27) {
                return callback();
            }
            return true;
        });
    };
})(jQuery);

(function($) {
    $.fn.notification = function(message, timeout, callback) {
        return $(this).each(function() {
            var me = $(this);
            me.prepend($('<div class="launchPadNotification" style="display: none;">' + message + '</div>'));
            var note = me.find('.launchPadNotification');

            if (me.css('textAlign') == 'left') {
                note.css({
                    position: 'relative',
                    left: parseInt((parseInt(me.width()) - parseInt(note.width())) / 2) + 'px'
                });
            }
            note.fadeIn(250);

            note.click(function() {
                $(this).fadeOut(250, function() { $(this).remove(); });
            });
            if (typeof timeout != 'undefined') {
                window.setTimeout(function() {
                    note.fadeOut(250, function() {
                        note.remove();
                    });
                    if (typeof callback != 'undefined' && callback) {
                        callback();
                    }
                }, timeout);
            }
        });
    }
})(jQuery);

(function($) {
    $.fn.renderTemplate = function(type, template, instance, callback) {
        $(this).setRenderTemplate(type, template, instance, null);
        $(this).render(callback);
    }
})(jQuery);

(function($) {
    $.fn.setRenderTemplate = function(type, template, instance, callback) {
        return $(this).each(function() {
            var thisRef = this;
            if (typeof instance == 'undefined' || instance == null) {
                instance = '';
            }
            var renderData = {
                type: type,
                template: template,
                instance: instance,
                callback: callback
            };
            $(this).data('launchPadRenderTemplate', renderData);
        });
    }
})(jQuery);

(function($) {
    $.fn.render = function(callback) {
        return $(this).each(function() {
            var thisRef = this;
            var renderTemplate = $(this).data('launchPadRenderTemplate');
            if (typeof renderTemplate != 'undefined' && renderTemplate) {
                $.postJSON('/__service/LaunchPad.Core.ObjectTemplate/RenderTemplateT=' + renderTemplate.type, { Template: renderTemplate.template, Instance: renderTemplate.instance }, function(renderTemplateResponse) {
                    $(thisRef).html(renderTemplateResponse.markup);
                    if (typeof renderTemplate.callback == 'function') {
                        renderTemplate.callback(renderTemplateResponse);
                    }
                    
                    if (typeof refreshTriggers[thisRef.id] != 'undefined') {
                        $(refreshTriggers[thisRef.id]).each(function() {
                            this();
                        });
                    }

                    $(thisRef).find('*').each(function() {
                        var subElementId = $(this).attr('id');
                        if (subElementId.length > 0 && typeof refreshTriggers[subElementId] != 'undefined') {
                            $(refreshTriggers[subElementId]).each(function() {
                                this();
                            });
                        }
                    });
                    
                    if (typeof callback != 'undefined' && callback) {
                        callback(renderTemplateResponse);
                    }
                });
            }
        });
    }
})(jQuery);

var refreshTriggers = {};
$.refreshTrigger = function(id, trigger) {
    if (typeof refreshTriggers[id] == 'undefined' || !refreshTriggers[id]) {
        refreshTriggers[id] = [];
    }
    if (typeof trigger != 'function') {
        switch (trigger) {
            case 'clear':
                refreshTriggers[id] = [];
                break;
            case 'clearRecurse':
                $('#' + id + ' *').each(function() {
                    if ($(this).attr('id').length > 0) {
                        $.refreshTrigger($(this).attr('id'), 'clear');
                    }
                });
                break;
        }
    } else {
        refreshTriggers[id].push(trigger);
    }
};

(function($) {
    $.fn.refresh = function(callback) {
        return $(this).each(function() {
            var thisRef = this;
            var renderTemplate = $(this).data('launchPadRenderTemplate');
            if (typeof renderTemplate != 'undefined' && renderTemplate) {
                $(this).render(callback);
            } else {
                $.get(location.href, function(getPageResponse) {
                    var refreshableStart = '<!--RefreshableStart_' + thisRef.id + '-->';
                    var refreshableEnd = '<!--RefreshableEnd_' + thisRef.id + '-->';
                    getPageResponse = getPageResponse.substr(getPageResponse.indexOf(refreshableStart) + refreshableStart.length);
                    getPageResponse = getPageResponse.substr(0, getPageResponse.indexOf(refreshableEnd));
                    $(thisRef).html(getPageResponse);

                    if (typeof refreshTriggers[thisRef.id] != 'undefined') {
                        $(refreshTriggers[thisRef.id]).each(function() {
                            this();
                        });
                    }

                    $(thisRef).find('*').each(function() {
                        var subElementId = $(this).attr('id');
                        if (subElementId.length > 0 && typeof refreshTriggers[subElementId] != 'undefined') {
                            $(refreshTriggers[subElementId]).each(function() {
                                this();
                            });
                        }
                    });

                    if (typeof callback != 'undefined' && callback) {
                        callback();
                    }
                });
            }
        });
    }
})(jQuery);

var dataObjectFormDefaults = {
    dataObjectId: '',
    instanceId: '',
    postVars: {},
    type: '',
    template: '',
    saveMethod: '',
    onLoad: function() { },
    onPreSave: function(obj) { },
    onSave: function() { },
    onCancel: function() { }
};
(function($) {
    $.fn.dataObjectForm = function(options) {

        options = $.extend({}, dataObjectFormDefaults, options);
        var dataObjectFormBaseUrl = '/__service/LaunchPad.Core.DataObjectFormT=' + options.type + '/';

        return $(this).each(function() {
            var target = $(this);

            var postData = { DataObjectID: options.dataObjectId, InstanceID: options.instanceId, Template: options.template };
            postData = $.extend(postData, options.postVars);
            $.postJSON(dataObjectFormBaseUrl + 'GetForm', postData, function(getFormResponse) {

                var dObj = getFormResponse.item;
                target.html(getFormResponse.markup);

                target.find('.btnCancel').click(function() {
                    options.onCancel();
                });

                target.find('.btnSave').click(function() {

                    target.find('.formRow').each(function() {
                        var ctl = $($(this).find('.formRowContent:first *:first-child'));
                        dObj[ctl.attr('rel')] = ctl.val();
                    });

                    delete dObj.Date_Created;
                    delete dObj.Date_Modified;
                    delete dObj.Expiry_Date;

                    options.onPreSave(dObj);

                    var savePostData = { DataObjectID: options.dataObjectId, InstanceID: options.instanceId, DataObject: $.compactJSON(dObj), SaveMethod: options.saveMethod };
                    savePostData = $.extend(savePostData, options.postVars);
                    $.postJSON(dataObjectFormBaseUrl + 'Save', savePostData, function(saveResponse) {
                        options.onSave(saveResponse);
                    });
                });

                target.find('.formRowContent input').each(function() {
                    $(this).enterPressed(function() {
                        target.find('.btnSave').click();
                        return false;
                    });
                    $(this).escapePressed(function() {
                        options.onCancel();
                        return false;
                    });
                });

                target.find('.formRowContent input:first').focus().select();

                options.onLoad();
            });
        });
    }
})(jQuery);

(function($) {
    $.fn.center = function() {
        return $(this).each(function() {
            $(this).css({
                marginTop: parseInt($(this).css('marginTop'), 10) + jQuery(window).scrollTop(),
                marginLeft: parseInt($(this).css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        });
    }
})(jQuery);

jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({ opacity: 'toggle' }, speed, easing, callback);
};

function launchPad__DataObjectSave(id, dataObjectType, collectionID, onSaveMethod, userVersion, languageVersion, extraInfoID, fieldNames, formIDs, types) {
    var fields = fieldNames.split('|');
    var ids = formIDs.split('|');
    var fieldTypes = types.split('|');
    var params = 'DataObjectID=' + id + '/DataObjectType=' + dataObjectType + '/DataObjectCollectionID=' + collectionID + '/UserVersion=' + userVersion + '/LanguageVersion=' + languageVersion + '/OnSaveMethod=' + onSaveMethod + '/CreateNotifications=' + $('#cn_' + extraInfoID).value + '/';

    for (var i = 0; i < ids.length; i++) {
        if (fieldTypes[i] != '') {
            var v = launchPad__DataObjectGetValue(fieldTypes[i], ids[i]);
            if (v.indexOf != null && v.indexOf != 'undefined') {
                v = __mps(v);
            }
            params += fields[i] + '=' + v + '/';
        }
    }

    __fnMakeUpdateCall('LaunchPad.Core.Web.Controls.DataObjectEditor', 'DataObjectSave', params, null);
}

function launchPad__DataObjectGetValue(type, field) {
    var v = '';
    switch (type) {
        case 'TextBox':
        case 'Password':
        case 'TextArea':
        case 'ImageSelector':
        case 'Page':
        case 'PageList':
        case 'GroupList':
        case 'PageSelector':
        case 'MultiPageSelector':
        case 'UserList':
        case 'ColourPicker':
        case 'DropDown':
        case 'DynamicDropDown':
        case 'LanguagePicker':
        case 'DataObject':

            if (type == 'Page' || type == 'PageList' || type == 'PageSelector' || type == 'MultiPageSelector') {
                field += '_selectedPages';
            }

            if ($('#' + field)) {
                v = $('#' + field).val();
            }

            break;
        case 'HTML':

            try {
                var oEditor = FCKeditorAPI.GetInstance(field);
                if (oEditor != null) {
                    v = oEditor.GetHTML();
                }
            }
            catch (e) { }

            break;
        case 'Date':
            var vDateField = $find(field);
            if (vDateField) {
                v = vDateField.get_selectedDate();
                try {
                    v = v.format('dd-MM-yyyy');
                }
                catch (e) { }
            }
            break;
        case 'Checkbox':
            if ($('#' + field)[0].checked) {
                v = 'true';
            }
            else {
                v = 'false';
            }
            break;
    }
    return v;
}

function launchPad__DataObjectSetValue(ctlType, ctlID, ctlValue) {
    switch (ctlType) {
        case 'TextBox':
        case 'Password':
        case 'TextArea':
        case 'ImageSelector':
        case 'ColourPicker':
        case 'DataObject':
        case 'LanguagePicker':
        case 'DropDown':

            $('#' + ctlID).val(ctlValue);

            if (ctlType == 'ImageSelector') {
                GetSelectedFileHTML(ctlID + '_c');
            }

            break;
        case 'HTML':

            try {
                var oEditor = FCKeditorAPI.GetInstance(ctlID);
                if (oEditor != null) {
                    oEditor.SetHTML(ctlValue);
                }
            }
            catch (e) { }

            break;

        case 'DynamicDropDown':
            var ddl = $('#' + ctlID)[0];

            ddl.options.length = 0;
            var dynamicIter = 0;
            var dynamicOptions = ctlValue.split('}}|{{');
            for (dynamicIter = 0; dynamicIter < dynamicOptions.length; dynamicIter++) {
                if (dynamicIter == (dynamicOptions.length - 1)) {
                    break;
                }
                var dynOpt = new Option(dynamicOptions[dynamicIter + 1], dynamicOptions[dynamicIter]);
                ddl.options[ddl.options.length] = dynOpt;
                dynamicIter++;
            }

            ctlValue = dynamicOptions[dynamicIter];
            $('#' + ctlID).val(ctlValue);
            break;
        case 'Date':
            if (ctlValue != '') {
                var vDateField = $find(ctlID);
                if (vDateField) {
                    vDateField.set_selectedDate(ctlValue);
                }
            }
            break;
        case 'Checkbox':
            if ($('#' + ctlID).length > 0) {
                if (ctlValue == 'true') {
                    $('#' + ctlID)[0].checked = true;
                }
                else {
                    $('#' + ctlID)[0].checked = false;
                }
            }
            break;
        case 'DataObjectCollection':
            try {
                eval("__dataObjectCollectionEditorInit_" + ctlID + "('" + ctlValue + "')");
            }
            catch (e) { }
            break;
        case 'Page':
        case 'PageList':
        case 'PageSelector':
        case 'MultiPageSelector':
            ctlID += '_selectedPages';
            $('#' + ctlID).val(ctlValue);
            eval('__rcmsPageSelectorUpdate(\'' + ctlID + '\')');
            break;
        case 'GroupList':
            $('#' + ctlID).val(ctlValue);
            eval('__rcmsGroupSelectorUpdate(\'' + ctlID + '\')');
            break;
        case 'UserList':
            $('#' + ctlID).val(ctlValue);
            eval('__rcmsUserSelectorUpdate(\'' + ctlID + '\')');
            break;
    }
}

function launchPad__DataObjectEditInit(data) {
    var splitData = data.split('}}{{');
    for (var i = 0; i < splitData.length; i++) {
        var ctlID = splitData[i];
        var ctlType = splitData[i + 1];
        var ctlValue = splitData[i + 2];

        launchPad__DataObjectSetValue(ctlType, ctlID, ctlValue);

        i = i + 2;
    }
}

/* DataObjectCollection Editor */

var __dataObjectSelectorCache = new Array();

function __fnDataObjectCollectionEditor_Edit(objectType, id, collection, isSession, field, useField, critField)
{
    $('#' + id + '_wrapper').html(_GLOBAL_LoadingHTML);
    var perPage = $('#' + id + '_perpage').length > 0 ? $('#' + id + '_perpage').val() : '10';
    var filter = $('#' + id + '_filter').length > 0 ? $('#' + id + '_filter').val() : '';
    var bUse = $('#' + useField).length > 0 ? $('#' + useField).val() : 'u';
    var critConfig = $('#' + critField).length > 0 ? $('#' + critField).val() : '';

    $.post('/__service/LaunchPad.Core.Web.Controls.DataObjectSelector/GetHTML', {
        s: id,
        t: objectType,
        p: perPage,
        c: collection,
        f: field,
        fi: filter,
        u: bUse,
        uf: useField,
        cf: critField,
        cc: critConfig,
        is: isSession
    }, function (resp) {

        var split = resp.split('}}{{');
        var guid = split[0].trim();
        var field = split[3].trim();
        $('#' + guid + '_wrapper').html(split[1].trim());
        var ids = $('#' + field).val().split('|');
        
        for (var iter = 0; iter < ids.length; iter++)
        {
            if (ids[iter] != null && ids[iter] != '')
            {
                if ($('#' + field).val().indexOf(ids[iter] + '|') > -1)
                {
                    if ($('#' + ids[iter] + '_item').length > 0) {
                        $('#' + ids[iter] + '_item').hide(0);
                        $('#' + guid + '_currentItems').html('<div id="' + ids[iter] + '_selectedItem" style="padding: 3px; margin: 1px; border: 1px solid #c4c4c4; cursor: pointer;" onclick="__dataObjectSelectorToggleSelectedItem(guid, field, ids[iter]);">' + $('#' + ids[iter] + '_item').html() + '</div>');
                    } else {
                        /*if (__dataObjectSelectorCache[ids[iter]] == null)
                        {
                            $.post('/__service/LaunchPad.Core.Web.Controls.DataObjectSelector/GetDataObjectToString', { id: ids[iter] }, function(dObjToString) (
                                var dObjToStringSplit = dObjToString.split('}}{{');
                                __dataObjectSelectorCache[dObjToStringSplit[0]] = dObjToStringSplit[1];
                                $('#' + dObjToStringSplit[0] + '_selectedItem').html(dObjToStringSplit[1]);
                            });
                        }
                        $('#' + guid + '_currentItems').html('<div id=""' + ids[iter] + '_selectedItem"" style=""padding: 3px; margin: 1px; border: 1px solid #c4c4c4; cursor: pointer;"" onclick=""__dataObjectSelectorToggleSelectedItem(guid, field, ids[iter]);"">' + __dataObjectSelectorCache[ids[iter]] + '</div>');*/
                    }
                }
            }
        }

    });
}

function __dataObjectSelectorUpdateValues(critField, useField, id)
{
    if ($('#' + critField).length > 0 && $('#' + id + '_orderField').length > 0 && $('#' + id + '_order').length > 0 && $('#' + id + '_limit').length > 0)
    {
        var concatConfig = '';
        concatConfig += $('#' + id + '_orderField').val() + '}{';
        concatConfig += $('#' + id + '_order').val() + '}{';
        concatConfig += $('#' + id + '_limit').val() + '}{';
        concatConfig += $('#' + id + '_listformat').val() + '}{';
        concatConfig += $('#' + id + '_displayformat').val() + '}{';
        concatConfig += $('#' + id + '_whereField').val() + '}{';
        concatConfig += $('#' + id + '_whereOperator').val() + '}{';
        concatConfig += $('#' + id + '_whereValue').val();
        $('#' + critField).val(concatConfig);
    }
}

function __dataObjectSelectorToggleItem(element, guid, field, obj, txt)
{
    if ($('#' + field).val().indexOf(obj + '|') == -1)
    {
        $(element).hide(0);
        $('#' + field).val($('#' + field).val() + obj + '|');
        $('#' + guid + '_currentItems').html('<div id="' + obj + '_selectedItem" style="padding: 3px; margin: 1px; border: 1px solid #c4c4c4; cursor: pointer;" onclick="__dataObjectSelectorToggleSelectedItem(guid, field, obj);">' + txt + '</div>');
    }
}

function __dataObjectSelectorToggleSelectedItem(guid, field, obj)
{
    $('#' + obj + '_selectedItem').hide(0).attr('id', '_' + obj + '_selectedItem');
    $('#' + obj + '_item').show(0);
    $('#' + field).val($('#' + field).val().replace(obj + '|', ''));
}

(function($) {
    $.launchPad_DataObjectEditor = function(element, params) {
        var opts = {
            type: ''
        };
        opts = $.extend(opts, params);
    }
})(jQuery);

(function($) {
    $.launchPad_DataObjectSelector = function(ddl, params) {
        var opts = {
            type: '',
            allowCreate: false
        };
        opts = $.extend(opts, params);

        if (opts.allowCreate && 1 == 2) {
            var createLink = $('&nbsp;&nbsp;&nbsp;<a href="javascript:void(0);">Create...</a>');
            createLink.click(function() {
            });
            ddl.after(createLink);
        }
    }
})(jQuery);

function __updateDialogPos(id, width, fillPage) {

    var __dlg = $('#' + id);
    __dlg.css('position', 'absolute').css('z-index', $('#' + id + '_d').val() == '1' ? '600' : '800');

    if (fillPage) {
        $('#' + id + '_in').height((parseInt($(window).height()) * 0.9) + 'px');
        $('#' + id).width(Math.ceil(parseInt(vpWidth * 0.96)) + 'px').css('top', '1%').css('left', '1%');
    }
    else {
        if (parseInt(width) > 0) {
            __dlg.width(width + 'px');
        }

        if ($('#' + id + '_x').length > 0) {
            __dlg.css('left', $('#' + id + '_x').val() + 'px');
        }
        else {
            $('#' + id).css('left', Math.floor((vpWidth - parseInt(width)) / 2) + 'px');
        }

        if ($('#' + id + '_y').length > 0) {
            __dlg.css('top', $('#' + id + '_y').val() + 'px');
        }
        else {
            $('#' + id).css('top', (parseInt(parseInt(document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)) + 50) + 'px');
        }
    }
    $('#' + id).hide(0);
}

function __tmlSaveOrder(listid, type, method, pageid, zoneid) {
    if ($('#__' + listid + '_moduleOrder').val() != $('#' + listid).sortable('serialize')) {
        __fnMakeUpdateCall(type, method, 'PageID=' + pageid + '/ZoneID=' + zoneid + '/Order=' + __mps($('#' + listid).sortable('serialize')) + '/', null)
        $('#__' + listid + '_moduleOrder').val($('#' + listid).sortable('serialize'));
    }
}

/* Shade */

function launchPad__ShowShade(shadeID) {
    var scrollTop = parseInt(document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    $('#' + shadeID).height((parseInt(screen.height) + scrollTop) + 'px').width('100%').css('left', '0px').slideDown(500);
}

var vpWidth, vpHeight;

if (window.innerWidth) {
    vpWidth = window.innerWidth;
    vpHeight = window.innerHeight;
}
else if (document.documentElement && document.documentElement.clientWidth) {
    vpWidth = document.documentElement.clientWidth;
    vpHeight = document.documentElement.clientHeight;
}
else {
    if ($('body').length > 0) {
        vpWidth = $('body')[0].clientWidth;
        vpHeight = $('body')[0].clientHeight;
    }
}

function launchPad__GetWindowScrollTop() {
    var y;
    if (self.pageYOffset) {
        y = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        y = document.documentElement.scrollTop;
    }
    else if (document.body) {
        y = document.body.scrollTop;
    }
    return y;
}

function launchPad__GetWindowScrollLeft() {
    var x;
    if (self.pageYOffset) {
        x = self.pageXOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop) {
        x = document.documentElement.scrollLeft;
    }
    else if (document.body) {
        x = document.body.scrollLeft;
    }
    return x;
}

$().ready(function() {
    $('#launchPad__EditorShade').width(vpWidth + 'px').height(vpHeight + 'px').fadeTo('normal', 0.8);
});

/* Notifications */

  var __notificationsAllowRefresh = true;
  function __fnUpdateNotifications() {
    if (__notificationsAllowRefresh) {
        __notificationsAllowRefresh = false;
        $.get('/__service/LaunchPad.Core.Web.Controls.NotificationArea/GetServiceMessagesHTML', function(data) {


            __notificationsAllowRefresh = true;
            var notificationsDiv = $('#launchPad__Notifications');
            notificationsDiv.hide(0);
            if (notificationsDiv.html() != data) {
                notificationsDiv.html(data);

                if (notificationsDiv.find('li').length > 0) {
                    notificationsDiv.slideToggle(150);
                }
            }

            window.setTimeout('__fnUpdateNotifications()', 10000);
        });
    }
}

function __fnShowNotificationDesc(id) {
    $.get('/__service/LaunchPad.Core.Web.Controls.NotificationArea/GetNotificationText/ID=' + id, function(data) {
        $('#launchPad__NotificationDesc').html(data);
        $('#launchPad__NotificationDesc').css('bottom', parseInt(parseInt($('#launchPad__Notifications')[0].offsetHeight) + 10) + 'px');
        $('#launchPad__NotificationDesc').show(0);
    });
}

function __fnHideNotificationDesc() {
    $('#launchPad__NotificationDesc').hide(0);
}

/* JSON */

(function($) {
    function toIntegersAtLease(n)
    { return n < 10 ? '0' + n : n; }
    Date.prototype.toJSON = function(date) {
        return this.getUTCFullYear() + '-' +
toIntegersAtLease(this.getUTCMonth()) + '-' +
toIntegersAtLease(this.getUTCDate());
    }; var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g; var meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }
    $.quoteString = function(string) {
        if (escapeable.test(string)) {
            return '"' + string.replace(escapeable, function(a) {
                var c = meta[a]; if (typeof c === 'string') { return c; }
                c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"'
        }
        return '"' + string + '"';
    }
    $.toJSON = function(o, compact) {
        var type = typeof (o); if (type == "undefined")
            return "undefined"; else if (type == "number" || type == "boolean")
            return o + ""; else if (o === null)
            return "null"; if (type == "string")
        { return $.quoteString(o); }
        if (type == "object" && typeof o.toJSON == "function")
            return o.toJSON(compact); if (type != "function" && typeof (o.length) == "number") {
            var ret = []; for (var i = 0; i < o.length; i++) { ret.push($.toJSON(o[i], compact)); }
            if (compact)
                return "[" + ret.join(",") + "]"; else
                return "[" + ret.join(", ") + "]";
        }
        if (type == "function") { /*throw new TypeError("Unable to convert object of type 'function' to json.");*/ }
        ret = []; for (var k in o) {
            var name; var type = typeof (k); if (type == "number")
                name = '"' + k + '"'; else if (type == "string")
                name = $.quoteString(k); else
                continue; val = $.toJSON(o[k], compact); if (typeof (val) != "string") { continue; }
            if (compact)
                ret.push(name + ":" + val); else
                ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    }
    $.compactJSON = function(o)
    { return $.toJSON(o, true); }
    $.evalJSON = function(src)
    { return eval("(" + src + ")"); }
    $.secureEvalJSON = function(src) {
        var filtered = src; filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@'); filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")"); else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    }
})(jQuery);

/* Base64 */

(function($) {

    var keyString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    var uTF8Encode = function(string) {
        string = string.replace(/\x0d\x0a/g, "\x0a");
        var output = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                output += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                output += String.fromCharCode((c >> 6) | 192);
                output += String.fromCharCode((c & 63) | 128);
            } else {
                output += String.fromCharCode((c >> 12) | 224);
                output += String.fromCharCode(((c >> 6) & 63) | 128);
                output += String.fromCharCode((c & 63) | 128);
            }
        }
        return output;
    };

    var uTF8Decode = function(input) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < input.length) {
            c = input.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = input.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = input.charCodeAt(i + 1);
                c3 = input.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }

    $.extend({
        base64Encode: function(input) {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = uTF8Encode(input);
            while (i < input.length) {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2)) {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3)) {
                    enc4 = 64;
                }
                output = output + keyString.charAt(enc1) + keyString.charAt(enc2) + keyString.charAt(enc3) + keyString.charAt(enc4);
            }
            return output;
        },
        base64Decode: function(input) {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length) {
                enc1 = keyString.indexOf(input.charAt(i++));
                enc2 = keyString.indexOf(input.charAt(i++));
                enc3 = keyString.indexOf(input.charAt(i++));
                enc4 = keyString.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64) {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64) {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = uTF8Decode(output);
            return output;
        }
    });
})(jQuery);

/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* Name: jContext
* Version: 1.0 (April 28, 2008)
* Requires: jQuery 1.2+
*/
(function($) {
    $.fn.showMenu = function(options) {
        var opts = $.extend({}, $.fn.showMenu.defaults, options);
        $(this).bind("contextmenu", function(e) {
            $(opts.query).show().css({
                top: e.pageY + "px",
                left: e.pageX + "px",
                position: "absolute",
                opacity: opts.opacity,
                zIndex: opts.zindex
            });
            $(opts.query).find('li').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
            return false;
        });
        $(document).bind("click", function(e) {
            $(opts.query).hide();
        });
    };

    $.fn.showMenu.defaults = {
        zindex: 2000,
        query: document,
        opacity: 1.0
    };
})(jQuery);

(function($) {
    $.fn.keyCodePressed = function(keyCode, callback) {
        return this.keypress(function(e) {
            var code = e.keyCode || e.which;
            if (code == keyCode) {
                return callback();
            }
            return true;
        });
    };
})(jQuery);

jQuery.autocomplete = function(input, options) {
    // Create a link to self
    var me = this;

    // Create jQuery object for input element
    var $input = $(input).attr("autocomplete", "off");

    // Apply inputClass if necessary
    if (options.inputClass) $input.addClass(options.inputClass);

    // Create results
    var results = document.createElement("div");
    // Create jQuery object for results
    var $results = $(results);
    $results.hide().addClass(options.resultsClass).css("position", "absolute");
    if (options.width > 0) $results.css("width", options.width);

    // Add to body element
    $("body").append(results);

    input.autocompleter = me;

    var timeout = null;
    var prev = "";
    var active = -1;
    var cache = {};
    var keyb = false;
    var hasFocus = false;
    var lastKeyPressCode = null;

    // flush cache
    function flushCache() {
        cache = {};
        cache.data = {};
        cache.length = 0;
    };

    // flush cache
    flushCache();

    // if there is a data array supplied
    if (options.data != null) {
        var sFirstChar = "", stMatchSets = {}, row = [];

        // no url was specified, we need to adjust the cache length to make sure it fits the local data store
        if (typeof options.url != "string") options.cacheLength = 1;

        // loop through the array and create a lookup structure
        for (var i = 0; i < options.data.length; i++) {
            // if row is a string, make an array otherwise just reference the array
            row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

            // if the length is zero, don't add to list
            if (row[0].length > 0) {
                // get the first character
                sFirstChar = row[0].substring(0, 1).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[sFirstChar]) stMatchSets[sFirstChar] = [];
                // if the match is a string
                stMatchSets[sFirstChar].push(row);
            }
        }

        // add the data items to the cache
        for (var k in stMatchSets) {
            // increase the cache size
            options.cacheLength++;
            // add to the cache
            addToCache(k, stMatchSets[k]);
        }
    }

    $input
	.keydown(function(e) {
	    // track last key pressed
	    lastKeyPressCode = e.keyCode;
	    switch (e.keyCode) {
	        case 38: // up
	            e.preventDefault();
	            moveSelect(-1);
	            break;
	        case 40: // down
	            e.preventDefault();
	            moveSelect(1);
	            break;
	        case 9:  // tab
	        case 13: // return
	            if (selectCurrent()) {
	                // make sure to blur off the current field
	                $input.get(0).blur();
	                e.preventDefault();
	            }
	            break;
	        default:
	            active = -1;
	            if (timeout) clearTimeout(timeout);
	            timeout = setTimeout(function() { onChange(); }, options.delay);
	            break;
	    }
	})
	.focus(function() {
	    // track whether the field has focus, we shouldn't process any results if the field no longer has focus
	    hasFocus = true;
	})
	.blur(function() {
	    // track whether the field has focus
	    hasFocus = false;
	    hideResults();
	});

    hideResultsNow();

    function onChange() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
        if (lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32)) return $results.hide();
        var v = $input.val();
        if (v == prev) return;
        prev = v;
        if (v.length >= options.minChars) {
            $input.addClass(options.loadingClass);
            requestData(v);
        } else {
            $input.removeClass(options.loadingClass);
            $results.hide();
        }
    };

    function moveSelect(step) {

        var lis = $("li", results);
        if (!lis) return;

        active += step;

        if (active < 0) {
            active = 0;
        } else if (active >= lis.size()) {
            active = lis.size() - 1;
        }

        lis.removeClass("ac_over");

        $(lis[active]).addClass("ac_over");

        // Weird behaviour in IE
        // if (lis[active] && lis[active].scrollIntoView) {
        // 	lis[active].scrollIntoView(false);
        // }

    };

    function selectCurrent() {
        var li = $("li.ac_over", results)[0];
        if (!li) {
            var $li = $("li", results);
            if (options.selectOnly) {
                if ($li.length == 1) li = $li[0];
            } else if (options.selectFirst) {
                li = $li[0];
            }
        }
        if (li) {
            selectItem(li);
            return true;
        } else {
            return false;
        }
    };

    function selectItem(li) {
        if (!li) {
            li = document.createElement("li");
            li.extra = [];
            li.selectValue = "";
        }
        var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
        input.lastSelected = v;
        prev = v;
        $results.html("");
        $input.val(v);
        hideResultsNow();
        if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
    };

    // selects a portion of the input string
    function createSelection(start, end) {
        // get a reference to the input element
        var field = $input.get(0);
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

    // fills in the input box w/the first match (assumed to be the best match)
    function autoFill(sValue) {
        // if the last user key pressed was backspace, don't autofill
        if (lastKeyPressCode != 8) {
            // fill in the value (keep the case the user has typed)
            $input.val($input.val() + sValue.substring(prev.length));
            // select the portion of the value not typed by the user (so the next character will erase)
            createSelection(prev.length, sValue.length);
        }
    };

    function showResults() {
        // get the position of the input field right now (in case the DOM is shifted)
        var pos = findPos(input);
        // either use the specified width, or autocalculate based on form element
        var iWidth = (options.width > 0) ? options.width : $input.width();
        // reposition
        $results.css({
            width: parseInt(iWidth) + "px",
            top: (pos.y + input.offsetHeight) + "px",
            left: pos.x + "px"
        }).show();
    };

    function hideResults() {
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(hideResultsNow, 200);
    };

    function hideResultsNow() {
        if (timeout) clearTimeout(timeout);
        $input.removeClass(options.loadingClass);
        if ($results.is(":visible")) {
            $results.hide();
        }
        if (options.mustMatch) {
            var v = $input.val();
            if (v != input.lastSelected) {
                selectItem(null);
            }
        }
    };

    function receiveData(q, data) {
        if (data) {
            $input.removeClass(options.loadingClass);
            results.innerHTML = "";

            // if the field no longer has focus or if there are no matches, do not display the drop down
            if (!hasFocus || data.length == 0) return hideResultsNow();

            if ($.browser.msie) {
                // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
                $results.append(document.createElement('iframe'));
            }
            results.appendChild(dataToDom(data));
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            if (options.autoFill && ($input.val().toLowerCase() == q.toLowerCase())) autoFill(data[0][0]);
            showResults();
        } else {
            hideResultsNow();
        }
    };

    function parseData(data) {
        if (!data) return null;
        var parsed = [];
        var rows = data.split(options.lineSeparator);
        for (var i = 0; i < rows.length; i++) {
            var row = $.trim(rows[i]);
            if (row) {
                parsed[parsed.length] = row.split(options.cellSeparator);
            }
        }
        return parsed;
    };

    function dataToDom(data) {
        var ul = document.createElement("ul");
        var num = data.length;

        // limited results to a max number
        if ((options.maxItemsToShow > 0) && (options.maxItemsToShow < num)) num = options.maxItemsToShow;

        for (var i = 0; i < num; i++) {
            var row = data[i];
            if (!row) continue;
            var li = document.createElement("li");
            if (options.formatItem) {
                li.innerHTML = options.formatItem(row, i, num);
                li.selectValue = row[0];
            } else {
                li.innerHTML = row[0];
                li.selectValue = row[0];
            }
            var extra = null;
            if (row.length > 1) {
                extra = [];
                for (var j = 1; j < row.length; j++) {
                    extra[extra.length] = row[j];
                }
            }
            li.extra = extra;
            ul.appendChild(li);
            $(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
        }
        return ul;
    };

    function requestData(q) {
        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        // recieve the cached data
        if (data) {
            receiveData(q, data);
            // if an AJAX url has been supplied, try loading the data now
        } else if ((typeof options.url == "string") && (options.url.length > 0)) {
            var criteria = q;
            if (typeof options.getCriteria == "function") {
                criteria = options.getCriteria();
            }
            $.post(options.url, { criteria: criteria }, function(data) {
                data = parseData(data);
                addToCache(q, data);
                receiveData(q, data);
            });
            // if there's been no data found, remove the loading class
        } else {
            $input.removeClass(options.loadingClass);
        }
    };

    function makeUrl(q) {
        var url = options.url + "?q=" + encodeURI(q);
        for (var i in options.extraParams) {
            url += "&" + i + "=" + encodeURI(options.extraParams[i]);
        }
        return url;
    };

    function loadFromCache(q) {
        if (!q) return null;
        if (cache.data[q]) return cache.data[q];
        if (options.matchSubset) {
            for (var i = q.length - 1; i >= options.minChars; i--) {
                var qs = q.substr(0, i);
                var c = cache.data[qs];
                if (c) {
                    var csub = [];
                    for (var j = 0; j < c.length; j++) {
                        var x = c[j];
                        var x0 = x[0];
                        if (matchSubset(x0, q)) {
                            csub[csub.length] = x;
                        }
                    }
                    return csub;
                }
            }
        }
        return null;
    };

    function matchSubset(s, sub) {
        if (!options.matchCase) s = s.toLowerCase();
        var i = s.indexOf(sub);
        if (i == -1) return false;
        return i == 0 || options.matchContains;
    };

    this.flushCache = function() {
        flushCache();
    };

    this.setExtraParams = function(p) {
        options.extraParams = p;
    };

    this.findValue = function() {
        var q = $input.val();

        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        if (data) {
            findValueCallback(q, data);
        } else if ((typeof options.url == "string") && (options.url.length > 0)) {
            $.get(makeUrl(q), function(data) {
                data = parseData(data)
                addToCache(q, data);
                findValueCallback(q, data);
            });
        } else {
            // no matches
            findValueCallback(q, null);
        }
    }

    function findValueCallback(q, data) {
        if (data) $input.removeClass(options.loadingClass);

        var num = (data) ? data.length : 0;
        var li = null;

        for (var i = 0; i < num; i++) {
            var row = data[i];

            if (row[0].toLowerCase() == q.toLowerCase()) {
                li = document.createElement("li");
                if (options.formatItem) {
                    li.innerHTML = options.formatItem(row, i, num);
                    li.selectValue = row[0];
                } else {
                    li.innerHTML = row[0];
                    li.selectValue = row[0];
                }
                var extra = null;
                if (row.length > 1) {
                    extra = [];
                    for (var j = 1; j < row.length; j++) {
                        extra[extra.length] = row[j];
                    }
                }
                li.extra = extra;
            }
        }

        if (options.onFindValue) setTimeout(function() { options.onFindValue(li) }, 1);
    }

    function addToCache(q, data) {
        if (!data || !q || !options.cacheLength) return;
        if (!cache.length || cache.length > options.cacheLength) {
            flushCache();
            cache.length++;
        } else if (!cache[q]) {
            cache.length++;
        }
        cache.data[q] = data;
    };

    function findPos(obj) {
        var curleft = obj.offsetLeft || 0;
        var curtop = obj.offsetTop || 0;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
        return { x: curleft, y: curtop };
    }
}

jQuery.fn.autocomplete = function(url, options, data) {
    // Make sure options exists
    options = options || {};
    // Set url as option
    options.url = url;
    // set some bulk local data
    options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

    // Set default values for required options
    options.inputClass = options.inputClass || "ac_input";
    options.resultsClass = options.resultsClass || "ac_results";
    options.lineSeparator = options.lineSeparator || "\n";
    options.cellSeparator = options.cellSeparator || "|";
    options.minChars = options.minChars || 1;
    options.delay = options.delay || 400;
    options.matchCase = options.matchCase || 0;
    options.matchSubset = options.matchSubset || 1;
    options.matchContains = options.matchContains || 0;
    options.cacheLength = options.cacheLength || 1;
    options.mustMatch = options.mustMatch || 0;
    options.extraParams = options.extraParams || {};
    options.loadingClass = options.loadingClass || "ac_loading";
    options.selectFirst = options.selectFirst || false;
    options.selectOnly = options.selectOnly || false;
    options.maxItemsToShow = options.maxItemsToShow || -1;
    options.autoFill = options.autoFill || false;
    options.width = parseInt(options.width, 10) || 0;

    this.each(function() {
        var input = this;
        new jQuery.autocomplete(input, options);
    });

    // Don't break the chain
    return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
    return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == e) return i;
    }
    return -1;
};