var DEBUG = true;

if (!DEBUG || !window.console) {
    var c = window.console = {};
    c.log = function () {};
    c.error = function () {};
    c.warn = function () {};
    c.dir = function () {};
}

$(function () {

    window.fp = Forpeople();

});

var Forpeople = function () {

    var contact, placeholder, logo, blueprint;

    contact = Contact();
    placeholder = $('#placeholder').remove();
    logo = $('#logo').fadeTo(0, 0.0);

    blueprint = (function () {

        var hour, file;
		
        hour = (new Date).getHours();
        if (hour >= 9 && hour < 18) {
            file = 'assets/day.json';
        }
        else {
            file = 'assets/night.json';
        }
		
		if(window.location.hash === "#night"){
			file = 'assets/night.json';
		}
		
        return file;
    })();

	
    $.ajax({
        url: blueprint,
        success: function (data) {
            console.log('JSON successfully downloaded.');
            start(data);
        },
        error: function () {
            console.error('JSON file not found.');
            console.log('Returning things to a non-JS state.');
            contact.cancel();
            $('#frame').prepend(placeholder);
            logo.fadeTo(0, 1.0);
        }
    });

    var bookshelf, slideshow, state;

    state = 'slideshow';

    function switchTo(s) {

        if (s.match(/bookshelf/)) {
            slideshow.cancel();
            bookshelf.start();
            state = s;
        }

        if (s.match(/slideshow/)) {
            bookshelf.cancel();
            slideshow.start();
            state = s;
        }

        console.log('Switching to '+state);
    }

    function start(data) {
        $('body').append('<div id="backstage"></div>');
        bookshelf = Bookshelf(data.bookshelf);
        slideshow = Slideshow(data.slides);

        logo.attr('title', 'Click to skip.');
        logo.css('cursor', 'pointer');
        logo.click(function () {
            if (state.match(/bookshelf/)) {
                switchTo('slideshow');
            }
            else if (state.match(/slideshow/)) {
                switchTo('bookshelf');
            }
        });

        var showAfter;
        showAfter = data.slides[0].fade || 1.0;
        showAfter += data.slides[0].hold / 2 || 2.0;
        showAfter *= 1000;

        $('#backstage').bind('fp:slide0', function () {
            logo.fadeTo(0, 0.0).delay(showAfter).fadeTo(1000, 1.0);
        });

        slideshow.start();
    }

    return {
        switchTo: switchTo
    }
}

var Slideshow = function (slides) {

    var stage, backstage;

    stage = $('<div id="slideshow" class="stage above"></div>');
    $('#frame').prepend(stage);
    backstage = $('#backstage');

    loadSlide(0);

    function loadSlide(i) {

        if (i >= slides.length) return;
		
		switch(slides[i].type)
		{
			case "image":
					var img;
					console.log('Slide '+i+' set.');
			        img = $('<img id="slide'+i+'" class="slide framed">');
			        img.load({ele: img, seq: i}, function (evt) {
			            var i = evt.data.seq;
			            console.log('Slide '+i+' loaded.');
			            _.defer(loadSlide, i+1);
			            backstage.trigger('fp:slide'+i);
			        });
			        backstage.append(img);
					img.attr('src', slides[i].url);
					slides[i].element = img;
					
				break;
			case "html":
					var div;
					console.log('Slide '+i+' set.');
					div = $('<div id="slide'+i+'" class="slide framed"></div>');
					div.append( slides[i].contentHTML );
					backstage.append(div);
			    	slides[i].element = div;
					console.log('Slide '+i+' ready.');
					_.defer(loadSlide, i+1);
				break;
			case "video":
			
				var div;
				
				console.log('Slide '+i+' set.');
				
				div = $('<div id="slide'+i+'" class="slide framed video"></div>');
				
				var videoStr = "<video id=\"slide_video_"+i+"\" class=\"video_player\" width=\"880\" height=\"503\">";
				videoStr += "</video>";
				
				
				div.append( videoStr );
				backstage.append(div);
		    	slides[i].element = div;
				
				console.log('Slide '+i+' ready.');
								
				jwplayer("slide_video_"+i).setup({
					flashplayer: "jwplayer/player.swf", 
					width: 880,
					height: 501, 
					skin: "skins/forpeople/forpeople.zip",
					autostart:false,
					logo:{},
					//bufferlength:1,
					stretching:"fill",
					icons: false,
					"controlbar.idlehide": true,
					events: {
						onComplete:function(){
							// move onto the next item
							console.log("slide_video_"+i+" complete");
							delay(transistion, 0, i+1);
						},
						onError:function(){
							// move onto the next item
							console.log("slide_video_"+i+" error");
							delay(transistion, 0, i+1);
						},
						onTime:function(event)
						{
							if(slides[i].stopTime && event.position >= slides[i].stopTime)
							{
								console.log("slide_video_"+i+" complete");
								jwplayer("slide_video_"+i).stop();
								delay(transistion, 0, i+1);
							}
						}
					},
					levels: [
					            { file: slides[i].mp4 },    // H.264 version
					            { file: slides[i].webm },   // WebM version
					            { file: slides[i].ogg }     // Ogg Theora version
					        ],
					modes: [
								{ type: 'flash', src: 'jwplayer/player.swf' },
								{ type: "html5" }
					        ]
				});
				
				//
				_.defer(loadSlide, i+1);
				
			
				break;
		}
	}
		

    var cancelled, timeouts, delay;

    timeouts = [];

    delay = _.wrap(_.delay, function (f) {
        var args = Array.prototype.slice.call(arguments, 1);
        timeouts[timeouts.length] = f.apply(f, args);
    });

    function transistion(i) {
		
        if (cancelled) return;

        if (i >= slides.length) {
            fp.switchTo('bookshelf');
            return;
        }

        var slide;
		
        slide = slides[i];

        if (!slide.element) {
            console.warn('Slide '+i+' is not ready.');
            backstage.bind('fp:slide'+i, {seq: i}, function (evt) {
                var i = evt.data.seq;
                console.log('Slide '+i+' now ready.');
                delay(transistion, 0, i);
            });
            return;
        }
		
		//
		if( $(slide.element).hasClass('video') )
		{			
            console.log('Slide '+i+' has video : playing.');
			jwplayer("slide_video_"+i).play();
		}
		
		
        var fade, hold;

        fade = slide.fade ? slide.fade * 1000 : 2000;
        hold = slide.hold ? slide.hold * 1000 : 1000;
		
		if( !$(slide.element).hasClass('video') )
		{
			delay(transistion, fade+hold, i+1);
		}
		
		//slide.element.appendTo(stage);
        slide.element.appendTo(stage).fadeTo(0, 0.0);
        slide.element.fadeTo(fade, 1.0);

    }

    return {
        start : function () {
            cancelled = false;
            stage.addClass('above').removeClass('below');
            stage.children().stop().appendTo(backstage);
            transistion(0);
        },
        cancel : function () {
						
			// stop/clear all videos
			$.each(slides, function(index, slide){
				if($('#slide'+index).hasClass('video')){
					jwplayer('slide_video_'+index).stop();			
				}				
			});
			
            cancelled = true;
            stage.removeClass('above').addClass('below');
            backstage.unbind();
            for (var i = 0; i < timeouts.length; i++) {
                clearTimeout(timeouts[i]);
            }
        }
    }
};

var Bookshelf = function (books) {

    var stage, backstage, delay, timeouts;

    stage = $('<div id="bookshelf" class="stage below"></div>');
    backstage = $('#backstage');

    timeouts = [];
    delay = _.wrap(_.delay, function (f) {
        var args = Array.prototype.slice.call(arguments, 1);
        timeouts[timeouts.length] = f.apply(f, args);
    });

    $('#frame').prepend(stage);

    var background, slogan, map, atz;

    background = background();

    slogan = slogan();
    map = map();
    atz = atz();

    function background() {
        books.bg.element =  $('<img class="bg framed">').appendTo(stage)
                                .attr('src', books.bg.url)
                                .fadeTo(0, 0.0);
        return {
            start: function () {
                var fade = books.bg.fade ? books.bg.fade * 1000 : 2000;
                books.bg.element.stop().fadeTo(fade, 1.0);
            },
            cancel : function () {
                books.bg.element.stop().fadeTo(0, 0.0);
            }
        }
    }

    function atz() {
        books.atz.element = $('<img id="atz">').appendTo(stage)
                                               .attr('src', books.atz.url)
                                               .fadeTo(0, 0.01)
                                               .css('cursor', 'pointer');

        var mouseenter = function () {
            var atz;
            atz = $(this).unbind('mouseenter');
            
            atz.attr('src', atz.attr('src'));

            window.setTimeout(function () {
                atz.mouseenter(mouseenter);
            }, 2000);
        };

        books.atz.element.mouseenter(mouseenter);
        books.atz.element.click(map.toggle);

        return {
            start : function () {
                var fade = books.bg.fade ? books.bg.fade * 1000 : 2000;
                books.atz.element.stop().fadeTo(fade+200, 1.0);
            },
            cancel : function () {
                books.atz.element.stop().fadeTo(0, 0.0);
            }
        }
    }

    function map() {
        var close, print;

        close = $('<a class="close"></a>');
        close.click(toggle);
        print = $('<a class="print"></a>')
                 .attr('href', books.map.print.url);

        books.map.element = $('<div id="map"></div>')
                             .appendTo(backstage)
                             .append($('<img class="framed">')
                                      .attr('src', books.map.web.url))
                             .append(close)
                             .append(print);

        books.map.element.children().fadeTo(0, 0.0);

        var mapVisible, fade;

        mapVisible = false;
        fade = books.map.web.fade ? books.map.web.fade * 1000 : 1000;

        function toggle() {
            if (mapVisible) {
                console.log('Map toggled off.');
                books.map.element.stop().children().fadeTo(fade, 0.0);
                books.atz.element.stop().fadeTo(fade, 1.0);
                window.setTimeout(function () {
                    books.map.element.appendTo(backstage);
                }, fade);
            }
            else {
                console.log('Map toggled on.');
                books.map.element.appendTo(stage);
                books.map.element.stop().children().fadeTo(fade, 1.0);
                books.atz.element.stop().fadeTo(fade, 0.0);
            }
            mapVisible = !mapVisible;
        }

        function cancel() {
            if (mapVisible) {
                toggle();
            }
        }

        return {
            toggle: toggle,
            cancel: cancel
        }
    };

    function slogan() {

        var ftd;

        ftd = $('<div id="ftd"></div>');

        if (books.type && books.type.match(/^night$/)) {
            ftd.addClass('night');
        }
		
        for (var i = 0; i < books.slogan.length; i++) {
            $('<img>').attr('src', books.slogan[i].url)
                      .appendTo(ftd).fadeTo(0, 0.0);
        }

        quote = $('<img id="quote">').attr('src', books.quote.url);
        quote.appendTo(stage).fadeTo(0, 0.0);

        ftd.appendTo(stage);

        function quote_ani() {
            delay(function () {
                ftd.children().fadeTo(2000, 0.0)
            }, 4000);

            delay(function () {
                ftd.children().fadeTo(2000, 1.0);
            }, 18000);

            delay(function () {
                quote.fadeTo(2000, 1.0);
            }, 6000);
            delay(function () {
                quote.fadeTo(2000, 0.0);
            }, 16000);
        }

        function night_ani() {

            var bgFade, children;

            bgFade = books.bg.fade ? books.bg.fade * 1000 : 2000;

            children = ftd.children();

            delay(function () {
                ftd.children().fadeTo(300, 1.0)
                              .fadeTo(50, 0.2)
                              .fadeTo(200, 1.0, quote_ani);
            }, bgFade+500);
        }

        function day_ani() {

            var bgFade;

            bgFade = books.bg.fade ? books.bg.fade * 1000 : 2000;
            
            ftd.children().each(function (i) {
                var e = $(this);
                delay(function () {
                    e.fadeTo(2000, 1.0);
                }, i*2000+(bgFade+500));
            });
            delay(function () {
                quote_ani();
            }, 8500+3*bgFade);
        }

        function cancel() {
            for (var i = 0; i < timeouts.length; i++) {
                    window.clearTimeout(timeouts[i]);
            }
            timeouts = [];
            quote.clearQueue().stop().fadeTo(0, 0.0);
            ftd.children().clearQueue().stop().fadeTo(0, 0.0);
        }

        if (books.type && books.type.match(/^night$/)) {
            return {
                start : night_ani,
                cancel : cancel
            };
        }
        else if (books.type && books.type.match(/^day$/)) {
            return {
                start : day_ani,
                cancel : cancel
            };
        }

        return {ani: function() {}, cancel: function () {}};

    }

    return {
        start : function () {
            // stage to above. make sure hidden before fade in.
            stage.removeClass('below').addClass('above');
            //stage.children().fadeTo(2000, 1.0);
            background.start();
            atz.start();
            slogan.start();
        },
        cancel : function () {
            // stage to below. actually hide here
            stage.removeClass('above').addClass('below');
            //stage.children().stop().hide();
            background.cancel();
            map.cancel();
            atz.cancel();
            slogan.cancel();
        }
    }
};

var Contact = function () {

    var footer, letterbox;

    footer = $('#footer');
    letterbox = $('<div id="letterbox"></div>').appendTo(footer);

    reassembleEmail();

    function reassembleEmail() {

        console.log('Making the email clickable.');

        var old_ele, new_ele, email;

        old_ele = $('#mail'),
        email = old_ele.text().replace(/(.+) at (.+)/, '$1@$2'),
        new_ele = $('<a href="mailto:'+email+'" id="mail"></a>');

        new_ele.text(email);
        old_ele.replaceWith(new_ele);
    }

    var visible, fade;

    visible = false;
    fade = 1000;

    function toggle() {
        if (visible) {
            letterbox.stop().fadeTo(fade, 1.0);
        }
        else {
            letterbox.stop().fadeOut(fade);
        }
        visible = !visible;
    }

    footer.mouseenter(toggle);
    footer.mouseleave(toggle);

    function cancel() {
        letterbox.remove();
        $('#footer').unbind();
    }

    return {
        cancel: cancel
    };
};


