// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
var gridCargada = false;//indica si ya se ha generado la rejilla con imagenes
var parametroQuery;
var categoriaQuery;
var URLQuery;
var MySQLDomServer = "http://www.myavdf.org/inssa/";

// funcion que crea un la instancia del objeto XMLHttpRequest
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;
}//createXmlHttpRequestObject
 
// funcion que procesa las actividades de la pagina, obtiene los graficos del marco de la pagina
function process(parQuery, catQuery)
{
  parametroQuery = parQuery;//string: inssa, bianchi...
  categoriaQuery = catQuery;//number: 0, 1-3

  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
      // initiate the asynchronous HTTP request: "inssa representa el marco general"
	  //xmlHttp.open("GET", MySQLDomServer+"DomMarco.php?hoja="+parametroQuery, true);
	  xmlHttp.open("GET", "DomMarco.php?hoja="+parametroQuery, true);
      xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}//process

// funcion llamada cuando el estado HTTPRequest cambia
function handleRequestStateChange() 
{
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponse();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}//handleRequestStateChange

// manipula la respuesta recivida desde el servidor y se encarga del diseño del marco del apagina
function handleServerResponse()
{
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML;
  
  // obtain the XML's document element
  xmlRoot = xmlResponse.documentElement;  
  
  // obtener el conjunto arreglado desde el script de php 
  imgArray = xmlRoot.getElementsByTagName("imagen");
  linkArray = xmlRoot.getElementsByTagName("link");
  descArray = xmlRoot.getElementsByTagName("desc");
  
  myImg = document.getElementById("logojd");
  myImg.src = imgArray.item(0).firstChild.data;
  myImg.style.cursor = "hand";
  myImg.style.cursor = "pointer";
  myImg.onclick = function(){
	  abrirSeccion("http://www.inssa.com.co");//abre la hoja parametrizada
	};  
  
  myImg = document.getElementById("logoemail");
  myImg.src = imgArray.item(1).firstChild.data;
  myImg.style.cursor = "hand";
  myImg.style.cursor = "pointer";
  myImg.onclick = function(){
	  //abrirSeccion();
	  mostrarEmail("contacto");
   
	};  

  myImg = document.getElementById("ams");
  myImg.src = imgArray.item(2).firstChild.data;
  myImg = document.getElementById("bianchi");
  myImg.src = imgArray.item(3).firstChild.data;
  myImg = document.getElementById("elcor");
  myImg.src = imgArray.item(4).firstChild.data;
  myImg = document.getElementById("inssa");
  myImg.src = imgArray.item(5).firstChild.data;
  myImg = document.getElementById("oranfresh");
  myImg.src = imgArray.item(6).firstChild.data;
  
  myImg = document.getElementById("logoinssa");
  myImg.src = imgArray.item(7).firstChild.data;
  
  myImg = document.getElementById("banner");
  myImg.src = imgArray.item(8).firstChild.data;  
  
  myTxt = document.getElementById("myBnr");
  myTxt.innerHTML = descArray.item(8).firstChild.data;
  
  //lanzamiento de la rejilla correspondiente a la selleccion elejida desde la pagina incial!!!
  //procesarGrid("inssa");
  procesarGrid();
  
  myLink = document.getElementById("ams");
  myLink.style.cursor = "hand";
  myLink.style.cursor = "pointer";
  myLink.onclick = function(){
	  abrirSeccion("sp_marca_ams.html");
	};
  myLink = document.getElementById("bianchi");
  myLink.style.cursor = "hand";
  myLink.style.cursor = "pointer";
  myLink.onclick = function(){
	  abrirSeccion("sp_marca_bianchi.html");
	};
  myLink = document.getElementById("elcor");
  myLink.style.cursor = "hand";
  myLink.style.cursor = "pointer";
  myLink.onclick = function(){
	  abrirSeccion("sp_marca_elcor.html");
	};
  myLink = document.getElementById("oranfresh");
  myLink.style.cursor = "hand";
  myLink.style.cursor = "pointer";
  myLink.onclick = function(){
	  abrirSeccion("sp_marca_oranfresh.html");
	};
  myLink = document.getElementById("inssa");
  myLink.style.cursor = "hand";
  myLink.style.cursor = "pointer";
  myLink.onclick = function(){
	  abrirSeccion("sp_marca_inssa.html");
	};
	
//inclusiones de scriptaculous!!
  incluir("prototype.js");
  incluir("scritaculous.js");

}//handleServerResponse

//Funcion encargad de incluir las clases de striptaculous.js y prototype.js
function incluir(clase)
{
	// Create the Script Object
	var script = document.createElement('script');
	script.src = clase;
	script.type = 'text/javascript';
	script.defer = true;
	script.id = 'scriptID'; // This will help us in referencing the object later for removal
	// Insert the created object to the html head element
	//var head = document.getElementsByTagName('head').item(0);
	//head.appendChild(script);
}//incluir

//Funcion encargada de gargar de manera aleatoria los indices o imagenes principales
function cargarImgIndice()
{
	var miArray = new Array(5);
	
	miArray[0] = "img/paginas/fader_bianchi_horeca.png"; 
	miArray[1] = "img/paginas/fader_elcor.png";
	miArray[2] = "img/paginas/fader_inssa.png"; 
	miArray[3] = "img/paginas/fader_oranfresh.png";
	var randomnumber=Math.floor(Math.random()*4);
	myImg = document.getElementById("indice");
	myImg.src =  miArray[randomnumber];

	$(myImg).fade({ duration: 5.0, from: 0, to: 1 });

	//alert(randomnumber);
	setTimeout("cargarImgIndice();", 10 * 1000);
}//cargarImgIndice

//Funcion utilizada para animar los thumbs
function animarThumb(thumb)
{
	$(thumb).fade({ duration: 3.0, from: 0.5, to: 1 });
}//animarThumb

//Funcion utilizada mostrar el formulario de email
function mostrarEmail(thumb)
{
	window.open('email/Email.swf', this.target, 'location=no, width=550,height=400');
}//mostrarEmail

//funcion encargada de abrir al seccion correspondiente al icono
function abrirFichaComercial(ficha)
{
	var url = ficha;
	var name = "Maquinas HORECA - JD Ossa Colombia";
	window.open(url, name,this.target, 'location=no, width=550,height=400');
	}//abrirFichaComercial

/**
*INICIO RUTINA AJAX ENCARGADA DE MOSTRAR LAS IMAGENES EN REJILLA DE CENTRO DE PAGINA!!!!!!!
**/
//read a file from the server ¡¡procesarGrid(imagenes)!!
function procesarGrid()
{
  //evaluacion del tipo de grupo que se va a consultar
  switch(categoriaQuery)
  {
	  case 0://consulta por marca
	   URLQuery = "DomHojas.php?marca="+parametroQuery+"&negocio=na&maquina=na";
	  break;
	  case 1://consulta por tipo de negocio
	   URLQuery = "DomHojas.php?marca=na&negocio="+parametroQuery+"&maquina=na";
	  break;
	  case 2://consulta por tipo de maquina
	   URLQuery = "DomHojas.php?marca=na&negocio=na&maquina="+parametroQuery;
	  break;
	  case 3://consulta por tipo sistemas de pago
	   URLQuery = "DomHojas.php?marca=na&negocio=na&maquina="+parametroQuery;
	  break;
	  default:
	  	//alert("Error inesperado!!");
		return;
  }
   //alert(categoriaQuery+" , "+parametroQuery+" , "+URLQuery); Debug!!!
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
	  // initiate the asynchronous HTTP request
	  xmlHttp.open("GET", URLQuery, true);
	  //xmlHttp.open("GET", MySQLDomServer+URLQuery, true);
      xmlHttp.onreadystatechange = handleRequestStateChangeGrid;
      xmlHttp.send(null);//DATA SEND ONLY FOR "POST" MUST BE > 512 PREFFERED
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}//procesarGrid

// function called when the state of the HTTP request changes
function handleRequestStateChangeGrid() 
{
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponseGrid();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}//handleRequestStateChange

// manipula la respuestanrecibida desde el servidor y la transforma en la rejilla de imagenes
function handleServerResponseGrid()
{
  // objeto que lee el mensaje requerido desde el servidor
  var xmlResponse = xmlHttp.responseXML;
  // obtenemos los elementos XML del documento
  xmlRoot = xmlResponse.documentElement;  
  // estos arreglos obtienen los nodos principales desde la pagina php 
  imgArray = xmlRoot.getElementsByTagName("imagen");
  linkArray = xmlRoot.getElementsByTagName("link");
  nombArray = xmlRoot.getElementsByTagName("nomb");
  dscArray = xmlRoot.getElementsByTagName("desc");
  //for loop variables
  var arrayLen = imgArray.length;
  var columnas = 4;
  var filas = Math.ceil(arrayLen/columnas);
  
  // generate HTML output
  var html = "";  
  var th = '<table id="dsk" width="100%" height="100%" border="0" cellspacing="2" cellpadding="0">';
  var hrows = '<tr>';
  var trows = '</tr>';
  var tf = '</table>';
  html += th;//header table label add
  var idr = 0;
  
  // iterate through the arrays and create an HTML structure
  for (var i=0; i<filas; i++)
  {
	html += hrows;
	for(var j=0; j<columnas; j++)
	{
		var tdid = "tst"+idr;
		html+='<td id="'+tdid+'"></td>';
		idr++;
	}
	html += trows;
  }
  html += tf;//footer table label add
  
  // obtain a reference to the <div> element on the page
  // display the HTML output  
  myImg = document.getElementById("myPGrid");
  myImg.innerHTML = html;
  
  //after retrieve the grid we must print the images
  for (var i=0; i<imgArray.length; i++)
  {
	var tdid = "tst"+i;
	var mtst = document.getElementById(tdid);
	var ficha = linkArray.item(i).firstChild.data;
	var nom = nombArray.item(i).firstChild.data;
	var dsc = dscArray.item(i).firstChild.data;

	mtst.innerHTML = '<img src="'+imgArray.item(i).firstChild.data+'" onclick=window.open("'+ficha+'") ></img>'+
	                 '<tr><td align="center">'+nom+'</td></tr>'+
					 '<tr><td align="center"><br>{'+dsc+'}</td></tr>'+
					 '<tr><td align="center"><a href="'+ficha+'" target="_blank"><br>[Ver Mas!]</a></td></tr>'+
					 '<tr><br><br></tr>';
	mtst.style.cursor = "hand";
	mtst.style.cursor = "pointer";

	}

}//handleServerResponse
/*
*FIN RUTINA AJAX ENCARGADA DE MOSTRAR LAS IMAGENES EN REJILLA DE CENTRO DE PAGINA¡¡¡¡
*/
//funcion encargada de abrir al seccion correspondiente al icono
function abrirSeccion(url)
{
	var name = "Maquinas dispensadoras automaticas :: JD Ossa SAS - Colombia";
	window.open(url,'_self', name);
	//alert(url);
	}//abrirSeccion

