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 __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 launchPad__DataObjectSave(id, dataObjectType, collectionID, onSaveMethod, userVersion, 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 + '/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);