var __month_short_names = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var __day_short_names = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var __gat = null; // global google analytics pagetracker

/* open a centered window */
var popWin = function(url,n,w,h) {
    var _pw_l, _pw_t, _pw_z;
    if (!n) n='_gc'; if (!w) w=1000; if (!h) h=700; // defaults
    if (w>screen.availWidth-12) w=screen.availWidth-12;
    if (h>screen.availHeight-48) h=screen.availHeight-48;
    _pw_l=(screen.availWidth-w-12)/2;
    _pw_t=(screen.availHeight-h-48)/2;
    if (n=='offsite') __gat._trackPageview('/offsite'+url); // fire pixel for outbound links

    if (navigator.userAgent.indexOf('Chrome/') > 0) { // chrome window focus bug workaround:
        if (window._pw_z) { window._pw_z.close(); window._pw_z = null; }
        window._pw_z=window.open(url,n,'status=1,scrollbars=1,location=1,toolbar=1,resizable=1,width='+w+',height='+h+',left='+_pw_l+',top='+_pw_t);
        window._pw_z.focus();
    } else { // all other browsers
        _pw_z=window.open(url,n,'status=1,scrollbars=1,location=1,toolbar=1,resizable=1,width='+w+',height='+h+',left='+_pw_l+',top='+_pw_t);
        _pw_z.focus();
    }
};

/* launch gamestream play-by-play */
var launchPBP = function(gameid){
    popWin('/game-'+gameid+'/plays','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    //popWin('/game-'+gameid+'/playbyplay','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    return false;
};

/* launch live box score */
var launchLB = function(gameid){
    popWin('/game-'+gameid+'/stats/live','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    //popWin('/game-'+gameid+'/boxscore/live','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    return false;
};

/* launch box score */
var launchBS = function(gameid){
    popWin('/game-'+gameid+'/stats','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    //popWin('/game-'+gameid+'/boxscore','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    return false;
};

/* launch gamestream play-by-play (new game page)*/
var launch_plays = function(gameid){
    popWin('/game-'+gameid+'/plays','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    return false;
};

/* launch live box score (new game page)*/
var launch_stats_live = function(gameid){
    popWin('/game-'+gameid+'/stats/live','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    return false;
};

/* launch box score (new game page)*/
var launch_stats = function(gameid){
    popWin('/game-'+gameid+'/stats','_stream'+gameid,1000,700,'status=1,scrollbars=1,location=no,menubar=no,toolbar=no');
    return false;
};

// confirm game removal via schedule editor or box score editor
function confirmDeleteGame() { return confirm("Remove this game from the team schedule? \n\nDeletion is permanent and CANNOT be reversed!"); }

// asynchronous email lookup
var do_check_email = function(t) {
    $.get("/do-check-email", { "email": t.value }, function (ret) {
       if (ret == 'exists') {
           $("#email").addClass("error");
           $("#email").addClass("error2");
           $("#email").valid()
           $("#btn_submit").attr("disabled",true);
       } else {
           $("#email").removeClass("error");
           $("#email").removeClass("error2");
           $("#email").valid()
           $("#emailmsg").empty();
           $("#btn_submit").removeAttr("disabled");
       }
    });
};

// overlay defaults
if ($.tools) {
    $.tools.overlay.conf.expose = { color:'#000',opacity:0.5 };
}

function initialize_overlays(template_names, after_complete) {  
  $(function(){
    if(typeof(template_names) == "undefined") {
      $(document).trigger('dom:loaded_overlay_templates');
    } else {
      var to_load = (typeof(template_names) == 'string') ? [template_names] : template_names;

      var loading_count = to_load.length;
      
      $(to_load).each(function(i,template_name){
        $.ajax({
          url: '/overlays/' + template_name + (template_name.indexOf('?') == -1 ? "?" : "&") + "context_path=" + location.pathname,
          success: function(response){
            $('body').append($(response));
            
            loading_count = (loading_count - 1);
            if (loading_count == 0) {
              if(typeof(after_complete) == 'function')
                after_complete();
              else
                $(document).trigger('dom:loaded_overlay_templates');
            }
          },
          dataType: 'html',
          cache: false
        });
      });
    }
  });
}

$(document).bind('dom:loaded_overlay_templates', function(){
  $("a[rel], li[rel], input[type=button][rel]").overlay();
});

// tablesorter extra widgets and defaults
if ($.tablesorter) {
    $.tablesorter.addWidget({
        id: "columnHighlight",
        format: function(table) {
            $("td", table.tBodies[0]).removeClass("sortedeven").removeClass("sortedodd");
            var ascSort = "th." + table.config.cssAsc;
            var descSort = "th." + table.config.cssDesc;
            $(table.tHead[0]).find(ascSort).add($(table.tHead[0]).find(descSort)).each(function(){
                $("tr:visible", table.tBodies[0]).find("td:nth-child(" + ($("thead th", table).index(this) + 1) + ")")
                    .filter(':even').addClass("sortedeven").end()
                    .filter(':odd').addClass("sortedodd");
            });
        }
    });
    $.tablesorter.defaults.widgets = ['zebra', 'columnHighlight']; // tablesorter default zebra-striping
}

/* indexOf fix for IE */
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt /*, from*/) {
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0) from += len;
        for (; from < len; from++) { if (from in this && this[from] === elt) return from; }
        return -1;
    };
}

/* ISO date functions for gamestream bar */
function dateFromISO(s) {
    var d = new Date();
    d.setISO8601(s);
    return d;
}

Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));
    var offset = 0;
    var date = new Date(d[1], 0, 1); // jan 1 of gamedate's year

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }
//    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
};

$(function () {
    if ($.cookie('just_subscribed')) {
        $('.banners.freeTrial.success.hide').removeClass('hide');//.fadeOut(10000,'swing',function () {
        $.cookie('just_subscribed',null);
        //});
    }
    if ($.cookie('just_prepaid')) {
        $('.banners.freeTrial.success.hide').removeClass('hide');//.fadeOut(10000,'swing',function () {
        $.cookie('just_prepaid',null);
        //});
    }
});
