// variables

var highLight = 0; // highlighted driver
var highLightColor = "#d3d3d3";
var zebraDark = "#f3f3f3";
var zebraLight = "#fefefe";
var baseurl = "/tulospalvelu";

var expands = new Array();
expands["R"] = new Array();
expands["Q"] = new Array();
expands["P"] = new Array();
expands["W"] = new Array();

// toggles on/off highlighting and resets already highlighted items
function toggleHighLight(driver) {
  // reset current
  if(highLight > 0) {
    var dRace = document.getElementById("R" + highLight);
    var dQual = document.getElementById("Q" + highLight);
    var dPrac = document.getElementById("P" + highLight);
    var dWup = document.getElementById("W" + highLight);
    
    if(dRace != null) {
      resetColor(dRace);
    }
    if(dQual != null) {
      resetColor(dQual);
    }
    if(dPrac != null) {
      resetColor(dPrac);
    }
    if(dWup != null) {
      resetColor(dWup);
    }
    
  }
  
  if(highLight != driver) {
    highLight = driver;
    
    var dRace = document.getElementById("R" + driver);
    var dQual = document.getElementById("Q" + driver);
    var dPrac = document.getElementById("P" + driver);
    var dWup = document.getElementById("W" + driver);
    
    if(dRace != null) {
      dRace.style.backgroundColor=highLightColor;
    }
    if(dQual != null) {
      dQual.style.backgroundColor=highLightColor;
    }
    if(dPrac != null) {
      dPrac.style.backgroundColor=highLightColor;
    }
    if(dWup != null) {
      dWup.style.backgroundColor=highLightColor;
    }

  }
  else
    highLight = 0;
}

// resets the color, used by toggleHighLight
function resetColor(doc) {
  if(doc.className == 'zebra_dark')
    doc.style.backgroundColor=zebraDark;
  else
    doc.style.backgroundColor=zebraLight;
}

// ajaxing laptimes to race results
function showLapTimes(dButton, race, session, driver, sim) {

  var rowId = dButton.parentNode.parentNode.rowIndex;
  var dRow = dButton.parentNode.parentNode;
  var colSpan = 3;

  
  switch(session) {
    case "R":
      dTable = document.getElementById("Race");
      colSpan = 6;
      break;
    case "W":
      dTable = document.getElementById("Warmup");
      break;
    case "Q":
      dTable = document.getElementById("Qualify");
      break;
    case "P":
      dTable = document.getElementById("Practice");
      break;
  }

  if(expands[session].indexOf(dRow.id) == -1) {

    var myRow = dTable.insertRow(rowId + 1);
    var tmp = myRow.insertCell(-1);
    var tmp2 = myRow.insertCell(-1);
    var myCell = myRow.insertCell(-1);
    // two empty cells

    myCell.colSpan = colSpan;
    myCell.style.padding = "0";

    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else {
      // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", baseurl + "/ajax.php?GetLapTime=1&race="+ race +"&driver=" + driver +"&session=" + session + "&sim=" + sim, false);
    xmlhttp.send(null);
    myCell.innerHTML=xmlhttp.responseText;
    
    dButton.src = baseurl + "/gfx/collapse.gif";
    expands[session].push(dRow.id);
  }
  else {
    dTable.deleteRow(rowId + 1);
    expands[session].splice(expands[session].indexOf(dRow.id), 1);
    dButton.src = baseurl + "/gfx/expand.gif";
  }
}

// highlighting changes in admin section
function highLightChange(doc, value) {

  if(doc.value != value) {
    doc.style.backgroundColor = "#ee2229";
    doc.style.color = "#fff";
  }
  else {
    doc.style.backgroundColor = "#fff";
    doc.style.color = "#000";
  }

}

// disables selected input if 1st param is 0
function disableInput(select, input) {
  var chosen = select.options[select.selectedIndex];
  if (chosen.value != "Ei listattu, määrittele alle...") {
    document.getElementById(input).value = "";
    document.getElementById(input).disabled = true;
  }
  else {
    document.getElementById(input).disabled = false;
  }
}

// valid file dialogs for uploading
function toggleFileDialogs(dSelect, sim) {

  function addRow(session, content, dTable) {
    var myRow = dTable.insertRow(rowId + 2);
    var myCellContent = myRow.insertCell(-1);
    myCellContent.innerHTML = "<input type=\"file\" name=\"file[" + session + "]\"/>";
    var myCellTitle = myRow.insertCell(-1);
    myCellTitle.innerHTML = content;
  }

  // delete rows
  var dTable = document.getElementById("addTable");
  var totalRows = dTable.rows;
  var rowId =  dSelect.parentNode.parentNode.rowIndex;

  while(document.getElementById("addTable").rows.length > 4) {
    dTable.deleteRow(rowId + 2);
  }
  
  // add rows
  switch(sim) {
    case "GPL":
      addRow('0', 'Logi', dTable);
      break;
      
    case "RF":
      addRow('R', 'Kilpailun logi', dTable);
      addRow('W', 'Lämmittelyn logi', dTable);
      addRow('Q', 'Aika-ajon logi', dTable);
      addRow('P', 'Harjoitusten logi', dTable);
      break;
      
    case "IR":
      addRow('0', 'Result-sivu', dTable);
      addRow('1', 'Replay parserin XML', dTable);
      break;
      
  }
}

// updates driver selectbox according to the selected race
function reloadDrivers(SelectId, race) {

  dSelect = document.getElementById(SelectId);
  dSelect.options.length=1;
  
  if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else {
      // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", baseurl + "/ajax.php?GetDrivers=1&race="+ race, false);
    xmlhttp.send(null);
    
    dSelect.innerHTML = xmlhttp.responseText;
    
}

function updateMergeDriver(id, name, SelectId) {

  var dSelect = document.getElementById(SelectId);
  var deleteFlag = 0;
  
  // check if exits, if so, delete
  for (i=0; i < dSelect.options.length; i++){
    if(dSelect.options[i].value == id) {
      dSelect.options[i]=null;
      deleteFlag = 1;
    }
  }
  
  if(deleteFlag == 0) {
    dSelect.options[dSelect.options.length]=new Option(name, id, false, false)
  }
}

/*
    Quick nav
*/

// ran on pageload
function QnInit() {

  dQn = document.QnForm;

  for(i=0; i < dQn.elements.length; i++) {
    switch(dQn.elements[i].name) {
      case "season":
        QnLoadSeason();
        break;
      case "race":
        QnLoadRace('0');
        break;
      case "driver":
        QnLoadDrivers('0');
        break;
      case "team":
        QnLoadTeams('0', '');
        break;
    }
  }

}

function QnLoadSeason() {
  
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
  }
  else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET", baseurl + "/ajax.php?GetSeasons=1", false);
  xmlhttp.send(null);
  
  document.QnForm.season.innerHTML = xmlhttp.responseText;

}

function QnLoadRace(seasonId) {
  
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
  }
  else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET", baseurl + "/ajax.php?GetRaces=1&season=" + seasonId, false);
  xmlhttp.send(null);
  
  document.QnForm.race.innerHTML = xmlhttp.responseText;

}

function QnLoadDrivers(id, get) {
  
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
  }
  else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET", baseurl + "/ajax.php?GetDrivers=1&"+ get +"=" + id, false);
  xmlhttp.send(null);
  
  document.QnForm.driver.innerHTML = xmlhttp.responseText;

}

function QnLoadTeams(id, get) {
  
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
  }
  else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET", baseurl + "/ajax.php?GetTeams=1&"+ get +"=" + id, false);
  xmlhttp.send(null);
  
  document.QnForm.team.innerHTML = xmlhttp.responseText;

}

/* tabs */
function toggleTab(selected, type) {

  switch(type) {
    case "Race":
      var loop = new Array("Race", "Warmup", "Qualify", "Practice", "Lapgraph", "Lapchart");
      var styleDisplay = "table";
      break;
    case "courseImage":
      var loop = new Array("map_canvas", "course_image");
      var styleDisplay = "block";
      break;
    case "Driver":
      var loop = new Array("Races", "Teams", "Records", "Achievements");
      var styleDisplay = "table";
      break;
    case "Season":
      var loop = new Array("Drivers", "Teams", "Pointchart", "Teampointchart", "Pointgraph");
      var styleDisplay = "table";
      break;
  }

  for (var i in loop) {
      doc = document.getElementById(loop[i]);
      if(doc != null) {
        if(i == selected) {
          doc.style.display = styleDisplay;
          document.getElementById("menu"+ i).className = 'current'; 
        } else {
          doc.style.display = "none";
          document.getElementById("menu"+ i).className = 'none';
        }
     }
  }
  

  // fixing lapgraph width
  if((type == "Race" && selected == 4) || (type == "Season" && selected == 4) ) {
    loadChart();
  }
  
}

/* testing coordinates */
function PopupGMaps(lat, lon, zoom) {
	newwindow2=window.open('','gmaps','width=600,height=400');
	var tmp = newwindow2.document;
	tmp.write('<html>');
	tmp.write('<head>');
	tmp.write('<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>');
	tmp.write('<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>');
	tmp.write('<script type="text/javascript">');
	tmp.write('  function initialize() {');
	tmp.write('    var latlng = new google.maps.LatLng('+ lat +', '+ lon +');');
	tmp.write('    var myOptions = {');
	tmp.write('      zoom: '+ zoom +',');
	tmp.write('      center: latlng,');
	tmp.write('      mapTypeId: google.maps.MapTypeId.HYBRID,');
	tmp.write('      navigationControl: false,');
	tmp.write('      scaleControl: false');
	tmp.write('    };');
	tmp.write('    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);');
	tmp.write('  }');
	tmp.write('</script>');
	tmp.write('</head>');
	tmp.write('<body onload="initialize()">');
	tmp.write('  <div id="map_canvas" style="width:100%; height:100%"></div>');
	tmp.write('</body>');
	tmp.write('</html>');
	tmp.close();

}

/* 
		Saving form data to cookies, makes admin's life easier
*/

function getFormValues(form) {

	function getCookie(c_name) {
		if (document.cookie.length>0) {
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) {
				c_start=c_start + c_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 "";
	}

  if (document.cookie.length > 0) {
		for (i=0; i < form.elements.length; i++) {	
			if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "textarea") {
				if(getCookie(location.pathname +"_"+ form.elements[i].name)) {
					form.elements[i].value = getCookie(location.pathname +"_"+ form.elements[i].name);
				}
			}
		}
	}
}


function setFormValues(form) {
  
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + 7); // expire in week
  
  for (i=0; i < form.elements.length; i++) {
  	if(form.elements[i].type == "text" || form.elements[i].type == "select-one" || form.elements[i].type == "textarea") {
			document.cookie=location.pathname +"_"+ form.elements[i].name +"="+ escape(form.elements[i].value) + ";expires=" + exdate.toUTCString();
		}
  }

}


