$('.no-js').removeClass('no-js');
$('#no-js').remove();

var App = (function() {
    
    // PRIVATE VARS & FUNCTIONS
    
    var userEmail;
    var appTitle = document.title;
    var pageData = {};
    var teamData = {};
    var currQuestion = 0;
    var totalQuestions = 0;
    var currScore = 0;
    var api = 'api/functions.php';
    var enableAnswer = true;
    var entryComplete = false;

    //--------------------------------------
    //  NAVIGATION
    //--------------------------------------
    
    function changePage(pageID, pageTitle, data) {
        
        // update page data
        if (!data) {
            pageData = {};
        } else {
            pageData = data;    
        }
        
        // update title
        updatePageTitle(pageTitle);
        
        // update page
        $.address.value(pageID);
    }
    
    function updatePageTitle(pageTitle) {
        if (appTitle) {
            $.address.title(appTitle+' | '+pageTitle);
        } else {
            $.address.title(pageTitle);
        }
    }
    
    function updateContent(pageName) {
        
        if (pageName === 'welcome') {
            pageData = {};
        } else if (pageName === 'prizing') {
            pageData = teamData;
        } else if (pageName === 'enter') {
            pageData = {score:currScore,id:teamData.id};
        }
        
        pageData.teams = TEAMS;     // defined in data.js
        
        var pageID = '#'+pageName;
        
        // empty content
        $('#content').empty();
        
        // add screen size and team data for use in templates
        pageData.size = sizeit.size();
        
        // add the content
        $(pageID+'Template').tmpl(pageData).appendTo('#content').trigger('create');
        
        // adjust footer for entry form
        if (pageID == '#enter' && pageData.size == 'large') {
            $('#footer').css('bottom','-260px');    
        }
        
        // Scroll to top
        window.scrollTo(0,0);
        
        // add team colors
        if (teamData.colors) {
            $('.team-headline').css('color',teamData.colors.headline);
            if (teamData.colors.headline == '#000000') {
                $('.team-headline').css('text-shadow','none');
            }
            $('.scoreboard-background')
                .css('background','#000')
                .css('background','-moz-linear-gradient(top, #000 0%, '+teamData.colors.scoreboard+' 100%)')
                .css('background','-webkit-gradient(linear, left top, left bottom, color-stop(0%,#000), color-stop(100%,'+teamData.colors.scoreboard+'))')
                .css('background','-webkit-linear-gradient(top, #000 0%,'+teamData.colors.scoreboard+' 100%)')
                .css('background','-o-linear-gradient(top, #000 0%,'+teamData.colors.scoreboard+' 100%)')
                .css('background','-ms-linear-gradient(top, #000 0%,'+teamData.colors.scoreboard+' 100%)')
                .css('filter',"progid:DXImageTransform.Microsoft.gradient( startColorstr='#000000', endColorstr='"+teamData.colors.scoreboard+"',GradientType=1 )")
                .css('background','linear-gradient(top, #000 0%,'+teamData.colors.scoreboard+' 100%)');
        }
    }
    
    function setPageEvents() {
        
        // MODALS
        
        $('#wrapper')
            .delegate('#rules', 'click', function(e){
                e.preventDefault();
                $('#rules').remove();
                $('#footer').show();
            })
            .delegate('#answer', 'click', function(e){
                e.preventDefault();
                $('#answer').remove();
                nextQuestion();
            })
        
        // CHECKBOXES
            
            .delegate('.checkbox-button', 'click', function(e){
                e.preventDefault();
                var checked = $(this).attr('active') == 'off' ? 'on' : 'off';
                $(this).attr('active',checked);
                $('img',this).attr('src','_/img/checkbox_'+checked+'.png');
            });
        
        $('#content')
        
            // WELCOME PAGE
                
            .delegate('a.team-button', 'click', function(e){
                e.preventDefault();
                var teamID = $(this).jqmData('team');
                $('#content').empty();
                $.getJSON('_/data/'+teamID+'.json', function(data) {
                    teamData = data;
                    teamData.id = teamID;
                    totalQuestions = data.questions.length;
                    changePage('prizing','Start Challenge',teamData);
                    _gaq.push(['_trackEvent', 'Team Select', teamData.id]);
                });
            })
            
            // PRIZING PAGE
            
            .delegate('#start-button', 'click', function(e){
                e.preventDefault();
                currQuestion = 0;
                currScore = 0;
                if ($('#prizing-agree').attr('active') === 'off') {
                    $('.error').css('visibility','visible');
                } else {
                    // start questions
                    $('.error').css('visibility','hidden');
                    $('#content').empty();
                    _gaq.push(['_trackEvent', 'Quiz', 'Start', teamData.id]);
                    nextQuestion();
                }
            })
            .delegate('#rules-link', 'click', function(e){
                e.preventDefault();
                _gaq.push(['_trackEvent', 'Rules', 'View', teamData.id]);
                $('#rulesTemplate').tmpl().appendTo('#wrapper');
                $('div.modal').trigger('create').css('display','block');
                $('#rules-contain').load('_/rules/'+teamData.id+'.html');
                $('#footer').hide();
            })
            
            // QUIZ PAGE
            
            .delegate('a.quiz-button', 'click', function(e){
                e.preventDefault();
                if (enableAnswer) {
                    enableAnswer = false;
                    answerQuestion($(this).jqmData('id'));
                    _gaq.push(['_trackEvent', 'Quiz', 'Answer'+currQuestion+1, teamData.id]);
                }
            })
            
            // ENTER PAGE
            
            .delegate('#enter-button', 'click', function(e){
                e.preventDefault();
                submitEntry();
            })
            .delegate('#play-again', 'click', function(e){
                e.preventDefault();
                _gaq.push(['_trackEvent', 'Quiz', 'Play Again', teamData.id]);
                currQuestion = 0;
                currScore = 0;
                teamData = {};
                enableAnswer = true;
                entryComplete = false;
                changePage('welcome','Play Again');
            });
    }
    
    //--------------------------------------
    //  QUIZ
    //--------------------------------------
    
    function nextQuestion() {
        currQuestion++;
        if (currQuestion > totalQuestions) {
            changePage('enter','Enter',{score:currScore,id:teamData.id});
        } else {
            // update title
            updatePageTitle('Question '+currQuestion);
            pageData = {
                q:currQuestion-1,
                total:totalQuestions,
                score:currScore,
                questions:teamData.questions,
                colors:teamData.colors,
                id:teamData.id
            };
            updateContent('quiz');
            enableAnswer = true;
        }
    }
    
    function answerQuestion(answer) {
        var qData = teamData.questions[currQuestion-1];
        var isCorrect = qData.correct === answer;
        currScore = isCorrect ? currScore + 10 : currScore;
        var resultData = {
            answer: qData.answers[answer],
            factoid: qData.factoid,
            correct: isCorrect ? 'Correct' : 'Incorrect',
            questions: teamData.questions,
            finished: (currQuestion === totalQuestions) ? true : false
        };
        $('#answerTemplate').tmpl(resultData).appendTo('#result').trigger('create');
    }

    //--------------------------------------
    //  VALIDATION
    //--------------------------------------
    
    function submitEntry() {
        $('#input-firstname').css('background','white');
        $('#input-lastname').css('background','white');
        $('#input-email').css('background','white');
        $('#input-address').css('background','white');
        $('#select-state').parent().css('border','none');
        $('#input-zip').css('background','white');
        $('#select-day').parent().css('border','none');
        $('#select-month').parent().css('border','none');
        $('#select-year').parent().css('border','none');
        
        // validate enter form
        var enterValid = true;
        
        // Data object for form data
        var entryData = {};
        
        entryData.firstName = $('#input-firstname').val();
        if (!validateName(entryData.firstName)) {
            enterValid = false;
            $('#input-firstname').css('background','yellow');
        }
        
        entryData.lastName = $('#input-lastname').val();
        if (!validateName(entryData.lastName)) {
            enterValid = false;
            $('#input-lastname').css('background','yellow');
        }
        
        entryData.email = $('#input-email').val();
        if (!validateEmail(entryData.email)) {
            enterValid = false;
            $('#input-email').css('background','yellow');
        }
        
        entryData.address = $('#input-address').val();
        if (!validateAddress(entryData.address)) {
            enterValid = false;
            $('#input-address').css('background','yellow');
        }
        
        entryData.city = $('#input-city').val();
        if (!validateCity(entryData.city)) {
            enterValid = false;
            $('#input-city').css('background','yellow');
        }
        
        entryData.state = $('#select-state').val();
        if (entryData.state == '') {
            enterValid = false;
            $('#select-state').parent().css('border','solid 2px yellow');
        }
        
        entryData.zip = $('#input-zip').val();
        if (!validateZip(entryData.zip)) {
            enterValid = false;
            $('#input-zip').css('background','yellow');
        }
        
        entryData.dobDate = $('#select-day').val();
        if (entryData.dobDate == '') {
            enterValid = false;
            $('#select-day').parent().css('border','solid 2px yellow');
        }
        
        entryData.dobMonth = $('#select-month').val();
        if (entryData.dobMonth == '') {
            enterValid = false;
            $('#select-month').parent().css('border','solid 2px yellow');
        }
        
        entryData.dobYear = $('#select-year').val();
        if (entryData.dobYear == '') {
            enterValid = false;
            $('#select-year').parent().css('border','solid 2px yellow');
        }
        
        entryData.optin = $('#prizing-agree').attr('active') === 'on' ? 1 : 0;
        
        entryData.team = teamData.id;
        
        entryData.keycode = teamData.keycode;
        entryData.agency = teamData.agency;
        
        if (enterValid) {
            $('#content').empty();
            $.post('submit.php', entryData, function(data) {
                _gaq.push(['_trackEvent', 'Entry', 'Submit', teamData.id]);
                changePage('end','Thanks For Playing');
                entryComplete = true;
            });   
        }
    }
    
    function validateEmail(emailTest) {
        var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
        if (filter.test(emailTest) && emailTest.length < 99) {
            return true;
        } else {
            return false;
        }
    }
    
    function validateName(nameTest) {
        // only letters
        var filter = /[^a-z\s]/gi;
        var valid = !(filter.test(nameTest));
        
        // at least 2 letters
        if (nameTest.length < 2) {
            valid = false;
        }
        
        // no extra spaces
        filter = /\s{2,}/g;
        if (filter.test(nameTest)) {
            valid = false;
        }
        
        return valid;
    }
    
    function validateAddress(addressTest) {
        // at least 5 letters
        return addressTest.length > 5;
    }
    
    function validateCity(cityTest) {
        // at least 2 letters
       return cityTest.length > 2;
    }
    
    function validateZip(zipTest) {
        var filter = /[^0-9]/gi;
        var valid = !(filter.test(zipTest));
        
        // must be 5-digit zip
        if (zipTest.length !== 5 ) {
            valid = false;
        }
        
        return valid;
    }
    
    
    // PUBLIC VARS & FUNCTIONS
    
    return {       
        
        init : function() {
            
            // use jQuery address for app navigation
            $.address
                .init(function(event) {
                    changePage('welcome','Welcome');
                })
                .change(function(event) {
                    if (event.value.substring(1) != '' && !entryComplete) {
                        updateContent(event.value.substring(1));   
                    } else {
                        updateContent('welcome');   
                    }
                });
            
            setPageEvents();
        }   
    };
}());

$(document).ready(function(){
    App.init();
});
