// JavaScript code for DB/Text InfoCart
//  Copyright © 2002, Inmagic, Inc., Woburn, MA, USA. All rights reserved.

// Revided July 31, 2002

   // These variables need to be updated for every tb
   // each string variable contains the name\value pair required by webPub
   // They must be URL encoded.
   
//Infocart Internet

   //cookie name for this database or app
   var rl = "0";
   var dl = "1";
   var np = "-1";
   
   //added to enable XML support
   
   var xml = "1";
   var xsl = "";
   
   
   //sets the domain the cookie can be used in
   //null means just the default domain
   var domain = null;

   //set expiration date 7 days ahead
   /* Hay algunas paginas que necesitan ponerse el expiration como igual a vacio, como en el caso de cat-cip
   entonces hay que verificar si previamente la variable expiration ya fue definida */
   if (expiration==undefined){
    var expiration = new Date();
    expiration.setTime(expiration.getTime() + 604800000);
   }

// Heinle's function for retrieving a cookie. INFOCART

function getCookie(name){
   var cname = name + "=";
   var dc = document.cookie;
   if (dc.length > 0) {
     begin = dc.indexOf(cname);
     if (begin != -1) {
       begin += cname.length;
       end = dc.indexOf(";", begin);
          if (end == -1) end = dc.length;
            return unescape(dc.substring(begin, end));
     }
   }
  return null;
}

// An adaptation of Dorcht's function for setting a cookie.
function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

// An adaptation of Dorcht's function for deleting a cookie.
function delCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
  //send them back to Query Page
    window.location.href = queryPageURL ;

}


//set this cookie
function setPassword(form){
	var password = form.ID.value;
	setCookie('inmusers', password, expiration, null, domain, null);
	}
	
//get this cookie
function getPassword(){	
	if (getCookie('inmusers') != null){ 	
		document.qbe_form.ID.value = getCookie('inmusers');
	}
}
//delete this cookie
function clearPassword(form){
	document.qbe_form.ID.value = "";
	delCookie('inmusers', null, domain);
}

// Clear all the boxes on the form except the password
function clearForm (form) {
   var formLength = form.elements.length;
   
   //walk through all the elements of the form
   for(i=0;i<formLength;i++){

      //if it is a text element then clear it. wont work for textarea
      if (form.elements[i].type == 'text') {
         form.elements[i].value = '';
      }
   }
}

// check for id already in cookie

function checkDup(idValueArray,value){
   
   var valueLength = idValueArray.length
   var x = 0;
   
   while (x < valueLength){
      
      if (idValueArray[x] == value){
         //alert("You have already selected this item.");
         return false;
         }
      x++;
    }
      return true;
   
}
//====================================================
// Function:   upDateCount
// Purpose:    counts the items in the cart
// Parameters: none
// Returns:    sets the count number on the page
// Note:       
//====================================================
function updateCount()
{
   if (getCookie(cartName)){
      var cookieValueString = getCookie(cartName);
      var cookieValueArray = cookieValueString.split('/');
      document.cartStatus.cartCount.value = cookieValueArray.length;
   }
   else
      document.cartStatus.cartCount.value = "No";
}
//====================================================
// Function:   addIDbtn
// Purpose:    This will write the info to a cookie
// Parameters: form - pointer to the host form
// Returns:    -
// Note:       update item count disabled
//====================================================


function addIDbtn(value){


   var arrayLength;
   var idValueArray = new Array;
   var cookieValue = '';
   
      // check for existing cookie and get existing values
   
   if(getCookie(cartName)){
         cookieValue = getCookie(cartName);
         idValueArray = cookieValue.split('/');
         
      }
       
         if (checkDup(idValueArray,value)){
            idValueArray[idValueArray.length] = value;
            }

   
   
   // join the ids into a string then add to any existing values
     
   cookieValue = idValueArray.join('/');
   setCookie(cartName,cookieValue,expiration,"/",null,null);
   //update the count in the cart at the bottom of the page if it exists
   if(idValueArray.length>0)
//      document.cartStatus.cartCount.value = idValueArray.length;
      document.forms[0].cartCount.value = idValueArray.length;
}


// run a canned query to get the record selected
function getRecords(cartName){
   var searchString = getCookie(cartName);
   var CannedQuery = '/dbtw-wpd/exec/dbtwpub.dll?';
   CannedQuery += 'TN=' + textbase;
   CannedQuery += '&QF0='+ idField;
   CannedQuery += '&QI0=' + searchString;
   CannedQuery += '&BU=' + bu;
   CannedQuery += '&MR=' + recordsPerPage;
   CannedQuery += '&RF=' + reportForm;
   CannedQuery += '&RL=' + rl;
   CannedQuery += '&DF=' + displayForm;
   CannedQuery += '&DL=' + rl;
   CannedQuery += '&NP=' + np;
   
//xml options
//   CannedQuery += '&XML=' + xml;
//   CannedQuery += '&XSL=' + xsl;

   CannedQuery += '&AC=QBE_QUERY';
   //alert(CannedQuery);
   if(getCookie(cartName)){
      window.location.href = CannedQuery;
      }
   else {
      alert("Your cart is empty. You will be returned to the search page.");
      window.location.href = queryPageURL;
       }
}


//copyright 2000 Inmagic, Inc.
function deleteArrayValue(removeVal,array){


   var arrayLength = array.length;
   var i = 0;
   var j = 0;
   var tempArray = new Array;
   
   while (i < arrayLength) {
      if (array[i] == removeVal){
         i++
         }
      else{
         tempArray[j] = array[i];
         i++;
         j++;
         }     
      }
      return tempArray;
}

function removeIDbtn (id) {

  if(getCookie(cartName)) {
   var idValue = id;
   var cartString = getCookie(cartName);
   var cartArray =  cartString.split('/');
   
   cartArray = deleteArrayValue(idValue,cartArray);
   cookieValue = cartArray.join('/');
   setCookie(cartName,cookieValue,expiration,"/",null,null);
   }
   getRecords(cartName);
}

function parseQuery(strQuery)
{
   var strQuery = unescape(strQuery);
   var arrQuery = strQuery.split('&');
               
   var queryLength = arrQuery.length;
   var searchString = "";
   var i = 0;
   var n = 0;
//alert(queryLength);
   while(i < queryLength)
   {
      if (arrQuery[i].substring(0, 2) == "QI")
      {
         
         if (n > 0)
         {
            searchString += " & ";
         }
         
         var lastChar = arrQuery[i].length;
         searchString += arrQuery[i].substring(4, lastChar);
         alert(searchString);
         n++;
      }
      i++;
   }
 document.qbe_form.QI0.value = searchString;
}


// Checkear si el checkbox esta marcado entonces anadir o eliminar item

function remove (id) {

  if(getCookie(cartName)) {
   var idValue = id;
   var cartString = getCookie(cartName);
   var cartArray =  cartString.split('/');
   
   cartArray = deleteArrayValue(idValue,cartArray);
   cookieValue = cartArray.join('/');
   setCookie(cartName,cookieValue,expiration,"/",null,null);
   }
document.forms[0].cartCount.value = document.forms[0].cartCount.value-1
}

// ****************************************************************************
// -----------------  FUNCIONES CREADAS POR JP --------------------------------
// ****************************************************************************

// ****************************************************************************
// ESTA FUNCION SE INICIA CON LA PAGINA Y SIRVE PARA AUTOCHEKEAR LOS QUE YA
// FUERON SELECCIONADOS Y PARA INICIAR EL CONTADOR SE COLOCA EN EL BODY ONLOAD
// ****************************************************************************
function inicializar(){
	
var index=0 ;
var arrayLength;
var idValueArray = new Array;
var cookieValue = '';
   
 // check for existing cookie and get existing values
   
   if(getCookie(cartName)) {
         cookieValue = getCookie(cartName);
         idValueArray = cookieValue.split('/');
                           }
// AUTOCHECK DE LOS QUE YA EXISTEN
if (document.forms[0].myCheck.length==undefined) {

	if  (checkDup(idValueArray,document.forms[0].myItem.value)==false){
       document.forms[0].myCheck.checked=true ; }

} else {

 for (index=0; index<document.forms[0].myCheck.length; index++) {
	 
  if  (checkDup(idValueArray,document.forms[0].myItem[index].value)==false){
       document.forms[0].myCheck[index].checked=true ;}
                                                                 }
}

// CONTADOR
if(idValueArray.length>=0) {
      document.forms[0].cartCount.value = idValueArray.length;
   } else {
	  document.forms[0].cartCount.value = 0 ;
	   }
}

// ****************************************************************************
// VERIFICAR SI UN ELEMENTO YA FUE SELECCIONADO DE NO SER ASI ENTONCES AGREGAR
// AL CARRITO
// ****************************************************************************
function checkear(item, valor){

if (item.checked) {
 addIDbtn(valor) 
} else {
 remove(valor)
}

}

// Para el Accession List
function getRecordsAccession(cartName){
   var searchString = getCookie(cartName);
   
   var CannedQuery = '/research/training/library/mis_adqselected.asp?';
   CannedQuery += 'codigos=' + searchString;
   
 if(getCookie(cartName)){
      window.location.href = CannedQuery;
      }
   else {
      alert("Your cart is empty. You will be returned to the search page.");
      window.location.href = queryPageURL;
       }

}


function removeIDbtnAccession (id) {

  if(getCookie(cartName)) {
   var idValue = id;
   var cartString = getCookie(cartName);
   var cartArray =  cartString.split('/');
   
   cartArray = deleteArrayValue(idValue,cartArray);
   cookieValue = cartArray.join('/');
   setCookie(cartName,cookieValue,expiration,"/",null,null);
   }
   getRecordsAccession(cartName);
}

// **************************************************************************
// ------------ FIN FUNCIONES CREADAS POR JP -------------------------------- 
// **************************************************************************