﻿$.ui.dialog.defaults.bgiframe = true;
var helpdesk = {};
var selectedLink;
var skipUpdate = false;
var setupAttachComplete = false;

$(document).ready(function() {
    helpdesk.disableSubmit();
    helpdesk.stylelizeButtons();
    helpdesk.setupBox();
    helpdesk.setupNavigation();
    helpdesk.setupTabs();
    //helpdesk.setupGrids();

    // this should stay last
    helpdesk.setupSidebar();
    $(".hd-datepicker").datepicker({ showButtonPanel: true });
});

$.extend(helpdesk, {
    setupAttachments: function() {
        if (setupAttachComplete) return;
        helpdesk.addStateHover($('div.ui-state-default'));
        $('#hd-ticket-attachments').append('<ul id="hd-ticket-delete"></ul>');
        $('#hd-ticket-input input.attach').change(function() {
            helpdesk.addNewFile(this);
        });
        $('#hd-ticket-savedattach img').each(function() {
            $(this).click(function() {
                $(this).parent().find('input').attr('name', 'deleteAttachment');
                $(this).parent().hide();

            });
        });
        setupAttachComplete = true;
    },
    addStateHover: function(selector) {
        // hover class toggles in app panel
        $(selector).hover(
                 function() { $(this).addClass('ui-state-hover'); },
                 function() { $(this).removeClass('ui-state-hover'); }
                 );
    },
    addNewFile: function(input) {
        if ($(input).val() != '') {
            $(input).hide();
            var cnt = $(input).parent()[0].childElementCount + 1;
            var wrapper = $(input).parent();
            wrapper.append('<input class="attach" type="file" name="file' + cnt + '"/>');
            wrapper.find('input.attach:last').change(function() {
                helpdesk.addNewFile(this);
            });
            $('#hd-ticket-delete').append('<li><img width="16" height="16" class="ui-icon ui-icon-circle-minus" src="' + helpdesk.getBase() + 'css/images/spacer.gif" /><p>' + helpdesk.getFilename($(input).val()) + '</p></li>');
            $('#hd-ticket-delete').find('li img:last').each(function() {
                $(this).click(function() {
                    $(this).parent().remove();
                    $(input).remove();
                });
            });
        }
    },
    getFilename: function(fullPath) {
        var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
        var filename = fullPath.substring(startIndex);
        if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
            filename = filename.substring(1);
        }
        return filename;
    },
    setupGrids: function() {
        //        $('.grid').each(function() {
        //            var width = getElementWidth($(this).find('table')[0]);
        //            $(this).css('width', width);
        //            var elm = $(this)[0];
        //            elm.style.display = 'none';
        //            var fix = elm.offsetHeight;
        //            elm.style.display = 'block';

        //            $(this).find('a.ui-button').each(function() {
        //                elm = $(this)[0];
        //                elm.style.display = 'none';
        //                var fix = elm.offsetHeight;
        //                elm.style.display = 'block';
        //            });
        //        });
    },
    disableSubmit: function() {
        $('form').disableOnSubmit();
    },
    setupTabs: function() {
        $('.hd-tabs').tabs();
    },
    setupSidebar: function() {
        var sidebar = $("#hd_sidebar");

        if ($(sidebar).length != 0) {
            // hide sidebar if it doesnt have any content
            if (sidebar.children().length == 0) {
                // moved to a control on page
                // $(sidebar).hide();
                // $("body").addClass("sidebaroff");
            } else {

                /* Sidebar Height */
                setTimeout(function() {
                    var main = $('#hd-main');
                    var ie = $.browser.msie;

                    if (sidebar.height() > main.height()) {
                        if (ie) {
                            main.css('height', sidebar.height());
                        } else {
                            main.css('min-height', sidebar.height());
                        }
                    }
                }, 250);
            }
        }
    },
    setupNavigation: function() {
        $('#hd-nav a').each(function() {
            var parent = $(this).parent();
            parent.hover(
                function() { $(this).toggleClass("ui-state-hover", true) },
                function() { $(this).toggleClass("ui-state-hover", false) }
            );
            var loc = document.location.href;
            if (document.location.search.length > 0) {
                loc = loc.substring(0, loc.length - document.location.search.length);
            }
            if (loc == this.href) {
                $(this).parent().addClass("ui-tabs-selected ui-state-active");
            }
        });
    },
    setupBox: function() {
        // add jquery styling to boxes
        //$(".hd-box").addClass("ui-tabs ui-widget ui-widget-content");
    },
    stylelizeButtons: function() {
        helpdesk.addStateHover(".hd-button");
    },
    setupTicketLinkClick: function() {
        $("#hd-main").before('<div id="tcktclkdialog" title="Open Ticket" style="display: none;"><p>Do you wish to open Ticket #:<span id="dlg-ticket-num" style="font-weight:bold;"></span> in a New Window or the Current Window?</p></div>');
        $("#tcktclkdialog").dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                "New Window": function() {
                    window.open(selectedLink);
                    $(this).dialog("close");
                },
                "Current Window": function() {
                    window.location = selectedLink;
                    $(this).dialog("close");
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        });
    },
    ticketLinkClick: function(link, text) {
        skipUpdate = true;
        selectedLink = link;
        $("#dlg-ticket-num").text(text);
        setTimeout($("#tcktclkdialog").dialog("open"), 20);
        skipUpdate = false;
        return false;
    },
    setupStopWatch: function(txtBoxSelector, buttonSelector) {
        var s = new Stopwatch(function(runtime) {
            $(this.txtBoxSelector).attr('value', (runtime / 60000).toFixed(2));
        }, txtBoxSelector);

        $(buttonSelector).bind("click", function() { s.startStop(); });
        s.doDisplay();

    }
});

function getElementWidth(element) {
    if (typeof element.clip !== "undefined") {
        return element.clip.width;
    } else {
        if (element.style.pixelWidth) {
            return element.style.pixelWidth;
        } else {
            return element.offsetWidth;
        }
    }
}

function getElementHeight(element) {
    if (typeof element.clip !== "undefined") {
        return element.clip.height;
    } else {
        if (element.style.pixelHeight) {
            return element.style.pixelHeight;
        } else {
            return element.offsetHeight;
        }
    }
}
function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

function setupDirty(selector) {
    var el = $(selector);
    el.data('oldVal', el.val());
    el.focus(function() {
        $(this).data('oldVal', $(this).val());
    });
}

function getDisplayName() {
    var firstName = $(".edtFirstName").val();
    var initials = $(".edtInitials").val();
    var lastName = $(".edtLastName").val();

    var text = trim(firstName);

    if (trim(initials).length > 0) {
        text += (" " + trim(initials));
    }

    if (trim(lastName).length > 0) {
        text += (" " + trim(lastName));
    }
    return text;
}

function updateDisplayName() {
    var displayName = $(".edtDisplayName");

    if (trim(displayName.val()).length == 0 || boolCanEdit) {
        displayName.val(getDisplayName());
    }
}

function setupEditDisplayName() {
    setupDirty(".edtFirstName");
    setupDirty(".edtInitials");
    setupDirty(".edtLastName");
    setupDirty(".edtDisplayName");

    $(".edtFirstName").change(updateDisplayName);
    $(".edtInitials").change(updateDisplayName);
    $(".edtLastName").change(updateDisplayName);

    var displayName = $(".edtDisplayName");
    displayName.data('editing', false);
    displayName.focus(function() {
        displayName.data('editing', true);
    });
    displayName.blur(function() {
        displayName.data('editing', false);
    });
    displayName.change(function() {
        if ($(this).data('editing')
                            && $(this).val() != $(this).data('oldVal')) {
            boolCanEdit = ($(this).val() == getDisplayName() || trim($(this).val()).length == 0);
        }

    });

    if (trim(displayName.val()) == getDisplayName()
                        || displayName.val().length == 0) {
        boolCanEdit = true;
    }
}