/**
*   @preserve cfc.js
*   chattanooga football club
*   copyright (c) 2010 MEDIUM
*/
(function( $ ) {

    var CFC = {

        styleFormElements: function () {
            $('.schedule-form select').elect();
        },

        topLink: function () {
            $('a.back-to-top').click(function (e) {
                e.preventDefault();
                $('html, body').animate({
                    scrollTop: 0
                }, 'slow');
            })
        },

        shareDat: function () {
            $.getScript('/media/js/share.min.js', function () {
                $('.share').share("Email, Twitter, Facebook, Digg, Del.icio.us, LinkedIn", {
                    position: 'bottom',
                    url: window.location.href
                });
            });
        },

        sponsorsRotate: function () {
            var box      = $('.sponsor-container'),
                sponsors = $('.sponsor-container .image').hide(),
                next     = box.find('.next'),
                prev     = box.find('.prev'),
                count    = sponsors.length,
                cur      = 1000 * count;

            function change(diff) {
                sponsors.eq(cur % count).fadeOut();
                cur = cur + diff;
                sponsors.eq(cur % count).fadeIn();
            }
            next.click(function () {
                change(1)
            });
            prev.click(function () {
                change(-1)
            });
            change(0);
        },

        glowingLogo: function () {
            $('#masthead').prepend($('<a/>', {
                'id': 'glow',
                'href': '/'
            }).css({
                'opacity': '0'
            }).hover(function () {
                $(this).stop().animate({
                    'opacity': '1'
                }, 666)
            }, function () {
                $(this).stop().animate({
                    'opacity': '0'
                }, 666)
            }));
        },

        tabs: function () {
            $('.tabbed-interface').each(function (i, ti) {
                $(this).find('li.tab').each(function (i, li) {
                    $(li).click(function () {
                        $(ti).find('.pane').hide().eq(i).show()
                        $(li).addClass('selected').siblings('li').removeClass('selected');
                    });
                });
                $(this).find('li.tab').eq(0).click();
            });
        },

        homeSlider: function () {
            var largeText = $('.large-image').find('.text'),
                timeout, next, resetTimeout = function (i) {
                    clearTimeout(timeout);
                    next = i;
                    timeout = setTimeout(function () {
                        $('.small-images').children('.text').eq(next).click();
                    }, 6666)
                },
                nextImage = function (thumb, i) {
                    $(thumb).siblings().removeClass('selected').end().addClass('selected');
                    $(thumb.counterpart).fadeIn('slow').siblings('img').fadeOut('slow');
                    largeText.find('h4').text($(thumb).find('h5').text());
                    largeText.find('p').text($(thumb).find('p').text());
                    largeText.find('a').attr('href', $(thumb).find('span').text());
                    resetTimeout((i + 1) % 4);
                };

            $('.small-images').children('.text').each(function (i, thumb) {
                thumb.counterpart = $('.large-image').children('img').eq(i);
                thumb.counterpart.hide();
                $('<div />', {
                    'class': 'tip'
                }).appendTo(thumb);
                $('<div />', {
                    'class': 'frame'
                }).appendTo(thumb);
                $(thumb).click(function () {
                    nextImage(thumb, i);
                });
            }).first().click();
        },

        scheduleView: function () {
            $('.schedule-unit').each(function (i, unit) {
                $(unit).find('.toggle').toggle(

                function (e) {
                    $(unit).find('.details').show().end().find('.sub-details').show().end().find('.promotion').show();
                    $(unit).find('.w').hide().end().find('.when').css({
                        'height': 171
                    }).find('.result').show();
                    $(unit).find('.toggle h6').text('-');
                }, function (e) {
                    $(unit).find('.details').hide().end().find('.sub-details').hide().end().find('.promotion').hide();
                    $(unit).find('.w').show().end().find('.when').css({
                        'height': 30
                    }).find('.result').hide();
                    $(unit).find('.toggle h6').text('+');
                });
            });
            $('.schedule-unit.next').find('.toggle').click();
        },

        video: function () {
            $('.img-for-video').each(function (i, vid) {
                var par = $(vid).parent('.media').css({
                    'width': '600px',
                    'min-height': '420px',
                    'cursor': 'pointer'
                });
                par.append($('<img class="shield" src="/media/images/video-shield.png"/>').hide().fadeIn('slow'));
                par.find('object').hide();

                $(par).click(function () {
                    $(par).find('img').fadeOut().end().find('object').show().end().animate({
                        'height': $(par).find('object').height()
                    }, 500);
                });
            });
        },
        
        products: function () {
            
            // Vertically align all product images in their 360px tall frames
            $('div.product-unit img').each(function (i, item) {
                var $im   = $(item),
                    delta = (360 - $im.height()) / 2 + 10;
                $im.css('top', delta);
            });
            
            // Toggle back button
            $('div.toggle-back-front').toggle(function() {
                $(this).addClass('back')
                    .prev('img.back').show().prev('img.front').hide();
                return false;
            }, function() {
                $(this).removeClass('back')
                    .prev('img.back').hide().prev('img.front').show();
                return false;
            });            
        },

        twitterz: function () {
            var target = $('.twitterz ul')
            $.getScript('/media/js/jquery.timeago.min.js', function (data) {
                window.populateTwitter = function (data) {
                    $.each(data, function (i, twit) {
                        var status = twit.text;
                        status = status.replace(/((https?:\/\/(www\.)?|www\.)([^\s]+)\.[a-z]{2,5}([^\s]+)?)/gm, '<a target="new" title="$1" href="$1">$1</a>').replace(/href="www\./, 'href="http://www.'), status = status.replace(/@([a-zA-Z0-9_]+)/gm, '<a target="new" title="$1" href="http://twitter.com/$1">@$1</a>');
                        $('<li/>', {
                            'html': status + ' <a class="timestamp" href="http://twitter.com/' + twit.user.screen_name + '/status/' + twit.id + '">' + $.timeago(twit.created_at) + '</a>'
                        }).appendTo( target );
                    });
                }
                $.getScript('http://api.twitter.com/1/statuses/user_timeline/chattanoogafc.json?count=5&callback=populateTwitter');
            });
        },

        handleForm: function () {
            $('#signup-form').find('input[type=text]').each(function (i, input) {
                input.initialValue = $(input).val();
                $(input).focus(function () {
                    var $i = $(this);
                    if ( $i.val() === input.initialValue ) {
                        $i.val('');
                    }
                }).blur(function () {
                    var $i = $(this);
                    if ( $i.val() === "" ) {
                        $i.val( input.initialValue );
                    }
                });
            });
            $.getScript('/media/js/checkform.js', function () {
                CFC.newsletterAjax();
            });
        },

        newsletterAjax: function () {
            var nl_form = '#signup-form',
                nl_thanks = '<h5 class="nl-thanks">Thank You</h5><p class="nl-thanks">You have now been added to the mailing list and will receive the next email broadcast soon. If you wish to unsubscribe, simply use the <i>"unsubscribe"</i> link included in the next Chattanooga FC email.</p>',
                nl_req = '#signup-form input[type=text]',
                nl_load = '#loading';
            CFC.ajaxSend(nl_form, nl_thanks, nl_req, nl_load);
        },

        /**
        *   Send forms with ajax
        *   @param {object} f Forms to bind to the submission.
        *   @param {string} thanks Thank you message (html) which replaces the form.
        *   @param {string} place Selector for where to place errors.
        *   @param {string} loading Selector for the loading gif to show and hide.
        */
        ajaxSend: function (f, thanks, place, loading) {
            $(f).submit(function (e) {
                var form = this,
                    loadingGif = $(loading),
                    placeText = $(place);

                if ( !window.checkForm(form) ) {
                    e.preventDefault();
                    placeText.show();
                    return false;
                }
                e.preventDefault();
                $.ajax({
                    type: form.method,
                    url: form.action,
                    timeout: 5000,
                    data: $(form).serialize(),
                    dataType: "json",
                    success: function (data) {
                        loadingGif.hide();
                        if (data.status === "error") {
                            placeText.html( data.html );
                        } else {
                            $(form).replaceWith( thanks );
                        }
                    },
                    error: function (req, error) {
                        loadingGif.hide();
                        if (error === 'error') {
                            error = req.statusText;
                        }
                        var errormsg = 'There was a communication error: ' + error;
                        placeText.html( errormsg );
                    },
                    beforeSend: function (data) {
                        loadingGif.show();
                    }
                });
                return false;
            });
        },

        roster: function () {
            var selector = $('select#roster'),
                list = selector.siblings('ul');
            selector.elect();

            $.getScript('/media/js/underscore.min.js', function () {
                $.getJSON('/team/json/', function (data) {
                    var group, blah;

                    function fetchObject(pos) {
                        group = _.detect(data, function (datum) {
                            return datum.position == pos;
                        })
                        return group;
                    }

                    function populateList(pos) {
                        pos = pos.replace(/s$/, '')
                        var players = _.toArray(fetchObject(pos).players),
                            blah = "";
                        _.each(players, function (player) {
                            blah += "<li><a href='" + player.link + "'>" + player.name + "</a></li>"
                        })
                        list.html(blah)
                    }

                    selector.change(function (e) {
                        populateList(selector.find(':selected').text())
                    })

                    populateList(selector.find(':selected').text())

                    $('.elect-option').each(function () {
                        // pluralize
                        $(this).val($(this).text() + "s")
                    })

                    if ($('#Player').length) {
                        var pos, name;
                        pos = $('.playerinfo .name span.position').text();
                        name = $('.playerinfo .name').text().replace(pos, '').replace(/^\s+|\s+$/gm, '');
                        category = _.detect(data, function (datum) {
                            return datum.position == pos;
                        });
                        $('.elect-option:contains("' + category.position + '")').mouseup();
                        $('.pane').find('li a:contains("' + name + '")').addClass('active');
                    }
                });
            })

            $('.team-sidebar .pane').each(function (i, pane) {
                if ($(pane).find('a.active').length) {
                    $('.team-sidebar').find('.tab').eq(i).click()
                }
            });
        },

        facebookComments: function () {
            $('#comment-with-facebook').click(function () {
                $("#comments-here").html('<fb:comments width="600"></fb:comments>');
                FB.XFBML.parse(document.getElementById('comments-here'));
            });
        },

        ticketsPage: function () {
            $('.ticket').each(function (i, tix) {
                $(tix).hover(function () {
                    $(tix).find('.purchase').stop().animate({
                        'top': '0'
                    }, 333);
                }, function () {
                    $(tix).find('.purchase').stop().animate({
                        'top': '192'
                    }, 333);
                });
            });
        },

        mediaGallery: function () {
            $.getScript('/media/js/jquery.media.min.js', function () {
                $.getJSON('/media-gallery/media/', function ( data ) {
                    var slider   = $('.slider'),
                        images   = $('.images ul'),
                        showcase = $('.showcase'),
                        maxW     = 920,
                        maxH     = 520, 
                        uloffset = 0,
                        itemW    = 218,
                        totW     = 0,
                        bindex, atFarRight, atFarLeft;

                    function appendItem(item, type) {
                        if ( type == "video" ) {
                            item.src = item['media:content']['media:thumbnail']['url'];
                            item.big = $("<div class='video-wrapper'><a href='" + item['media:content']['media:player']['url'] + "'/>")
                            item.mgnode = $('<li/>', {
                                "class": type,
                                "html": "<img src='" + item.src + "'/>",
                                "click": function () {
                                    if ( bindex == item.index ) {
                                        return 0;
                                    }
                                    bindex = item.index;
                                    var leaving = showcase.children();
                                    leaving.fadeOut('fast', function () {
                                        showcase.append($(item.big).hide().fadeIn('slow', function () {
                                            leaving.remove();
                                            showcase.find('a').media({
                                                width: 920,
                                                height: 520,
                                                autoplay: true
                                            }).css({
                                                'position': 'absolute',
                                                'left': '10px'
                                            });
                                        }));
                                    });
                                }
                            });
                        }

                        if (type == "photo") {
                            item.src = item['media:content'].url;
                            item.h   = item['media:content'].height;
                            item.w   = item['media:content'].width;

                            if (item.h > maxH) {
                                var oldH = item.h,
                                    oldW = item.w;
                                item.h = maxH;
                                item.w = oldW * item.h / oldH
                            }

                            if (item.w > maxW) {
                                var oldH = item.h,
                                    oldW = item.w;
                                item.w = maxW;
                                item.h = oldH * item.w / oldW
                            }


                            item.big = $('<img/>', {
                                'src': item.src,
                                'css': {
                                    'marginLeft': -item.w / 2,
                                    'marginTop': -item.h / 2,
                                    'width': item.w,
                                    'height': item.h,
                                    'left': '50%',
                                    'top': '50%'
                                }
                            });

                            item.mgnode = $('<li/>', {
                                'class': type,
                                'html': "<img src='" + item.src + "'/>",
                                'click': function () {
                                    if (bindex == item.index) {
                                        return 0;
                                    }
                                    bindex = item.index;
                                    var leaving = showcase.children();
                                    leaving.fadeOut('fast', function () {
                                        showcase.append($(item.big).hide().fadeIn('slow', function () {
                                            leaving.remove()
                                        }));
                                    });
                                }
                            });
                        }
                        images.append(item.mgnode); // add item to list
                        totW += itemW; // Keep track of total list width
                    }

                    $(data.value.items).each(function (i, item) {
                        item.index = i;
                        if (item.link.match(/vimeo/)) {
                            appendItem(item, "video")
                        };
                        if (item.link.match(/flickr/)) {
                            appendItem(item, "photo")
                        };
                    });

                    $('.rarr').click(function () {
                        if (atFarRight) {
                            return false;
                        }
                        images.animate({
                            'left': parseInt(images.css('left'), 10) - 864
                        }, 500, function () {
                            uloffset = parseInt(images.css('left'), 10);
                            status();
                        });
                    });

                    $('.larr').click(function () {
                        if ( atFarLeft ) {
                            return false;
                        }
                        images.animate({
                            'left': parseInt(images.css('left'), 10) + 864
                        }, 500, function () {
                            uloffset = parseInt(images.css('left'), 10);
                            status();
                        });
                    });

                    function status () {
                        atFarLeft  = uloffset == 0;
                        atFarRight = Math.abs(uloffset) + 864 > totW;
                    }

                    status();
                    images.find('li').first().click();
                });
            });

        },

        activeNewsTab: function () {
            $('div.news-sidebar').find('.pane').each(function (i, pane) {
                if ($(pane).find('li a.active').length) {
                    $('div.news-sidebar').find('.tab').eq(i).click();
                }
            });
        }
    }

    $(document).ready(function () {

        CFC.topLink();
        CFC.glowingLogo();
        CFC.sponsorsRotate();
        CFC.handleForm();

        if ($('div.tabbed-interface').length) CFC.tabs();

        if ($('.schedule-unit').length) CFC.scheduleView();

        if ($('.share').length) CFC.shareDat();

        if ($('.schedule-form').length) CFC.styleFormElements();

        if ($('#home-slider').length) CFC.homeSlider();

        if ($('.twitterz').length) CFC.twitterz();

        if ($('.img-for-video').length) CFC.video();

        if ($('#MediaGalleryPage').length) CFC.mediaGallery();

        if ($('#roster').length) CFC.roster();

        if ($('#comment-with-facebook').length) CFC.facebookComments();

        if ($('#TicketsPage').length) CFC.ticketsPage();

        if ($('div.news-sidebar').length) CFC.activeNewsTab();

        $('.prevlink').click(function (e) {
            e.preventDefault();
            history.back();
        });
    });

    $(window).load(function () {
        if ($('div.product-unit').length) CFC.products();
    })

})( jQuery );

window.fbAsyncInit = function () {
    FB.init({
        status: true,
        cookie: true,
        xfbml: true
    });
};

(function () {
    var e = document.createElement('script');
    e.async = true;
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    document.getElementById('fb-root').appendChild(e);
}());
