﻿function dateOnly(d) {
    return (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
}

function getGroupItemChecked(group, value, includeDisabled) {
    var groupItems = group.items.items
    var i = 0;
    for (i = 0; i < groupItems.length; i++) {
        if (groupItems[i].valueString == value && groupItems[i].checked == true &&
                          (includeDisabled == true || groupItems[i].disabled == false)) {
            return true;
        }
    }
    return false;
}

function getCheckedGroupItems(group) {
    var result = [];
    var groupItems = group.items.items
    var i = 0;
    for (i = 0; i < groupItems.length; i++) {
        if (groupItems[i].checked == true) {
            result.push(groupItems[i].valueString);
        }
    }
    return result;
}

function getCheckedEnabledGroupItems(group) {
    var result = [];
    var groupItems = group.items.items
    var i = 0;
    for (i = 0; i < groupItems.length; i++) {
        if (groupItems[i].checked == true && groupItems[i].disabled == false) {
            result.push(groupItems[i].valueString);
        }
    }
    return result;
}

function getCheckedGroupItemsCsv(group) {
    if (group == undefined) { return; };

    var result = '';
    var groupItems = group.items.items
    var i = 0;
    for (i = 0; i < groupItems.length; i++) {
        if (groupItems[i].checked == true && groupItems[i].disabled == false) {
            result += groupItems[i].valueString + ',';
        }
    }
    if (result.length > 0) {
        result = result.substring(0, result.length - 1);
    }
    return result;
}


function resetChechboxGroup(group, addMode) {
    var groupItems = group.items.items
    var i = 0;
    for (i = 0; i < groupItems.length; i++) {
        if (addMode == true) {
            groupItems[i].setValue(groupItems[i].defaultValue);
            groupItems[i].setDisabled(groupItems[i].defaultDisabled);
        }
        else {
            groupItems[i].setValue(false);
            groupItems[i].setDisabled(false);
        }
    }
}

function setVisible(isAdmin) {
    if (isAdmin == true) {
        return 'inline';
    }
    return 'none'
}

function object(o) {
    function F() { }
    F.prototype = o;
    return new F();
}

function cleanConfig(config) {
    var configCopy = [];
    for (var i = 0; i < config.length; i++) {
        configCopy[i] = {};
        configCopy[i].sortable = config[i].sortable;
        configCopy[i].width = config[i].width;
        configCopy[i].dataIndex = config[i].dataIndex;
        configCopy[i].header = config[i].header;
        configCopy[i].id = config[i].id;
        configCopy[i].summaryType = config[i].summaryType;
        configCopy[i].hidden = config[i].hidden;
        configCopy[i].sortable = config[i].sortable;
    }
    return configCopy
}

function right(str, n) {
    if (n <= 0) {
        return "";
    }
    else if (n > String(str).length) {
        return str;
    }
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}

function rtfSetValue(html, rtfEditor) {
    rtfEndSpell(rtfEditor);
    if (html == null) { html = '' };
    rtfEditor.get_contentArea().innerHTML = html;
}

function rtfGetValue(rtfEditor) {
    rtfEndSpell(rtfEditor);
    var value = rtfEditor.get_html();
    if (value.substring(value.length - 4) == '<br>') {
        value = value.substring(0, value.length - 4)
    };

    return value;
}

function rtfEndSpell(rtfEditor) {
    if (rtfEditor.get_ajaxSpellCheck() != undefined) {
        rtfEditor.get_ajaxSpellCheck().cancelSpellCheck();
    };
}

function getString(value) {
    if (value == null) {
        return ''
    }
    else {
        return value
    }
}


String.prototype.trim = function () { return this.replace(/^\s+|\s+$/g, "") };

String.prototype.replaceAll = function (find, replace) {
    var str = this;
    str += "";
    var indexOfMatch = str.indexOf(find);
    while (indexOfMatch != -1) {
        str = str.replace(find, replace);
        indexOfMatch = str.indexOf(find);
    }
    return str;
}

function rtfOnClientLoad(editor, args) {
    //sets convinient global variable instead of using $find method
    window[editor.get_id().split("_").pop()] = editor;

    var buttonsHolder = $get(editor.get_id() + "Top");
    var buttons = buttonsHolder.getElementsByTagName("A");
    for (var i = 0; i < buttons.length; i++) {
        var a = buttons[i];
        a.tabIndex = -1;
        a.tabStop = false;
    }

    //attach to the onkeydown event, check whether the tab key is pressed and paste &nbsp; in the editor
    editor.attachEventHandler("onkeydown", function (e) {
        if (e.keyCode == '9') {
            editor.pasteHtml("&nbsp;&nbsp;&nbsp;&nbsp;");
            if (!document.all) {
                e.preventDefault();
                e.preventBubble();
                e.stopPropagation();
            }
            else {
                e.returnValue = false;
                e.cancelBubble = true;
            }
        }    
    });

    Telerik.Web.UI.Editor.CommandList["LTR"] = function (commandName, editor, args) {
        SetDirectionOfSelection(editor, "ltr");
    }
    Telerik.Web.UI.Editor.CommandList["RTL"] = function (commandName, editor, args) {
        SetDirectionOfSelection(editor, "rtl");
    }
}

function csv(value, append) {
    if (value == '') {
        return append;
    }
    else {
        return value + ',' + append
    };
}

function toggleMoreInfo(imgPath) {
    if ($j('.moreInfo').css('display') == 'none') {
        $j('.moreInfo').css('display', 'block');
        $j('.imgMoreInfo').attr('src', imgPath + 'min.gif');
    }
    else {
        $j('.moreInfo').css('display', 'none');
        $j('.imgMoreInfo').attr('src', imgPath + 'max.gif');
    }
}

function positionWindow(sender, control) {
    if (control != null) {
        window[control].focus(false, 100);
    }

    var windowElement = $j('#' + sender.id);
    if (windowElement.css('left').substring(0, 1) == '-') {
        windowElement.css('left', '0px');
    }
    if (windowElement.css('top').substring(0, 1) == '-') {
        windowElement.css('top', '0px');
    }
}

function commandToolbar(grid, toolbar, rowIndex, record) {
    toolbar.add(new Ext.Button({
        tooltip: "Edit",
        iconCls: "edit17png",
        command: "edit"
    }));
    toolbar.add(new Ext.Button({
        tooltip: "Delete",
        iconCls: "bullet_crosspng",
        command: "delete"
    }));
}

function toggleOther(cmb) {
    var txtID = cmb.id.replace('cmb', 'txt') + 'Other';
    var recordindex = cmb.store.findBy(function (record) { return record.get(cmb.valueField) == cmb.getValue(); });

    if (recordindex > -1) {
        var description = cmb.store.getAt(recordindex).data[cmb.displayField];

        if (description == 'Other') {
            window[txtID].show();
        }
        else {
            window[txtID].hide();
        }
    }
    else {
        window[txtID].hide();
    }
}

function resetCombobox(cmb) {
    if (cmb.store.data.items[0] != undefined) {
        cmb.setValue(cmb.store.data.items[0].data[cmb.valueField]);
    }
    else {
        cmb.setValue('');
    }
}

String.prototype.contains = function (it) { return this.indexOf(it) != -1; };

function SetDirectionOfSelection(editor, strDirection) {
    var rngSelection = editor.getSelection();
    var strTagNames;
    strTagNames = "|H1|H2|H3|H4|H5|H6|P|PRE|TD|DIV|BLOCKQUOTE|DT|DD|TABLE|HR|IMG|TR|UL|OL|";
    if (rngSelection.getParentElement()) {
        var elemSelectionParent = rngSelection.getParentElement();
        while ((elemSelectionParent != null) && (strTagNames.indexOf("|" + elemSelectionParent.tagName + "|") == -1)) {
            elemSelectionParent = elemSelectionParent.parentNode;
        }
        if (elemSelectionParent) {
            SetDirectionOnElement(elemSelectionParent, strDirection);
        }
        else {
            var oDoc = editor.get_document();

            var para = createPara(oDoc, strDirection, editor.getSelectionHtml());
            if (editor.getSelectionHtml()) {
                var tmpRng = editor.getSelection().getRange();
                if ($telerik.isIE) {
                    tmpRng.pasteHTML("");
                }
                else {
                    tmpRng.deleteContents();
                }
            }

            var range = editor.getSelection().getRange();

            //handle possitioning of the cursor inside the new paragraph

            if ($telerik.isIE) {
                range.moveToElementText(para);
                range.select();
            }
            else {
                range = document.createRange();
                range.selectNodeContents(para);
                editor.getSelection().selectRange(range);
            }
            editor.getSelection().collapse();

            SetDirectionOfSelection(editor, strDirection);
        }
    }
}

function SetDirectionOnElement(element, strDirection) {
    if ("ltr" == strDirection) {
        element.dir = "ltr";
        element.align = "left";
    }
    else if ("rtl" == strDirection) {
        element.dir = "rtl";
        element.align = "right";
    }
}

function createPara(doc, dir, content) {
    var par = doc.createElement("div");
    SetDirectionOnElement(par, dir)
    par.innerHTML = content;
    doc.body.appendChild(par);
    return par;
}



function showFancybox(url,w,h) {
    $j.fancybox({
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'href': url,
        'type': 'iframe',
        'titleShow': false,
        'padding': 0,
        'width': w || 5000,
        'height': h || 5000,
        'onComplete': function () {
            $j.fancybox.showActivity();
        }
    });
}

//Fix for postback of overflow items error  http://forums.ext.net/showthread.php?15101-toolbar-overflow-can-t-post-back-when-it-was-hided
Ext.layout.ToolbarLayout.override({
    createMenuConfig: function (component, hideOnClick) {
        var config = Ext.apply({}, component.initialConfig),
                group = component.toggleGroup;

        Ext.copyTo(config, component, [
                'iconCls', 'icon', 'itemId', 'disabled', 'handler', 'scope', 'menu'
            ]);

        Ext.apply(config, {
            text: component.overflowText || component.text,
            hideOnClick: hideOnClick
        });

        if (group || component.enableToggle) {
            Ext.apply(config, {
                group: group,
                checked: component.pressed,
                listeners: {
                    checkchange: function (item, checked) {
                        component.toggle(checked);
                    }
                }
            });
        }

        //fix
        if (config.directEvents && config.directEvents.click) {
            if (!(config.listeners && config.listeners.click)) {
                config.listeners = {
                    click: {}
                };
            }
            config.listeners.click.fn = function () {
                component.fireEvent("click", component)
            }

            delete config.directEvents;
        }
        //end fix

        delete config.ownerCt;
        delete config.xtype;
        delete config.id;

        return config;
    }
});
