var applicationUrl = '';

function initializeJQueryCode(rootselector) {
    if (rootselector == null) rootselector = document;
    
    $(".save", rootselector).click(function() {
        $.validity.start();
        $(".requiredfield").require();
        $(".datefield").match("date");
        $(".emailfield").match("email");
        $(".integerfield").match("number");
        $(".numberfield").match("number");
        $(".numericfield").match("number");
        $(".decimalfield").match("number");
        $(".moneyfield").match("number");
        var result = $.validity.end();
        return result.valid;
    });
    try {
        $(".datefield", rootselector).datepicker({ changeMonth: true, changeYear: true, numberOfMonths: 1, showOtherMonths: true, selectOtherMonths: true, showOn: 'focus' });
        $(".datefield", rootselector).datepicker('option', '{showAnim: slideDown}');
    } catch (err) { }
    try {
        $(".datefield", rootselector).attr('autocomplete', 'off');
    } catch (err) { }
    try {
        $("a.dialog", rootselector).colorbox({ iframe: 'true', innerWidth: '75%', innerHeight: '75%', scrolling: 'true', current: '{current} of {total}', onOpen: function() { ClearPopupHistory(); } });
    } catch (err) { }
    try {
        $("a.alert-dialog", rootselector).colorbox({ iframe: 'true', innerWidth: '75%', innerHeight: '75%', scrolling: 'true', current: '{current} of {total}', onOpen: function() { ClearPopupHistory(); }, onClosed: function() { RefreshAlerts(); } });
    } catch (err) { }
    try {
        $("a.customer-note-dialog", rootselector).colorbox({ iframe: 'true', innerWidth: '75%', innerHeight: '75%', scrolling: 'true', current: '{current} of {total}', onOpen: function() { ClearPopupHistory(); }, onClosed: function() { RefreshCustomerNotes(); } });
    } catch (err) { }
    try {
        $("a.message-dialog", rootselector).colorbox({ iframe: 'true', innerWidth: '75%', innerHeight: '75%', scrolling: 'true', current: '{current} of {total}', onOpen: function() { ClearPopupHistory(); }, onClosed: function() { RefreshUnhandledMessages(); } });
    } catch (err) { }
    $(".accordion", rootselector).accordion({ autoHeight: false, collapsible: true, navigation: true });

    setTimeout(function() {
        $(".pagemessage", rootselector).fadeOut('slow');
    }, 5000);

    $(".pagemessage", rootselector).click(function() { $(this).hide(); });

    $(".collapsible-list-open-first .collapsible-body:first", rootselector).show();
    //toggle the component with class msg_body
    $(".collapsible-header", rootselector).click(function() {
        var body = $(this).next(".collapsible-body");
        $(body).toggle();
        var visibleid = $(body).attr('visibleid');
        if (visibleid != null) {
            var isvisible = null;
            if ($(body).is(':visible')) isvisible = 'visible';
            else isvisible = 'hidden';
            $.cookie(visibleid, isvisible, 1);
        }
    });

    $('.collapsible-body[visibleid]', rootselector).each(function() {
        var visibleid = $(this).attr('visibleid');
        var isvisible = $.cookie(visibleid);
        if (isvisible == 'visible') $(this).show();
        else if (isvisible == 'hidden') $(this).hide();
    });

    var ckconfig = {
        enterMode: CKEDITOR.ENTER_BR,
        shiftEnterMode: CKEDITOR.ENTER_P,
        contentsCss: [applicationUrl + '/css/designer.css'],
        toolbar:
        [
    ['Source', '-', 'Preview'],
    ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'SpellChecker', 'Scayt'],
    ['Undo', 'Redo', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
    ['BidiLtr', 'BidiRtl'],
    '/',
    ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'],
    ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote', 'CreateDiv'],
    ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
    ['Link', 'Unlink', 'Anchor'],
    ['Table', 'HorizontalRule', 'SpecialChar'],
    '/',
    ['Styles', 'Format', 'Font', 'FontSize'],
    ['TextColor', 'BGColor'],
    ['Maximize', 'ShowBlocks', '-', 'About', 'checkoff']
		]
    };
    $('textarea.htmleditor', rootselector).ckeditor(ckconfig);

    $('.jq_watermark', rootselector).watermark();

    try {
        $(".autocomplete", rootselector).autocomplete({
            source: function(request, response) {
                var IdField = this.element.attr("IdField");
                $.ajax({
                    type: 'POST',
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    url: (applicationUrl + "/Services/Lookup.asmx/GetLookupResults"),
                    data: "{ 'lookupTable': '" + this.element.attr("LookupTable") + "', 'lookupField': '" + this.element.attr("LookupField") +
                        "', 'lookupIdField': '" + this.element.attr("LookupIdField") + "', 'term': '" + request.term + "' }",
                    success: function(data, XMLHttpRequest, textStatus) {
                        response($.map(data.d, function(item) {
                            return {
                                value: item.Result,
                                cID: item.ObjectId,
                                idField: IdField
                            }
                        }))
                    }
                });
            },
            minLength: 1,
            select: function(event, ui) {
                $('#' + ui.item.idField).val(ui.item.cID);
            }
        });

        $(".autocomplete", rootselector).keypress(function(event) {
            if (event.keyCode == '13') return;
            if (event.keyCode == '9') return;
            var idField = $(this).attr("IdField");
            $('#' + idField).val("");
        });
    }
    catch (err) { }

    $(".tabs").tabs({
        cookie: {
            // store cookie for a day, without, it would be a session cookie
            expires: 1
        }
    });

    $('span.set-flag > :checkbox').click(function() {
        var flagId = $(this).parent().attr('FlagId');
        var flagType = $(this).parent().attr('FlagType');
        if ($(this).is(':checked')) {
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                url: (applicationUrl + "/Services/AJAX.asmx/SetFlag"),
                data: "{ 'flagType': '" + flagType + "', 'flagId': '" + flagId +
                    "', 'flagValue': 'true' }",
                success: function(msg) {
                }
            });
        }
        else {
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                url: (applicationUrl + "/Services/AJAX.asmx/SetFlag"),
                data: "{ 'flagType': '" + flagType + "', 'flagId': '" + flagId +
                    "', 'flagValue': 'false' }",
                success: function(msg) {
                }
            });
        }
    });

    $(".showwhenloaded", rootselector).show();
    $(".stop-click", rootselector).click(function (event) { event.stopPropagation(); });

    $(".filetree").treeview({
        collapsed: true,
        persist: "location"
    });
}

$(document).ready(function() {
    initializeJQueryCode();
});

function selectTreeFirst() {
    var selected = $(".filetree a.selected");
    if (selected.length == 0) {
        $(".filetree li a").first().addClass("selected");
    } else {
        selected.parents("li.expandable").children("div.hitarea").click();
    }
}

function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        initializeJQueryCode();
    }
}

function ClearPopupHistory() {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: (applicationUrl + "/Services/AJAX.asmx/ClearPopupHistory")
    });
}

function RefreshAlerts(selector) {
    if (selector == null) selector = '#sidebar-alerts';
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: (applicationUrl + "/Services/AJAX.asmx/HtmlQuery"),
        data: "{ 'queryType': 'current-alerts', 'parms': '' }",
        success: function(data, XMLHttpRequest, textStatus) {
            $(selector).html(data.d.Html);
            initializeJQueryCode(selector);
        }
    });
}

function RefreshCustomerNotes(selector) {
    if (selector == null) selector = '#sidebar-customer-notes';
    var customerId = $(selector).attr("CustomerId");
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: (applicationUrl + "/Services/AJAX.asmx/HtmlQuery"),
        data: "{ 'queryType': 'current-customer-notes', 'parms': '"+customerId+"' }",
        success: function(data, XMLHttpRequest, textStatus) {
            $(selector).html(data.d.Html);
            initializeJQueryCode(selector);
        }
    });
}

function RefreshUnhandledMessages(selector) {
    if (selector == null) selector = '#home-unhandled-messages';
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        url: (applicationUrl + "/Services/AJAX.asmx/HtmlQuery"),
        data: "{ 'queryType': 'home-unhandled-messages', 'parms': '' }",
        success: function(data, XMLHttpRequest, textStatus) {
            $(selector).html(data.d.Html);
            initializeJQueryCode(selector);
        }
    });
}

function PopupWindow(aUrl, w, h, sb, rs, tb, dir, st, mnu) {
    if (!sb) sb = "yes"; if (!rs) rs = "yes"; if (!tb) tb = "no"; if (!dir) dir = "no"; if (!st) st = "no"; if (!mnu) mnu = "no";
    popupWin = window.open(aUrl, "PopupWin", "scrollbars=" + sb + ",resizable=" + rs + ",toolbar=" + tb + ",directories=" + dir + ",status=" + st + ",menubar=" + mnu + ",width=" + w + ",height=" + h + ",resizable=yes");
    popupWin.self.focus();
}

function PopupNamedWindow(aName, aUrl, w, h, sb, rs, tb, dir, st, mnu) {
    if (!sb) sb = "yes"; if (!rs) rs = "yes"; if (!tb) tb = "no"; if (!dir) dir = "no"; if (!st) st = "no"; if (!mnu) mnu = "no";
    popupWin = window.open(aUrl, aName, "scrollbars=" + sb + ",resizable=" + rs + ",toolbar=" + tb + ",directories=" + dir + ",status=" + st + ",menubar=" + mnu + ",width=" + w + ",height=" + h + ",resizable=yes");
    popupWin.self.focus();
}

function PopupUniqueWindow(aUrl, w, h, sb, rs, tb, dir, st, mnu) {
    if (!sb) sb = "yes"; if (!rs) rs = "yes"; if (!tb) tb = "no"; if (!dir) dir = "no"; if (!st) st = "no"; if (!mnu) mnu = "no";
    popupWin = window.open(aUrl, "PopupWin" + (new Date()).getTime(), "scrollbars=" + sb + ",resizable=" + rs + ",toolbar=" + tb + ",directories=" + dir + ",status=" + st + ",menubar=" + mnu + ",width=" + w + ",height=" + h + ",resizable=yes");
    popupWin.self.focus();
}

function HideShowControl(ctrlid) {
    var ctrl = document.getElementById(ctrlid);
    if (ctrl.style.display == "none") {
        ctrl.style.display = "";
    }
    else {
        ctrl.style.display = "none";
    }
}

function HideControl() {
    var ctrl;

    for (i = 0; i < arguments.length; i++) {
        ctrl = document.getElementById(arguments[i]);
        if (ctrl.style.display != "none") {
            ctrl.style.display = "none";
        }
    }
}

function ShowControl() {
    var ctrl;

    for (i = 0; i < arguments.length; i++) {
        ctrl = document.getElementById(arguments[i]);

        if (ctrl.style.display == "none") {
            ctrl.style.display = "";
        }
    }
}

