var isPressed = false;
var alertWaitPageSubmit = "Espera, la pagina se esta cargando!";
function getBrowser(){
  return navigator.appName + navigator.appVersion;
}
function trim(stringa){
  while(stringa.charAt(0)==" ") stringa=stringa.substr(1);
  while(stringa.charAt(stringa.length-1)==" ") stringa=stringa.substr(0, stringa.length-1);
  return stringa;
}
function NumericField(inVal){
  if(inVal.search(/\D/)!=-1){
     return false;
  }else{
     return true;
  }
}
function showHideDiv(divID){
  var theDiv = document.getElementById(divID);
  if(theDiv){
     if((theDiv.style.display=="none") || (theDiv.style.display=="") || (theDiv.style.display=="undefined")){
     	theDiv.style.display="inline";
     }else{
        theDiv.style.display="none";
     }
  }
}
function findOffsetLeft(element){
  return findOffset(element, "offsetLeft");
}
function findOffsetTop(element){
  return findOffset(element, "offsetTop");
}
function findOffset(element, type){
  var os = 0;
  while(element){
      os += element[type];
      element = element.offsetParent;
  }
  return os;
}
function fSubmit(idForm){
  if(isPressed){
     alert(alertWaitPageSubmit);
     return false;
  }else{
     isPressed = true;
  }
  document.getElementById(idForm).submit();
  return true;
}
function fSubmitAction(idForm, inAction){
  if(isPressed){
     alert(alertWaitPageSubmit);
     return false;
  }else{
     isPressed = true;
  }
  document.getElementById(idForm).action=inAction;
  document.getElementById(idForm).submit();
  return true;
}
function fSubmitActionTarget(idForm, inAction, inTarget){
  document.getElementById(idForm).action=inAction;
  document.getElementById(idForm).target=inTarget;
  document.getElementById(idForm).submit();
  return true;
}
function stringToArray(stringa, delim){
  var arrOut = stringa.split(delim);
  return arrOut;
}
function openPop(inURL,inName,inWidth,inHeight){
  re = /&/gi;
  re2 = /\?/gi;
  var theURL = inURL.replace(re,'%26');
  theURL = theURL.replace(re2,'%3F');
  var params = "width="+inWidth+",height="+inHeight+",left=1,top=1,resizable=yes,scrollbars=yes,menubar=yes,toolbar=yes,directories=no,location=no,status=no";
  window.open(theURL,inName,params);
}
function openPopSubmitForm(inURL,inName,inWidth,inHeight,idForm){
  openPop(inURL,inName,inWidth,inHeight);
  document.getElementById(idForm).target=inName;
  document.getElementById(idForm).submit();
}

function medline(p_autor){
  var url = "http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=PureSearch&db=pubmed&details_term="+p_autor+"%5BFull%20Author%20Name%5D";
  window.open(url, "", "");
}

function cita(p_div, p_msg, p_txt1, p_txt2){
	var oDiv = document.getElementById(p_div);
	var oMsg = document.getElementById(p_msg);
	var oTxtMs = document.getElementById(p_txt1);
	var oTxtNs = document.getElementById(p_txt2);
	oDiv.style.display = "block";
	if ( window.clipboardData && clipboardData.setData ) {
		clipboardData.setData("Text", oMsg.innerText);
		oTxtMs.style.display="block";
	} else {
		oTxtNs.style.display="block";
	}
}

function cerrar(p_div){
	var oDiv = document.getElementById(p_div);
	oDiv.style.display = "none";
}

//AJAX-1-FUNC
theFunc="";
function setQueryString(formName){
  queryString="";
  var frm = document.forms[formName];
  var numberElements = frm.elements.length;
  for(var i = 0; i < numberElements; i++)  {
      if(i < numberElements-1)  {
         queryString += frm.elements[i].name+"="+encodeURIComponent(frm.elements[i].value)+"&";
      }else{
         queryString += frm.elements[i].name+"="+encodeURIComponent(frm.elements[i].value);
      }
  }
}
function submitFormAjax(inUrl, outFunc, formName){
  theFunc = outFunc;
  setQueryString(formName);
  if(window.XMLHttpRequest){
     request = new XMLHttpRequest();
  }else if (window.ActiveXObject){
     request=new ActiveXObject("Msxml2.XMLHTTP");
     if(!request){
        request=new ActiveXObject("Microsoft.XMLHTTP");
     }
  }
  if(request){
     request.onreadystatechange=AjaxResponse;
     request.open("POST", inUrl, true);
     request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
     request.send(queryString);
  }
}
function AjaxResponse(){
  if(request.readyState == 4){
    if(request.status == 200){
       if(theFunc=="enviarArticulo"){
       	  setMessageDiv(request.responseText);
       }else if(theFunc=="updateUnidades"){
       	  updateUnidades(request.responseText);
       }else if(theFunc=="contactar"){
       	  setMessageDiv(request.responseText);
       }else if(theFunc=="searchSuggest"){
       	  searchSuggest(request.responseText);
       }else{
         if(request.responseText!=""){
            alert(request.responseText);
         }
       }
    }else{
       //alert("ERRORE JAVASCRIPT");
    }
  }
}
function showHiddenDivEnviar(){
  var divEnviar = document.getElementById("divEnviar");
  if(divEnviar){
     if((divEnviar.style.display=="none") || (divEnviar.style.display=="") || (divEnviar.style.display=="undefined")){
     	divEnviar.style.display="inline";
     }else{
        divEnviar.style.display="none";
     }
  }
  setMessageDiv('');
}
function setMessageDiv(text){
  var theMessageDiv = document.getElementById("theMessageDiv");
  if(theMessageDiv){
     theMessageDiv.innerHTML=text;
  }
}
function delItemsFromCesta(inKey){
  document.getElementById("key").value=inKey;
  if(isPressed){
     alert(alertWaitPageSubmit);
     return false;
  }else{
     isPressed = true;
  }
  document.getElementById("fCesta").action="ctl_servlet?_f=35";
  document.getElementById("fCesta").submit();
}

function updateUnidadesObject(inArray){
  this.vKey = inArray[0];
  this.vPrecio = inArray[1];
  this.vUnidades = inArray[2];
  this.vSubTotal = inArray[3];
  this.vTotal = inArray[4];
  this.vGastos = inArray[5];
  this.vTotalMasGastos = inArray[6];
}

function updateUnidades(resp){
  try{
     //the servlet-output is an array to create a updateUnidadesObject object
     var oArray = eval(resp);
     var oUpdateUnidadesObject = new updateUnidadesObject(oArray);
     var vKey = oUpdateUnidadesObject.vKey;
     var vPrecio = oUpdateUnidadesObject.vPrecio;
     var vUnidades = oUpdateUnidadesObject.vUnidades;
     var vSubTotal = oUpdateUnidadesObject.vSubTotal;
     var vTotal = oUpdateUnidadesObject.vTotal;
     var vGastos = oUpdateUnidadesObject.vGastos;
     var vTotalMasGastos = oUpdateUnidadesObject.vTotalMasGastos;
     //update SubTotal
     document.getElementById("fSubTotal_"+vKey).value = vSubTotal;
     document.getElementById("divSubTotal_"+vKey).innerHTML = vSubTotal;
     //update Total
     document.getElementById("fTotal").value = vTotal;
     document.getElementById("divTotal").innerHTML = vTotal;
     //update Gastos
     document.getElementById("fGastos").value = vGastos;
     document.getElementById("divGastos").innerHTML = vGastos;
     //update TotalMasGastos
     document.getElementById("fTotalMasGastos").value = vTotalMasGastos;
     document.getElementById("divTotalMasGastos").innerHTML = vTotalMasGastos;
  }catch(e){
     alert("ERROR: " + e);
  }
}

function fCestaSubmit(){
  if(isPressed){
     alert(alertWaitPageSubmit);
     return false;
  }else{
     isPressed = true;
  }
  document.getElementById("fCesta").action="ctl_servlet?_f=36&url_after_user_save=38";
  document.getElementById("fCesta").submit();
}

function setListaTarjetaTipo(){
  var idx = document.getElementById("listaTarjetaTipo").selectedIndex;
  var val = document.getElementById("listaTarjetaTipo").options[idx].value;
  var txt = document.getElementById("listaTarjetaTipo").options[idx].text;
  document.getElementById("tarjetaTipo").value=val;
}

var alertNoTarjetaTitular = " - Titular de la Tarjeta\n";
var alertNoTarjetaTipo = " - Tipo Tarjeta\n";
var alertNoTarjetaNumero = " - Numero Tarjeta\n";
var alertNoTarjetaFechaMMYY = " - Caduca final\n";
var alertNoTarjetaSecCode = " - Código de Seguridad\n";

function fPagoSubmit(){
  var alertText = "";
  var comma = ",";
  //Initialize required fields classes
  if((typeof(errorId) != "undefined") && (errorId != "")){
     aErrorId = errorId.split(",");
     for(var i=0; i<=aErrorId.length-1; i++){
         if(aErrorId[i] != ""){
            if(document.getElementById(aErrorId[i]).className=="FieldAlert"){
               document.getElementById(aErrorId[i]).className="FieldRequired";
            }
         }
     }
  }
  errorId = "";
  if(document.getElementById("LabelTarjetaTipo")){
     var tarjetaTipo = document.getElementById("tarjetaTipo").value;
     if((trim(tarjetaTipo)=="") || (trim(tarjetaTipo)=="0")){
        alertText += alertNoTarjetaTipo;
        errorId = errorId + "LabelTarjetaTipo" + comma;
     }
  }
  if(document.getElementById("LabelTarjetaTitular")){
     var tarjetaTitular = document.getElementById("tarjetaTitular").value;
     if(trim(tarjetaTitular)==""){
        alertText += alertNoTarjetaTitular;
        errorId = errorId + "LabelTarjetaTitular" + comma;
     }else if(tarjetaTitular.search(/\d/) != -1){
        alertText += alertNoTarjetaTitular;
        errorId = errorId + "LabelTarjetaTitular" + comma;
     }
  }
  if(document.getElementById("LabelTarjetaNumero")){
     var tarjetaNumero = document.getElementById("tarjetaNumero").value;
     if(trim(tarjetaNumero)==""){
        alertText += alertNoTarjetaNumero;
        errorId = errorId + "LabelTarjetaNumero" + comma;
     //}else if(!(NumericField(tarjetaNumero)){
     }else if(tarjetaNumero.search(/\D/) != -1){
        alertText += alertNoTarjetaNumero;
        errorId = errorId + "LabelTarjetaNumero" + comma;
     }else if(!isCreditCard(tarjetaNumero)){
        alertText += alertNoTarjetaNumero;
        errorId = errorId + "LabelTarjetaNumero" + comma;
     }
  }
  if(document.getElementById("LabelTarjetaFechaMMYY")){
     var tarjetaFechaMM = document.getElementById("tarjetaFechaMM").value;
     var tarjetaFechaYY = document.getElementById("tarjetaFechaYY").value;
     if(!checkExpirationDate(tarjetaFechaMM, tarjetaFechaYY)){
        alertText += alertNoTarjetaFechaMMYY;
        errorId = errorId + "LabelTarjetaFechaMMYY" + comma;
     }     
  }
  if(document.getElementById("LabelTarjetaSecCode")){
     var tarjetaSecCode = document.getElementById("tarjetaSecCode").value;
     if(trim(tarjetaSecCode)!=""){
        if(tarjetaSecCode.search(/\D/) != -1){
           alertText += alertNoTarjetaSecCode;
           errorId = errorId + "LabelTarjetaSecCode" + comma;
        }
     }
  }
  if(alertText!=""){
     alert("Campos obligatorios:\n\n" + alertText);
     if((typeof(errorId) != "undefined") && (errorId != "")){
        aErrorId = errorId.split(",");
        for(var i=0; i<=aErrorId.length-1; i++){
            if(aErrorId[i] != ""){
               if(document.getElementById(aErrorId[i]).className=="FieldRequired"){
                  document.getElementById(aErrorId[i]).className="FieldAlert";
               }
            }
        }
     }
     return false;
  }else{
     if(isPressed){
        alert(alertWaitPageSubmit);
        return false;
     }else{
        isPressed = true;
     }
     document.getElementById("fPago").submit();
     return true;
  }
}
function checkExpirationDate(MM, YY){
  var valida = true;
  if((MM.search(/\D/)!=-1) || (trim(MM)=="") || (trim(MM)=="0") || (trim(MM)=="00")  || (MM.length!=2)){
     valida = false;
  }else{
     MM = MM/1;
  }
  if((YY.search(/\D/)!=-1) || (trim(YY)=="") || (trim(YY)=="0") || (trim(YY)=="00")  || (YY.length!=2)){
     valida = false;
  }else{
     YY = YY/1;
  }
  if(MM<1 || MM>12 || YY<0){
     valida = false;
  }
  return valida;
}
function isCreditCard(CC){                         
  if(CC.length > 19){
     return false;
  }
  sum = 0;
  mul = 1;
  l = CC.length;
  for(i = 0; i < l; i++){
      digit = CC.substring(l-i-1,l-i);
      tproduct = parseInt(digit ,10)*mul;
      if(tproduct >= 10){
         sum += (tproduct % 10) + 1;
      }else{
         sum += tproduct;
      }
      if(mul == 1){
         mul++;
      }else{
         mul--;
      }
  }
  if((sum % 10)==0){
      return true;
  }else{
      return false;
  }
}
//popAlert
function showPopAlert(redir_url, redir_params){
  var all_params = "";
  var array_params = redir_params.split('&');
  for(var i=0; i<=array_params.length-1; i++){
      var param = array_params[i];
      all_params+="&"+param;
  }
  new Ajax.Updater('popAlert', 'plantilla_alert.jsp?redir_url='+redir_url+all_params, {asynchronous:true});
  var elTapun = $('elTapun');
  if(document.body.offsetWidth>1002){
     elTapun.style.width=document.body.offsetWidth;
  }
  if(document.body.scrollHeight>0){
     elTapun.style.height=document.body.scrollHeight;
  }
  elTapun.style.display='inline';
  Element.show('popAlert');
}
