﻿/// <reference path="scripts/jQuery-vsdoc.js" />

// OBS: Kraever at position.js er inkluderet andetsteds!

(function($) {
    $.fn.tableKeyNavigate = function(options) {

        var defaults = {
            mouseover: false,
            csshighlight: "highlight",
            csscolor: "yellow",
            tabToLinks: false,
            tabToTable: true,
            mouseClick: true,
            onMouseClick: {},
            onMouseDblClick: { shortcutclass: "redi", action: null }, //null,
            shortcuts: {},
            canGoToTopRow: false
        };

        var options = $.extend(defaults, options);
        var csshighlightclass = '.' + options.csshighlight;
        var objectID;
        var isShift = false;
        var isAlt = false;
        var isCtrl = false;
        var selectedInputID = '';
        var currentRow = null;
        var mouseDblClick = (options.onMouseDblClick != null);
        var outerDiv = null;

        return this.each(function() {

            obj = $(this);
            objectID = obj.attr("id");
            outerDiv = obj.parent().parent();
            //alert(outerDiv.attr("id") + ", " + objectID);

            outerDiv.bind("scroll", function(e) {

                $('#' + objectID + ' ' + csshighlightclass + " :first").each(function() {
                    var highlightedRow = $('#' + objectID + ' ' + csshighlightclass);
                    if (highlightedRow.length != 1)
                        return;

                    highlightedYPosition = highlightedRow[0].offsetTop + (highlightedRow[0].clientHeight / 2);

                    var newPosition = highlightedYPosition - ($('#DivSurveys').height() / 2);

                    if (newPosition < 0)
                        newPosition = 0;

                    outerDiv.scrollTop(newPosition);
                });
            });

            //            $("#DivSurveys").bind("scroll", function(e) {
            //                if (!controllingScrolling)
            //                    PlaceContentScrollbar();
            //            });

            // Make highlight rows (mouseover)
            if (options.mouseover) {
                obj.find("tbody tr").hover(
                        function() {
                            if (options.tabToTable) {
                                if (selectedInputID != '') {
                                    obj.find(csshighlightclass).removeClass(options.csshighlight);
                                    $(this).addClass(options.csshighlight);
                                }
                                else {
                                    currentRow = $(this);
                                    $('#TabTo' + objectID).focus();
                                }
                            }
                            else {
                                $(this).removeClass(options.csshighlight);
                                $(this).addClass(options.csshighlight);
                            }
                        },
                        function() {
                            // no action, when moving cursor away from table
                        }
                    );
            }

            if (mouseDblClick) {
                obj.find("tbody tr").dblclick(function() {
                    // behaviour
                    debug("dblclick");
                    obj.find(csshighlightclass).removeClass(options.csshighlight);
                    $(this).addClass(options.csshighlight);
                    $(this).find("." + options.onMouseDblClick.shortcutclass + " a:first").click();
                });
            }

            if (options.mouseClick) {
                obj.find("tbody tr").click(function() {
                    // Default mouseclick behaviour
                    if (selectedInputID != '') {
                        debug("her...");
                        obj.find(csshighlightclass).removeClass(options.csshighlight);
                        $(this).addClass(options.csshighlight);
                    }
                    else {
                        debug("her...2");
                        obj.find(csshighlightclass).removeClass(options.csshighlight);
                        $(this).addClass(options.csshighlight);
                        //currentRow = $(this);
                        //$("TabTo" + objectID).focus();
                    }
                    //                        else {
                    //                            obj.find(csshighlightclass).removeClass(options.csshighlight);
                    //                            $(this).addClass(options.csshighlight);
                    //                        }
                });
            }

            // Remove taborder on links in table (if tabToLinks is set)
            if (!options.tabToLinks) {
                obj.find("a").attr("tabindex", "-1");
            }

            if (options.tabToLinks) {

                obj.find("tbody tr a").focus(function() {
                    $(this).parent().parent().addClass(options.csshighlight);
                });
                obj.find("tbody tr a").blur(function() {
                    $(this).parent().parent().removeClass(options.csshighlight);
                });
            }

            if (options.tabToTable && !options.tabToLinks) {
                var invisible = "style='background-color:transparent;border-style:solid 0px white;border:none;height:0px;width:0px'";
                //var invisible = '';

                obj.before("<input id='TabTo" + objectID + "' type='button' " + invisible + " />");
                obj.after("<input id='TabFrom" + objectID + "' type='button' " + invisible + " />");

                $('#TabTo' + objectID + ',#TabFrom' + objectID).focus(function() {
                    selectedInputID = $(this).attr("id");
                    var hasHighlightedRow = obj.find(csshighlightclass).length != 0;

                    if (hasHighlightedRow) {
                        obj.find(csshighlightclass).removeClass(options.csshighlight);
                        return;
                    }

                    debug("currentRow == null: " + (currentRow == null));

                    obj.find(csshighlightclass).removeClass(options.csshighlight);
                    if (currentRow == null)
                        obj.find("tbody tr:first").addClass(options.csshighlight);
                    else {
                        currentRow.addClass(options.csshighlight);
                        currentRow = null;
                    }
                });

                $('#TabTo' + objectID + ',#TabFrom' + objectID).blur(function() {
                    selectedInputID = '';
                    if (obj.find(csshighlightclass).length != 0 && currentRow == null) {
                        currentRow = obj.find(csshighlightclass);
                    }

                    obj.find(csshighlightclass).removeClass(options.csshighlight);
                });
            }

            // Keybinding
            $(document).keyup(
                    function(e) {
                        if (e.which == 16)
                            isShift = false;
                        if (e.which == 17)
                            isCtrl = false;
                        if (e.which = 18)
                            isAlt = false;
                    }).keydown(
                    function(e) {
                        if (e.which == 16) {
                            isShift = true;
                        }
                        if (e.which == 17)
                            isCtrl = true;

                        if (e.which == 18)
                            isAlt = true;
                    });

            if ($.browser.mozilla) {
                $(document).keydown(checkKey);
            } else {
                $(document).keydown(checkKey);
            }
        });

        function debug(text) {
            var tid = new Date();
            var hour = tid.getHours();
            var min = tid.getMinutes();
            var sec = tid.getSeconds();

            var timestamp = hour + ":" + min + ":" + sec;

            var currentText = $("#debugdiv").html();
            var newText = timestamp + ":" + text + "<br>" + currentText;

            $("#debugdiv").html(newText);
        }

        function checkKey(e) {
            //',#TabTo' + objectID
            //$('#' + objectID).find(csshighlightclass).each(function() {
            $('#' + objectID + ' ' + csshighlightclass).each(function() {
                var highlightedRow = $('#' + objectID + ' ' + csshighlightclass);
                if (highlightedRow.length == 0)
                    return;

                var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

                if (key == 9 && isShift && !options.tabToLinks) {
                    debug("SHIFT-TAB");

                    if (obj.find(csshighlightclass).length != 0 && currentRow == null) {
                        currentRow = obj.find(csshighlightclass);
                        debug("currentRow sat fra SHIFT-TAB");
                    }

                    if (selectedInputID == 'TabFrom' + objectID)
                        $('#TabTo' + objectID).focus();
                    //highlightedRow.removeClass(options.csshighlight);
                    //alert('ups');
                    //if ($('#TabTo' + objectID).focus() == true)
                    //    debug("tabber fra TABTO");
                    //if ($('#TabFrom' + objectID).focus() == true)
                    //    debug("tabber fra TABFROM");
                }
                else if (key == 9 && !isShift && !options.tabToLinks) {
                    debug("TAB");

                    if (obj.find(csshighlightclass).length != 0 && currentRow == null) {
                        currentRow = obj.find(csshighlightclass);
                        debug("currentRow sat fra TAB");
                    }

                    if (selectedInputID == 'TabTo' + objectID) {
                        $('#TabFrom' + objectID).focus();
                    }
                    //if (selectedInputID == 'TabFrom' + objectID)
                    //    highlightedRow.removeClass(options.csshighlight);
                }
                else if (key == 38) {
                    // Arrow UP
                    if (options.canGoToTopRow == false && highlightedRow.prev().prev().attr("tagName") != "TR")
                        return;

                    if (highlightedRow.prev().length != 0) {
                        highlightedRow.removeClass(options.csshighlight);
                        highlightedRow.prev().addClass(options.csshighlight);
                    }
                }

                else if (key == 40) {
                    // Arrow DOWN
                    if (highlightedRow.next().length != 0) {
                        highlightedRow.removeClass(options.csshighlight);
                        highlightedRow.next().addClass(options.csshighlight);
                    }
                }

                for (i = 0; i < options.shortcuts.length; i++) {
                    //debug("key == shortcutkey: " + key + " == " + parseInt(options.shortcuts[i].shortcutkey));
                    if (key == parseInt(options.shortcuts[i].shortcutkey)) {
                        //alert("found key!");
                        isShift = isCtrl = isAlt = false;
                        //debug("find: " + escape(highlightedRow.find("." + options.shortcuts[i].shortcutclass).html()));
                        //currentRow = obj.find(csshighlightclass);
                        //highlightedRow.removeClass(options.csshighlight);
                        //alert(highlightedRow.find("." + options.shortcuts[i].shortcutclass).attr("tagName"));
                        highlightedRow.find("." + options.shortcuts[i].shortcutclass).click();
                    }
                }
            });
        }

        function getY(oElement, div) {
            var positionObject = Position.get(oElement, div);
            return positionObject.top;
        }

        function PlaceContentScrollbar() {

            controllingScrolling = true;
            //$('#DivSurveys')[0].scrollTop = 0;
            //return;

            $('#' + objectID + ' ' + csshighlightclass + " :first").each(function() {
                var highlightedRow = $('#' + objectID + ' ' + csshighlightclass);

                if (highlightedRow.length != 1)
                    return;
                var div = $('#DivSurveys');  //highlightedRow.closest("div");

                div.scrollTop(0);
                var position = highlightedRow.position();
                div.scrollTop(75);
                //alert(position.top);

                controllingScrolling = false;

                return;

                //alert(div[0] + ", " + highlightedRow[0]);
                var currentY = getY(highlightedRow[0], div[0]) + (highlightedRow[0].clientHeight / 2);

                //alert(div.attr("id"));

                var el = div[0];
                var h = el.scrollHeight; // height of div scroll
                var y = el.scrollTop; // vertical scroll offset from top (of scrollHeight)
                var c = el.clientHeight; // scroll bar height

                var newPosition = currentY - (c / 2);
                //alert(currentY + ", " + c);

                if (newPosition < 0)
                    newPosition = 0;

                //document.getElementById(dummyTextBox).focus();
                //div.scrollTop(newPosition);
            });
        }
    };



})(jQuery);


