﻿/// <reference path="jquery.intellisense.js"/>

var site = {
    start: function() {
        lightBox.start();
        caseStudies.start();
        smoothScroller.start();
        worklistHover.start();
        imageRotator.start(
            [
                [
                    /* websites */
                    {banner: 'wp-content/themes/MWP2.0/images/bnr_medn01.jpg', lightbox: 'wp-content/themes/MWP2.0/images/medn01.jpg' }
                ],
                [
                    /* photography */
                    {banner: 'wp-content/themes/MWP2.0/images/bnr_aype01.jpg', lightbox: 'wp-content/themes/MWP2.0/images/aype01.jpg' }
                ]
            ],
            7000
        );
    }
};

var externalLinks = {
    start: function() {
        $('a[rel="external"]').attr('target', '_blank');
    }
};

var caseStudies = {
    start: function() {
        $('#cstudies a').click(function() {
            var link = $(this);
            var target = $('.' + link.attr('class') + 'l');
            target.click();
            return false;
        });
    }
};

var smoothScroller = {
    start: function() {
        $('a[href!="#"][href^="#"]').each(function(i) {
            this.el = this.href.substring(this.href.indexOf('#'));
            this.href = 'javascript:void(0)';
        }).click(function(e) {
            var target = $(this.el);
            $('html,body').animate({scrollTop: target.offset().top}, 600, 'swing', null);
        });
    }
};

var worklistHover = {
    start: function() {
        $('ul.worklist li a').mouseover(function(e) {
            if(this.timer) {
                clearTimeout(this.timer);
                this.timer = null;  
            } else {
                var box = $($(this).siblings('.box')[0]);
                var top = box.height() + 46;
                box.css({
                    'opacity' : '0',
                    'display' : 'block',
                    'margin' : '-' + top + 'px 0 0 80px'
                }).animate({ 'opacity' : '1' }, 200, 'linear', null);
            }
        }).mousemove(function(e) {
            var left = e.clientX - $(this).offset().left;
            $(this).siblings('.box').css('margin-left', left);
        }).mouseout(function(e) {
            var x = this;
            this.timer = setTimeout(function() {
                x.timer = null;
                var box = $($(x).siblings('.box')[0]);
                box.animate({ 'opacity' : '0' }, 20, 'linear', function() {
                    box.css('display', 'none');
                });
            }, 10);
        });
    }
};

var lightBox = {
    start: function() {
        var links = $('a[rel="lightbox"]');
        links.each(function(i) {
            this.href = 'javascript:void(0)';
        });

        links.click(function(e) {
            lightBox.show(this);
        });
    },

    show: function(link) {
        // create background
        var bg = $($.create('div', { 'id': 'lightbox_bg' }));
        bg.css({
            'opacity': 0,
            'height': $(document).height()
        });
        $('#main').append(bg);
        bg.click(function(e) {
            lightBox.hide();
        });

        // create lightbox 
        var lightbox = $($.create('div', { 'id': 'lightbox' }));
        lightbox.click(function(e) {
            lightBox.hide();
        });
        lightbox.css({
            'margin-top': $(window).scrollTop(),
            'opacity': 0
        });
        $('#main').append(lightbox);
        var container = $($.create('div', { 'id': 'container' }));

        // prevent lightbox closing when clicking in container
        container.click(function(e) {
            e.stopPropagation();
        });
        lightbox.append(container);

        // create close link
        var close = $($.create('a', { 'href': 'javascript:void(0)', 'title': 'Close this window (You can also press your \'Escape\' key', 'id': 'btn_close' }));
        container.append(close);
        close.click(function(e) {
            lightBox.hide();
        });

        // add imgwrapper 
        var imgwrapper = $($.create('div', { 'class': 'imgwrapper' }));
        container.append(imgwrapper);

        // create first / main image
        var imageUrl = $($(link).siblings('.box').find('a')[0]).attr('href');
        var mainImageHolder = $($.create('div', { 'id': 'lightbox_imageholder' }));
        var mainImage = $($.create('img', { 'alt': 'screenshot', 'src': imageUrl, 'id': 'lightbox_image' }));
        mainImageHolder.append(mainImage);
        container.append(mainImageHolder);

        lightBox.showContent(link, false);

        // display
        bg.css('opacity', '.9');
        mainImageHolder.css('opacity', '0');
        lightbox.css('opacity', '1');

        mainImageHolder.animate({ opacity: '1' }, 300, 'linear', null);
    },

    showContent: function(link, transition) {
        var lightbox = $('#lightbox');
        var img = $('#lightbox_image');
        var container = $('#lightbox #container');

        // create imgnav 
        var imgnav = $($(link).siblings('.box').find('.imgnav')[0]).clone();
        if (!transition)
            container.append(imgnav);
        else
            imgnav.replaceAll('#lightbox .imgnav');
    
        // hook up imgnav links
        var imgnavLinks = imgnav.find('a');
        imgnavLinks.each(function(i) {
            this.img = this.href;
            this.href = 'javascript:void(0)';
            $(this).click(function(e) {
                lightBox.switchImage(this);
            });
        });
    
        // create boxcopy
        var boxcopy = $($(link).siblings('.box').find('.boxcopy')[0]).clone();
        if (!transition)
            container.append(boxcopy);
        else
            boxcopy.replaceAll('#lightbox .boxcopy');

    
        // replace rel="external" with target="_blank" in boxcopy
        var boxcopyLinks = boxcopy.find('a[rel="external"]');
        boxcopyLinks.each(function(i) {
            $(this).attr('target', '_blank');
        });

        // work out previous / next links
        var links = $('a[rel="lightbox"]');
        var index = -1;
        links.each(function(i) {     
            if (this == link) {
                index = i;
                return false;
            }
        });
        var next = index == links.length - 1 ? links[0] : links[index + 1];
        var prev = index == 0 ? links[links.length - 1] : links[index - 1];

        // create previous link
        var prevproject = $($.create('div', { 'id': 'prevproject' }));
        var prevlink = $($.create('a', { 'id': 'btn_imgprev', 'title': 'View the previous project', 'href': 'javascript:void(0)' }));
        prevlink.click(function(e) {
            lightBox.showContent(prev, true);
        });
        prevproject.append(prevlink);

        if (!transition)
            container.append(prevproject);
        else
            prevproject.replaceAll('#lightbox #prevproject');

        // create next link
        var nextproject = $($.create('div', { 'id': 'nextproject' }));
        var nextlink = $($.create('a', { 'id': 'btn_imgnext', 'title': 'View the next project', 'href': 'javascript:void(0)' }));
        nextlink.click(function(e) {
            lightBox.showContent(next, true);
        });
        nextproject.append(nextlink);

        if (!transition)
            container.append(nextproject);
        else
            nextproject.replaceAll('#lightbox #nextproject');

        // load in first image on transition
        if (transition) {
            lightBox.switchImage($('#lightbox .imgnav a')[0]);
        }
    },

    hide: function() {
        $('#lightbox_bg').remove();
        $('#lightbox').remove();
    },

    switchImage: function(link) {
        $(link).parent().parent().find('a').removeClass('over');
        $(link).addClass('over');
        var img = $('#lightbox_image');
        var holder = $('#lightbox_imageholder');

        // fade out image
        img.animate({ opacity: '0' }, 300, 'linear', function() {

            // fix height
            holder.height(img.height());
            holder.css('overflow', 'hidden');

            // fade in new image
            img.load(function() {
                holder.animate({ 'height': img.height() }, 250, 'swing', function() {
                    img.animate({ opacity: '1' }, 300, 'linear', null);
                });
            }).attr('src', link.img);
        });
    }
}

var imageRotator = {
    images: new Array(),
    delay: 3000,
    timer: null,
    paused: false,
    
    start: function(images, delay) {
        this.index = 0;
        this.images = images;
        if(delay != null)
            this.delay = delay;
        
        this.img = $("#mainimage");
        this.div = $("#mainimageholder");
        
        imageRotator.timer = setTimeout(this.nextImage, this.delay);
        //alert(images.websites);
        /*for(var i in images) {
            alert(i);
        }*/
        //alert(images[0][0].banner);
        //alert(images.length);
    },
    
    nextImage: function() {
        if(imageRotator.paused) {
            imageRotator.timer = setTimeout(imageRotator.nextImage, imageRotator.delay); 
            return;
        }
        
        nextIndex = imageRotator.index + 1;
        if(nextIndex >= imageRotator.images.length)
            nextIndex = 0;
        imageRotator.index = nextIndex;
        imageRotator.div.css("background", "url(" + imageRotator.images[nextIndex] + ")");
        $(new Image()).load(function() {
            // fade out image
            imageRotator.img.animate({opacity:0.01}, 900, 'swing', function() {
                // fade in image
                imageRotator.img.attr("src", imageRotator.images[nextIndex]);
                imageRotator.img.css('opacity', 1);
                imageRotator.timer = setTimeout(imageRotator.nextImage, imageRotator.delay); 
            });
        }).attr('src', imageRotator.images[nextIndex]);
    }
};

jQuery.create = function() {
    if (arguments.length == 0) return [];
    var args = arguments[0] || {}, elem = null, elements = null;
    var siblings = null;

    // In case someone passes in a null object,
    // assume that they want an empty string.
    if (args == null) args = "";
    if (args.constructor == String) {
        if (arguments.length > 1) {
            var attributes = arguments[1];
                if (attributes.constructor == String) {
                            elem = document.createTextNode(args);
                            elements = [];
                            elements.push(elem);
                            siblings =
        jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
                            elements = elements.concat(siblings);
                            return elements;

                    } else {
                            elem = document.createElement(args);

                            // Set element attributes.
                            var attributes = arguments[1];
                            for (var attr in attributes)
                                jQuery(elem).attr(attr, attributes[attr]);

                            // Add children of this element.
                            var children = arguments[2];
                            children = jQuery.create.apply(null, children);
                            jQuery(elem).append(children);

                            // If there are more siblings, render those too.
                            if (arguments.length > 3) {
                                    siblings =
        jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
                                    return [elem].concat(siblings);
                            }
                            return elem;
                    }
            } else return document.createTextNode(args);
      } else {
              elements = [];
              elements.push(args);
              siblings =
        jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
              elements = elements.concat(siblings);
              return elements;
      }
};

$(document).ready(function () {
    site.start();
});