/* handle the main tab functions for all the XPRIZE pages */

if (typeof(XPRIZE) == "undefined") {
    XPRIZE = {};
}
XPRIZE.main = function() {
            // private
            var JS_FILES = {"teams": "js/teams.js",
//                            "social": "js/social.js",
                            "dashboard": "js/dashboard.js"};
            var CONTENT_FUNCTIONS;
            var contentPage = null;
			var currentStage = null;
            var localOffset = 0;
            var zoneOffset = 0;
            var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
            var FOOTER_SECTIONS = {
                "terms_conds": "Terms and Conditions",
                "privacy_policy": "Privacy Policy",
                "contact_us": "Contact Us"
            };
            var INACTIVE = 0;
            var HIGHLIGHT = -43;
            var SELECTED = -86;
			
			var STAGE_EVENT_INFO = "<h3>APRIL 26 - MAY 7, 2010: SHAKEDOWN STAGE (COMPETITION EVENT)<br />Location: Michigan International Speedway, Brooklyn, MI</h3><p>The purpose of this first stage is to conduct safety inspections and on-track dynamic safety evaluations of competition vehicles. Teams must submit their cars to on-the-ground challenges for the purpose of shaking out problem areas and preparing their vehicles for the Knockout Qualifying Stage that follows, all without risk of elimination by the judges. Vehicles will be tested on braking speed, lane change ability, acceleration and refueling/recharging time, among other elements.</p><h3>JUNE 20-30, 2010 KNOCKOUT QUALIFYING STAGE (COMPETITION EVENT)<br />Location: Michigan International Speedway</h3><p>To narrow the field of competitors, Progressive Insurance Automotive X PRIZE officials will re-conduct inspections and certify readiness for knockout stage challenges. In order to pass this stage, teams must demonstrate that their vehicles can achieve at least two-thirds of the stated 100 MPGe (miles per gallon or energy equivalent) goal while also meeting expectations for range, emissions, and real world performance. Achieving emissions thresholds will prove a significant hurdle for teams in this stage as will the \"hill climb\" challenge.</p><h3>JULY 19-30, 2010 FINALS STAGE (COMPETITION EVENT)<br />Location: Michigan International Speedway</h3><p>To identify the top finalists in each class, after a quick repeat of the static and dynamic safety checks, the remaining teams will compete in scored on-track challenges, and close with a \"coast down\" exercise to gain key performance information about the aerodynamics and rolling resistance to properly prepare the vehicles for the validation stage. Speed will be important and a maximum and minimum time for events will be established.</p><h3>AUGUST 2010 VALIDATION STAGE (COMPETITION EVENT)<br />Location: EPA Labs (Ann Arbor, MI) and Argonne National Labs (Chicago, IL)</h3><p>In this final technical event, the top finalists in both the Mainstream and Alternative classes will undergo dynamometer testing under controlled laboratory conditions at certified labs to verify technical performance results. The results of this testing, combined with the speed, efficiency and emissions results from the earlier events at Michigan International Speedway, will determine the winners of the Progressive Insurance Automotive X PRIZE.</p>";

            var cookie_expires = new Date();
            // set the cookie expiration date to 6 months in the future
            cookie_expires.setDate(cookie_expires.getDate() + 180);

            function set_backpos_y(ele, val) {
				if (!ele) return;
                if ($(ele).css("background-position-y")) {
                    $(ele).css("background-position-y", val + "px");
                }
                else {
                    var posX = $(ele).css("background-position").split(" ")[0];
                    $(ele).css("background-position", posX + " " + val + "px");
                }
            }
            function setTimezone(timezone) {
                var timezoneOffsets = {"Eastern": 4, "Central":5, "Mountain":6, "Pacific":7};
                var now = new Date();
                // get the local time offset from GMT in milliseconds (minutes * 60000)
                localOffset = now.getTimezoneOffset() * 60000;
                // get the selected timezone offset from GMT in milliseconds (hours * 3600000)
                zoneOffset = timezoneOffsets[timezone] * 3600000;
                displayTime();
            }
            function displayTime() {
                var now = new Date();
                var utc = now.getTime() + localOffset;
                var local = new Date(utc - zoneOffset);
                var datestr = MONTHS[local.getMonth()] + " " + local.getDate() + ", " + local.getFullYear() + ", ";
                var hrs = local.getHours();
                var ampm = "AM";
                if (hrs >= 12) {
                    ampm = "PM";
                    if (hrs > 12) hrs -= 12;
                }
                var minstr = local.getMinutes().toString();
                if (minstr.length < 2) minstr = "0" + minstr;
                datestr += hrs + ":" + minstr + " " + ampm;
                $("#date_content").html(datestr);
				
				setAlertMessage(now);
            }
            function initClock(timezone) {
                setTimezone(timezone);
                setInterval("XPRIZE.main.updateClock()", 30000);
            }
            function setAlertMessage(datetime) {
				var newStage = XPRIZE.stages.getCurrentStage(datetime);
				if (newStage) {
					if (currentStage == newStage) return;
					currentStage = newStage;
                	$("#alert_main").html(currentStage + " Stage In Progress!");
					$("#alert_button").removeClass("alert_off").addClass("alert_on");
				}
				else {
					var nextStage = XPRIZE.stages.getNextStage(datetime);
					if (nextStage) {
						var stage_start = XPRIZE.stages.getStageDetails(nextStage).startDate;
						if (new Date(stage_start) - datetime < (24 * 60 * 60 * 1000))
							$("#alert_main").html(nextStage + " Stage Begins TOMORROW!");
						else
		                	$("#alert_main").html(nextStage + " Stage Begins " + stage_start + "!");
					}
					else
						$("#alert_main").html("Competition Complete!");
					$("#alert_button").removeClass("alert_on").addClass("alert_off");
				}
			}
            function initAlertMessage() {
                $("#alert_sub").click(function() {
				   // open lightbox
				   XPRIZE.main.showLightbox(STAGE_EVENT_INFO, 800, 520);
				});
            }
            function initSection(params) {
				// no content in social section anymore...
				if (contentPage == "social") {
					return;
				}
                if (!CONTENT_FUNCTIONS.hasOwnProperty(contentPage)) {
                    alert("Error! No content for this page: " + contentPage);
                    return;
                }
                // first initialize the breadcrumbs for this page
                // make first char uppercase
                var crumb = contentPage.slice(0,1).toUpperCase() + contentPage.slice(1);
                XPRIZE.breadcrumbs.init(crumb);
                if (typeof(CONTENT_FUNCTIONS[contentPage]) == "undefined") {
                    $.getScript(JS_FILES[contentPage], function() {
                        //for lack of a better way I am saving the current object
                        if (contentPage == "teams")
                            CONTENT_FUNCTIONS[contentPage] = XPRIZE.teams;
                        else if (contentPage == "dashboard")
                            CONTENT_FUNCTIONS[contentPage] = XPRIZE.dashboard;
//                        else
//                            CONTENT_FUNCTIONS[contentPage] = XPRIZE.social;
                        CONTENT_FUNCTIONS[contentPage].init(params);
                    });
                }
                else CONTENT_FUNCTIONS[contentPage].init(params);
            }
            function initTracking() {
                XPRIZE.tracker.init();
            }
            // thanks to JQUERY HOWTO for this snippet to decode url params
            function getUrlVars(){
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for(var i = 0; i < hashes.length; i++)
                {
                  hash = hashes[i].split('=');
                  vars.push(hash[0]);
                  vars[hash[0]] = hash[1];
                }
                return vars;
            }
            function createLightbox() {
                // note that message can't be inside greyed out div because in FF, inner divs have same opacity
                var html = ['<div class="grey_out"></div><div id="lightbox_wrapper">'];
                html.push('<div id="lightbox_top_section"><div id="lightbox_topleft" class="png_fix"></div><div id="lightbox_top" class="fix_width png_fix"></div><div id="lightbox_topright" class="png_fix"></div></div><div style="clear:both;"></div>');
                html.push('<div id="lightbox_middle_section"><div id="lightbox_middleleft" class="fix_height png_fix"></div><div id="lightbox_middle" class="fix_width fix_height png_fix">');
                html.push('<div style="float:right;width:100px;"><a class="no_underline_link exit_lightbox" style="float:left;" href="#">Exit Window</a><div class="exit_lightbox png_fix" id="x-circle"></div></div>');
                html.push('<div id="lightbox_content"></div>');
                html.push('</div><div id="lightbox_middleright" class="fix_height png_fix"></div></div><div style="clear:both;"></div>');
                html.push('<div id="lightbox_bottom_section"><div id="lightbox_bottomleft" class="png_fix"></div><div id="lightbox_bottom" class="fix_width png_fix"></div><div id="lightbox_bottomright" class="png_fix"></div></div><div style="clear:both;"></div>');

                html.push('</div>');

                $('body').append(html.join(''));

                $('div.exit_lightbox').hover(function() {
                    $(this).css('background-position', '-88px 0');
                }, function() {
                    $(this).css('background-position', '-61px 0');
                });
                $('.exit_lightbox').click(function() {
                    $(".help_on").click();  // this turns off the help button if it is on
                    $('#lightbox_wrapper').fadeOut(450);
                    $(".grey_out").fadeOut(500);
                });
            }
            function displayLightbox(content, width, height, lb_left, lb_top) {
                var lb_width = width || 500;
                var lb_height = height || 350;
				// set lightbox values
                $('.fix_width').width(lb_width - 32);
                $('.fix_height').height(lb_height - 32);
                $('#lightbox_content').html(content);
                // get page dimensions
                var winWidth = document.documentElement.clientWidth;
                var winHeight = window.innerHeight || document.documentElement.clientHeight;
                var pageHt = document.body.clientHeight;
				// calculate position if not supplied
				if (!lb_left) {
					var lb_left = Math.round(winWidth/2) - lb_width/2;
					if (lb_left < 0) lb_left = 0;
				}
				if (!lb_top) {
					var winTop = document.documentElement.scrollTop || document.body.scrollTop;
					var lb_top = winTop + Math.round((winHeight - lb_height)/2);
					if (lb_top < 0) lb_top = 0;
				}
                // have to set dimensions specifically to get full page height and to get it to work in IE at all
                $('.grey_out').css({'height': ''+(pageHt > winHeight ? pageHt : winHeight)+'px', 'width': ''+winWidth+'px'}).fadeIn(500, function() {
					// had to add this for IE																															  
					$(this).css("filter","alpha(opacity=50)");
				}).click(function() {
					$('.exit_lightbox').click();
				});
                // set position of lightbox
                $('#lightbox_wrapper').css({'left': ''+lb_left+'px', 'top': ''+lb_top+'px'}).fadeIn(500);
            }
            return {
                init: function(initPage) {
                    contentPage = initPage;
                    var params = getUrlVars();
            		CONTENT_FUNCTIONS = {"teams": XPRIZE.teams,
                                    "social": XPRIZE.social, 
                                    "dashboard": XPRIZE.dashboard};
                    // set timezone function
                    $("#timezone").change(function(e) {
                        var selected = this.options[this.selectedIndex];
                        setTimezone(selected.text);
                        // save to cookie
                        var opts = {expiresAt: cookie_expires};
                        $.cookies.set("xprize_timezone", selected.text, opts);
                    });
                    // add main tab functions
                    var tab = $("#" + contentPage + "_tab");
                    tab.addClass("selected");
                    set_backpos_y(tab.get(0), SELECTED);

                    $(".main_nav_tab").hover(function(e) {
                        var tab = $(this);
                        if (!tab.hasClass("selected"))
                            set_backpos_y(this, HIGHLIGHT);
                    }, function(e) {
                        if (!$(this).hasClass("selected")) {
                            set_backpos_y(this, INACTIVE);
                        }
                    });

                    $(".help_button").hover(function(e) {
                        // show hover if button is not on
                        if (!$(this).hasClass("help_on"))
                            $(this).addClass("help_hover");
                    }, function(e) {
                        $(this).removeClass("help_hover");
                    });
                    $(".help_button").click(function(e) {
                        $(this).toggleClass("help_on");
                        if ($(this).hasClass("help_on")) {
                            // get the content from the active page
                            CONTENT_FUNCTIONS[contentPage].siteHelp();
                        }
                    });
                    $(".footer_link").click(function() {
                        $(".content-wrapper").hide();
                        var id = $(this).attr('id');
                        $("#" + id + "_wrapper").show();
                        // have to close tab and tell cookie crumbs....
                        CONTENT_FUNCTIONS[contentPage].closeAll();
                        XPRIZE.breadcrumbs.addCrumb(FOOTER_SECTIONS[id]);
						//return false;
                    });
                    $(".addthis_button").mouseenter(function() {
                        // we need to add the query portion of the url to the share-this button to identify the current context
                        var link = CONTENT_FUNCTIONS[contentPage].linkToThis();
						if (!link) {
							// one of the footer pages must be active
							var url = window.location.href
        					link = url.substring(0, url.indexOf(".html")+5);
							var page = $(".footer-contents:visible").attr("id");
							if (page.indexOf("terms") == 0)
								link += "?p=" + "trm";
							else if (page.indexOf("contact") == 0)
								link += "?p=" + "cnt";
							else if (page.indexOf("privacy") == 0)
								link += "?p=" + "prv";
						}
                        this.share.url = link;  // NOTE this is totally undocumented but it works (for now)
                    });
                    initAlertMessage();
                    // set the default time--use cookie?
                    var timezone = $.cookies.get("xprize_timezone");
                    if (!timezone)
                        initClock("Eastern");
                    else {
                        $("#timezone option[value=" + timezone + "]").attr("selected", "selected");
                        initClock(timezone);
                    }

                    // initialize Team's I'm Tracking
                    initTracking();

                    // initialize content
                    initSection(params);

            },
            updateClock: function() {
                displayTime();
            },
            trackedTeamSelected: function(teamkey) {
				if (contentPage != "teams") {
					var url = "index.html?p=telemetry&tk=" + teamkey;
			window.location.href = url;
				}
				else
                	CONTENT_FUNCTIONS[contentPage].goToTeam(teamkey);
            },
            // note: may not need this function anymore
            setPageContent: function(type) {
                CONTENT_FUNCTIONS[contentPage].setContent(type);
            },
            followBreadcrumb: function(crumb) {
                CONTENT_FUNCTIONS[contentPage].goToView(crumb);
            },
            showLightbox: function(contentHtml, width, height) {
                if ($(".grey_out").length == 0)
                    createLightbox();
                displayLightbox(contentHtml, width, height)
            },
			doQuery: function(url, onSuccess, onFailure) {
				//var URL_BASE = "http://progautoxp.appspot.com/";
				var URL_BASE = "/";
				// set timeout for 10 seconds
				var timer = setTimeout(onFailure || function(){}, 10000);
				try {
					$.get(URL_BASE + url, function(data) {
						// cancel timeout
						clearTimeout(timer);
						// check return code
						var recs = data.split('\n');
						if (recs[0] == "200") {
							// remove the return code
							recs.shift();
							if (onSuccess) onSuccess(recs);
						}
						else {
							if (onFailure) onFailure(recs[0]);
						}
					});
				}
				catch(err) {
					if (onFailure) onFailure(["exception"]);
				}
			}
        }
}();

