/**
 * Namespaced object. Encapsulating private methods, exposing these 
 * as public via an object proxy. 
 *
 * @author 		Zone
 * @email		info@zonecontent.com
 * @url 		http://www.zonecontent.com/
 * @copyright 	Copyright (c) 2009, zonecontent.com. All rights reserved.
 */
var newlooktv = window.newlooktv = function($) {

    // Private constants
    var APP_ID = "app-content",
		MENU_ID = "app-menu",
		SCRIPT_ID = "yt-script";

    // YouTube API constants
    var YT_FEED_URL = "http://gdata.youtube.com/feeds/api/",
		YT_CONTEST_URL = "yt_api.php",
		YT_CONTEST_API_SUBMIT = "submit_video",
		YT_CONTEST_API_ENTRIES = "list_contest_entries",
		YT_FEED_PLAYLIST_IDS = {
		    SEASON: "EA53B848E6A12635",
		    CHALLENGE: "FB65D69B359AA759",
		    PRESENTER: "C69BE334FF15A8F5"
		},
		YT_CONTEST_API_CATEGORIES = {
		    SEASON: 3,
		    CHALLENGE: 2,
		    PRESENTER: 1
		},
		YT_API_ERRORS = {
		    PARAM_ERROR: 90901,
		    VERSION_ERROR: 90902,
		    AUTH_ERROR_BAD_TOKEN: 90910,
		    AUTH_ERROR_TIMESTAMP_EXPIRED: 90911,
		    AUTH_ERROR_LIST_CONTESTS: 90912,
		    INVALID_VIDEO_ERROR: 90920,
		    ENTRY_EXISTS_ERROR: 90921,
		    INVALID_CONTEST_ERROR: 90922
		};

    // Private variables 
    var loadedPageCache = {},
		submissionPreset = false,
		submissionCategory = null,
		currentPageLoaded = null,
		defaultSection = 1,
		episodePlaylistData = null,
		presenterPlaylistData = null,
		challengePlaylistData = null,
		seasonPlaylistData = null,
		uploadPlaylistData = null,
        counterImage = new Image();


    // Constructor
    (function() {
        configureApplicationMenu();
        hideOverlay();
    })();

    // -------------------------------

    function configureApplicationMenu() {
        $("#" + MENU_ID + " li a").click(
			function(event) {
			    var el = $(this);
			    var section = el.parent().attr("id").split("menu-")[1];
			    hideOverlay();
			    newlooktv.loadPage(section);
			    return (false);
			}
		);
    }

    // -------------------------------

    function activateMenuItem(sectionId) {
        $("#app-menu li").removeClass("active");
        $("#" + sectionId).addClass("active");
    }

    // -------------------------------

    function addPageLinks() {
        var pages = [
			newlooktv.PAGE_HOME,
			newlooktv.PAGE_PRESENTER,
			newlooktv.PAGE_CHALLENGE,
			newlooktv.PAGE_SEASON,
			newlooktv.PAGE_SUBMIT
		];

        for (var i = 0; i < pages.length; i++) {
            $("#app-content a[href*='#" + pages[i] + "']").click(
				function(event) {
				    var el = $(this);
				    hideOverlay();

				    if (el.hasClass("submission-preset")) {
				        submissionPreset = currentPageLoaded; // Dodgy hack on page ID
				    }

				    newlooktv.loadPage(el.attr("href").split("#")[1]);
				    return (false);
				}
			);
        }
    }

    // -------------------------------

    function configurePageSections(sectionNumber) {
        var app = $("#app-content");
        var sections = app.find(".sub-section");
        if (sections) {
            sections.filter(":not(.section-" + sectionNumber + ")").hide();
        }
    }

    // -------------------------------

    function togglePageSection(sectionNumber) {
        var app = $("#app-content");
        app.find(".sub-section:not(.section-" + sectionNumber + ")").hide();
        app.find(".sub-section.section-" + sectionNumber + "").show();
    }

    // -------------------------------

    function hideOverlay() {
        $("#overlay").hide();
    }

    // -------------------------------

    function showOverlay(html) {
        var page = $("#page");
        var overlay = $("#overlay");
        overlay.find("#overlay-content").html(html);
        overlay.find("#close-button").click(
			function(event) {
			    hideOverlay();
			}
		).show();
        overlay.width(
			page.outerWidth()
		).show();

        return (overlay);
    }

    // -------------------------------

    function addTabbing() {

        $(".tabbed:not(.ready)").each(function() {
            var el = $(this);
            var sections = el.children(".content");

            // Init
            sections.each(function() {
                var section = $(this);
                var tab = el.find("a[href*='" + section.attr("id") + "']");
                if (tab) {
                    // Valid title element
                    section.hide();
                    tab.click(
						function(event) {
						    sections.hide();
						    el.find(".title li.active").removeClass("active");
						    el.attr("class", "tabbed ready " + tab.attr("id"));
						    tab.parent().addClass("active");

						    $("#" + tab.attr("href").split("#")[1]).show();
						    return (false);
						}
					);
                }
            });
            el.find("ol.title li:first a").click();
            el.addClass("ready");
        });

    }

    // -------------------------------

    function loadPageHTML(pageUrl, callbackFunc, sectionId) {
        var app = $("#" + APP_ID);

        defaultSection = (sectionId) ? sectionId : 1;
        if (!loadedPageCache[pageUrl]) {
            app.load(pageUrl, '', callbackFunc);
        } else {
            app.empty();
            app.html(loadedPageCache[pageUrl].html());
            callbackFunc(app);
        }
    }

    // -------------------------------

    function homePageLoaded(el, success, xmlResponse) {

        addTabbing();
        addFacebookShare();
        addMySpaceShare();

        FB.init("412341a298327c1ad85a85573f1ff8f6", "xd_receiver.html",{
			    "ifUserConnected": function() {}
			});

        addPageLinks();


        // Load data
        if (episodePlaylistData) {
            newlooktv.homeDataLoaded(episodePlaylistData);
        } else {
            loadYouTubeData("playlists/A17B4FEF36601022", "homeDataLoaded");
        }
    }

    // -------------------------------

    function presenterPageLoaded(el) {
        addPageLinks();
        configurePageSections(defaultSection);
        if (presenterPlaylistData) {
            newlooktv.presenterDataLoaded(presenterPlaylistData);
        } else {
            loadYouTubeData("playlists/" + YT_FEED_PLAYLIST_IDS.PRESENTER, "presenterDataLoaded");
        }
    }

    // -------------------------------

    function challengePageLoaded(el) {
        addPageLinks();
        configurePageSections(defaultSection);
        if (challengePlaylistData) {
            newlooktv.challengeDataLoaded(challengePlaylistData);
        } else {
            loadYouTubeData("playlists/" + YT_FEED_PLAYLIST_IDS.CHALLENGE, "challengeDataLoaded");
        }
    }

    // -------------------------------

    function seasonPageLoaded(el) {
        addPageLinks();
        configurePageSections(defaultSection);
        if (seasonPlaylistData) {
            newlooktv.seasonDataLoaded(seasonPlaylistData);
        } else {
            loadYouTubeData("playlists/" + YT_FEED_PLAYLIST_IDS.SEASON, "seasonDataLoaded");
        }
    }

    // -------------------------------

    function submitPageLoaded(el) {
        addPageLinks();
        configurePageSections(defaultSection);
        if (defaultSection == 1) {
            newlooktv.configureSubmissionForm();
        }
    }

    // -------------------------------

    function loadYouTubeData(apiUrl, callbackName, params) {
        $("body").append('<script type="text/javascript" src="' + YT_FEED_URL + apiUrl + '?v=2&alt=json-in-script&format=5&max-results=48&callback=newlooktv.' + callbackName + (params ? "&" + params.join("&") : "") + '"></script>');
    }

    function loadYouTubeDataUserUpload(apiUrl, callbackName, params) {
        $("body").append('<script type="text/javascript" src="' + YT_FEED_URL + apiUrl + '?v=2&alt=json-in-script&callback=newlooktv.' + callbackName + (params ? "&" + params.join("&") : "") + '"></script>');
    }

    // -------------------------------

    function queryYouTubeContestAPI(method, params, successCallback, failedCallback) {
        params["method_name"] = method;
        $.get(
			YT_CONTEST_URL,
			params,
			function(data) {

			    if (data.indexOf("<?xml") > -1) {
			        // We've got a valid XML response document
			        var xml = $(data);
			        if (xml.attr("status") === "ok") {
			            successCallback(xml);
			        } else {
			            if (console && console.log) {
			                console.log("API query failed", "XMl status error = 0", data);
			            }
			            failedCallback();
			        }
			    } else {
			        $.each(YT_API_ERRORS,
						function(i, code) {
						    if (data.indexOf(code) > -1) {

						        if (failedCallback) {
						            failedCallback(code);
						        }
						        if (console && console.log) {
						            console.log("API query failed", i, code);
						        }
						    }
						}
					);
			    }
			}
		);
    }

    // -------------------------------

    function getYouTubeUserUploadPlaylist(username) {
        loadYouTubeDataUserUpload(
			"users/" + username + "/uploads",
			"youTubeUserVideoDataLoaded"
		);
    }

    // -------------------------------

    function embedYouTubeVideo(videoUrl, id, width, height, autoplay) {
        swfobject.embedSWF(
			videoUrl,
			id,
			width,
			height,
			'9.0.0',
			false,
		    {
		        autoplay: (autoplay ? '1' : '0'),
		        hd: '1',
		        rel: '1',
		        border: '0',
		        fs: '1',
		        showinfo: '0',
		        iv_load_policy: '3',
		        showsearch: '0'
		    },
			{
			    allowfullscreen: 'true'
			}
		);
    }

    // -------------------------------

    function addVideoInfoPanel(section) {
        var panel = $("body").find("#info-panel");
        if (panel.length > 0) {
            panel.remove();
        }
        panel = $("body").append(
			'<div id="info-panel" class="' + section + '">'
				+ '<div id="info-panel-wrapper">'
					+ '<div class="content">'
					+ '</div>'
					+ '<img src="img/border_arrow_24_' + section + '.png" />'
				+ '</div>'
			+ '</div>'
		).children("#info-panel");
        panel.hide();
        return (panel);
    }

    // -------------------------------

    function addPlaylistView(section, el, items, columns, rows) {

        el.empty(); // Force clear 

        var ol = el.append('<ol class="grid"></ol>').children("ol"),
			panel = addVideoInfoPanel(section),
			info = panel.find(".content");

        $.each(items, function(i, playlistItem) {

            if (i >= columns * rows) {
                return (false); // Break
            }

            var id = playlistItem.id.$t.split("video:")[1];
            var duration = Number(playlistItem.media$group.yt$duration.seconds);
            var seconds = duration % 60;
            var time = Math.floor(duration / 60) + ":" + (seconds < 10 ? "0" + seconds : seconds);

            var a = ol.append('<li><span>' + time + '</span><a rel="' + i + '" href="#' + id + '"><img src="' + playlistItem.media$group.media$thumbnail[0].url + '" /></a></li>').find("a:last");
            a.click(
				function(event) {
				    var item = items[Number($(this).attr("rel"))];
				    showOverlay(
						'<div id="overlay-video-replace"></div>'
					);
				    embedYouTubeVideo(
						item.media$group.media$content[0].url,
						"overlay-video-replace",
						540, 325
					);
				    return (false);
				}
			).mouseenter(
				function(event) {
				    var target = $(this),
						item = items[Number(target.attr("rel"))],
						position = target.parent().offset();
				    info.html(
						'<p><strong>' + item.media$group.media$title.$t + '</strong>'
						+ '<br />'
						+ item.author[0].name.$t
						+ '</p>'
					);

				    panel.css(
						{
						    "top": (position.top - target.parent().height()) + "px",
						    "left": position.left + "px"
						}
					);

				    panel.show();
				}
			).mouseleave(
				function(event) {
				    panel.hide();
				}
			);


        });

        ol.children("li:nth-child(" + columns + "n)").addClass("last");
        ol.children("li:nth-child(" + columns + 1 + "n)").addClass("clear");
    }

    // -------------------------------	

    function validateForm(form) {
        var username = form.find("#username");
        var category = form.find("#competition");
        var result = true;

        if (username.val().length === 0) {
            addInputError(username, "Don't forget your username!");
            result = false;
        } else {
            removeInputError(username);
        }

        if (category.children("option:selected").val() === "false") {
            addInputError(category, "Choose a category!");
            result = false;
        } else {
            removeInputError(category);
        }

        return (result);
    }

    // -------------------------------	

    function addFacebookShare() {
        $("#app-content #share-facebook").click(
			function(event) {

			    var u = location.href,
					t = document.title;

			    window.open(
					'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t),
					'sharer',
					'toolbar=0,status=0,width=626,height=436'
				);

			    return (false);
			}
		);
    }

    // -------------------------------	

    function addMySpaceShare() {
        $("#app-content #share-myspace").click(
			function(event) {

			    var u = location.href,
					t = document.title;

			    window.open(
					'http://www.myspace.com/Modules/PostTo/Pages/?t=' + encodeURIComponent("New Look TV") + '&t=' + encodeURIComponent(t)
				);

			    return (false);
			}
		);
    }

    // -------------------------------	

    function addInputError(element, error) {
        removeInputError(element);
        element.before('<span class="error">' + error + '</span>');
    }

    // -------------------------------	

    function removeInputError(element) {
        element.siblings(".error:first").remove();
    }

    // -------------------------------

    function addGridVideoSubmitOptions() {
        var grid = $("#app-content #submit .grid");
        grid.parent().addClass(submissionCategory);
        grid.find("li").each(
			function(i) {
			    var el = $(this),
					item = uploadPlaylistData.feed.entry[Number(el.find("a").attr("rel"))],
			        title = item.title.$t,
			        checkbox = el.append('<label><input type="radio" name="video" value="' + i + '" />Select</label>').find("input");

			    checkbox.change(
					function(event) {

					    var el = $(this);
					    if (el.is(":checked")) {
					        grid.find("li.active").removeClass("active");
					        el.parent().parent().addClass("active");
					    }

					}
				);
			}
		);
    }

    // -------------------------------

    return {

        PAGE_HOME: "home",
        PAGE_PRESENTER: "presenter",
        PAGE_CHALLENGE: "challenge",
        PAGE_SEASON: "season",
        PAGE_SUBMIT: "submit",

        // -------------------------------

        seasonDataLoaded: function(data) {
            seasonPlaylistData = data;

            // Get list of items
            var hub = $("#season-hub"),
				library = $("#season-hub"),
				recentPlaylist = $("#recent-playlist"),
				libraryPlaylist = $("#library-playlist"),
				moreButton = $("#control-more"),
				nextButton = $("#control-next"),
				previousButton = $("#control-back"),
				columns = 4,
				rows = 3,
				viewPosition = 0;

            addPlaylistView(
				"season",
				recentPlaylist,
				seasonPlaylistData.feed.entry,
				2, 3
			);

            moreButton.click(
				function(event) {
				    togglePageSection(2);
				    addPlaylistView(
						"season",
						libraryPlaylist,
						seasonPlaylistData.feed.entry.slice(0),
						columns, rows
					);

				    if (seasonPlaylistData.feed.entry.length <= viewPosition) {
				        nextButton.hide();
				    }
				    return (false);
				}
			);

            nextButton.click(
				function(event) {

				    viewPosition += (columns * rows);
				    var list = seasonPlaylistData.feed.entry.slice(viewPosition);
				    addPlaylistView(
						"season",
						libraryPlaylist,
						list,
						columns, rows
					);
				    if (list.length <= (columns * rows)) {
				        nextButton.hide();
				    }
				    return (false);

				}
			);

            previousButton.click(
				function(event) {

				    nextButton.show();
				    if (viewPosition === 0) {
				        togglePageSection(1);
				        return;
				    }
				    viewPosition -= (columns * rows);
				    addPlaylistView(
						"season",
						libraryPlaylist,
						seasonPlaylistData.feed.entry.slice(viewPosition),
						columns, rows
					);
				    return (false);

				}
			);

        },

        // -------------------------------

        challengeDataLoaded: function(data) {

            challengePlaylistData = data;

            // Get list of items
            var hub = $("#challenge-hub"),
				library = $("#challenge-hub"),
				recentPlaylist = $("#recent-playlist"),
				libraryPlaylist = $("#library-playlist"),
				moreButton = $("#control-more"),
				nextButton = $("#control-next"),
				previousButton = $("#control-back"),
				columns = 4,
				rows = 3,
				viewPosition = 0;

            addPlaylistView(
				"challenge",
				recentPlaylist,
				challengePlaylistData.feed.entry,
				2, 3
			);

            moreButton.click(
				function(event) {
				    togglePageSection(2);
				    addPlaylistView(
						"challenge",
						libraryPlaylist,
						challengePlaylistData.feed.entry.slice(0),
						columns, rows
					);

				    if (challengePlaylistData.feed.entry.length <= viewPosition) {
				        nextButton.hide();
				    }

				    return (false);
				}
			);

            nextButton.click(
				function(event) {

				    viewPosition += (columns * rows);
				    var list = challengePlaylistData.feed.entry.slice(viewPosition);
				    addPlaylistView(
						"challenge",
						libraryPlaylist,
						list,
						columns, rows
					);
				    if (list.length <= (columns * rows)) {
				        nextButton.hide();
				    }
				    return (false);

				}
			);

            previousButton.click(
				function(event) {

				    nextButton.show();
				    if (viewPosition === 0) {
				        togglePageSection(1);
				        return;
				    }
				    viewPosition -= (columns * rows);
				    addPlaylistView(
						"challenge",
						libraryPlaylist,
						challengePlaylistData.feed.entry.slice(viewPosition),
						columns, rows
					);
				    return (false);

				}
			);

        },

        // -------------------------------

        presenterDataLoaded: function(data) {

            presenterPlaylistData = data;

            // Get list of items
            var hub = $("#presenter-hub"),
				library = $("#presenter-hub"),
				recentPlaylist = $("#recent-playlist"),
				libraryPlaylist = $("#library-playlist"),
				moreButton = $("#control-more"),
				nextButton = $("#control-next"),
				previousButton = $("#control-back"),
				columns = 4,
				rows = 3,
				viewPosition = 0;

            addPlaylistView(
				"presenter",
				recentPlaylist,
				presenterPlaylistData.feed.entry,
				2, 3
			);

            moreButton.click(
				function(event) {
				    togglePageSection(2);
				    addPlaylistView(
						"presenter",
						libraryPlaylist,
						presenterPlaylistData.feed.entry.slice(0),
						columns, rows
					);

				    if (presenterPlaylistData.feed.entry.length <= viewPosition) {
				        nextButton.hide();
				    }

				    return (false);
				}
			);

            nextButton.click(
				function(event) {
				    viewPosition += (columns * rows);
				    var list = presenterPlaylistData.feed.entry.slice(viewPosition);
				    addPlaylistView(
						"presenter",
						libraryPlaylist,
						list,
						columns, rows
					);
				    if (list.length <= (columns * rows)) {
				        nextButton.hide();
				    }
				    return (false);
				}
			);

            previousButton.click(
				function(event) {
				    nextButton.show();
				    if (viewPosition === 0) {
				        togglePageSection(1);
				        return;
				    }
				    viewPosition -= (columns * rows);
				    addPlaylistView(
						"presenter",
						libraryPlaylist,
						presenterPlaylistData.feed.entry.slice(viewPosition),
						columns, rows
					);
				    return (false);
				}
			);

        },

        // -------------------------------

        homeDataLoaded: function(data) {
            episodePlaylistData = data;

            // Get episode
            var episode,
				title = $("h1"),
				views = $("#view-count");

            embedEpisode(episodePlaylistData.feed.entry[0]);

            // Simplified embed call 
            function embedEpisode(episodeObj) {

                episode = episodeObj;
                episodenumber = episode.title.$t.split("-")[1].replace("Episode", "");

                //Set the Episode description in the about box               
                //alert(episode.media$group.media$description.$t);
                $("#episode-description").text(episode.media$group.media$description.$t);
                
                title.children("span").text(episode.title.$t.replace("New Look TV - ",""));
                //title.children("span").text("Episode#" + parseInt(episodenumber));

                views.html('<img class="counter" src="http://c.statcounter.com/5138189/0/17b9f663/0/?' + Math.random() + '" alt="..." /> views');
                embedYouTubeVideo(
					episode.media$group.media$content[0].url,
					"episode-video-replace",
					540, 325, 1
				);
            }

            // Add controls
            // Activate after first week!!!
            $("#control-video-next").click(
            function(event) {
                $.each(episodePlaylistData.feed.entry, function(i, el) {
                    if (el.id.$t == episode.id.$t) {
                        if (i == episodePlaylistData.feed.entry.length - 1) {
                            embedEpisode(episodePlaylistData.feed.entry[0]);
                        } else {
                            embedEpisode(episodePlaylistData.feed.entry[i + 1]);
                        }
                        return (false);
                    }
                }
            );
                return (false);
            });

            $("#control-video-previous").click(function(event) {
                $.each(episodePlaylistData.feed.entry, function(i, el) {
                    if (el.id.$t == episode.id.$t) {
                        if (i == 0) {
                            embedEpisode(episodePlaylistData.feed.entry[episodePlaylistData.feed.entry.length - 1]);
                        } else {
                            embedEpisode(episodePlaylistData.feed.entry[i - 1]);
                        }
                        return (false);
                    }
                });
                return (false);
            });

        },

        // -------------------------------

        configureSubmissionForm: function() {
            var form = $("#user-details form"),
				button = form.find("#user-submit"),
				category = form.find("#competition");

            if (submissionPreset !== false) {
                category.children("option[value*=" + submissionPreset + "]").attr("selected", "selected");
                submissionPreset = false;
            }

            button.click(
				function(event) {
				    if (validateForm(form)) {
				        // authenticateYouTubeUser( 
				        // 	form.find("#username").val(),
				        // 	form.find("#password").val(),
				        // 	null
				        // );
				        getYouTubeUserUploadPlaylist(
							form.find("#username").val()
						);
				    }
				    return (false);
				}
			);
        },

        // -------------------------------

        youTubeUserVideoDataLoaded: function(data) {

            if (!data.feed.entry) {
                addInputError($("#username"), "We can't find any videos for that username!");
            } else {

                uploadPlaylistData = data;

                var uploadPlaylist = $("#upload-playlist"),
					nextButton = $("#control-more"),
					previousButton = $("#control-back"),
					submitButton = $("#video-submit"),
					container = $("#video-finder"),
					termsLink = $("#terms"),
					columns = 4,
					rows = 2,
					viewPosition = 0;

                submissionCategory = $("#submit #competition option:selected").val();

                // Insert standard playlist
                addPlaylistView(
					submissionCategory,
					uploadPlaylist,
					uploadPlaylistData.feed.entry,
					columns, rows
				);

                // Modify standard playlist
                addGridVideoSubmitOptions();

                // Update other elements
                container.find("h1").empty().html(
					'<img src="img/title_submit_' + submissionCategory + '.png" />'
				);
                container.find(".box-title span").empty().text(uploadPlaylistData.feed.author[0].name.$t + " videos");

                termsLink.click(
					function(event) {
					    window.open(this.href);
					    return (false);
					}
				);

                // Button controls
                submitButton.click(

					function(event) {

					    // Validate form
					    if ($("#upload-playlist input:checked").length === 0) {
					        addInputError($("#video-details input"), "Select a video!");
					        return (false);
					    }
					    if ($("#video-details input:checked").length === 0) {
					        addInputError($("#video-details input"), "Please read the Terms and Conditions");
					        return (false);
					    }

					    var selected = new Array();
					    $("#video-finder #upload-playlist input:checked").each(
							function(i) {
							    var el = $(this);
							    var ytVideo = uploadPlaylistData.feed.entry[Number(el.parent().parent().children("a").attr("rel"))];
							    selected.push(ytVideo);
							}
						);

					    if (selected.length > 0) {

					        // Remove errors
					        removeInputError($("#video-details input"));

					        // Contest API query
					        for (var i = 0; i < selected.length; i++) {
					            queryYouTubeContestAPI(
									YT_CONTEST_API_SUBMIT,
									{
									    "ytId": selected[i].id.$t.split("video:")[1],
									    "categoryId": YT_CONTEST_API_CATEGORIES[submissionCategory.toUpperCase()]
									},

									function(responseXML) {

									    var plural = selected.length === 1 ? "video has" : "videos have";
									    var overlay = showOverlay(
											'<div id="confirm-submit">'
												+ '<h1><img src="img/title_submit_thanks.jpg" /></h1>'
												+ '<p>Your ' + plural + ' been submitted to New Look TV</p>'
												+ '<a href="#continue"><img src="img/button_submit_continue.png" /></a>'
											+ '</div>'
										);

									    // Configre overlay
									    overlay.find("#close-button").hide();
									    overlay.find("#confirm-submit a").click(
											function(event) {
											    hideOverlay();
											    // togglePageSection( 1 );
											    return (false);
											}
										);
									},

									function(code) {
									    var error = "Something's gone wrong with your submission. Please try again!";
									    if (code) {
									        switch (code) {
									            case YT_API_ERRORS.ENTRY_EXISTS_ERROR:
									                error = "You've submitted " + (selected.length > 1 ? "one of your videos" : "this video") + " before. Please check and try again.";
									                break;
									        }
									    }

									    showOverlay(
											'<div id="confirm-submit">'
												+ '<h1><img src="img/title_submit_error.jpg" /></h1>'
												+ '<p>' + error + '</p>'
											+ '</div>'
										);
									}
								);
					        }

					    }

					    return (false);
					}
				);

                nextButton.click(
					function(event) {

					    viewPosition += (columns * rows);
					    previousButton.show();

					    var list = uploadPlaylistData.feed.entry.slice(viewPosition);
					    addPlaylistView(
							submissionCategory,
							uploadPlaylist,
							uploadPlaylistData.feed.entry.slice(viewPosition),
							columns, rows
						);

					    if (list.length <= (columns * rows)) {
					        nextButton.hide();
					    }
					    addGridVideoSubmitOptions();

					    return (false);
					}
				);

                previousButton.click(
					function(event) {

					    nextButton.show();
					    viewPosition -= (columns * rows);
					    if (viewPosition === 0) {
					        previousButton.hide();
					    }

					    addPlaylistView(
							submissionCategory,
							uploadPlaylist,
							uploadPlaylistData.feed.entry.slice(viewPosition),
							columns, rows
						);
					    addGridVideoSubmitOptions();

					    return (false);
					}
				).hide();

                togglePageSection(2);
            }

        },

        // -------------------------------

        loadPage: function(page, sectionId) {

            counterImage.src = "http://c.statcounter.com/5138189/0/17b9f663/1/?0.2967069689184427?" + Math.random();
            activateMenuItem("menu-" + page);
            currentPageLoaded = page;
            switch (page) {

                case newlooktv.PAGE_HOME:
                    loadPageHTML(
						"home.html",
						homePageLoaded
					);
                    break;

                case newlooktv.PAGE_PRESENTER:
                    loadPageHTML(
						"presenter.html",
						presenterPageLoaded
					);
                    break;

                case newlooktv.PAGE_CHALLENGE:
                    loadPageHTML(
						"challenge.html",
						challengePageLoaded
					);
                    break;

                case newlooktv.PAGE_SEASON:
                    loadPageHTML(
						"season.html",
						seasonPageLoaded
					);
                    break;

                case newlooktv.PAGE_SUBMIT:
                    loadPageHTML(
						"submit.html",
						submitPageLoaded,
						sectionId ? sectionId : 1
					);
                    break;
            }
        }

    };

} (jQuery);