function startFetchLivescore(){
    	if(parseInt(livescoreUpdateInterval) < 15){
		livescoreUpdateInterval = 15;
	}
	new PeriodicalExecuter(function(pe){	
		new Ajax.Request('/livescoreupdate.php',
		{
	   	method:'get',
	   	parameters: {mdate: mdate, lang: lang},
	   	onSuccess: function(transport){	
	   		var matches = eval('(' + transport.responseText + ')');   		
         	updateLivescore(matches);
	   	}
	});} , livescoreUpdateInterval);
}

function updateLivescore(response){
    if(response["mod_date"]){
        mdate = response["mod_date"];
    }

    var statusUpdated = false;
    var scoreUpdated = false;
    var matches = response["matches"];
     for(var i = 0;i < matches.length; i++){
		var data = matches[i];
		if(data["sid"] == 0){
			continue;
		}
		var match = null;
		switch(data['sport']){
			case "tennis":
				match = new gwMatchTennis(data);
				break;
			case "soccer":
				match = new gwMatchSoccer(data);
				break;
			default:
				match = new gwMatch(data);
				break;
		}                
        if(matchShouldBeAdded(match)){
            addNewMatch(match);
		}
		updateMatch(match);
		statusUpdated |= match.statusUpdated;
		scoreUpdated |= match.scoreUpdated;
	}    
	if(soundEnabled && playsound){
		if(scoreUpdated && (soundsettings.indexOf("goal") != -1)) {
            GW.plong.play();
            
        }
        else if(statusUpdated && (soundsettings.indexOf("start_end") != -1)){
            GW.plong.play();
        }
	}
}

function matchShouldBeAdded(match){
	if(match.exists){
		return false;
	}
	if(match.status_id > 50){
		return false;
	}
	return true;
}

function updateMatch(match){
	if(! match.exists){
		return false;
	}
	match.update();
	if(match.rowUpdated){
		return true;
	}
	else{
		return false;
	}
}

function addNewMatch(match){
	if(! ongoing){
		return;
	}
	var league = $(match.leagueId);
	if(! league){
		return;
	}
	if(match.sport == "tennis"){		
		league.down("tbody").appendChild(match.row);
		league.down("tbody").appendChild(match.row2);
	}
	else{
		league.down("tbody").appendChild(match.row);
	}
	league.show();
	league.up(".matches").show();
	league.down("tbody").show();
	if($('nomatches')){
		$('nomatches').hide();
	}
	showCategory(match);
}

//display the category in the left menu
function showCategory(match){	
	if(! $('allgames')){
		return;
	}
	var category = $(match.categoryId);
	if(! $(category)){
		return;
	}
	$(category).show();
	$(category).up("li").show();
	$('allgames').show();
}

function initUpdateInterval(){
	var interval = getCookie('updateinterval');
	if(interval != null){
		livescoreUpdateInterval = parseInt(interval);
	}
}

var gwMatch = Class.create({
	initialize: function(data) {
		this.time = data["date"].substr(11, 5);
		this.id = data['id'];
		this.status_id = data["sid"];
		this.status = statusCodes[this.status_id];
		this.sport = data["sport"];
                if(this.status_id == 0 || this.status_id == 60 || this.status_id == 61){
                    this.rowclass = "not_started";
                }
                else if(this.status_id >= 70 && this.status_id <= 120){
                    this.rowclass = "finished";
                }
                else{
                    this.rowclass = "";
                }
		this.rowId = "gw_match_" + this.id
		this.leagueId = "gw_league_" + data["lid"];
		this.categoryId = "ci_" + data["cid"];
		this.hometeam = data["home"];
		this.awayteam = data["away"];
		this.scorehome = data["score_home"];
		this.scoreaway = data["score_away"];
		if(data["details"]){
			this.matchdetails = data["details"];
			this.addMatchdetails();
		}		
		this.showInfobox = data["showInfoBox"];
		//FIXME: Add host to hh url
		this.hhUrl = "/" + lang + "/head_to_head/" + this.id;
		this.rowUpdated = false;
		this.scoreUpdated = false;
		this.statusUpdated = false;
		
		if($(this.rowId)){
			this.setRow();
			this.exists = true;
		}
		else{
			this.createRow();
			this.exists = false;
		}		
	  },
	  
	  setRow: function(){
		  this.row = $(this.rowId);  
	  },
	  
	  createRow: function(){
		  this.row = new Element('tr', {id: this.rowId});
		  this.addColumnsToRow();
	  },
	  
	  addColumnsToRow: function(){
		  this.row.appendChild(this.getDateCol());
		  this.row.appendChild(this.getHomeTeamCol());
		  this.row.appendChild(this.getAwayTeamCol());
		  this.row.appendChild(this.getScoreCol());
		  this.row.appendChild(this.getStatusCol());
		  this.row.appendChild(this.getExtraCol());
	  },
	  
	  getExtraCol: function(){
		  var rowExtra = new Element('td', {'class': 'gw_extra'});
		  if(gwExtraButtons.indexOf("sms") != -1){
			  rowExtra.appendChild(this.getSMSIcon());
		  }
		  rowExtra.appendChild(this.getInfobox());
		  if(gwExtraButtons.indexOf("checkbox") != -1){
			  rowExtra.appendChild(this.getSelectMatchCheckbox());
		  }
		  return rowExtra;
	  },
	  
	  getSelectMatchCheckbox: function(){
		  var div = new Element('div', {'class': 'gw_selmatch'});
		  div.appendChild(new Element('input', {'type': 'checkbox', 'name': 'match[]', 'value': this.id}));
		  return div;
	  },
	  
	  getInfobox: function(){
		  var div = new Element("div", {"class": "gw_info"});
		  var span = new Element('span', {'class': "infoph"});
		  //add host to img
		  var img = new Element("img", {"width": 15, "src": "/img/dot.gif"});
		  span.appendChild(img);
		  div.appendChild(span);
		  return div;
	  },
	  
	  getStatusCol: function(){
		  return new Element('td', {'class': 'gw_status'}).update(this.status);
	  },
	  
	  getScoreCol: function(){
		var td = new Element('td', {'class': 'gw_scores'});
		td.appendChild(new Element('span', {'class': "gw_score_home"}).update(this.scorehome));
		td.appendChild(new Element('span').update("-"));
		td.appendChild(new Element('span', {'class': "gw_score_away"}).update(this.scoreaway));
		return td;
	  },
	  
	  getDateCol: function(){
		  return new Element('td', {'class': 'gw_date'}).update(this.time);  
	  },
	  
	  getHomeTeamCol: function(){
		  var td = new Element('td', {'class': 'gw_hometeam'});
		  var a = new Element('a', {'class': 'hh', 'title': 'Head to Head', 'href': this.hhUrl}).update(this.hometeam);
		  this.addHeadToHeadEvent(a);
		  td.appendChild(a);
		  return td;
	  },
	  
	  getAwayTeamCol: function(){
		  var td = new Element('td', {'class': 'gw_awayteam'});
		  var a = new Element('a', {'class': 'hh', 'title': 'Head to Head', 'href': this.hhUrl}).update(this.awayteam);
		  this.addHeadToHeadEvent(a);
		  td.appendChild(a);
		  return td;
	  },
	  
	  update: function(){
		  this.updateScoreHome();
		  this.updateScoreAway();
		  this.updateStatus();
		  this.addMatchdetails();
	  },
	  
	  updateScoreHome: function(){
		  var el = this.row.down('.gw_score_home');
		  var newScore = String(this.scorehome);
		  if(this.updateValue(el, newScore)){
			  this.scoreUpdated = true;
		  }
	  },
	  
	  updateScoreAway: function(){
		  var el = this.row.down('.gw_score_away');
		  var newScore = String(this.scoreaway);
		  if(this.updateValue(el, newScore)){
			  this.scoreUpdated = true;
		  }
	  },
	  
	  updateStatus: function(){
		  var el = this.row.down('.gw_status');
		  if(this.updateValue(el, this.status)){
			  this.statusUpdated = true;
		  }
		  if(this.status_id > 50){
			  this.setMatchFinished();
		  }
          else{
              this.setMatchStarted();
          }
	  },

      setMatchStarted: function(){
        this.row.removeClassName("not_started");
      },
	  
	  setMatchFinished: function(){
		  this.row.addClassName("finished");  
	  },
	  
	  updateValue: function(el, newValue){
		  if(typeof newValue == "undefined"){
			  return false;
		  }
		  if(! newValue){
			  return false;
		  }
		  if(newValue == el.innerHTML){
			  return false;
		  }
		  el.update(newValue);
		  this.highLightCell(el);
		  this.rowUpdated = true;
		  return true;
	  },
	  
	  highLightCell: function(cell){
		  cell.addClassName("highlight");
		  this.highLightRow();
		  this.addHighlightTimeoutEvent(cell);
	  },
	  
	  highLightRow: function(){
		  if(! this.row.hasClassName("highlight")){
			  this.row.addClassName("highlight");
		  }
	  },
	  
	  addHighlightTimeoutEvent: function(element){
		  var row = this.row;
		  setTimeout(function(){
				$(element).removeClassName('highlight');
				if(! row.down(".highlight") && row.hasClassName("highlight")){
					row.removeClassName("highlight");  
				}
		  }, 35000); 	//35 seconds
	  },
	  
	  addHeadToHeadEvent: function(a){
		  Event.observe(a, 'click',
				function(e) {
					Event.stop(e);
					showHeadToHead(a);				
				}
		  );	
	  },

	  getSMSIcon: function(){
		  //FIXME: is ice-hockey a valid name?
		  var validSports = ["tennis", "soccer", "ice-hockey"];
		  if(validSports.indexOf(this.sport) == -1){
			  return;
		  }
		  var div = new Element('div', {'class': 'sms'});
		  var a = new Element('a', {'href': 'javascript:;', 'title': 'Add  match to SMS order'});
		  var id = this.id;
		  Event.observe(a, 'click',
			function(e) {			  
			  SMS_addMatch(id);
		  	}
		  );
		  var img = new Element('img', {'src': '/img/icon/phone.gif', 'alt': 'Add match to SMS order', 'id': 'sms_phone_' + this.id, 'class': 'sms_phone_icon'});
		  a.appendChild(img);
		  div.appendChild(a);
		  return div;
	  },
	  	  
	  addMatchdetails: function(){			
		  if(! this.matchdetails){
			  return;
		  }	
		  matchdetails[this.id] = this.matchdetails;
		  this.addInfoBox();	
	  },

	  addInfoBox: function(){
		if(! this.showInfobox){
				return;
		}
		if(! this.row.down('.infoph')){
			return;
		}
		//add the infoicon if its not there
		if(! this.row.down('img.info')){			
			//FIXME: add host to url
			var img = new Element('img', {'src': '/img/icon/info.gif', 'class': 'info', 'title': ''});
			var infoph = this.row.down('.infoph');
			//remove the dot if its there
			var dot = infoph.down('img');
			if(dot){
				dot.parentNode.removeChild(dot);
			}
			infoph.appendChild(img);
			Event.observe(img, 'mouseover',
				function(e) {
					showTooltip(img);
				}
			);
		}
	}
});

var gwMatchTennis = Class.create(gwMatch, {
	
	initialize: function($super, data) {
		this.gemHome = [false, data["gem_h1"], data["gem_h2"], data["gem_h3"], data["gem_h4"], data["gem_h5"]];		
		this.gemAway = [false, data["gem_b1"], data["gem_b2"], data["gem_b3"], data["gem_b4"], data["gem_b5"]];
                $super(data);
		this.showInfobox = false;
	},
	
	setRow: function(){
		this.row = $(this.rowId);
		this.row2 = this.row.next("tr.row2");
	},
	
	createRow: function(){
		  this.row = new Element('tr', {id: this.rowId});
		  this.row2 = new Element('tr', {'class': "row2"});
		  this.addColumnsToRow();
		  this.addColumnsToRow2();		  
	},
	
	addColumnsToRow: function(){
		this.row.appendChild(this.getDateCol());
		this.row.appendChild(this.getHomeTeamCol());
		this.row.appendChild(this.getGem("gem_h1"));
		this.row.appendChild(this.getGem("gem_h2"));
		this.row.appendChild(this.getGem("gem_h3"));
		this.row.appendChild(this.getGem("gem_h4"));
		this.row.appendChild(this.getGem("gem_h5"));
		this.row.appendChild(this.getStatusCol());
		this.row.appendChild(this.getExtraCol());		  
	},
	
	addColumnsToRow2: function(){
		this.row2.appendChild(new Element("td"));
		this.row2.appendChild(this.getAwayTeamCol());
		this.row2.appendChild(this.getGem("gem_b1"));
		this.row2.appendChild(this.getGem("gem_b2"));
		this.row2.appendChild(this.getGem("gem_b3"));
		this.row2.appendChild(this.getGem("gem_b4"));
		this.row2.appendChild(this.getGem("gem_b5"));
		this.row2.appendChild(new Element("td", {"colspan": 2}));		
	},
	
	getGem: function(name){
		var td = new Element('td', {'class': 'gw_gem'});
		var span = new Element('span', {'class': name});
		td.appendChild(span);	
		return td;
	},
	
	updateScoreHome: function(){		
		for(var i = 1; i <= 5; i++){
			if(this.updateValue(this.row.down('.gem_h' + i), this.gemHome[i])){
				this.scoreUpdated = true;
			}
		}
	},
	
	updateScoreAway: function(){		
		for(var i = 1; i <= 5; i++){			
			if(this.updateValue(this.row2.down('.gem_b' + i), this.gemAway[i])){
				this.scoreUpdated = true;
			}
		}
	},
	
	highLightRow: function(row){
		if(! this.row.hasClassName("highlight")){
			this.row.addClassName("highlight");
		}
		if(! this.row2.hasClassName("highlight")){
			this.row2.addClassName("highlight");
		}
	},
	
	addMatchdetails: function(){
		return false;
	},
	
	addInfoBox: function(){
		return false;
	},
	
	setMatchFinished: function(){
		  this.row.addClassName("finished");  
		  this.row2.addClassName("finished");
	},

    setMatchStarted: function(){
        this.row.removeClassName("not_started");
        this.row2.removeClassName("not_started");
    },
	
	addHighlightTimeoutEvent: function(element){
		  var row = this.row;
		  var row2 = this.row2;
		  setTimeout(function(){
				$(element).removeClassName('highlight');
				if( (! row.down(".highlight")) && (! row2.down(".highlight")) && (row.hasClassName("highlight")) ){
					row.removeClassName("highlight");
					row2.removeClassName("highlight");
				}
		  }, 35000); 	//35 seconds
	  }
});

var gwMatchSoccer = Class.create(gwMatch, {
	
	initialize: function($super, data) {
		this.cardhomestr = data['cardhomestr'];
		this.cardawaystr = data['cardawaystr'];
		$super(data);
	},
	
	update: function($super){
		$super();
		this.updateCardsHome();
		this.updateCardsAway();
	},
	
	addColumnsToRow: function(){
		this.row.appendChild(this.getDateCol());
		this.row.appendChild(this.getHomeTeamCol());
		this.row.appendChild(this.getCardHomeCol());
		this.row.appendChild(this.getAwayTeamCol());
		this.row.appendChild(this.getCardAwayCol());
		this.row.appendChild(this.getScoreCol());
		this.row.appendChild(this.getStatusCol());
		this.row.appendChild(this.getExtraCol());
	 },
	
	 getCardHomeCol: function(){
		 return new Element('td', {"class": "gw_cardhome"});
	 },
	 
	 getCardAwayCol: function(){
		 return new Element('td', {"class": "gw_cardaway"});
	 },
	 
	 updateCardsHome: function(){
		 this.updateCardInfo(this.cardhomestr, ".gw_cardhome");
	 },
	 
	 updateCardsAway: function(){
		 this.updateCardInfo(this.cardawaystr, ".gw_cardaway");
	 },
	 
	 updateCardInfo: function(cardinfo, el){
		if(! cardinfo){
			return;
		}
		var ph = this.row.down(el);
		if(! ph.down('img')){
			var img = new Element('img', {'src': '/img/icon/redcard2.gif', 'class': 'card', 'alt': ''});
			ph.appendChild(img);
		}
		ph.down('img').title = cardinfo;
	 }
});
