// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// the name of the XSLT file
var xsltFileUrl = "./Vote.xsl";
// the results of vote
var xsltresult = "./result.xsl";
// File for the last persons hwo participate
var xsltvotant = "./votants.xsl";
// the file that returns the requested data in XML format
var feedGridUrl = "./Votes.php";

// the id of the grid div
var gridDivId = "Questions";
// the id of the results div
var resultDivId = "ResultDiv";
// the grid of the status div
var statusDivId = "Status";
// stores temporary row data
var tempRow;
// the ID of the product being edited
var editableId = null;
// the XSLT document
var stylesheetDoc;
// XSLT doc for results
var stylesheetRes;
// id if received ajx request
var ajx_last;

// id question
var idquestion;

// id of category
var cat_id ;

// **********************************************
// global variables for map
var map;
var centerLatitude = 40.4419;
var centerLongitude =-2.5419;
var startZoom = 4;
var xmlhttp,myxmlhttp;
var markers;
var highlightCircle;
var currentMarker;
var iconeVert = new GIcon();
var updateInterval = 20000;

var myxmlHttp =  GXmlHttp.create();



iconeVert.shadow = "./FLAG/ombre.png";
iconeVert.iconSize = new GSize(18, 30);
iconeVert.shadowSize = new GSize(22, 20);
iconeVert.iconAnchor = new GPoint(6, 20);
iconeVert.infoWindowAnchor = new GPoint(4, 1);
// **********************************************



function createMsxml2DOMDocumentObject()
{
  // will store the reference to the MSXML object
  var msxml2DOM;
  // MSXML versions that can be used for our grid
  var msxml2DOMDocumentVersions = new Array("Msxml2.DOMDocument.6.0",
                                            "Msxml2.DOMDocument.5.0",
                                            "Msxml2.DOMDocument.4.0");
  // try to find a good MSXML object
  for (var i=0; i<msxml2DOMDocumentVersions.length && !msxml2DOM; i++)
  {
    try 
    { 
      // try to create an object
      msxml2DOM = new ActiveXObject(msxml2DOMDocumentVersions[i]);
    } 
    catch (e) {}
  }
  // return the created object or display an error message
  if (!msxml2DOM)
    alert("Please upgrade your MSXML version from \n" + 
          "http://msdn.microsoft.com/XML/XMLDownloads/default.aspx");
  else 
    return msxml2DOM;
}

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
 
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}


// makes asynchronous request to load a new page of the grid
function loadGridPage(pageNo)
{
  // disable edit mode when loading new page
  editableId = false;
  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
    var query = feedGridUrl + "?action=FEED_GRID_PAGE&page=" + pageNo;
    xmlHttp.open("GET", query, true);
    xmlHttp.onreadystatechange = handleGridPageLoad;
    xmlHttp.send(null);
  }
}
 
// makes asynchronous request to update avote stat
function InsertVote(rep,ques)
{

  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
    var query = feedGridUrl + "?action=InsertVote&rep=" + rep+"&question="+ques;
    xmlHttp.open("GET", query, true);
    xmlHttp.onreadystatechange = handleGridVoteLoad;
    xmlHttp.send(null);
  }  
}

// makes asynchronous request to update avote stat
function readstat(id)
{

  // continue only if the XMLHttpRequest object isn't busy
  if (xmlHttp && (xmlHttp.readyState == 4 || xmlHttp.readyState == 0))
  {
    var query = feedGridUrl + "?action=readstat&question="+id;
    xmlHttp.open("GET", query, true);
    xmlHttp.onreadystatechange = handleGridVoteLoad;
    xmlHttp.send(null);
  }  
}

// handle receiving the server response with a new page of products
function handleGridPageLoad()
{
  // when readyState is 4, we read the server response
  if (xmlHttp.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200)
    {
      // read the response
      response = xmlHttp.responseText;
      // server error?
      if (response.indexOf("ERRNO") >= 0 
          || response.indexOf("error") >= 0
          || response.length == 0)
      {
        // display error message
        alert(response.length == 0 ? "Server serror." : response);
        // exit function
        return;
      }

      document.getElementById('Questions').innerHTML = response;

  }
 }
}

// handle receiving the server response of vot stats for a choosed question
function handleGridVoteLoad()
{
  // when readyState is 4, we read the server response
  if (xmlHttp.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200)
    {
      // read the response
      response = xmlHttp.responseText;
      // server error?
      if (response.indexOf("ERRNO") >= 0 
          || response.indexOf("error") >= 0
          || response.length == 0)
      {
        // display error message
        alert(response.length == 0 ? "Server serror." : response);
        // exit function
        return;
      }

      document.getElementById('Stat').innerHTML = response;

  }
 }
}


var deselectCurrent = function() {};

function initializePoint(pointData) {
        var Resp2marker= "./FLAG/"+pointData.response+".png";
        iconeVert.image =Resp2marker ;
	var point = new GLatLng(pointData.latitude, pointData.longitude);
	var marker = new GMarker(point,{icon: iconeVert, title: pointData.nom});

	var listItem = document.createElement('li');
	var listItemLink = listItem.appendChild(document.createElement('a'));
	listItemLink.href = "#";

       // listItem.style.listStyleImage="url(./FLAG/"+pointData.nom+".png)";

	listItemLink.onmouseover = function() {	marker.setImage("./FLAG/rouge.png");}

	listItemLink.onmouseout = function() { marker.setImage(Resp2marker);}

	listItemLink.innerHTML =  '<table><tr><td><img src="./FLAG/'+pointData.nom+'.png" />' + pointData.nom + ' </td><td><span>' + ', ' + pointData.ville + '</span></td></tr></table >';
	var focusPoint = function() {
		deselectCurrent();
		listItem.className = 'current';
		marker.setImage("./FLAG/rouge.png");
		deselectCurrent = function() { listItem.className = ''; marker.setImage(Resp2marker);}
		marker.openInfoWindowHtml('<table width="200px"><tr><td width="20%">'+ pointData.ville+'</td><td width="60%"> </td><td width="20%"><img src="./FLAG/'+pointData.nom+'.png"></td></tr></table><div class="sml">il y a:'+pointData.timevote+'</div>');

		return false;
	}
	listItemLink.onclick = focusPoint;
	GEvent.addListener(marker, 'click', focusPoint);
	GEvent.addListener(marker, 'mouseover', function() { marker.setImage("./FLAG/rouge.png"); });
	GEvent.addListener(marker, 'mouseout', function() { marker.setImage(Resp2marker); });
	GEvent.addListener(marker, 'infowindowclose', function(){marker.setImage(Resp2marker);});
	document.getElementById('sidebar-list').appendChild(listItem);

	map.addOverlay(marker);
	map.recenterOrPanToLatLng(point);
}

var   markerlength=0;
function initData() {
       var i=0;
        //document.getElementById('sidebar-list').innerHTML="";
	if(markerlength<markers.length) {
	  initializePoint(markers[markers.length-markerlength-1]);
	  markerlength++;
          setTimeout("initData();",600);

	}


}

function handleResize() {
	var height_map = 400;
	var height_side = 350;
	document.getElementById('map').style.height = height_map + 'px';
	document.getElementById('sidebar-list').style.height = height_side + 'px';

}


// function that displays an error message
function displayError(message)
{
  // display error message, with more technical details if debugMode is true
  var divError = document.getElementById('sidebar');
  divError.innerHTML =divError.innerHTML +"Error accessing the server!"+message;

}


/* function that handles the http response when updating messages */
function handleReceivingMessages() 
{

  // continue if the process is completed
  if (myxmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (myxmlHttp.status == 200) 
    {
      try
      {
        // process the server's response

        var responseText = myxmlHttp.responseText.toString();
        var tab = responseText.split('&');
        if(tab[1]){
                        ajx_last=parseInt(tab[0]);
			markers = eval(tab[1].toString());
			markerlength=0;
  			initData();
        }
        setTimeout('CenterCarte('+idquestion+','+cat_id+');', updateInterval);
     }
      catch(e)
      {
        // display the error message
        displayError(e.toString());
      }
    } 
    else
    {
      // display the error message
      displayError(myxmlHttp.statusText);
    }
  }
}


function CenterCarte(idquest,catid)
{  
	handleResize();
  // only continue if xmlHttpGetMessages isn't void
  if(myxmlHttp)
  {
    try
    {
      // don't start another server operation if such an operation 
      //   is already in progress 
      if (myxmlHttp.readyState == 4 ||
          myxmlHttp.readyState == 0) 
      {
        s='ajx_last='+ajx_last+'&idquest='+idquest+'&catid='+catid;
        // call the server page to execute the server-side operation
        myxmlHttp.open("POST",'json2.php',true);
        myxmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        myxmlHttp.onreadystatechange = handleReceivingMessages;
 
        myxmlHttp.send(s);
      }
      else
      {
        // we will check again for new messages 
        setTimeout('CenterCarte('+idquest+','+catid+');', updateInterval);
      }
    }
    catch(e)
    {
      displayError(e.toString());
    }
  }
}


/* this function initiates the chat; it executes when the chat page loads */
function init(id,catid)
{
         idquestion = id;
         cat_id     = catid;

	map = new GMap(document.getElementById("map"));
	map.addControl(new GMapTypeControl());
	map.addControl(new GLargeMapControl());
	map.addControl(new GOverviewMapControl(new GSize(60,80)));
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	var bounds = new GLatLngBounds();

	
  CenterCarte(idquestion,cat_id);

}


