//layers being used in this matchcentre
var layers = Array("commentary","lineup","teamstats","playerstats","standings","formation","shots","touches","rankings","report","facts","form_guide","myhistory","scoreline","fixtures");

var updatesaj = null;

// holds array of last updated components
var _updatedwhen= Array();
var contentaj;
// holds valid ajax requests
var _toupdate = Array();
var majax= Array();
var updateChecker,imgChecker;
var images_ready = false;
var tAjax;
var update_once = true;
var tries = Array();
var playerstats_shown="";
var updateTO;

//function gets name & return object reference
function getObj(name)
{
  if (document.getElementById)
  {
  	return document.getElementById(name);
 }
  else if (document.all)
  {
	return document.all[name];
  }
  else if (document.layers)
  {
   	return document.layers[name];
   }
}

//function to check if string contains substr

function checkIt(string)
{
        place = detect.indexOf(string) + 1;
        thestring = string;
        return place;
}

//function to show/hide layers & apply different stylesheet on bottoms

function showhide (layer_ref,state){
  ml = getObj(layer_ref);

  if(getObj(layer_ref)==null) return;

 //hidde all layers
  for(i=0;i<layers.length;i++){
   mbtn = getObj(layers[i]+"_btn")
   mlr = getObj(layers[i])
   mlnk = getObj(layers[i]+"_lnk")

   if(mlr==null || ml.className!=mlr.className) continue;
   if(layer_ref != layers[i]){
     showhidelayer(layers[i],'h')
      if(mlnk) mlnk.className=mlnk.className.replace('On','Off')
      if(mbtn) mbtn.className=mbtn.className.replace('On','Off')
     }else{
      if(mlnk) mlnk.className=mlnk.className.replace('Off','On')
      if(mbtn) mbtn.className=mbtn.className.replace('Off','On')
     }
  }
  showhidelayer(layer_ref,state)
  
 if(layer_ref =="playerstats"){
   hide_playerstats();
   playerstats_shown=(playerstats_shown)?playerstats_shown:"main_home";
   showhidelayer(playerstats_shown,'v');	
  }else {
   hide_playerstats();
   playerstats_shown="";	
  }
}

function showhidelayer(layer_ref,state) {
if(state=='v'){
   if(layer_ref=="scoreline" || layer_ref=="scoreline") viewing[0] = layer_ref;
    else if(layer_ref=="facts" || layer_ref=="form_guide" || layer_ref=="myhistory") viewing[2]= layer_ref;
       else if(layer_ref=="main_home" || layer_ref=="away_home" || layer_ref=="secondary_home" || layer_ref=="secondary_away") viewing[1]="playerstats"
         else viewing[1] = layer_ref
         getUpdates();
}

state=(state == 'v')?'visible':'hidden';
if(getObj(layer_ref)==null) return;

if (document.all) { //IS IE 4 or 5 (or 6 beta)
eval( "document.all." + layer_ref + ".style.visibility = state");
}
if (document.layers) { //IS NETSCAPE 4 or below
document.layers[layer_ref].visibility = state;
}
if (document.getElementById &&!document.all) {
hza = document.getElementById(layer_ref);
hza.style.visibility = state;
}
}

//Ajax class
function AJAXRequest( method, url, data, process, async, dosend) {
    // self = this; creates a pointer to the current function
    // the pointer will be used to create a "closure". A closure
    // allows a subordinate function to contain an object reference to the
    // calling function. We can't just use "this" because in our anonymous
    // function later, "this" will refer to the object that calls the function 
    // during runtime, not the AJAXRequest function that is declaring the function
    // clear as mud, right?
    // Java this ain't
    
    var self = this;

    // check the dom to see if this is IE or not
    if (window.XMLHttpRequest) {
	// Not IE
        self.AJAX = new XMLHttpRequest();
    } else if (window.ActiveXObject) {

   var strName="Msxml2.XMLHTTP"
   if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
      {
      strName="Microsoft.XMLHTTP"
      }
   try
      {
      self.AJAX = new ActiveXObject(strName)
      }
   catch(e)
      {
      alert("Error. Scripting for ActiveX might be disabled")
       }
     }
    
    // if no callback process is specified, then assing a default which executes the code returned by the server
    if (typeof process == 'undefined' || process == null) {
        process = executeReturn;
    }

    self.process = process;

    // create an anonymous function to log state changes
    self.AJAX.onreadystatechange = function( ) {
        self.process(self.AJAX);
    }

    // if no method specified, then default to POST
    if (!method) {
        method = "POST";
    }

    method = method.toUpperCase();

    if (typeof async == 'undefined' || async == null) {
        async = true;
    }
    self.AJAX.open(method, url, async);

    if (method == "POST") {
        self.AJAX.setRequestHeader("Connection", "close");
        self.AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }

    // if dosend is true or undefined, send the request
    // only fails is dosend is false
    // you'd do this to set special request headers

    if ( dosend || typeof dosend == 'undefined' ) {
 	  try{
            self.AJAX.send(null);
        } catch(e){
           document.location.href=document.location.href;
        }
    }

  return self.AJAX;
}

//return current date
function todayDate(){
var mydate = new Date();

  var month=new Array(12)
  month[0]="January"
  month[1]="February"
  month[2]="March"
  month[3]="April"
  month[4]="May"
  month[5]="June"
  month[6]="July"
  month[7]="August"
  month[8]="September"
  month[9]="October"
  month[10]="November"
  month[11]="December"

  day= mydate.getDate();
  month =  mydate.getUTCMonth() + 1

  return(mydate.getFullYear() + "" + month + "" + day)
}

function ifupdates(){
 refreshUpdates();
}

function refreshUpdates(){
if(tries['update']>5) {
	updatesaj=null;
	tries['update']=0;
}

if(updatesaj!=null){ //waiting for response
  tries['update']++;
  setTimeout('ifupdates()',2000);
  return;
}

if( checkIt('aol')) updateTO = setTimeout("getUpdates()",20000);
 else updateTO=setTimeout("getUpdates()",15000);
}

//continious check of updates
function getUpdates(){
try{
 if(updatesaj==null) updatesaj = AJAXRequest("GET" , updateurl + Math.random() , ''  , analyseupdates );
    PATH = './graphics/'+ comp_id + '/f'+ game_id+'/'

   var todaydate = todayDate();

  found = false;
  //update just once as files are unlikely to change
 if(typeof(dates_valid)!="undefined") {
	for(t=0;t<dates_valid.length;t++){
	   if (todaydate.indexOf(dates_valid[t])>=0) found = true
	}
}
 tries['update']=1;
 if(found) refreshUpdates();
}catch(e){
  updatesaj=null;
  setTimeout('refreshUpdates()',2000);
}
}

//check if any valid ajax requests
function ifajaxWaiting(){
  var ifok=false;
  for(refname in majax){
   if(majax[refname]!=null){
	return true;
   }
 }
}


function debug(what){
 getObj("debugme").innerHTML+="<br/>" + what
}


function getMonth(string){
  var months= Array();
  months['Jan']=0;
 months['Feb']=1;
 months['Mar']=2;
 months['Apr']=3;
 months['May']=4;
 months['Jun']=5;
 months['Jul']=6;
 months['Aug']=7;
 months['Sep']=8;
 months['Oct']=9;
 months['Nov']=10;
 months['Dec']=11;
if(typeof(months[string])!="undefined") return months[string]
 else return 0;
}

function getMilliseconds(mdate){
//var mdate ="Saturday, 10 Jun 2006 07:00:27 BST"

var datearr = mdate.split(/ /);
//construct a string

/*
live web server uses different date format
Sun, 11 Jun 2006 18:03:52 BST
var mday = datearr[1].split(/-/);
var mtime = datearr[2].split(/:/);

//needed format year,month,day,hours,minutes,seconds
var myear = mday[2];
var mmonth = getMonth(mday[1]);
var mday1 = mday[0]*1;
*/

if(typeof(datearr[3])=="undefined" || !isInteger(datearr[3])) return 0;

var myear = datearr[3]*1;
var mmonth= getMonth(datearr[2])
var mday1= datearr[1]*1;

var mtime = datearr[4].split(/:/);
var hours= mtime[0]*1;
var mins= mtime[1]*1;
var seconds= mtime[2]*1;

if(typeof(mday1)=="undefined" || typeof(mtime)=="undefined") return 0;

var d = new Date(myear, mmonth, mday1, hours, mins, seconds);

mdatestring = d.toString()
var ms = Date.parse(mdatestring)

return ms
}


function getMilliseconds_web(mdate){
//var mdate ="Saturday, 10-Jun-2006 07:00:27 BST"
var datearr = mdate.split(/ /);
//construct a string

//web server uses  a different date string format
var mday = datearr[1].split(/-/);
var myear = mday[2];
var mmonth = getMonth(mday[1]);
var mday1 = mday[0]*1;
var mtime = datearr[2].split(/:/);

//needed format year,month,day,hours,minutes,seconds

var hours= mtime[0]*1;
var mins= mtime[1]*1;
var seconds= mtime[2]*1;

if(typeof(mday)=="undefined" || typeof(mtime)=="undefined") return 0;

var d = new Date(myear, mmonth, mday1, hours, mins, seconds);

mdatestring = d.toString()
var ms = Date.parse(mdatestring)

return ms
}

function isInteger(s)
{   var i;
    s = new String(s);
    if(typeof(s.length) == "undefined") return false; 

    for (i = 0; i < s.length; i++)
    {
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

//update divs with loaded content
function checkResponse(){
var found = false;
  for(refname in majax){ 

    if(majax[refname]!=null && (majax[refname].readyState==4 || majax[refname].readyState=="complete")){
   try {
        mstatus = majax[refname].status;
   }catch (e) {
        continue;
   }


      if(mstatus==200){
   
//        if(typeof(majax[refname].responseText)!="undefined") continue;
  
	//check if successful response recieven
       if(getObj(refname)!=null)  getObj(refname).innerHTML = majax[refname].responseText
		
      if(refname=="touches") {

        if(_updatedwhen[refname]!=0){
                   images_ready=1;
		   TCH_load_content("prefer_old",'h');
	           TCH_load_content("prefer_old",'a');
        }
	}else if(refname=="playerstats" && playerstats_shown) {
		 a = playerstats_shown.split("_");
		 selectMe(a[1],a[0]);
        } else if(refname =="shots") AG_load_content("prefer_new");
 	
	}else if(mstatus==404) {
	if(getObj(refname)!=null) getObj(refname).innerHTML= "Coming Soon"
	}

	_toupdate[refname]=null;
	majax[refname]=null;	
}  
  if(_toupdate[refname]!= null) found=true
 }
if(found)  setTimeout('checkResponse()',10000);
}

//parse repository file 
function analyseupdates(me){
if (tries['update']!=0 && me!=null && (me.readyState==4 || me.readyState=="complete")){

 latest = new String(me.responseText).split("\n");
      
    for(i=0;i<latest.length;i++){
		
                var temp = latest[i].split("#");
		if(temp.length!=3) continue;
		refname = temp[0];
  	        temp[2] = getMilliseconds(temp[2]);
 	        if(!isInteger(temp[2])) temp[2]=0;


                if(typeof(_updatedwhen) == "undefined" || 
		   typeof(_updatedwhen [ refname ]) == "undefined" ||
		   _updatedwhen[ refname ] < temp[2]){
                   //updates needed if last minute update different than recorded
//  		    debug("update needed "+ refname +  temp[2]);

   		if(viewing.join(":").indexOf(refname)!=-1 ||  typeof(_updatedwhen [ refname ]) == "undefined"){
                   _updatedwhen[ refname ] = temp[2];
	           _toupdate[ refname ] = temp[1];
			}
                }
      }
    updatesaj=null 
    getContent();
 }
}

//function to load content
function getContent(){
//looking at a queuee where value is not null 
for(refname in _toupdate){
   if(_toupdate[refname]!=null){
     //create a request to get url from _toupdate[refname]	
	      if(majax[refname]==null)  majax[refname] = AJAXRequest("GET" , _toupdate[refname] +  "?" + Math.random() , ''  , checkResponse );
   }
 }
}


//playerstats library
var myhome_away='home';

function selectMe(home_away,main_secondary){
 oppos_main_secondary = (main_secondary=="main")? "secondary":"main";

if(home_away!=null){
 oppos_home_away = (home_away=="home")? "away":"home";
 getObj('players_'+home_away).className="selected"
 getObj('players_'+oppos_home_away).className="unselected"
 myhome_away=home_away
}
 getObj('players_'+main_secondary).className="selected"
 getObj('players_'+oppos_main_secondary).className="unselected"
 hide_playerstats();
 showhidelayer(main_secondary+'_'+myhome_away,'v')
 playerstats_shown = main_secondary + "_"+ myhome_away
}

function hide_playerstats(){
  if(getObj('main_home')==null) return;
  showhidelayer('main_home','h')
  showhidelayer('secondary_home','h')
  showhidelayer('main_away','h')
  showhidelayer('secondary_away','h')
}

function getURL(url){
 document.location.href = url
}


