﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference path="../client_scripts/ClientFoundation/Frameworks/JQuery/jquery.intellisense.js" />
/// <reference path="../../../../../../Core/Source/Core/client_scripts/ClientFoundation/Frameworks/JQuery/jquery.intellisense.js" />
/// <reference path="../Services/PictureGalleryService.svc" />

var pgm = new function() {
};
/*********pgm.layout*******/
pgm.layouts = function() {
}
pgm.layouts.registerItem = function(containerId, type) {
    var instance = eval("new pgm.layouts." + type + "('" + containerId + "');");
    return instance;
}
pgm.layouts.scrollbarWidth = function() {
    var inner = document.createElement('p');
    inner.style.width = "100%";
    inner.style.height = "200px";

    var outer = document.createElement('div');
    outer.style.position = "absolute";
    outer.style.top = "0px";
    outer.style.left = "0px";
    outer.style.visibility = "hidden";
    outer.style.width = "200px";
    outer.style.height = "150px";
    outer.style.overflow = "hidden";
    outer.appendChild(inner);

    document.body.appendChild(outer);
    var w1 = inner.offsetWidth;
    outer.style.overflow = 'scroll';
    var w2 = inner.offsetWidth;
    if (w1 == w2) w2 = outer.clientWidth;

    document.body.removeChild(outer);

    return (w1 - w2);
}
pgm.layouts.hasVerticalScroll = function(element) {
    var y = element.scrollTop;
    var yAdd, yLess;
    yAdd = ++element.scrollTop;
    element.scrollLeft = y;
    yLess = --element.scrollTop;
    element.scrollLeft = y;

    var output = false;
    if (yAdd != y || yLess != y) {
        output = true;
    }
    return output;
}
pgm.layouts.baseLayout = function(containerId) {
    var that = this;
    this.container = document.getElementById(containerId);
    this.move_next_delegate = function() { that.move_next.apply(that); };
    this.move_previous_delegate = function() { that.move_previous.apply(that); };

}
pgm.layouts.baseLayout.prototype = {
    get_container: function() {
        return this.container;
    },
    get_galleryContainer: function() {
        var galleryContainer = $("div.Gallery_Container", this.get_container());
        return galleryContainer;
    },
    get_currentPictureContainer: function() {
        var currentPictureContainer = $(".Gallery_Current_Picture", this.get_galleryContainer());
        return currentPictureContainer;
    },
    get_currentPictureWrapper: function() {
        var currentPictureWrapper = $(".Gallery_Current_Picture_Wrapper", this.get_currentPictureContainer());
        return currentPictureWrapper;
    },
    get_descriptionContainer: function() {
        var descriptionContainer = $(".Description", this.get_galleryContainer());
        return descriptionContainer;
    },
    get_descriptionElement: function() {
        var descriptionElement = $("span", this.get_descriptionContainer());
        return descriptionElement;
    },
    get_navigationContainer: function() {
        var navigationContainer = $(".Gallery_Navigation", this.get_galleryContainer());
        return navigationContainer;
    },
    get_moveNextButton: function() {
        var nextButton = $(".Gallery_Navigation_Next", this.get_navigationContainer());
        return nextButton;
    },
    get_movePreviousButton: function() {
        var prevButton = $(".Gallery_Navigation_Previous", this.get_navigationContainer());
        return prevButton;
    },
    get_pictures: function() {
        var pictures = $("img", this.get_currentPictureContainer());
        return pictures;
    },
    get_currentPicture: function() {
        var currentPicture = $("img.Selected_Picture", this.get_currentPictureContainer());
        return currentPicture;
    },
    get_thumbnailsContainer: function() {
        var thumbnailsContainer = $(".Gallery_Thumbnails", this.get_galleryContainer());
        return thumbnailsContainer;
    },
    get_thumbnails: function() {
        var thumbnails = this.get_thumbnailsContainer().find("li");
        return thumbnails;
    },
    get_selectedThumbnail: function() {
        var selectedThumbnail = this.get_thumbnails().filter(".thumbnail_selected");
        return selectedThumbnail;
    },
    get_selectedThumbnailPicture: function() {
        var selectedThumbnailPicture = this.get_selectedThumbnail().find("img");
        return selectedThumbnailPicture;
    },
    get_thumbnailLinks: function() {
        var thumbnailLinks = this.get_thumbnails().children("a");
        return thumbnailLinks;
    },
    get_thumbnailImages: function() {
        var thumbnailImages = this.get_thumbnailLinks().children("img");
        return thumbnailImages;
    },
    get_moduleID: function() {
        return $(this.get_container()).attr("moduleID");
    },
    get_siteID: function() {
        return $(this.get_container()).attr("siteID");
    },
    get_addCommentMessage: function() {
        return $(this.get_container()).attr("addCommentMessage");
    },
    _isBrowserInQuirksMode: function() {
        return document.compatMode == 'BackCompat';
    },
    isEditable: function() {
        return $(this.get_container()).hasClass("Editable");
    },
    get_thumbnailStrategy: function() {
        return $(this.get_container()).attr("thumbnailStrategyName");
    },
    get_thumbnailPropertyName: function() {
        if (this.get_thumbnailStrategy() == "Squared") {
            return "squaredThumbnailUrl";
        }
        else {
            return "symmetricThumbnailUrl";
        }
    },
    setThumbnailImagePosition: function(img) {
        var jimage = $(img);
        var width = jimage.width();
        var height = jimage.height();
        var parentWidth = jimage.parents("li").width();
        var parentHeight = jimage.parents("li").height();
        jimage.css("top", (parentHeight - height) + "px ").css("left", ((parentWidth - width) / 2) + "px");
    },
    setThumbnailsImagesSizes: function() {
    },
    parseLinkInfo: function(link) {
        var output = $(link).attr("jsonInfo");
        if (typeof output == 'string') {
            output = eval('(' + $(link).attr("jsonInfo") + ')');
        }
        return output;
    },
    setLinkInfo: function(link, linkInfo) {
        $(link).removeAttr("jsonInfo").each(function() {
            this["jsonInfo"] = linkInfo;
        });
    },
    setThumbnailSelected: function(caller) {
        var selectedThumbnail = this.get_selectedThumbnail();
        selectedThumbnail.removeClass("thumbnail_selected");
        $(caller).addClass("thumbnail_selected");
    },
    afterLoadPicture: function(caller) {
        this.setThumbnailSelected(caller);
    },
    loadPicture: function(params, link) {
        var currentPicture = this.get_currentPicture();
        var description = this.get_descriptionElement();
        var descriptionContainer = this.get_descriptionContainer();
        description.text(params.description);
        description.attr("title", description.text());
        if (this.isEditable()) {
            if (params.description == "") {
                descriptionContainer.addClass("description_empty");
                description.text(this.get_addCommentMessage());
            }
            else {
                descriptionContainer.removeClass("description_empty");
            }
        }
    },
    move_forward: function(count, noClick) {
        var next = this.get_selectedThumbnail();
        for (var index = 0; index < count; index++) {
            next = next.next();
            if (next.size() == 0) {
                next = this.get_thumbnails().filter(":first");
            }
        }
        if (noClick) {
            this.setThumbnailSelected(next);
        }
        else {
            next.click();
        }
    },
    move_next: function() {
        this.move_forward(1);
    },
    move_backward: function(count, noClick) {
        var prev = this.get_selectedThumbnail();
        for (var index = 0; index < count; index++) {
            prev = prev.prev();
            if (prev.size() == 0) {
                prev = this.get_thumbnails().filter(":last");
            }
        }
        if (noClick) {
            this.setThumbnailSelected(prev);
        }
        else {
            prev.click();
        }
    },
    move_previous: function() {
        this.move_backward(1);
    },
    cacheImages_CallBack: function(src, onLoadHandler) {
        window.setTimeout(function() {
            $.cacheImage(src,
            {
                load: onLoadHandler
            }
            );
        }, 100);
    },
    cacheImages: function() {
        var that = this;
        var index = 0;
        var pictures = this.get_pictures();

        this.get_thumbnailLinks().each(function() {
            var caller = this;
            var params = that.parseLinkInfo(this);
            var src = params.imageUrl;
            var picture = pictures.eq(index);
            var timeout = parseInt(index / 10);
            window.setTimeout(function() {
                that.cacheImages_CallBack(src, function() {
                    picture.attr("src", src);
                    picture.attr("loaded", true);
                });
            }, 3000 * (timeout));
            index++;
        });
    },
    fetchThumbnails_callBack: function(img, src) {
        img.src = src;
        this.cacheImages_CallBack(src, function() {
            $(img).parents(".Gallery_Thumbnails li").addClass("Thumbnail_Loaded");
        });
    },
    fetchThumbnails: function() {
        var that = this;
        var thumbnailProperty = this.get_thumbnailPropertyName();
        var index = 0;
        this.get_thumbnailImages().each(function() {
            var params = that.parseLinkInfo(this);
            var caller = this;
            var timeout = parseInt(index / 10);
            window.setTimeout(function() {
                var src = params[thumbnailProperty];
                that.fetchThumbnails_callBack(caller, src);
            }, 500 * timeout);
            index++;
        });
    },
    cycle_options: function() {
        var that = this;
        var output = {
            speed: 500,
            timeout: 0,
            pager: "ul",
            slideExpr: "img",
            pagerAnchorBuilder: function(idx, slide) {
                return that.get_thumbnails().eq(idx);
            },
            before: function(currSlideElement, nextSlideElement, options, forwardFlag) {

                var img = $(this);
                var parentWidth = img.parent().width();
                var parentHeight = img.parent().height();
                var width = img.width();
                var height = img.height();

                img.css({ marginLeft: (parentWidth - width) / 2 });
                img.css({ marginTop: (parentHeight - height) / 2 });

                var desc = that.get_descriptionContainer();

                desc.width(img.width());
                desc.css({ marginLeft: (parentWidth - width) / 2 });
                desc.css({ marginTop: (-(parentHeight - height) / 2) });

                if (!img.attr("loaded")) {

                    var pictures = that.get_pictures();
                    var thumbnailImages = that.get_thumbnailImages();
                    var index = pictures.index(this)
                    var params = that.parseLinkInfo(thumbnailImages.eq(index))
                    var src = params.imageUrl;
                    var picture = pictures.eq(index);

                    var currSlide = pictures.eq(options.currSlide);
                    currSlide.css("display", "none");


                    that.cacheImages_CallBack(src, function() {
                        picture.attr("src", src);
                        pictures.css("display", "none");
                    });

                    picture.bind("load", function() {
                        picture.attr("loaded", true);
                        var link = that.get_thumbnails().eq(index);
                        link.click();
                        window.setTimeout(function() {
                            pictures.css("display", "block");
                        }, 0);
                    });
                }

            }
        };
        return output;
    },
    get_cycleGallery: function() {
        var gallery = $(".Gallery_Current_Picture_Container", this.get_container());
        return gallery;
    },
    setup_cycle: function() {
        var gallery = this.get_cycleGallery();
        gallery.cycle(this.cycle_options());
    },
    document_keyDown_Left: function(e) {
        if (this._navigate) {
            return;
        }
        var that = this;
        this._navigate = true;
        this._navigate_to_previous = true;
        this._navigate_cancel_mouseup = false;
        this._navigate_interval = window.setInterval(function() {
            that._navigate_cancel_mouseup = true;
            that.move_backward(1, true);
        }, 500);
    },
    document_keyDown_Right: function(e) {
        if (this._navigate) {
            return;
        }
        var that = this;
        this._navigate = true;
        this._navigate_to_next = true;
        this._navigate_cancel_mouseup = false;
        this._navigate_interval = window.setInterval(function() {
            that._navigate_cancel_mouseup = true;
            that.move_forward(1, true);
        }, 500);
    },
    document_keyUp_After_keyDown_Left_Or_Right: function(e) {
        window.clearInterval(this._navigate_interval);
        if (!this._navigate_cancel_mouseup) {
            if (this._navigate_to_next) {
                this.move_forward(1);
            }
            if (this._navigate_to_previous) {
                this.move_backward(1);
            }
        }
        else {
            this.get_selectedThumbnail().click();
        }
        this._navigate = false;
        this._navigate_to_next = false;
        this._navigate_to_previous = false;
        this._navigate_cancel_mouseup = false;
    },
    setup_navigationButtons: function() {
        var that = this;
        this.get_moveNextButton().bind("click", that.move_next_delegate);
        this.get_movePreviousButton().bind("click", that.move_previous_delegate);
        this._navigate = false;
        this._navigate_to_next = false;
        this._navigate_to_previous = false;
        this._navigate_cancel_mouseup = false;

        $().bind("keydown", "right", function(e) {
            that.document_keyDown_Right(e);
        });
        $().bind("keydown", "left", function(e) {
            that.document_keyDown_Left(e);
        });
        $().bind("keyup", function(e) {
            if (that._navigate) {
                that.document_keyUp_After_keyDown_Left_Or_Right(e);
            }
        });
    },

    _hack_ieGalleryNavigationHackWhenIsInQuirskMode: function() {
        if ($.browser.msie && this._isBrowserInQuirksMode()) {
            var that = this
            window.setTimeout(function() {
                var navigationControls = that.get_navigationContainer().children(".Gallery_Navigation_Next,.Gallery_Navigation_Previous");
                navigationControls.each(function() {
                    var navigationControl = $(this);
                    var navigationControlWidth = navigationControl.width();
                    navigationControl.width(0).width(navigationControlWidth);
                    navigationControl.css("zoom", "1");
                });
            }, 1000);
        }
    },
    run_hacks: function() {
        this._hack_ieGalleryNavigationHackWhenIsInQuirskMode();
    },
    makeEditable: function() {
        var descriptionContainer = this.get_descriptionContainer();
        var descriptionElement = this.get_descriptionElement();
        descriptionContainer
            .mouseover(function() {
                $(this).addClass("description_hover");
            })
            .mouseout(function() {
                $(this).removeClass("description_hover");
            });
        var editing = false;
        var that = this;
        var moduleID = this.get_moduleID();
        var siteID = this.get_siteID();
        var link = null;
        var img = null;
        var linkInfo = null;
        var pictureID = null;
        descriptionElement
            .click(function() {
                if (editing) {
                    return;
                }
                editing = true;

                descriptionContainer.removeClass("description_empty");
                this.contentEditable = true;
                descriptionContainer.addClass("description_editing");
                link = that.get_selectedThumbnail().children("a");
                linkInfo = that.parseLinkInfo(link);
                $(this).text(linkInfo.description);
                $(this).focus();
            })
            .blur(function() {
                this.contentEditable = false;
                descriptionContainer.removeClass("description_editing");

                link = that.get_selectedThumbnail().children("a");
                img = that.get_selectedThumbnailPicture();
                linkInfo = that.parseLinkInfo(link);
                pictureID = linkInfo.pictureID;

                var newDescription = descriptionElement.text();
                if (newDescription == linkInfo.description) {
                    link.click();
                    editing = false;
                    return;
                }
                PictureGalleryV2.Web.Admin.Services.IPictureManagerService.UpdateDescription(moduleID, pictureID, newDescription, siteID,
                function() {
                    linkInfo.description = newDescription;
                    descriptionElement.attr("title", newDescription);
                    img.attr("title", newDescription);
                    that.setLinkInfo(link, linkInfo);
                    that.setLinkInfo(img, linkInfo);
                    link.click();

                    editing = false;
                },
                function(res) {
                    descriptionElement.text(linkInfo.description);
                    link.click();
                    editing = false;
                    alert(res.get_message());
                });
            })
            ;
    },
    on_documentReady: function() {
        var that = this;
        window.setTimeout(function() { that.cacheImages(); }, 1000);
        this.get_thumbnails().filter(":first").addClass("thumbnail_selected");

        this.get_thumbnails().bind("click", function() {
            var link = $("a", this);
            that.loadPicture(that.parseLinkInfo(link), link);
            that.afterLoadPicture($(this));
        });


        this.setup_cycle();
        this.setup_navigationButtons();

        var loadCount = 0;
        var imageCount = this.get_thumbnails().size();
        this.get_galleryContainer().addClass(that._isBrowserInQuirksMode() ? "quirks_mode" : "strict_mode");

        this.get_thumbnailImages().bind("load", function() {
            if (!(that._isBrowserInQuirksMode() && $.browser.msie && $.browser.version.startsWith("6")) || $.browser.safari) {
                that.setThumbnailImagePosition(this);
            }
            loadCount++;
            if (loadCount == imageCount) {
                that.setThumbnailsImagesSizes();
                loadCount = 0;
            }
        });

        this.setThumbnailsImagesSizes();
        this.run_hacks();
        window.setTimeout(function() { that.fetchThumbnails(); }, 0);
        if (this.isEditable()) {
            this.makeEditable();
        }
    },
    initialize: function() {
        var that = this;
        $(document).ready(function() {
            that.on_documentReady();
        });
    }
}

pgm.layouts.baseLayout.registerClass("pgm.layouts.baseLayout");
/************************/
