var kb = {};

kb.initAjaxNews = function () {
    $.getJSON("/news/preview/", function(json) {
        var l = json.length;
        initView(json, l);
    });
    function initView(news, l) {
        var html = "";
        for (i = 0; i < l; i++) {
            html += "<h3>";
            html +=
                "<a href=\"news/" + news[i].fields.slug + "\">" + news[i].fields.title + "</a>";
            html += "<small class=\"date\">";
            html +=
                news[i].fields.publish;
            html +=
                "</small></h3>";
        }
        $('#news').append(html);
    }
};

kb.initAjaxPrevRace = function () {
    $.getJSON("/schedule/prevrace/", function(race){
        defRace(race);
    });
    function defRace(prevrace) {
        //lazy json
        var race = prevrace[0].fields;
        //if variable undefined
        if (race.qualified == null){race.qualified = "TBD"}
        if (race.finished == null){race.finished = "TBD"}
        if (race.standings == null){race.standings = "TBD"}

        //string builder
        var html = "<h3 class=\"anti-padding\">" + race.title;
        html += "<span class=\"mock_h6\">" + race.track + "</span></h3>";
        html += "<dl>";
        html += "<dt>" + race.location + "</dt>";
        html += "<dd>" + race.date + "</dd>";
        html += "<dt>Qualified</dt>";
        html += "<dd>" + race.qualified + "</dd>";
        html += "<dt>Finished</dt>";
        html += "<dd>" + race.finished + "</dd>";
        html += "<dt>Standings</dt>";
        html += "<dd>" + race.standings + "</dd>";
        html += "</dl>";
        $("#prev-race").append(html);
    };
};
kb.initAjaxNextRace = function () {
    $.getJSON("/schedule/nextrace/", function(race){
        defRace(race);
    });
    function defRace(nextrace) {
        var race = nextrace[0].fields;
        var html = "<h3 class=\"anti-padding\">" + race.title;
        html += "<span class=\"mock_h6\">" + race.track + "</span></h3>";
        html += "<dl>";
        html += "<dt>" + race.location + "</dt>";
        html += "<dd>" + race.date + "</dd>";
        html += "<dt>" + race.tv + "</dt>";
        html += "<dd>" + /*race.time*/ "&nbsp;" + "</dd>";
        html += "<dt>Qualified</dt>";
        if(!race.qualified) {
            html += "<dd>TBD</dd>";
        }
        else {
            html += "<dd>" + race.qualified + "</dd>";
        }
        html += "<dt>Best Finish</dt>";
        if(!race.bestfinish) {
            html += "<dd>N/A</dd>";
        }
        else {
            html += "<dd>" + race.bestfinish + "</dd>";
        }
        html += "</dl>";
        $("#next-race").append(html);
    };
};

kb.initAjaxRoster = function () {
    $.getJSON("/roster/ajaxroster/", function(prsn) {
        var l = prsn.length;
        initRoster(prsn, l);
    });
    function initRoster(prsn, l) {
        var html = "";
        for (i = 0; i < l; i++) {
            // lazy json - create prefix variable
            var p = prsn[i].fields;

            html += "<div><b class=\"mock_h4\">";
            html += p.firstname + " " + p.lastname;
            html += "</b><em class=\"position\">";
            html += p.position;
            html += "</em><span class=\"hometown\">";
            html += p.hometown;
            html += "</span></div>";
        }
        $('#roster').append(html);
    }
};
kb.initAnimateItems = function () {
    function closeAnimOpenItem() {
        $(opened_item).removeClass('open');
        if ($(opened_item).attr("id") == "aboutme") {
            $(opened_item).find('.content').css({display: 'none'});
        }
        $(opened_item).stop().animate({width: origWidth, height : origHeight}, function() {
                $(opened_item).css({zIndex: '', position: '', right: ''});
        });
        opened_menu = null;
    };
    $('.toggle').click(function(e) {
        if(!$(this).hasClass('open')) {
            if (kb.opened_item) {
                $(kb.opened_item).removeClass('open');
                $(kb.opened_item).stop().animate({width: origWidth, height : origHeight}, function() {
                        $(opened_item).css({zIndex: '', position: '', right: ''});
                });
            }
            var open_item = $(this);
            opened_item = open_item;
            $(open_item).addClass('open').css({zIndex: 100});

            // get and define object dimensions
            origWidth = open_item.width();
            origHeight = open_item.height();
            outerWidth = open_item.outerWidth();
            outerHeight = open_item.outerHeight();
            var mh = $(window).height() / 1.25;
            var cw = $(window).width() / 1.75;
            var ch = $(open_item).find('.content').height() / (cw + 20) * (outerWidth + 20) + 20;

            if ( opened_item.attr("id") == "aboutme" ) {
                $(opened_item).stop().animate({width: 600, height : 320}, function() {kb.initAboutCycle();});
                $(opened_item).find(".content").css({display: "block"});
            }
            else if ( opened_item.attr("id") == "watergeeks") {
                $(opened_item).stop().animate({width: 722, height : 392});
            }
            else if ( opened_item.attr("id") == "catco") {
                $(opened_item).stop().animate({width: 660, height : 205});
            }
            else if ( opened_item.attr("id") == "krugerfarms") {
                $(opened_item).stop().animate({width: 600, height : 205});
            }
            else if ( opened_item.attr("id") == "icp") {
                $(opened_item).stop().animate({width: 930, height : 160});
            }
            // test object location in DOM
            else if ( ($(opened_item).parent().attr("id") == "col_01") || ($(opened_item).parent().attr("id") == "col_02") ) {
                $(opened_item).css({zIndex: 100}).stop().animate({width: cw, height : ch, maxHeight: mh});
            }
            else {
                    $(open_item).css({zIndex: 100, position: 'absolute', right: 0}).stop().animate({width: cw, height : ch, maxHeight: mh});
            }

// close item if user clicks anywhere else in document
            $(document).click(function (e) {
                    if (!$(e.target).parents('.toggle').hasClass('open') && opened_item) {
                            closeAnimOpenItem();
                    }
            });
        }
        else {
                closeAnimOpenItem();
        }
    });
    return false
};

kb.initExternalLinks = function () {
	var h = window.location.href; // TODO :: WHEN LIVE AVOID INTERNAL DIRECT REFERENCES
	$("a[href^='http']").attr('target','_blank');
};

kb.initTwitter = function () {
	$("#twitter .feed").tweet({
            username: "kellybires",
            join_text: "auto",
            avatar_size: 36,
            count: 1,
            auto_join_text_default: "",
            auto_join_text_ed: "",
            auto_join_text_ing: "",
            auto_join_text_reply: "",
            auto_join_text_url: "",
            loading_text: "loading tweets..."
	});
};

kb.initFpMediaCycle = function () {
    if ($("#media .container")) {
        $("#media .container").cycle({fx: 'fade'});
    }
};

kb.initMediaCycle = function () {
	$.each($(".mm_cycle", "#galleries"), function(i) {
       $(this)
        .before('<div id="pager_' + i + '" class="pager" />')
        .cycle({
            fx:     'fade',
            pager:   '#pager_' + i
        });  
    });
};

kb.initAboutCycle = function () {
    $('#aboutme .content').cycle({
        fx:      'fade',
        prev:   '.prev',
        next:   '.next',
        timeout:  0
    });
};

/*
kb.initContactForm = function () {
    $('#btn-contact').click(function () {
       $('#contact').show();
    });
};
*/

$(document).ready(function () {
    //kb.initAjaxNews();
    //kb.initAjaxPrevRace();
    //kb.initAjaxNextRace();
    kb.initAjaxRoster();
    kb.initAnimateItems();
    kb.initExternalLinks();
    kb.initTwitter();
    kb.initFpMediaCycle();
    kb.initMediaCycle();
    //kb.initContactForm();
});