// http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html
$.extend({
    getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },
    getUrlVar: function(name){
        return $.getUrlVars()[name];
    }
});

var ebSrt = {
    log:function(msg){
        if (window.console && window.console.log) { console.log(msg); }
    },

    // STOPWATCH OBJECT
    StopWatch : (function() {
        var StopWatch = function(rcb) {
            this.renderCallBack = rcb;
            this.initialtime = new Date().getTime();
            this.delta = 0;
            this.timeout = null;
        };
        StopWatch.prototype.update = function () {
            var newTime = new Date().getTime();
            this.delta = Math.floor((newTime - this.initialtime)/1000);
        };
        StopWatch.prototype.start = function () {
            this.tick();
        };
        StopWatch.prototype.reset = function () {
            this.initialtime = new Date().getTime();
            this.renderCallBack(this.delta);
        };
        StopWatch.prototype.stop = function () {
            clearTimeout(this.timeout);
        };
        StopWatch.prototype.tick = function () {
            this.update();
            this.renderCallBack(this.delta);
            var self = this;
            this.timeout = setTimeout(function(){self.tick()},1000);
        };
        return StopWatch;
    })(),

    getUrlParameters:function() {
        var map = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            map[key] = value.split("#")[0];
        });
        return map;
    },
/*  This attaches appropriate click handlers to football player objects,
    which will display a "lightbox" with player stats  */
    spillerInfoBox:function(){
        var playerinfo = {},
            model = new PlayerBoxModel({}),
            view  = new PlayerBox({ el: $('#playerinfo'), model:model });
        $('.fnShowInfo').live('click',function(e){
            var field = (!document.getElementById('field')) ? false : true,
                ele = $(e.currentTarget),
                p = ele.attr('data-player'),
                t = ele.attr('data-team'),
                s = ele.attr('data-season');
            lookup(p, t, s);
            e.preventDefault();
        });
        function lookup(p, t, s) { // p : srt player id, t : srt team id, s : srt season id
            var data;
            if (typeof playerinfo[p] === 'undefined') {
                data = {
                    'spec':'playerinfo',
                    'player':p,
                    'team':t,
                    'season':s
                }
                $.getJSON('/srtjson/', data, prePackagedSuccess(p,t,s));
            } else {
                model.set(playerinfo[p]);
                showColorbox();
            }
        };
        function prePackagedSuccess (p, t, s) {
            return function (json) {
                success(json, p, t, s);
            };
        };
        function success(json, p, t, s) {
            var i;
            for (i=0; i<json.players.length; i+=1) {
                playerinfo[json.players[i].id] = json.players[i];
            }
            lookup(p, t, s);
        };
        function showColorbox() {
            $('#colorbox').addClass('srt-player');
            var playerinfoTing = '<div class="playerinfo">'+ $('#playerinfo').html()+'</div>';
            $.colorbox({
                html:playerinfoTing,
                width:"590px",
                speed:250,
                opacity:0.5
                // onCleanup:function(){
                //     $('#infowrapper').append($('#playerinfo'));
                // }
            });
        }
        if(!document.getElementById('matchTimeline')) ebSrt.hoverInfo();
    },
    hoverInfo:function(){
        function openDescription(e){
            var ele = $(e.currentTarget),
                isEvent = ele.hasClass('eventicon'),
                html = (isEvent) ? ele.find('.eventdescription').html() : ele.find('.oddsdescription').html(),
                yPos = (isEvent) ? e.pageY + 25 : ele.offset().top + ele.height() + 20,
                xPos = (isEvent) ? e.pageX - 10 : ele.offset().left + (ele.width()*.2),
                newEle = (document.getElementById('eventdescription')) ? $('#eventdescription').css({'display':'block','left':xPos,'top':yPos}).html('<span>'+html+'</span>') : '<div class="eventdescription" id="eventdescription" style="top:'+ yPos+ 'px;left:'+xPos+'px;"><span>'+html+'<span></div>';
            $('body').append(newEle);
        }
        function closeDescription(e){
            $('#eventdescription').css({'display':'none'}).html('');
        }
        if(!ebSrt.touchevents){
            $('.eventicon,.hoverInfo').live('mouseover',function(e){
                openDescription(e);
            });
            $('.eventicon,.hoverInfo').live('mouseout',function(e){
                closeDescription(e);
            });
        } else {
            $('.eventicon,.hoverInfo').live('click',function(e){
                var ele = $(e.currentTarget),
                    eleType = ele.attr('class'),
                    desc = (document.getElementById('eventdescription')) ? $('#eventdescription') : false;
                if(!desc || desc.is(':hidden') || !ele.hasClass('openHover')){
                    openDescription(e);
                    $('.openHover').removeClass('openHover');
                    ele.addClass('openHover');
                } else {
                    closeDescription(e);
                    ele.removeClass('openHover');
                }
                return false; /* added to ensure that fnOpenMatch isn't run */
            });
        }
    },
    bettingResultsHoverInfo:function(){
        if(!ebSrt.touchevents){
            $('.bettingResultsHoverInfo').live('mouseover',function(evt){
                var ele = $(this).find('.oddsdescription'),
                    content = ele.html();
                    offset = $(this).offset();
                    yPos = offset.top - 35,
                    xPos = offset.left - 12,
                    newEle = '<div class="ebsport" id="bettingResultsEventdescription" style="top:'+ yPos+ 'px;left:'+xPos+'px;"><span>'+content+'</span></div>';

                $('body').append(newEle);
            });
            $('.bettingResultsHoverInfo').live('mouseout',function(e){
                $('body').find('.ebsport#bettingResultsEventdescription').remove();
            });
        }
    },
    bettingResultsLinks:function(){
        $('.ebsport#bettingExpertPreviousResultsBox li').each(function(evt){
            var link = $(this).attr('data-link');
            if (link !== '') {
                $(this).css('cursor','pointer');
                $(this).click(function(){
                    window.location = link;
                });
            }
        });
    },
    oddsBettingSuggestionHeader:function(){
        var imageBox,
            offset,
            suggestionBox = $('#oddsBettingSuggestionHeader');
        if (suggestionBox.hasClass("onimage")) {
            imageBox = $('.art_img-topcontainer');
            offset = imageBox.offset();
            suggestionBox.css("position", "absolute");
            suggestionBox.css("top", offset.top + "px");
            suggestionBox.css("left", offset.left + "px");
            suggestionBox.css("width", imageBox.css('width'));
        }
    },
    benchForward:function(){
        function mov(e){
            var ele = $(e.currentTarget),
                dir = (ele.hasClass('btn-forward')) ? 'forward' : 'backward',
                which = (ele.hasClass('homeBackward') || ele.hasClass('homeForward')) ? $('#homebench') : $('#awaybench'),
                otherBtn = (dir == 'forward') ? ele.siblings('.btn-backward') : ele.siblings('.btn-forward'),
                curPos = which.position().left;

            if(dir == 'forward'){
                var pos = curPos - 100,
                    maxPos = -(which.width()-375);
                if(pos >= maxPos){
                    which.css({'left':pos});
                    otherBtn.css({'visibility':''});
                    if(pos == maxPos){
                        ele.css({'visibility':'hidden'});
                    } else {
                        otherBtn.css({'visibility':''});
                    }
                } else {
                    ele.css({'visibility':'hidden'});
                }
            } else {
                var pos = curPos + 100;
                if(pos <= -10){
                    which.css({'left':pos});
                    if(pos == -10){
                        ele.css({'visibility':'hidden'});
                    } else {
                        otherBtn.css({'visibility':''});
                    }
                } else {
                    ele.css({'visibility':'hidden'});
                }
            }
        }
        $('.benchplayers').each(function(){
            var ele = $(this);
                eleWidth = ele.find('.player').length * 100;
            ele.css({'width':eleWidth});
        });
        $('.fnBench').live('click',function(e){
            mov(e);
        });
        $('.btn-backward').css({'visibility':'hidden'});
        if(ebSrt.ostypeVersion == 'ipad5') {
            $('.btn-forward').css({'visibility':'hidden'});
        }
    },
    fnOpenMatch:function(){
        $('.fnOpenMatch').live('click',function(e){
            e.stopPropagation();
            location.href = $(e.currentTarget).attr('rel');
        });
    },
    lastUpdatedTimeStampToDate:function(s){
        var arr = s.split(/[-T:]+/),
            dat = new Date();
        dat.setFullYear(arr[0]);
        dat.setMonth(parseInt(arr[1])-1);
        dat.setDate(arr[2]);
        dat.setHours(arr[3]);
        dat.setMinutes(arr[4]);
        dat.setSeconds(arr[5]);
        return dat;
    },
    lastUpdatedDateFormat:function(d){
        s = "";
        x = d.getDay();
        if (x===0) s += "s&oslash;ndag";
        if (x===1) s += "mandag";
        if (x===2) s += "tirsdag";
        if (x===3) s += "onsdag";
        if (x===4) s += "torsdag";
        if (x===5) s += "fredag";
        if (x===6) s += "l&oslash;rdag";
        s += " d. " + d.getDate() + "/" + (d.getMonth()+1);
        s += " " + d.getHours();
		s += ":" + ((d.getMinutes() < 10) ? "0" : "") + d.getMinutes();
		s += ":" + ((d.getSeconds() < 10) ? "0" : "") + d.getSeconds();
        return s;
    },
    init:function(){
        ebSrt.touchevents = ('ontouchstart' in window);
        ebSrt.hoverInfo();
        if(document.getElementById('bettingExpertPreviousResultsBox')) {
            ebSrt.bettingResultsHoverInfo();
            ebSrt.bettingResultsLinks();
        }
        if(document.getElementById('playerinfo')) ebSrt.spillerInfoBox();
        if(document.getElementById('homebench')) ebSrt.benchForward();
        if(document.getElementById('SrtMatchOverview')) ebSrt.fnOpenMatch();
        if(document.getElementById('oddsBettingSuggestionHeader')) ebSrt.oddsBettingSuggestionHeader();
    },
/*  The os is added as a class to the html element to be used for os
    specific styling. Used for the -webkit-overflow-scroll property,
    which is only supported on ipad5 atm  */
    read:function(){
        ebSrt.ostype = navigator.platform.toLowerCase();
        ebSrt.ostypeVersion = '';
        if (ebSrt.ostype != undefined) {
            $('html').addClass(ebSrt.ostype);
            if (ebSrt.ostype == 'ipad') {
                var thing = navigator.appVersion.split('CPU OS ')[1], athing = thing.split(' like'), version = parseFloat(athing.join());
                ebSrt.ostypeVersion = (version >= 5) ? 'ipad5' : 'ipad';
                $('html').addClass(ebSrt.ostypeVersion);
            }
        }
    }
}
$(document).ready(function(){
    ebSrt.init();
});
ebSrt.read();
