//Prevent console.log errors
if (!console) {
    var console = console || {log: function() {}};
}

//Crockford's remedial supplant function for templates
if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}


/**
 * NOTES
 * The top level shorts namespace, and config are stored in templates: main/jsConfig
 *
 * CUSTOM EVENTS
 * Triggered on the body tag. Use $('body').bind(<event>, <handler>);
 *      FBReady : When the Facebook SDK is loaded
 */
 

/**
 * ROUTES
 * Regex matches that will run page specific scripts based on the page URL
 */
shorts.routes = {
    //Global
    '^/'              : function() {
        shorts.pages.global();
    },
    
    //Homepage
    '^/$': function() {
        shorts.helpers.selectNavItem('home');
        shorts.pages.homepage();
    },
    
    //Enter
    '^/enter': function() {
        shorts.helpers.selectNavItem('enter');
        shorts.pages.enter();
    },
    
    //About
    '^/page/about$': function() {
        shorts.helpers.selectNavItem('about');
    },
    
    //Judges
    '^/page/judges$': function() {
        shorts.helpers.selectNavItem('judges');
    },
    
    //Rules
    '^/page/rules$': function() {
        shorts.helpers.selectNavItem('rules');
    },
    
    //Supporters
    '^/page/supporters$': function() {
        shorts.helpers.selectNavItem('supporters');
    },

    //Register
    '^/register': function() {
        shorts.pages.register();
    },
    
    //Film
    '^/film': function() {
        shorts.pages.film();
    }
};



// STARTUP ON DOM READY
// ================================================================================
$(function() {
    
    //Get path name without script filename
    var url = window.location.pathname
        .replace(/\/[\w]*\.php/, '');    
    
    //Match routes
    var routes = shorts.routes;
    for (var route in routes) {
        var regex = new RegExp(route);
        if (regex.test(url)) routes[route]();
    }
    
});



// HELPER FUNCTIONS
// ================================================================================
shorts.helpers = {
    /**
     * Marks an item on the main nav as 'selected'
     *
     * @param string className  The CSS class name of the <li> item to select
     */
    selectNavItem: function(className) {
        $('.navigation .' + className).addClass('selected');
    },
    
    /**
     * Shortens a string by x number of words and optionally adds a suffix (e.g. '...')
     * 
     * @param {String}  The string to limit
     * @param {Number}  The number of words to limit to
     * @param {String}  The suffix to add if the string was shortened (e.g. '...') (optional)
     */
    limitWords: function(str, numWords, suffix) {
        if (!str || !numWords) throw new Error('Missing required params');
        
        //Limit the the number of words
        var newStr = str.split(' ')
            .splice(0, numWords)
            .join(' ');
        
        //If it was shortened and suffix supplied, add it to the string
        if (suffix && str !== newStr) newStr += suffix;
        
        return newStr;
    }
};



/**
 * PAGE SPECIFIC SCRIPTS
 */
shorts.pages = {},


// ALL PAGES
// ================================================================================
shorts.pages.global = function() {

    $('a.bfi').click(function(event){
        //add click tracking for the BFI site link
        var tag_url="http://fls.doubleclick.net/activityi;src=1841273;type=vmsho529;cat=vmsho184;ord="+Math.floor(Math.random()*999999)+"?";
        if(document.getElementById("DCLK_FLDiv")){var flDiv=document.getElementById("DCLK_FLDiv");}
        else{var flDiv=document.body.appendChild(document.createElement("div"));flDiv.id="DCLK_FLDiv";flDiv.style.display="none";}
        var DCLK_FLIframe=document.createElement("iframe");
        DCLK_FLIframe.id="DCLK_FLIframe_"+Math.floor(Math.random()*999999);
        DCLK_FLIframe.src=tag_url;
        flDiv.appendChild(DCLK_FLIframe);
    });

    //Notify user if their browser is unsupported (IE6)
    if (navigator.userAgent.match(/MSIE 6/i)) {
        window.location = shorts.config.paths.unsupportedBrowser;
    }
    
    //Move flashNotice element into the right place and add close button event handler
    (function() {
        var notice = $('#flashNotice');
        if (notice.length) {
            //Move the element to the right place
            notice.prependTo($('.wrap-2col')[0]);
            
            //Add close button handler
            $('.close-btn', notice).click(function() {
                notice.remove();
            });
        }
    })();
    
    //Search box
    (function() {
        var form = $('#searchForm'),
            input = $('input[name="q"]', form),
            defaultSearchText = input.val();
        
        //Don't search if empty or default text
        form.submit(function(event) {
            var q = input.val();
            if (q == '' || q == defaultSearchText)
                event.preventDefault();
        });
    })();
    
    //Open 'a.external' links in new window
    $('a[rel="ext"]').click(function() {
        window.open(this.href);
        return false;
    });
    
    //toggleBlock: 'read more' areas that are hidden by default
    $('.toggleBlock').each(function() {
        var visible = false,
            content = $('.togglee', this),
            button = $('.toggler', this)
            initialText = button.html();
        
        content.hide();
        button.click(function(event) {
            event.preventDefault();
            
            if (visible) {
                content.hide('normal');
                visible = false;
                button.text(initialText);
            } else {
                content.show('normal');
                visible = true;
                button.text('Hide');
            }
        });
    });
    
    //hideDefault: hides the default text when a user focuses on a text input
    $('input.hideDefault').each(function() {
        var cleared = false;
        
        $(this).focus(function() {
            if (!cleared) $(this).val('');
            cleared = true;
        });
    });
}



// HOMEPAGE
// ================================================================================
shorts.pages.homepage = function() {
    //Register <select> dropdown
    $('.register input[type="button"]').click(function() {
        window.location = $('.register select').val();
    });
     
    //Start carousel
    $('.film-carousel').each(function() {
        var carousel = new shorts.Carousel(this);
    });
};



// REGISTER PAGE
// ================================================================================
shorts.pages.register = function() {
    //Add validation
    $('#registerForm').validate();
    
    /**
     * Prefill the form when Facebook is ready
     */
    if (typeof FB != 'undefined' && FB.getSession()) {
        fillFacebookData();   
    }
    else {
        $('body').bind('FBReady', fillFacebookData);
    }
    
    /**
     * Fills in the form with Facebook data
     */
    function fillFacebookData() {
        //Must be connected to Facebook
        if (!FB.getSession()) return;

        //Get FB info
        FB.api('/me', function(response) {
            //Handle errors
            if (response.error) {
                console.log(
                    "There was a problem connecting to Facebook: ", 
                    response.error.message
                );
                return;
            }
            
            //Creates a username like 'jsmith'
            function suggestUsername() {
                var username = response.first_name.substring(0, 1)
                    + response.last_name;

                return username.toLowerCase();
            }

            //Map the Facebook data to the IDs of the fields they need to populate
            var fieldMapper = {
                user_first_name:    response.first_name,
                user_last_name:     response.last_name,
                user_email_address: response.email,
                user_email_confirm: response.email,
                user_username:      suggestUsername()
            };

            //Fill the form
            for (var i in fieldMapper) {
                var input = $('#' + i);

                //Don't overwrite fields the user has already typed into
                if (input.val() == '')
                    input.val(fieldMapper[i]);
            }

            //Change the profile pic
            var picUrl = 'http://graph.facebook.com/{id}/picture?type=large'
                .replace('{id}', response.id);
            
            $('#profilePic img').attr('src', picUrl);
        });
    };
};



// ENTER PAGES
// ================================================================================
shorts.pages.enter = function() {
    
    //Form validation
    $('#filmDetailsForm').validate();
    $('#checklistForm').validate();
    
};


// FILM PAGE
// ================================================================================
shorts.pages.film = function() {
    
    //Ask user to confirm film vote
    $('.voteBtn').click(function() {
        $('#voteConfirmDialog').modal({
            minHeight: 150,
            onShow: function(dialog) {
                var modal = this,
                    content = dialog.data[0];
                    
                //Cancel
                $('a.cancel', content).click(function(e) {
                    e.preventDefault();
                    modal.close();
                });
                
                //OK
                $('a.ok', content).click(function(e) {
                    e.preventDefault();
                    modal.close();
                    
                    $('#voteForm').submit();
                });
            }
        });
    });
    
};





// FACEBOOK
// ================================================================================
shorts.facebook = {
    //Runs once the Facebook Javascript SDK has loaded and initialised
    onLoaded: function() {
        //Let other scripts know the Facebook SDK is ready
        $('body').trigger('FBReady');
        
        //Respond to FB login
        FB.Event.subscribe('auth.login', function(response) {
            window.location = shorts.config.paths.facebookLogin;
        });

        //Respond to FB logout
        FB.Event.subscribe('auth.logout', function(response) {
            window.location = shorts.config.paths.logout;
        });
        
        //Init Facebook login button
        $('.fbLoginButton').click(function(event) {
            event.preventDefault();

            //Add in our click tracking
           var tag_url="http://fls.doubleclick.net/activityi;src=1841273;type=vmsho529;cat=vmsho424;ord="+Math.floor(Math.random()*999999)+"?";
           if(document.getElementById("DCLK_FLDiv")){var flDiv=document.getElementById("DCLK_FLDiv");}
           else{var flDiv=document.body.appendChild(document.createElement("div"));flDiv.id="DCLK_FLDiv";flDiv.style.display="none";}
           var DCLK_FLIframe=document.createElement("iframe");
           DCLK_FLIframe.id="DCLK_FLIframe_"+Math.floor(Math.random()*999999);
           DCLK_FLIframe.src=tag_url;
           flDiv.appendChild(DCLK_FLIframe);

            //If we already have a session, don't login to Facebook again
            //Just log into this site
            if (FB.getSession()) {
                window.location = shorts.config.paths.facebookLogin;
                return false;
            }
            
            //Otherwise, need to login to Facebook first:
            FB.login(null, {
                perms: shorts.config.facebookPermissions
            });
        });
        
        
        //Init Logout button - log out of Facebook first
        $('#accountNav .logout').click(function(event) {
            if (FB.getSession()) {
                event.preventDefault();
                console.log('Logging out of facebook');
                FB.logout();
            }
        });
    }
};
