﻿var firstId;
var lastId;
var prevId;
var nextId;
var section;
var gallery;

new function ($) {
    $.fn.loadData = function (id, direction) {
        var node = $("#frame img:visible");
        var jqxhr = $.getJSON("/Gallery/" + section + "/" + gallery + "/" + id, null, function (data) {
            if (data.length == 2) {
                var item;
                if (id == nextId) {
                    item = data[0];
                    var picture = document.createElement("IMG");
                    picture.setAttribute("id", "pic_" + item.ID);
                    picture.setAttribute("src", item.Src);
                    picture.setAttribute("alt", item.Title);
                    picture.setAttribute("style", "display:none");
                    $(picture).insertBefore(node);
                    prevId = data[0].ID;
                    $("#navigation a:last").removeAttr('href');
                    $("#navigation a:last").attr('style', 'color:Gray');
                    $("#navigation a:last").unbind('click');

                } else if (id == prevId) {
                    item = data[1];
                    var picture = document.createElement("IMG");
                    picture.setAttribute("id", "pic_" + item.ID);
                    picture.setAttribute("src", item.Src);
                    picture.setAttribute("alt", item.Title);
                    picture.setAttribute("style", "display:none");
                    $(picture).insertAfter(node);
                    nextId = data[1].ID;
                    $("#navigation a:first").removeAttr('href');
                    $("#navigation a:first").attr('style', 'color:Gray');
                    $("#navigation a:first").unbind('click');
                }
            }
            if (data.length == 3) {
                var item;
                var picture = document.createElement("IMG");
                picture.setAttribute("style", "display:none");

                switch (direction) {
                    case "Prev":
                        item = data[0];
                        picture.setAttribute("id", "pic_" + item.ID);
                        picture.setAttribute("src", item.Src);
                        picture.setAttribute("alt", item.Title);
                        $(picture).insertBefore(node);
                        prevId = data[0].ID;
                        nextId = data[2].ID;
                        break;
                    case "Next":
                        item = data[2];
                        picture.setAttribute("id", "pic_" + item.ID);
                        picture.setAttribute("src", item.Src);
                        picture.setAttribute("alt", item.Title);
                        $(picture).insertAfter(node);
                        nextId = data[2].ID;
                        prevId = data[0].ID;
                        break;
                    default:
                        picture.setAttribute("id", "pic_" + data[0].ID);
                        picture.setAttribute("src", data[0].Src);
                        picture.setAttribute("alt", data[0].Title);
                        $(picture).insertBefore(node);
                        prevId = data[0].ID;
                        var pic = document.createElement("IMG");
                        pic.setAttribute("style", "display:none");
                        pic.setAttribute("id", "pic_" + data[2].ID);
                        pic.setAttribute("src", data[2].Src);
                        pic.setAttribute("alt", data[2].Title);
                        $(pic).insertAfter(node);
                        nextId = data[2].ID;
                        break;
                }

            }
        }).error(function (a, b, c) {
            alert(c);
        });
        return jqxhr;
    }
} (jQuery);

new function ($) {
$.fn.processLinks = function (section, id, source) {
    
    // Убираем изменения цвета для сработавшей ссылки
    $("#navigation").find("a").removeAttr('style');

    // Выставляем локальный адрес и убираем события onclick для обеих ссылок
    // В этот момент нажатие на ссылку вызовет только лишь переход к #
    $("#navigation").find("a").attr('href', '#').unbind('click')

    // Выставляем новые адреса
    $("#navigation a:first").attr('href', "/Gallery/" + section + "/" + gallery + "/" + (prevId));
    $("#navigation a:last").attr('href', "/Gallery/" + section + "/" + gallery + "/" + (nextId));

    // Добавляем обработчик события onclick
    $("#navigation").find("a").click(function () {
        $().ChangeImage($(this));
        return false;
    });

    // Вся эта махинация нужна для случая, когда необходимо изменить направление движения
    // из-за достижения края списка. В противном случае неактивная ссылка, указывающая на 
    // элемент, следующий за крайним, так и останется неактивной несмотря на то, что 
    // движение пошло в обратную сторону и крайний элемент уже не крайний.

}
} (jQuery)

new function ($) {
$.fn.ChangeImage = function (source) {
    var node = $("#frame img:visible");
    var nextNode, prevNode;
    if (source != null) {
        var direction = $(source).attr('rel');
        var segments = $(source).attr('href').split('/');
        var id = segments[segments.length - 1];
        if (id != node.attr('id').substr(4)) {
            switch (direction) {
                case "Next":
                    nextNode = node.next();
                    prevNode = node.prev();
                    break;
                default:
                    nextNode = node.prev();
                    prevNode = node.next();
                    break;
            }

            // Убираем из ссылки адрес, изменяем ей цвет и убираем обработчик события onclick
            // с этого момента ссылка неактивна
            $(source).removeAttr('href');
            $(source).attr('style', 'color:Gray');
            $(source).unbind('click');

            node.fadeOut(400, function () {
                nextNode.fadeIn(400, function () {
                    var obj = $().loadData(id, direction);
                    obj.success(function () {
                        if (id != firstId && id != lastId) {
                            // Запрашиваемая картинка не является крайней с какой-либо из сторон
                            // Выполняем все действия по замене ссылок
                            $().processLinks(section, id, source);
                            $("#caption span").text(id);
                        } else if (id == firstId) {
                            // Запрашивамая картинка крайняя от начала
                            // Уменьшаяем id в ссылке на следующую на 1, ссылка на передыдущую остается неактивной
                            $("#navigation a:last").attr('href', "/Gallery/" + section + "/" + gallery + "/" + (nextId));
                        } else {
                            // Запрашивамая картинка крайняя от конца
                            // Уменьшаяем id в ссылке на предыдущую на 1, ссылка на следующую остается неактивной
                            $("#navigation a:first").attr('href', "/Gallery/" + section + "/" + gallery + "/" + (prevId));
                            $("#caption span").text(id);
                        }
                    });
                    obj.error(function (a, b, c) {

                    });
                });
            });

            if (prevNode.length > 0 && $(prevNode).get(0).tagName == "IMG")
                prevNode.remove();
        }
    }
}
} (jQuery);

(function ($) {
    $.fn.filterSet = function () {
        return this.each(function () {
            var $this = $(this);
            var url = document.location.href;
            var current = "";
            var startIndex = url.indexOf("?");

            if (startIndex != -1)
                current = url.substring(startIndex + 1);
            var segments = current.split(":");
            for (var i = 1; i <= segments.length; i++) {
                var node = $('#field_' + i);
                switch (node[0].tagName) {
                    case "SELECT":
                        $("#field_" + i + " option").each(function () {
                            if ($(this).val() == segments[i - 1]) {
                                $(this).attr("selected", "selected");
                            }
                        });
                        break;
                    default:
                        node.val(segments[i - 1]);
                        break;
                }
            }

            $("#applyButton").click(function () {
                var querystring = "";
                var fields = $('[id *= "field_"]').length;
                for (var i = 1; i <= fields; i++) {
                    var node = $('#field_' + i);
                    switch (node[0].tagName) {
                        case "SELECT":
                            querystring += $("#field_" + i + " option:selected").val() + ":";
                            break;
                        default:
                            querystring += node.val() + ":";
                            break;
                    }
                }
                var url = $(this).attr("href") + "?" + querystring;
                document.location = url.replace(/\:{1,}$/, "");
                return false;
            });
        });
    };
})(jQuery);

new function($) {
    $.fn.getCursorPosition = function() {
        var pos = 0;
        var input = $(this).get(0);
        // IE Support
        if (document.selection) {
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            pos = sel.text.length - selLen;
        }
        // Firefox support
        else if (input.selectionStart || input.selectionStart == '0')
            pos = input.selectionStart;

        return pos;
    }
} (jQuery);

new function($) {
    $.fn.setCursorPosition = function(pos) {
        this.each(function(index, elem) {
            if (elem.setSelectionRange) {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        });
        return this;
    };
} (jQuery);

new function($) {
    $.fn.formatInputNumbers = function(e) {
        /* TODO: 
        * Return cursor to position between the same characters just before inserting.
        * FireFox support.
        * Read point character from culture settings.
        */
        var cursor = $(this).getCursorPosition();   // Cursor position.
        var oldvalue = $(this).val();               // Previous value of the input field.
        var point = oldvalue.indexOf(",");          // Float point position, if present.
        var left, right;                            /* Parts of value before and after cursor at 
                                                         * beginning and floating point at the end. */
        var value;                                  // New value after processing input.

        var _code = e.which;                        // ASCII Code for pressed button.

        // Ignore special keys
        if ((e.ctrlKey || e.altKey || _code < 48) && _code != 8 && _code != 46)
            return true;
        var key = String.fromCharCode(_code);

        // Test if allowed key pressed - backspace, delete, comma or numeric key
        if (/[\d]/.test(key) || _code == 188 || _code == 8 || _code == 46) {
            left = oldvalue.substr(0, cursor);
            right = oldvalue.substr(cursor, oldvalue.length - cursor);
            if (_code == 8) {
                // Backspace key pressed
                value = left.substr(0, cursor - 1) + right;
            } else if (_code == 46) {
                // Delete key pressed
                value = left + right.substr(1, right.length);
            } else if (_code != 188) {
                // Numeric key pressed
                value = left + key + right;
                // Set new point position if new character will be inserted before this point
                if (point >= cursor)
                    point++;
            } else if (_code == 188) {
                value = left + "," + right;
                point = cursor;
            }
            // Now this variables stores parts of new value before and after floating point
            left = "";
            right = "";
            if (point > -1) {
                left = value.substr(0, point);
                right = value.substr(point, value.length - point);
            } else {
                left = value;
            }
            if (left.length > 0) {
                value = "";
                for (var i = 0; i < left.length; i++) {
                    if (!isNaN(parseInt(left[i]))) {
                        value += left[i];
                    }
                }
                value = $.format(parseInt(value), "n0");
            }

            if (right.length > 0) {
                value += ",";
                for (var i = 0; i < right.length; i++) {
                    if (!isNaN(parseInt(right[i]))) {
                        value += right[i];
                    }
                }
            }
            $(this).val(value);
        }
        return false;
    };
} (jQuery);
