﻿(function($) {
    var __slideShow = null;
    var __slideShowEffectDuration = 1500;
    var Config = null;

    $.extend(String.prototype, {
        isMatch: function(regExpression) {
            if (this.match(regExpression)) {
                return true;
            }

            return true;
        }
    });

    $.Page = function(configuration, url, effectDuration, imageDelay) {
        Config = configuration;
        this.PageName = url.substring(url.lastIndexOf('/') + 1).toLowerCase() || 'index.php';
        this.Config = configuration;
        this.EffectDuration = effectDuration;
        this.ImageDelay = imageDelay;
        this.StrategyImpl = null;

        //remove page extension
        this.PageName = this.PageName.substring(0, this.PageName.lastIndexOf("."));

        //slideshow pages
        var ssPages = /^(people|places|things|lifestyle|editorial|advertising)$/gi;

        if (this.PageName == "index" || this.PageName == "new-index") {
            this.StrategyImpl = new $.Page.Home(this.Config, this.EffectDuration, this.ImageDelay);
        } else if (this.PageName == "promos") {
            this.StrategyImpl = new $.Page.Promos(this.Config);
        } else if (this.PageName.isMatch(ssPages)) {
            this.StrategyImpl = new $.Page.SlideShow(this.Config, this.PageName);
        } else if (this.PageName == "client") {
            this.StrategyImpl = new $.Page.Client(this.Config, __username);
        }
    }

    $.extend($.Page, {
        /** Child Objects **/
        Home: function(configuration, effectDuration, imageDelay) {
            this.Config = configuration;
            this.EffectDuration = effectDuration;
            this.ImageDelay = imageDelay;
        },
        Promos: function(configuration) {
            this.Config = configuration;
        },
        Client: function(configuration, username) {
            this.Config = configuration;
            this.Username = username;
        },
        SlideShow: function(configuration, rootElement) {
            this.Config = configuration;
            this.RootElement = rootElement;
        },
        /** Prototype Extensions **/
        prototype: {
            init: function() {
                if (this.StrategyImpl != null)
                    this.StrategyImpl.load();
            }
        }
    });

    /** HOME PAGE **/
    $.extend($.Page.Home.prototype, {
        load: function() {
            //show random photo
            var randomPhotos = $(this.Config).find('random-photos').children();
            var index = Math.floor(Math.random() * randomPhotos.length);

            //preload
            $.preloadImages($(randomPhotos[index]).attr('path'));

            //set path
            $("#home-pic img").attr('src', $(randomPhotos[index]).attr('path'));
            $("#home-pic").fadeIn(this.EffectDuration);

            //wait 
            setTimeout(this.showHomePage, this.ImageDelay);
        },
        showHomePage: function() {
            $('#home-pic').fadeOut(this.EffectDuration, function() {
                setTimeout($('#wrap, #footer').fadeIn(this.EffectDuration), this.EffectDuration);
            });
        }
    });

    /** PROMOS PAGE **/
    $.extend($.Page.Promos.prototype, {
        load: function() {
            var cfg = this.Config;

            $(cfg).find("promo").each(function(i) {
                var a = $('<a></a>').attr('id', $(this).attr('id')).attr('href', '#' + i).text($(this).attr('name')).click(function(e) {
                    e.preventDefault();
                    document.location = '?' + $(this).attr('id');
                }).bind('showSlides', function() {
                    $('#promoList a').removeClass('active-link');
                    $(this).addClass('active-link');

                    var index = $(this).attr('href').substring($(this).attr('href').indexOf('#') + 1);
                    var promos = $(cfg).find('promos').children();

                    var images = [];
                    $(promos[index]).children().each(function() {
                        images.push({
                            name: $(this).attr('name') || '',
                            path: $(this).attr('path')
                        });
                    });


                    __slideShow = new $.SlideShow(images);
                    __slideShow.init();
                });

                $('<li></li>').html(a).appendTo('#promoList');
            });

            //click the first one
            if (!document.location.search || document.location.search == null) {
                $('#promoList a:first').trigger('click');
            }
            else {
                var id = document.location.search.substring(1);
                $('#promoList a#' + id).trigger('showSlides');
            }
        }
    });

    /** PEOPLE PAGE **/
    $.extend($.Page.SlideShow.prototype, {
        load: function() {
            var images = [];
            $(this.Config).find(this.RootElement).children().each(function() {
                images.push({
                    name: $(this).attr('name') || '&nbsp;',
                    path: $(this).attr('path')
                });
            });

            __slideShow = new $.SlideShow(images);
            __slideShow.init();
        }
    });

    /** CLIENT PAGE **/
    $.extend($.Page.Client.prototype, {
        load: function() {
            var images = [];
            var un = this.Username;
            var fullname = '';

            $(this.Config).find('clients').children().each(function() {
                if ($(this).attr('username') == un) {

                    fullname = $(this).attr('name');

                    $(this).children().each(function() {
                        images.push({
                            name: $(this).attr('name') || '&nbsp;',
                            path: $(this).attr('path')
                        });
                    });
                }
            });

            var a = $('<a></a>').attr('href', '#').addClass('active-link').html(fullname.toUpperCase()).click(function(e) {
                e.preventDefault();
            });

            $('<li></li>').html(a).appendTo('#promoList');

            __slideShow = new $.SlideShow(images);
            __slideShow.init();
        }
    });

    /** SlideShow Class **/
    $.SlideShow = function(images) {
        this.Images = images;
        this.CurrentIndex = 0;
    }

    $.extend($.SlideShow.prototype, {
        init: function() {
            $(".pager #next-link").unbind('click').click(function(e) {
                e.preventDefault();
                __slideShow.next();
            });

            $(".pager #prev-link").unbind('click').click(function(e) {
                e.preventDefault();
                __slideShow.prev();
            });

            //do we have any images to show?
            if (this.Images.length > 0) {
                var num = new $.NumberImage($(Config).find("number"), this.Images.length, '.pager #num3', '.pager #num4');
                this.showIndex(0);
            }
        },
        next: function() {
            if (this.CurrentIndex < (this.Images.length - 1))
                this.showIndex(this.CurrentIndex + 1);
            else
                this.showIndex(0);
        },
        prev: function() {
            if (this.CurrentIndex > 0)
                this.showIndex(this.CurrentIndex - 1);
            else
                this.showIndex(this.Images.length - 1);
        },
        showIndex: function(index) {
            this.CurrentIndex = index;

            //empty the container(s)
            $('.image-container').empty();

            //show loading?
            if (index < (this.Images.length - 1)) {
                $.preloadImages(this.Images[index].path, this.Images[index + 1].path);
            } else if (index == 0) {
                $.preloadImages(this.Images[index].path, this.Images[this.Images.length - 1].path);
            }

            var img = $('<img />')
                .attr('alt', this.Images[index].name)
                .attr('src', this.Images[index].path)
                .css('display', 'none');

            //fade the image in
            $('.image-container').html(img);
            img.fadeIn(__slideShowEffectDuration);

            //update numeric display
            $('.pager #name-container').html(this.Images[index].name);
            $('.pager p').html(this.Images[index].name);
            var num = new $.NumberImage($(Config).find("number"), (index + 1), '.pager #num1', '.pager #num2');
        }
    });

    $.NumberImage = function(spriteDefinitions, integer, elm1, elm2) {

        var intChar = integer.toString().charAt(0);
        $(spriteDefinitions).each(function() {
            if ($(this).attr('value') == intChar) {
                $(elm1).show();
                $(elm1).css('width', $(this).attr('width') + 'px');
                $(elm1).css('background-position', '-' + $(this).attr('x') + 'px 0');
            }
        });

        if (integer.toString().length > 1) {
            intChar = integer.toString().charAt(1);
            $(spriteDefinitions).each(function() {
                if ($(this).attr('value') == intChar) {
                    $(elm2).show();
                    $(elm2).css('width', $(this).attr('width') + 'px');
                    $(elm2).css('background-position', '-' + $(this).attr('x') + 'px 0');
                }
            });
        } else {
            $(elm2).hide();
        }
    };

    $.preloadImages = function() {
        $.each(arguments, function(e) {
            $(new Image()).load(function() { }).attr('src', this);
        });

        /*for (var i = 0; i < arguments.length; i++) {
        $("<img />").attr("src", arguments[i]);
        }*/
    }

})(jQuery);
