if (typeof window["console"] == 'undefined') {
    var console = {}; console.log = function() {};
}

if (document.images)
	{
	  preload_image_object = new Image();
	  // set image url
	  image_url = new Array();
	  image_url[0] = "/img/blog/bg_pane_tile_blog.png";
	  image_url[1] = "/img/blog/bg_pane_top_blog.png";
	  image_url[2] = "/img/blog/bg_pane_bottom_blog.png";
	  image_url[3] = "/img/blog/bg_pane_bottom_short_blog.png";

	   var i = 0;
	   for(i=0; i<=3; i++)
	     preload_image_object.src = image_url[i];
	}

function appendScript(id, src, callback) {
    if ($('#' + id).length) {
        if (callback) { // already embedded and callback, call the callback and return
            callback();
        }
        return;
    }
    var head = document.getElementsByTagName('head')[0];
    var s = document.createElement('script');
    s.setAttribute('type','text/javascript');
    s.setAttribute('src',src);
    s.setAttribute('id',id);
    if (callback) {
        s.onload = callback;
        s.onreadystatechange = function() {
            if (this.readyState == 'complete' || this.readyState == 'loaded') {
                callback();
            }
        };
    }
    head.appendChild(s);
}

function setScroll() {
    var windowHeight = $(window).height();
    var contentHeight = $('#content').height();
};

var getBestTop = function(windowHeight,contentHeight) {

    if ($('body').attr('id') == 'home') {
        return 0;
    } else {
        if (windowHeight - contentHeight > 100) {
    	    return ((windowHeight / 2) - (contentHeight / 2));
        } else {
            return 25;
        }
    }

    // return ((windowHeight / 2) - (contentHeight / 2));
};

function setContent() {
    var windowHeight = $(window).height();
    var contentHeight = $('#content').height();
    $('#content').css({position: 'relative', top: getBestTop(windowHeight,contentHeight)});
    if (windowHeight-80 < contentHeight && $('body').attr('id') != 'videos') {
        $('#footer').css('position', 'relative');
    } else {
        $('#footer').css('position', 'fixed');
    }
    if ($('body').attr('id') == 'home' && $('#content').width() >= $('body').width()) {
        $('#content').css('width',$('body').width());
    } else {
        $('#content').css('width','956px');
    }
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function el(node) {
    return document.getElementById(node);
}

var Router = function() {
    this.routes = [];
    this.currentRoute = null;
    this.currentURL = null;
};

Router.prototype.addRoute = function(routeNode) {
    routeNode.router = this;
    this.routes.push(routeNode);
};

Router.prototype.match = function(url) {
    for (var i = 0, len = this.routes.length; i < len; i++) {
        if (url == this.routes[i].url || (this.routes[i].matcher && url.match(this.routes[i].matcher))) {
            // having a matcher means we want to reset the URL to the current SWFAddress value,
            // since url and matcher are mutually exclusive
            if (this.routes[i].matcher) {
                this.routes[i].url = SWFAddress.getValue();
            }
            return this.routes[i];
        }
    }
    return false;
};

Router.prototype.invokeHandler = function(url)  {
    var route = this.match(url);
    if (route) {
        if (this.currentRoute) {
            this.currentRoute.onunload();
        }
        route.onload();
        route.handler();
        this.currentRoute = route;
        this.currentURL = url;
    } else {
        console.log("No matching URL found in routes (" + url + ")");
    }
};

var Route = function(opts) {
    var settings = ['url','matcher','handler','before','after','onload','onunload','router','bodyid'];
    for (var i = 0, len = settings.length; i < len; i++) {
        if (opts[settings[i]]) {
            this[settings[i]] = opts[settings[i]];
        }
    }
};

Route.prototype.handler = function() {
    this.transitionOut();
    return false;
};

Route.prototype.before = function() {
    return true;
};

Route.prototype.after = function() {
    return true;
};

Route.prototype.onload = function() {
    return true;
};

Route.prototype.onunload = function() {
    return true;
};

Route.prototype.transitionIn = function() {
    var handleSuccess = function() {
        var handler = this;
        return function(res) {
            var slug = handler.bodyid || handler.url.replace(/[\/0-9]+/g,'');
            if (slug == '') { slug = 'home'; }
            if (handler.before()) {
                $('body').attr('id',slug);
                $('#content').html(res);
                setContent();
                handler.after();
                app.attachLinks();
            }
            document.body.scrollTop = 0;
        };
    };

    var opts = {
        url: this.url,
        success: handleSuccess.call(this),
        error: function(res) {
            console.log('ERROR RETRIEVING URL');
            console.log(res);
        }
    };
    $.ajax(opts);
};

Route.prototype.transitionOut = function() {
    this.transitionIn();
    return true;
};


var app = (function() {

    var blinkInterval, initialized, router;

    var moveIn = function(el) {
        // 	if (wheel == true){
        // 	    $(el).hide().css({top:newY + 100},0);
        // 	    setTimeout(function() { $(el).show().animate({top:newY},1050, "easeOutElastic", setScroll);},1);
        // 	} else {
        // 	    $(el).hide().css({top:newY + 100},0);
        // 	    setTimeout(function() { $(el).show().animate({top:newY},1050, "easeOutElastic", setScroll);},1000);
        // 	}


    };

    var moveOut = function() {
// 	if (el.id != "video-container") {
// 	    $(el).animate({top:"+=15"},500, "easeInExpo");
// 	    setTimeout(function() {
// 		$(el).animate({top:-800}, 500, "easeInOutExpo", func);
// 	    },200);
//         } else {
// 	    func();
//         }
    };

    var blinky = function() {
        var lights = $('.lights, .lights-on');
        lights.toggleClass('lights-on');
    };

    router = new Router();

    router.addRoute(
        new Route({url: "/"})
    );

    router.addRoute(
        new Route({
            matcher: /^\/tour-stops\/[0-9]+\//,
            after: function() {
//                 var loadRouteList = function() {
//                     appendScript('route-list','/js/route-list.js',tourstops.init);
//                 };
                appendScript('google-api', 'http://www.google.com/jsapi?key=ABQIAAAAdh4tQvHsPhXZm0lCnIiqQxSo1sC_2pQFvLdxV6YDNPe3QdW06BSK1xV08h2VBrMmrXdkChf-4R8qbA', function() {
                    google.load('maps', '3', {callback: tourstops.init, other_params: 'sensor=false'});
                });
            },
	    handler: function() {
                if (!this.router.currentRoute || !this.router.currentURL.match(/^\/tour-stops/)) {
                    this.url = SWFAddress.getValue();
                    this.transitionIn();
                }
            }
        })
    );

    router.addRoute(
        new Route({
            url: "/tour-stops/",
            after: function() {
//                 var loadRouteList = function() {
//                     appendScript('route-list','/js/route-list.js',tourstops.init);
//                 };
                appendScript('google-api', 'http://www.google.com/jsapi?key=ABQIAAAAdh4tQvHsPhXZm0lCnIiqQxSo1sC_2pQFvLdxV6YDNPe3QdW06BSK1xV08h2VBrMmrXdkChf-4R8qbA', function() {
                    google.load('maps', '3', {callback: tourstops.init, other_params: 'sensor=false'});
                });
            }
        })
    );

    router.addRoute(
        new Route({
            matcher: /^\/videos\/[0-9]+\//,
	    handler: function() {
                if (!this.router.currentRoute || !this.router.currentURL.match(/^\/videos/)) {
                    this.url = SWFAddress.getValue();
                    this.transitionIn();
                }
            },
            onunload: function() {
                if (videos) {
                    videos.endVideo();
                }
            }
        })
    );

    router.addRoute(
        new Route({url: "/videos/"})
    );

    router.addRoute(
        new Route({
            url: "/entry-form/",
            before: function() {
                if (readCookie('ineligible')) {
                    go('/ineligible/',true);
                    return false;
                }
                return true;
            },
            after: function() {
                appendScript('recaptcha-js','http://api.recaptcha.net/js/recaptcha_ajax.js',function() {
                    Recaptcha.create(RECAPTCHA_KEY,
                                     "recaptcha-container", {
                                         theme: "custom"
                                     });

                });
            }
        })
    );

    router.addRoute(
        new Route({
            url: "/contest/",
            after: function() {
                clearInterval(blinkInterval);
                blinkInterval = setInterval(function() { blinky(); },300);
            }
        })
    );

    router.addRoute(
        new Route({
            url: "/spin-the-wheel/",
            after: function() {
		var spinWheel = function() {
                    $.ajax({
                        url: '/extensions/spin_wheel',
                        success: function(val) {
                            videoPlayer.pause();
                            videoPlayer.setOnEnded(function() {});
                            if (val == 'true') {
                                go('/congratulations/',true);
                            } else {
                                go('/try-again/',true);
                            }
                        },
                        error: function(val) {
                            videoPlayer.pause();
                            videoPlayer.setOnEnded(function() {});
                            go('/try-again/',true);
                        }
                    });
                };
                videoPlayer.swap('spin1');
                videoPlayer.setOnEnded(spinWheel);
            }
        })
    );

    router.addRoute(
        new Route({
            url: "/congratulations/",
            after: function() {
		clearInterval(blinkInterval);
                blinkInterval = setInterval(function() { blinky(); },300);
                setTimeout(function() {
                    videoPlayer.swap('loop');
                },3000);
            }
        })
    );

    router.addRoute(
        new Route({
            url: "/try-again/",
            after: function() {
                clearInterval(blinkInterval);
                setTimeout(function() {
                    videoPlayer.swap('loop');
                },3000);
            }
        })
    );

    router.addRoute(
        new Route({
            url: "/ineligible/"
        })
    );

    router.addRoute(
	new Route({
            matcher: /^\/share-form\/(tour-stops|videos)\/([0-9]+\/)?/,
	    handler: function() {
                if (!this.router.currentRoute || !this.router.currentURL.match(/^\/share-form/)) {
                    this.url = SWFAddress.getValue();
                    this.transitionIn();
                }
            },
            bodyid: 'share-form'
        })
    );

    router.addRoute(
        new Route({
            url: "/share-form/"
        })
    );

    router.addRoute(
    	new Route({
    	    url: "/about/"
    	})
    );

    router.addRoute( // Blog Main
        new Route({
            url: "/blog/",
            after: function() {
                Cufon.replace('#blog h2, #blog h3, #blog .date span', { fontFamily: 'Circustime', textShadow: '#07427a 1px 1px' });
                Cufon.replace('#blog #sidebar .nav a, #blog #paging, #blog #sidebar h3, #comments h4', { fontFamily: 'Cavalcade', textShadow: '#000 1px 1px' });
            }
        })
    );

    router.addRoute( // Blog Paging
        new Route({
            matcher: /^\/blog\/([0-9]+)\/$/,
            bodyid: 'blog',
            after: function() {
                Cufon.replace('#blog h2, #blog h3, #blog .date span', { fontFamily: 'Circustime', textShadow: '#07427a 1px 1px' });
                Cufon.replace('#blog #sidebar .nav a, #blog #paging, #blog #sidebar h3, #comments h4', { fontFamily: 'Cavalcade', textShadow: '#000 1px 1px' });
            }
        })
    );

    router.addRoute( // Blog Archive
        new Route({
            matcher: /^\/blog\/archive\/$/,
            bodyid: 'blog',
            after: function() {
                Cufon.replace('#blog h2, #blog h3, #blog .date span', { fontFamily: 'Circustime', textShadow: '#07427a 1px 1px' });
                Cufon.replace('#blog #sidebar .nav a, #blog #paging, #blog #sidebar h3, #comments h4', { fontFamily: 'Cavalcade', textShadow: '#000 1px 1px' });
            }
        })
    );

    router.addRoute( // Blog Archive Month/Year
        new Route({
            matcher: /^\/blog\/archive\/.*?\/.*?\/$/,
            bodyid: 'blog',
            after: function() {
                Cufon.replace('#blog h2, #blog h3, #blog .date span', { fontFamily: 'Circustime', textShadow: '#07427a 1px 1px' });
                Cufon.replace('#blog #sidebar .nav a, #blog #paging, #blog #sidebar h3, #comments h4', { fontFamily: 'Cavalcade', textShadow: '#000 1px 1px' });
            }
        })
    );

    router.addRoute( // Blog Detail
        new Route({
            matcher: /^\/blog\/.*?\/.*?\/$/,
            bodyid: 'blog',
            after: function() {
                Cufon.replace('#blog h2, #blog h3, #blog .date span', { fontFamily: 'Circustime', textShadow: '#07427a 1px 1px' });
                Cufon.replace('#blog #sidebar .nav a, #blog #paging, #blog #sidebar h3, #comments h4', { fontFamily: 'Cavalcade', textShadow: '#000 1px 1px' });
            }
        })
    );

    var handleChange = function(e) {

        var url = SWFAddress.getValue();

        if (url == '/' && !initialized) { return false; }

        // No ending slash, because we send the same URLs to Interface.
        // If there is no ending slash, we get redirected and get weird
        // results on AJAX calls
        if (!url.match(/\/$/)) {
            go(url + '/');
            return false;
        }

        router.invokeHandler(url);

        initialized = true;

        return false;
    };

    var go = function(url,skipSwfAddress) {
        if (skipSwfAddress) {
            router.invokeHandler(url);
        } else {
            SWFAddress.setValue(url);
        }
    };

    var attachLinks = function() {
        $('#content a').each(function(i,link) {
            if ($(link).attr('rel') == '') {
                $(link).click(function() {
                    go(this.href.replace(/^(http:\/\/.*?)?(\/.*?)$/,'$2'));
                    return false;
                });
            }
        });
    };

    var init = function() {
        SWFAddress.setStrict(true);
        SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);
        attachLinks();
	setContent();
	$(window).resize(setContent);
    };

    $(document).ready(init);

    return {
        go: go,
        attachLinks: attachLinks
    };

}());