//To avoid creating global variables we use a single global object to hold the
//application
//TODO: all goalwires functions, variables etc should be moved to this new object
var GW = {};

GW.matchdetails = Class.create({
    initialize: function(match){
        this.match = match;
        this.homeevents = this.createDetails(match.homecard, match.homegoal, match.homesubstitutions);
        this.awayevents = this.createDetails(match.awaycard, match.awaygoal, match.awaysubstitutions);
    },

    createDetails: function(cards, goals, substitutions){
        var details = [];
        details.add = function (items, type){
            if(! items){
                return;
            }
            for(var i = 0; i < items.length; i++){
                items[i].itemtype = type;
                this.push(items[i]);
            }
        };

        details.add(cards, "card");
        details.add(goals, "goal");
        details.add(substitutions, "substitution");

        //sort by time
        details.sort(function(a, b){
            if(a.time && b.time){
                return parseInt(a.time) - parseInt(b.time);
            }
            return 0;
        });

        return details;
    }
});




var clientMatches = Array();
var couponId = 'sms_coupon';

Event.observe(window, 'load',
	function() {	
		initSelectMatches();
		selectMyMatches();		
	}
);

function selectMyMatches(){
    	if( (typeof(myMatches) == "undefined") || (! myMatches) ){
		return;
	}
	myMatches.each(function(match){
		var id = "gw_match_" + match;
		if($(id)){
			$(id).down('input').checked = true;
		}
	});
}

function initSelectMatches(){
	$$('#livescore_tables .check').each(function(item){
		addSelectGameEvent(item);
	});
}

function addSelectGameEvent(item){
	item.observe('click', function(){
		item.toggleClassName("sub");
		var boxes = item.up('.ch').select('input');
		var subCheckboxes = item.up('.ch').down('tbody').select('input');
		if(item.hasClassName("sub")){
			boxes.each(function(item){
				item.checked = true;
			});
			subCheckboxes.each(function(item){
				item.addClassName("sub");
			});
		}
		else{
			boxes.each(function(item){
				item.checked = false;
			});
			subCheckboxes.each(function(item){
				item.removeClassName("sub");
			});
		}
	});
}

var offsetxpoint=-284 //Customize x offset of tooltip
var offsetypoint=0 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
var tipobj;

Event.observe(document, 'mousemove', positiontip);

function showTooltip(item){
    if(($('customize') && $('customize').visible()) ){
		return;
	}
	tipobj = $("tooltip");
	Event.observe(item, 'mouseout',
		function() {
			hideddrivetip();
		}
	);
    var tr = item.up('tr');
	var matchid = tr && tr.id && tr.id.substr(9);
	if(! matchid){
        return;
    }
    var details = matchdetails[matchid];
	if(details){
		ddrivetip(tr, new GW.matchdetails(details));
	}
}


function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(tr, info){
	if ((ns6||ie)){
		$('tooltip').classNames().each(function(cl){
			$('tooltip').removeClassName(cl);
		});
		$('tooltip').addClassName(info.match.sport);
                if(info.match.comment && info.match.comment.length > 0){
                    $('tooltip_comment').update(info.match.comment);
                    $('tooltip_comment').show();
                }
                else{
                    $('tooltip_comment').hide();
                }
		$("tooltip_hometeam").update($(tr).down('.gw_hometeam').down('a').innerHTML);
		$("tooltip_awayteam").update($(tr).down('.gw_awayteam').down('a').innerHTML);
		$("tooltip_result").update(tr.down('.gw_score_home').innerHTML + "-" +  tr.down('.gw_score_away').innerHTML);
		if(info.match["periodresults"]){
			$("tooltip_periodresult").update(info.match["periodresults"]);
		}
		else{
			$("tooltip_periodresult").update("-");
		}
        var addMatchEvents = function(parent, events){
            for(var i = 0; i < events.length; i++){
                var event = events[i];
                var li = li2 = false;
                if(event.itemtype === "goal"){
                    li = new Element('li', {'class': "goal"}).update(event["time"] + " " + event["player"]);
                }
                if(event.itemtype === "card"){
                    li = new Element('li', {'class': event["type"]}).update(event["time"] + " " + event["player"]);
                }
                if(event.itemtype === "substitution"){
                    li = new Element('li', {'class': "substitution_in"}).update(event["time"] + " " + event["player_in"]);
                    li2 = new Element('li', {'class': "substitution_out"}).update(event["time"] + " " + event["player_out"]);
                }

                if(li){
                    parent.appendChild(li);
                }
                if(li2){
                    parent.appendChild(li2);
                }
            }
        };

        var list = $("tooltip_stat_home");
        clearList(list);
        addMatchEvents(list, info.homeevents);

        var list = $("tooltip_stat_away");
        clearList(list);
        addMatchEvents(list, info.awayevents);

        var displayMatchDetails = info.homeevents.length || info.awayevents.length;
		if(! displayMatchDetails){
			$('tooltip_stat').hide();
		}
		else{
			$('tooltip_stat').show();			
		}
		enabletip=true;
		return false;
	}
}

function positiontip(e){
	if (enabletip){
		if(! $(tipobj).visible()){
			$(tipobj).show();
		}
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
		var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20
		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<tipobj.offsetWidth)
		{
			//move the horizontal position of the menu to the left by it's width
			tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
		}
		else if (curX<leftedge){
			tipobj.style.left="5px";
		}
		else{
			tipobj.style.left=curX+offsetxpoint+"px";
		}
		var topedge = ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint;
		if(topedge < 0){
			topedge = 120;
		}
		tipobj.style.top=topedge+"px";		
		tipobj.style.visibility="visible";
	}
}

function hideddrivetip(){
	if (ns6||ie){
		enabletip=false
		tipobj.style.visibility="hidden";
		tipobj.style.left="-1000px";		
	}
}

function initCustomize(){
	if(! $('customize')){
		return;
	}
	Sortable.create($('sport'));
	$('cancelCustomize').observe('click', function(event){
		$('customize').hide();
	});
	
	$('doCustomize').observe('click', function(event){
		var szSports = "";
		$('sport').select("li").each(function(item){
			if(item.down('input').checked == true){
				var id = item.id.substring(16);
				szSports += "sport[]=" + id + "&";
			}
		});
		szSports = szSports.replace(/(\&)*$/, '');
		$('sports').value = szSports;
		$('customizeform').submit();
	});	
}

function initSoundCheckbox(){
	if(! $('sh_playsound')){
		return;
	}
	Event.observe($('sh_playsound'), 'click',
		function() {
			playsound = $('sh_playsound').checked;
			var val = $('sh_playsound').checked ? "1" : "0";
                        if(val == "1" && GW.plong){
                            GW.plong.play();
                        }
			setCookie("playsound", val, 360);
		}
	);
}

function initTabs(){
	$$('.tabs li').each(function(item){
		item.observe('mouseover', function(event){
			item.addClassName('hover');
		});
		item.observe('mouseout', function(event){
			item.removeClassName('hover');
		});
	});	
}

function toggleOdds(item){
	var table = item.up('table');
	var tbody = table.down('tbody');
	var isExpanded = isTableExpanded(table);
	$(tbody).select('tr').each(function(tr){		
		["div.gw_odds", "div.gw_status", "div.gw_info", "div.sms", "div.gw_selmatch"].each(function(div){
			if(tr.down(div)){
				tr.down(div).toggle();
			}
		});		
	});	
	
	if(! isExpanded){
		expandTable(table);
	}
}

function toggleSMS(item){
	var table = item.up('table');
	var tbody = table.down('tbody');
	var isExpanded = isTableExpanded(table);
	$(tbody).select('tr').each(function(tr){		
		["div.gw_odds", "div.gw_status", "div.gw_info", "div.sms", "div.gw_availability", "div.gw_selmatch"].each(function(div){
			if(tr.down(div)){
				tr.down(div).toggle();
			}
		});		
	});	
	
	if(! isExpanded){
		expandTable(table);
	}
}

function showHeadToHead(item){
	Popup.open({url:item.href, width: 700, height: 500});
	return false;
}

function initChooseMatches(){
	if(! $$('.my_matches')){
		return;
	}
	$$('.my_matches').each(function(item){
		item.observe('click', function(event){
			if($('selectMyMatches')){
				$('selectMyMatches').submit();
				Event.stop(event);
			}
		});
	});
}

function initLeaguesHighlight(){
	if(! $$('.matches thead tr')){
		return;
	}

	$$('.matches thead tr').each(function(item){
		item.observe('mouseover', function(event){
			item.addClassName("highlight");		
		});
		item.observe('mouseout', function(event){
			item.removeClassName("highlight");
		});
	});
}

function initMatchHighlight(){
	if(! $$('.matches tbody .hh')){
		return;
	}
	$$('.matches tbody .hh').each(function(item){
		item.observe('mouseover', function(event){
			item.up('tr').addClassName("select");		
		});
		item.observe('mouseout', function(event){
			item.up('tr').removeClassName("select");
		});
	});
}

function initMatchesFolding(){
	$$('img.fold').each(function(item){
		addFoldEvent(item);
	});
}

/** Folds and unfolds matchtables */ 
function addFoldEvent(item){
	item.observe('click', function(){
		foldTable(item);
	});
}

function isTableExpanded(table){
	var fold = table.down('.fold');
	return ! fold.hasClassName("sub");
}

function expandTable(table){
	if(! isTableExpanded(table)){
		var fold = table.down('.fold');
		foldTable(fold);
	}
}

function foldTable(item){
	item.toggleClassName("sub");
	if(item.hasClassName("sub")){				
		item.up('.ch').select("tbody").invoke('hide');
		item.up('.ch').select(".fold").invoke('addClassName', 'sub');
	}
	else{
		item.up('.ch').select("tbody").invoke('show');
		item.up('.ch').select(".fold").invoke('removeClassName', 'sub');
	}
}

function SMS_addMatch(matchId) {
    if($('sms_phone_' + matchId).src.indexOf('/img/icon/phone_selected_red.gif') != -1) {
        return SMS_removeMatch(matchId);
    }
    
	new Ajax.Request('/' + lang + '/sms/orderform', {
        parameters : {
            'type' : 'match',
            'match_id' : matchId
        },
        method : 'post',
        onLoading : function () {
            $('sms_coupon_container').insert({top : '<div id="sms_loading" style="padding: 3px">Loading..</div>'});
        },
        onSuccess : function (req) {
            $('sms_phone_' + matchId).src = '/img/icon/phone_selected_red.gif';
            $('sms_coupon_container').update(req.responseText);
        }
    });
}

function SMS_addTeam(teamId, element) {
	new Ajax.Request('/' + lang + '/sms/orderform', {
        parameters : {
            'type' : 'team',
            'team_id' : teamId
        },
        method : 'post',
        onLoading : function () {
            $('sms_coupon_container').insert({top : '<div id="sms_loading" style="padding: 3px">Loading..</div>'});
        },
        onSuccess : function (req) {
            $('sms_coupon_container').update(req.responseText);
        }
    });
}

function SMS_removeMatch(matchId)
{
	new Ajax.Request('/' + lang + '/sms/orderform', {
        parameters : {
            'type' : 'match',
            'delete' : matchId
        },
        method : 'post',
        onLoading : function () {
            $('sms_coupon_container').insert({top : '<div id="sms_loading" style="padding: 3px">Loading..</div>'});
        },
        onSuccess : function (req) {
            $('sms_phone_' + matchId).src = '/img/icon/phone.gif';
            $('sms_coupon_container').update(req.responseText);
        }
    }
    ); //osv
}

function SMS_submitOrder()
{
	var smsOrderUrl = '/' + lang + '/sms/servicelevel';
    location.href = smsOrderUrl;
}

function SMS_createOrder()
{
    $('sms_order_form').request({
        onLoading : function ()
        {
            $('sms_order').insert('<div id="sms_order_result">Creating order..</div>');
        },
        onSuccess : function(req) { 
            $('sms_order_result').update(req.responseText);
        }
    });
    
    return false;
}

function SMS_resetOrder()
{
	new Ajax.Request('/' + lang + '/sms/orderform', {
        parameters : {
            'type' : 'match', // has no real effect, resets everything
            'reset' : true
        },
        method : 'post',
        onSuccess : function (req) {
            $$('img.sms_phone_icon').each(function(e)
            {
                e.src = '/img/icon/phone.gif';
            });
            $('sms_coupon_container').update(req.responseText);
        }
    }); 
}

function SMS_fetchList(e, target) {
    new Ajax.Request('/' + lang + '/sms/list', {
        parameters : {
            'sport_id' : $('first_list').options[$('first_list').selectedIndex].value,
            'list' : e.id,
            'id' : e.options[e.selectedIndex].value
        },
        method : 'post',
        onLoading : function () {
            
            if($('sms_team_selected')) $('sms_team_selected').remove();
            
            if(e.id == 'first_list') {
                $('sms_team_lists').update('');
            }
            else
            {
                e.up().nextSiblings().invoke('remove');
            }
        },
        onSuccess : function (req) {
            $('sms_team_lists').insert(req.responseText);
        }
    });
}


function getCookie(name){
	if (document.cookie.length>0){
  		c_start=document.cookie.indexOf(name + "=");
	  	if (c_start!=-1){ 
	    	c_start=c_start + name.length+1; 
	    	c_end=document.cookie.indexOf(";",c_start);
	    	if (c_end==-1) c_end=document.cookie.length;
	    	return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

function setCookie(name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=name+ "=" +escape(value)+
	";path=/" +
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

/** Remove all children in a list*/
function clearList(list){
	list = $(list);
	while (list.firstChild) {
		list.removeChild(list.firstChild);
	}
}

function unescapeHTML(html) {
	var htmlNode = new Element('div');
	htmlNode.innerHTML = html;
	return htmlNode.innerHTML;
}

var Popup = {
	open: function(options){
        this.options = {
            url: '#',
            width: 600,
            height: 400,
            scrollbars: 1
        }
        Object.extend(this.options, options || {});
        window.open(this.options.url, '', 'width=' + this.options.width + ',height=' + this.options.height + ', scrollbars=yes' + ', resizable=1');
    }
}



function base64_decode( data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
 
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof window['btoa'] == 'function') {
    //    return btoa(data);
    //}
 
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, dec = "", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data += '';
 
    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
 
        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
 
        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
    dec = utf8_decode(dec);
 
    return dec;
}

function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    var tmp_arr = [], i = ac = c1 = c2 = c3 = 0;
 
    str_data += '';
 
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}






function toggleCalendar(xOffset, yOffset) {
	if(! xOffset){
		xOffset = 50;
	}
	if(! yOffset){
		yOffset = 80;
	}
	var pos = $A($('toggleCalendar').cumulativeOffset());
	$('calendar').setStyle({
			left: (pos[0] + xOffset) + "px",
			top: (pos[1] - yOffset) + "px"
	});
	$('calendar').toggle();
	initCalendar();
}

function initCalendar(){
$$('#calendarmenu a').each(function(item){
	Event.observe(item, 'click',
	function(e) {
		Event.stop(e);
		var str = item.href.replace(/^\/+|\/+$/g, '') ;
		var date = str.substring(str.lastIndexOf("/") + 1, str.length)
		updateCalendar(date);
	});
});
}

function updateCalendar(date){		
new Ajax.Request("/" + lang + '/service/calendar',
	{
   	method:'post',
   	parameters: {date: date},
   	onSuccess: function(transport){
		$('calendar').innerHTML = transport.responseText;
		initCalendar();
   	}
});
}

function clearList(list){
list = $(list);
while (list.firstChild) {
	list.removeChild(list.firstChild);
}
}

Event.observe(document, 'click',
function(e) {
	if(! $('calendar')){
		return;
	}
	var target = (e && e.target) || (event && event.srcElement);
	if(target == $('toggleCalendar')){
		return;
	}
	checkParent(target) ? $('calendar').style.display='none' : null;
}
);

function checkParent(t){
while(t.parentNode){
	if(t==$('calendar')){
		return false
	}
	t=t.parentNode
}
return true
}
