﻿///<reference path="jquery-1.4.1-vsdoc.js"/>
var Teasers = function (options) {
    var _this = {
        settings: null,
        container: null,
        activeIndex: 0,
        scrollSpeed: 'slow',
        itemCount: 0,
        slideShowDelay: 10000,
        init: function () {
            _this.settings = jQuery.extend({
                handler: "#teasers"
            }, options);


            _this.container = $(_this.settings.handler);
            _this.itemCount = $("li", _this.container).length - 2;
            _this.navigationHandler();
            _this.startTimer();
        },
        navigationHandler: function () {
            var navigationItems = _this.container.find("li.prev, li.next");

            _this.container.hover(function () {
                navigationItems.fadeIn();
            }, function () {
                navigationItems.fadeOut();
            })

            _this.container.find("li.prev, li.next").click(function () {
                if ($(this).is(".prev")) { // clicked previous
                    _this.navigatePrev();
                } else if ($(this).is(".next")) { // clicked next
                    _this.navigateNext();
                }
                _this.startTimer();
                return false;
            });
        },
        navigatePrev: function () {
            if (_this.activeIndex > 0) {
                _this.navigate(_this.activeIndex - 1);
            } else {
                _this.navigate(_this.itemCount - 1);
            }

            return true;
        },
        navigateNext: function () {
            if (_this.activeIndex < _this.itemCount - 1) {
                _this.navigate(_this.activeIndex + 1);
            } else {
                _this.navigate(0);
            }

            return true;
        },
        navigate: function (newIndex) {
            var currentItem = $("li.active", _this.container);
            var newItem = $("li:eq(" + (newIndex + 1) + ")", _this.container);
            currentItem.fadeOut(_this.scrollSpeed, function () {
                currentItem.removeClass("active");
                newItem.fadeIn(_this.scrollSpeed, function () { newItem.addClass("active"); });
            });

            _this.activeIndex = newIndex;
        },
        startTimer: function () {
            $.doTimeout("teasers");
            $.doTimeout("teasers", _this.slideShowDelay, _this.navigateNext);
        }
    };

    _this.init();
};

var PressLightBox = function () {
    var _this = {
        container: null,
        curtains: null,
        fadeSpeed: 200,
        init: function () {
            _this.setupCurtains();
            _this.container = $("#itemContainer");
            $(".item").click(_this.startItemDisplay);
            $(".close", _this.container).click(_this.hideItem);

            if (location.hash.indexOf("#press-") == 0) {
                var pressId = location.hash.substring("#press-".length);
                $("#item" + pressId).click();
            }
        },
        setupCurtains: function () {
            _this.curtains = $("#curtainLayer");
            if (_this.curtains.length == 0) {
                $("body").append("<div id=\"curtainLayer\">&nbsp;</div>");
                _this.curtains = $("#curtainLayer").click(_this.hideItem);
            }
        },
        startItemDisplay: function () {
            var id = $(this).attr("id").substring(4);
            $.getJSON("/Assets/Services/GetPress.ashx", { id: id }, function (data) {
                _this.container.find(".image").attr("src", data.Image).attr("alt", data.Title);
                _this.container.find(".header").text(data.Title);
                _this.container.find(".issue").text(data.Issue);
                _this.container.find("a.cufon").attr("href", data.File).attr("target", "_blank");

                _this.curtains.height($(document).height()).show();
                _this.container.centerScreen(true).show(_this.fadeSpeed, function () {
                    _this.curtains.css("height", getDocHeight());
                });
                Cufon.refresh();
            });
        },
        hideItem: function () {
            _this.container.hide(_this.fadeSpeed);
            _this.curtains.hide();
        }
    };

    _this.init();
   };

   var VideoPlayer = function () {
   	var _this = {
   		container: null,
   		curtains: null,
   		fadeSpeed: 200,
   		init: function () {
   			_this.setupCurtains();
   			_this.container = $("#videoContainer");

   			$(".player[data-id!='']").click(_this.startVideoDisplay);
   			$(".close", _this.container).click(_this.hideItem);
   		},
   		setupCurtains: function () {
   			_this.curtains = $("#curtainLayer");
   			if (_this.curtains.length == 0) {
   				$("body").append("<div id=\"curtainLayer\">&nbsp;</div>");
   				_this.curtains = $("#curtainLayer").click(_this.hideItem);
   			}
   		},
   		startVideoDisplay: function () {
   			//var itemId = $(this).attr("id").substring(5);
   			var itemId = $(this).data("id");
   			if (itemId) {
   				var videoContainer = $(".inner", _this.container);
   				videoContainer.empty();
   				$.getJSON("/Assets/Services/GetVideo.ashx", { id: itemId }, function (data) {
   					var elementId = "video" + itemId;
   					var element = $("<div id=\"" + elementId + "\"></div>");
   					videoContainer.append(element);

   					if (data.Url) {
   						_this.defaultEmbed(elementId, data);
   					} else if (data.Embed) {
   						element.append(data.Embed);

   					} else {
   						_this.hideItem();
   						return false; // no meaning to continue
   					}

   					_this.container.centerScreen(true).show(_this.fadeSpeed, function () {
   						_this.curtains.css("height", getDocHeight());
   					});
   				});
   				_this.curtains.height($(document).height()).show();

   			}

   			return false;
   		},
   		defaultEmbed: function (elementId, videoItem) {
   			$("#" + elementId).css({
   				width: videoItem.Width,
   				height: videoItem.Height
   			});
   			flowplayer(elementId, "/Assets/Flashes/flowplayer-3.1.5.swf", {
   				plugins: {
   					controls: {
   						autoHide: 'always',
   						display: 'none'
   					}
   				},
   				clip: {
   					url: videoItem.Url,
   					autoPlay: true
   				}
   			});
   		},
   		hideItem: function () {
   			_this.container.hide(_this.fadeSpeed);
   			_this.curtains.hide();
   		}
   	};

   	_this.init();
   };

var Gallery = function () {
    var _this = {
        destinationDropDown: null,
        yearDropDown: null,
        periodDropDown: null,
        selectedFolderHidden: null,
        button: null,
        images: null,
        activeIndex: 0,
        imageContainer: null,
        prevButton: null,
        nextButton: null,
        fullscreenButton: null,
        isFullscreen: false,
        listViewButton: null,
        slideShowButton: null,
        isRunning: false,
        loader: null,
        slideShowDelay: 5000,
        curtains: null,
        imageLayer: null,
        fadeDelay: 300,
        listContainer: null,
        modes: { "image": 0, "list": 1 },
        mode: null,
        init: function () {
            _this.destinationDropDown = $("#destinationDropDown");
            _this.yearDropDown = $("#yearDropDown");
            _this.periodDropDown = $("#periodDropDown");
            _this.selectedFolderHidden = $("#selectedFolderHidden");
            _this.button = $("#showImagesButton");
            _this.imageContainer = $("#imageContainer");
            _this.slideShowButton = $("#navigation .slideshow");
            _this.prevButton = $("#navigation .prev");
            _this.nextButton = $("#navigation .next");
            _this.fullscreenButton = $("#navigation .fullscreen");
            _this.listViewButton = $("#navigation .listview");
            _this.loader = $(".two .loader");
            _this.imageLayer = $("#imageLayer");
            _this.listContainer = $("#listContainer");
            _this.mode = _this.modes.image;

            //_this.getImages();
            _this.setupEvents();
        },
        setupEvents: function () {
            $.doTimeout("slideshow");

            _this.destinationDropDown.change(function () {
                if ($(this).val() != "") {
                    _this.selectedFolderHidden.val($(this).val());
                    _this.loadContent($(this).val(), _this.yearDropDown);
                }
            });

            _this.yearDropDown.change(function () {
                if ($(this).val() != "") {
                    _this.selectedFolderHidden.val($(this).val());
                    _this.loadContent($(this).val(), _this.periodDropDown);
                }
            });

            _this.periodDropDown.change(function () {
                if ($(this).val() != "") {
                    _this.selectedFolderHidden.val($(this).val());
                }
            });

            _this.button.click(function () {
                var url = location.href;
                if (url.indexOf("selected=") > -1) {
                    url = url.replace(/selected=.*/g, "selected=" + _this.selectedFolderHidden.val());
                } else {
                    url = url + (url.indexOf("?") > -1 ? "&" : "?") + "selected=" + _this.selectedFolderHidden.val();
                }
                location.href = url;
                return false;
            });

            _this.slideShowButton.click(function () {
                if (_this.isRunning) {
                    $.doTimeout("slideshow");
                } else {
                    $.doTimeout("slideshow", _this.slideShowDelay, function () {
                        if (_this.activeIndex < _this.images.length - 1) {
                            _this.loadImage(_this.activeIndex + 1);
                            return true;
                        } else {
                            return false;
                        }
                    });
                }

                _this.isRunning = !_this.isRunning;

                return false;
            });

            _this.prevButton.click(function () {

                if (_this.activeIndex > 0) {
                    _this.loadImage(_this.activeIndex - 1);
                }
            });

            _this.nextButton.click(function () {
                if (_this.activeIndex < _this.images.length - 1) {
                    _this.loadImage(_this.activeIndex + 1);
                }
            });

            _this.fullscreenButton.click(function () {
                _this.loadFullscreen(_this.activeIndex);

                return false;
            });

            _this.listViewButton.click(function () {

                if (_this.mode == _this.modes.image) {
                    _this.imageContainer.hide();
                    _this.listContainer.show();
                    _this.mode = _this.modes.list;
                } else {
                    _this.listContainer.hide();
                    _this.imageContainer.show();
                    _this.mode = _this.modes.image;
                }

                return false;
            });
        },
        loadContent: function (path, target) {
            $.getJSON("/Assets/Services/GetFolderContent.ashx", { path: path }, function (list) {
                target.empty().append("<option value=\"\">Välj här ------></option>");
                $.each(list, function () {
                    target.append("<option value=\"" + this.Path + "\">" + this.Title + "</option>");
                });
            });
        },
        getImages: function () {
            _this.loader.show();
            $.getJSON("/Assets/Services/GetGalleryImages.ashx", { path: _this.selectedFolderHidden.val() }, function (list) {
                _this.images = list;
                if (_this.images.length > 0) {
                    _this.activeIndex = 0;
                    _this.setupList();
                    _this.loadImage(0);
                } else {
                    _this.loader.hide();
                }
            });
        },
        loadImage: function (index) {
            _this.loader.show();

            var current = _this.images[index];
            var image = new Image(640, 430);
            image.src = current.Image;
            image.onload = function () {
                _this.imageContainer.find("img").attr("src", current.Image);
                _this.activeIndex = index;
                _this.loader.hide();
            };
        },
        loadFullscreen: function (index) {
            var current = _this.images[index];

            if (_this.curtains == null) {
                $("body").append("<div id=\"curtainLayer\">&nbsp;</div>");
                _this.curtains = $("#curtainLayer");
                _this.curtains.click(function () {
                    _this.imageLayer.hide(_this.fadeDelay);
                    _this.curtains.hide();
                });
            }

            _this.imageLayer.find("img").attr("src", current.Image);
            _this.imageLayer.find("h2").text(current.Title);
            _this.imageLayer.find("div.description").html(current.Description);

            _this.curtains.height($(document).height()).show();
            _this.imageLayer.centerScreen().show(_this.fadeDelay);
        },
        setupList: function () {
            _this.listContainer.empty()
            $.each(_this.images, function (i) {
                var item = $("<img src=\"" + this.ImageSmall + "\" width=\"25%\" height=\"25%\" alt=\"" + this.Title + "\"/>");
                item.click(function () {
                    _this.loadFullscreen(i);
                });
                _this.listContainer.append(item);
            });
        }
    };

    _this.init();

    return _this;
};

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

jQuery.fn.centerScreen = function (onlyX, loaded) {
    var obj = this;
    if (!loaded) {
        obj.css('top', 60 + $(window).scrollTop());
        obj.css('left', $(window).width() / 2 - this.width() / 2);
        
        $(window).bind("resize scroll", function () {
            obj.centerScreen(onlyX, !loaded);
        })
    } else {
        obj.stop();
        if (!onlyX) {
            obj.animate({
                top: 60 + $(window).scrollTop(),
                left: $(window).width() / 2 - this.width() / 2
            },
			200, 'linear');
        } else {
            obj.animate({ left: $(window).width() / 2 - this.width() / 2 },
			200, 'linear');
        }
    }

    return obj;
}
