/**
 * Checks/unchecks all rows
 *
 * @param   string   the form name
 * @param   boolean  whether to check or to uncheck the element
 * @param   string   basename of the element
 * @param   integer  min element count
 * @param   integer  max element count
 *
 * @return  boolean  always true
 */
// modified 2004-05-08 by Michael Keck <mail_at_michaelkeck_dot_de>
// - set the other checkboxes (if available) too
function setCheckboxesRange(the_form, do_check, basename)
{
  for (var i = 0; i < document.forms[the_form].elements[basename].length; i++) {
        if (typeof(document.forms[the_form].elements[basename][i]) != 'undefined') {
            document.forms[the_form].elements[basename][i].checked = do_check;
        }
/*        if (typeof(document.forms[the_form].elements[basename + i + 'r']) != 'undefined') {
            document.forms[the_form].elements[basename + i + 'r'].checked = do_check;
        }*/
    }

    return true;
} // end of the 'setCheckboxesRange()' function


function setCheckbox(the_form, basename, the_value)
{
    for (var i = 0; i < document.forms[the_form].elements[basename].length; i++) {
        if (typeof(document.forms[the_form].elements[basename][i]) != 'undefined') {
          if (document.forms[the_form].elements[basename][i].value == the_value) {
              document.forms[the_form].elements[basename][i].checked = !document.forms[the_form].elements[basename][i].checked;
      }
        }
/*        if (typeof(document.forms[the_form].elements[basename + i + 'r']) != 'undefined') {
            document.forms[the_form].elements[basename + i + 'r'].checked = do_check;
        }*/
    }

    return true;
} // end of the 'setCheckboxesRange()' function

// added 2004-05-08 by Michael Keck <mail_at_michaelkeck_dot_de>
//   copy the checked from left to right or from right to left
//   so it's easier for users to see, if $cfg['ModifyAtRight']=true, what they've checked ;)
function copyCheckboxesRange(the_form, the_name, the_clicked)
{
    if (typeof(document.forms[the_form].elements[the_name]) != 'undefined' && typeof(document.forms[the_form].elements[the_name + 'r']) != 'undefined') {
        if (the_clicked !== 'r') {
            if (document.forms[the_form].elements[the_name].checked == true) {
                document.forms[the_form].elements[the_name + 'r'].checked = true;
            }else {
                document.forms[the_form].elements[the_name + 'r'].checked = false;
            }
        } else if (the_clicked == 'r') {
            if (document.forms[the_form].elements[the_name + 'r'].checked == true) {
                document.forms[the_form].elements[the_name].checked = true;
            }else {
                document.forms[the_form].elements[the_name].checked = false;
            }
       }
    }
}

/* Función para convertir los querystring  */
function urlencode(sString){
  var re = /[\s\@\+\*\/]/g;
  var aChars = sString.match(re);
  if(aChars){
    for(var i = 0; i < aChars.length; i++){
      sString = sString.replace(aChars[i], "%" + d2h(aChars[i].charCodeAt(0)));
    }
  }
  return sString;
}

/* Función para convertir de decimal a hexadecimal */
function d2h(d) {
var hD="0123456789ABCDEF";
var h = hD.substr(d&15,1);
  while(d>15) {
    d>>=4;
    h=hD.substr(d&15,1)+h;
  }
return h;
}

function otherProduct(oSelect, sHiddenObject){

  if($(oSelect.id).getValue() == '0'){
    $(sHiddenObject).show();
  }
  else{
    $(sHiddenObject).hide();
    $(sHiddenObject).value = "";
  }
}

function specifyOtherWay(oItem){

  if($(oItem).attr('checked'))
  {
    $('#spOtherWay').show('slow');
    $('#spOtherWay').css('opacity', 100);
  }
  else
  {
    $('#spOtherWay').hide('slow');
    $('#spOtherWay').val('');
  }
}

/* Comprueba si un objeto es un arreglo o no */
function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

/* Función para la detección de la posición de objetos en la página */
function getStartPosition(what, offsettype){
var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
var parentEl=what.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

/*
 * Funciones relacionadas al Mapa
 */
function selectComunity(nComunity){

  if(aComunities != "undefined"){
    if(nActiveComunity != nComunity) {
      //nStartX = getStartPosition(document.getElementById("imgSpainMap"), "left");
      //nStartY = getStartPosition(document.getElementById("imgSpainMap"), "top");
      document.getElementById("imgComunityMap").src = aComunities[nComunity][0];
      //document.getElementById("divComunityMap").style.left = nStartX + aComunities[nComunity][1] + "px";
      //document.getElementById("divComunityMap").style.top = nStartY + aComunities[nComunity][2] + "px";
      nTempComunity = nComunity;
      //document.getElementById("imgComunityMap").className = "on";
      document.getElementById("lnkComunity" + nComunity).className = "selected";
      nActiveComunity = nComunity;
    }
  }
}

function unselectComunity(nComunity){

  document.getElementById("imgComunityMap").src = "img/objects/1x1.gif";
  //document.getElementById("imgComunityMap").className = "off";
  if(nComunity != 0)
    document.getElementById("lnkComunity" + nComunity).className = "none";
  nActiveComunity = 0;
}

/* Funciones generales*/
var registrationForm = function (){	xajax_loadRegistration();}
var contactForm = function (){	xajax_loadContact();}
var warrantyForm = function (){	xajax_loadWarranty();}
var postSaleForm = function (){	xajax_loadPostSale();}
var callZoomImage = function (nPhotoId, sPhotoType) { xajax_zoomImage(nPhotoId, sPhotoType);} //alert(nPhotoId + " , " + sPhotoType)
var callRetailerInfo = function(nRetailerId) {xajax_loadRetailer(nRetailerId);}


function getCursorPosition(eventObject) {

    if (isCursorOver) {
      document.myForm.cursorX.value=eventObject.offsetX;
      document.myForm.cursorY.value=eventObject.offsetY;
    }
}

function loadPageCover(oFormFunction)
{
  $('#divPageCover').show("slow", oFormFunction);
}

function unloadPageCover()
{
  $('#divPageCover').hide("slow");
}

function loadForm(oFormFunction){
  loadPageCover(oFormFunction);
}

function unloadForm(){
  document.getElementById("divFormLoader").className = "off";
  unloadPageCover();
}

function closeAlert(){
  document.getElementById("divPageAlert").innerHTML = "";
  document.getElementById("divPageAlert").className = "off";
  unloadPageCover();
}

function closeZoom()
{
  $("#divPageZoom").html("");
  $("#divPageZoom").removeClass("on").addClass("off");
  unloadPageCover();
}

/* Funciones relacionadas con xajax */
xajax.loadingFunction = showLoading;
xajax.doneLoadingFunction = hideLoading;

function showHideLoading(sObject, nShow){
  document.getElementById(sObject).className = (nShow == 1)?'on':'off';
}

function showLoading(){
  //showHideLoading("divFormLoader", 1);
}

function hideLoading(){
  //showHideLoading("divFormLoader", 0);
}

function loadNewsList(sNewsTypeId){
  $('#divNewsContainer').load("inc/ajax_news_list.php", {news_type_id: sNewsTypeId});
  //xajax_loadNewsList(sNewsTypeId);
}
function loadNewsListPag(sNewsTypeId,sIni){
  $('#divNewsContainer').load("inc/news_list.php", {news_type_id: sNewsTypeId,ini: sIni});
  //xajax_loadNewsList(sNewsTypeId);
}

function loadProvinces(nComunityId){
  document.getElementById("tdComunity").innerHTML = aComunities[nComunityId][3];
  //document.getElementById("lnkComunity" + nComunityId).className = "selected";
  xajax_loadProvinces(nComunityId);
}

function loadRetailers(sProvinceId){
  xajax_loadRetailers(sProvinceId);
}

function loadRetailer(nRetailerId){
  loadPageCover(callRetailerInfo(nRetailerId));
}

function loadProductFamily(){
  xajax_loadProductFamily();
}

function selectProductFamily(nNewPFamilyId, nCurrPFamilyId)
{
  if(nCurrPFamilyId != 0)
    $('#pf_list_' + nCurrPFamilyId).hide();

  if($('#pf_list_' + nNewPFamilyId).empty()){
    xajax_loadProductsByFamily(nNewPFamilyId);
  }
  $('#pf_list_' + nNewPFamilyId).show();

  return nNewPFamilyId;
}

function loadMarkManuals(link_id, nMark)
{
  //xajax_loadMarkManuals(nMark);
  jQuery('#divMarkName').html(jQuery('#' + link_id).html());
  jQuery('#tdBody2').load("inc/ajax_manuals.php", {mark_id: nMark});
}

function loadMarkFaqs(nMark)
{
  xajax_loadMarkFaqs(nMark);
}

var submitForm = function(oForm)
{
  if( isValid(oForm.id) )
  {
    xajax_submitForm(Form.serialize(oForm));
  }
  else{
    $('#tdWarning').show();
    document.onclick = hideWarning;
  }
};

function zoomImage(nPhotoId, sPhotoType)
{
  var oPos = $('#divPage').offset();
  $('#divPageCover').css('left', Math.abs(oPos.left) + "px");
  $('#divPageCover').css('top', Math.abs(oPos.top) + "px");
  $('#divPageZoom').css('left', Math.abs(oPos.left) + "px");
  $('#divPageZoom').css('top', Math.abs(oPos.top) + "px");

  loadPageCover(callZoomImage(nPhotoId, sPhotoType));
}

function showMessage(message, top, left)
{
  $('#divMessage').html(message);
  $('#divMessage').css('top', top + 'px');
  $('#divMessage').css('left', left + 'px');
  $('#divMessage').show();
}

function showElementMessage(oElement, sMessage)
{
  $('#divMessage').html(sMessage);
  var oPos = $(oElement).offset();
  var nLeft = oPos.left - $('#divMessage').width();
  var nTop = oPos.top;
  showMessage(sMessage, nTop, nLeft);
}

function hideMessage()
{
  $('#divMessage').html('');
  $('#divMessage').hide();
}

/* Envio y validación de formularios */
function hideWarning()
{
  $('#tdWarning').html('');
  $('#tdWarning').hide();
}


function isValid(sForm){
  switch(sForm){
    case "frmRegistro":
      if($('#fullname').val() == ""){
        $('#tdWarning').html("Error: Debe especificar su nombre");
        $('#fullname').focus();
        return false;
      }
      if(!isEmail($('#email').val())){
        $('#tdWarning').html("Error: Formato de e-mail incorrecto");
        $('#email').focus();
        return false;
      }
    break;
    case "frmPostSale":
      if($('#fullname').val() == ""){
        $('#tdWarning').html("Error: Debe especificar su nombre");
        $('#fullname').focus();
        return false;
      }
      if($('#email_phone').val() == ""){
        $('#tdWarning').html("Error: Debe especificar un e-mail o un teléfono de contacto");
        $('#email_phone').focus();
        return false;
      }
      if($('#model').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el modelo");
        $('#model').focus();
        return false;
      }
      if($('#establishment').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el establecimiento donde adquirio el artículo.");
        $('#establishment').focus();
        return false;
      }
      if($('#comments').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el motivo de la consulta.");
        $('#comments').focus();
        return false;
      }
    break;
    case "frmWarranty":
      if($('#fullname').val() == ""){
        $('#tdWarning').html("Error: Debe especificar su nombre");
        $('#fullname').focus();
        return false;
      }
      if($('#address').val() == ""){
        $('#tdWarning').html("Error: Debe especificar su dirección postal");
        $('#address').focus();
        return false;
      }
      if($('#cp').val() == ""){
        $('#tdWarning').html("Error: Debe especificar su código postal");
        $('#cp').focus();
        return false;
      }
      if($('#city').val() == ""){
        $('#tdWarning').html("Error: Debe especificar su población");
        $('#city').focus();
        return false;
      }
      if($('#article').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el tipo de artículo");
        $('#article').focus();
        return false;
      }
      if($('#model').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el modelo");
        $('#model').focus();
        return false;
      }
      if($('#serial').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el número de serie");
        $('#serial').focus();
        return false;
      }
      if($('#establishment').val() == ""){
        $('#tdWarning').html("Error: Debe especificar el establecimiento donde adquirio el artículo.");
        $('#establishment').focus();
        return false;
      }
    break;
  }

  return true;
}

function addEvent(obj, evType, fn){
 if (obj.addEventListener){
   obj.addEventListener(evType, fn, false);
   return true;
 } else if (obj.attachEvent){
   var r = obj.attachEvent("on"+evType, fn);
   return r;
 } else {
   return false;
 }
}

function toggleNetworkLinks()
{
  //TODO: Estirar todas las columnas
  $('#network_links').toggle();
}

function filterVideos(control_id, container)
{
  $('#'+container).load("inc/ajax_videos_list.php", { control: control_id, value: $('#'+control_id).val() } );
  switch(control_id)
  {
    case 'mark_id':
      $('#pf_id').val(0);
    break;
    case 'pf_id':
      $('#mark_id').val(0);
    break;
  }
}

function showCatalog(mark_id)
{
  var options = "height=600,width=740,channelmode=0,dependent=0,directories=0,fullscreen=0,location=0,menubar=0,resizable=0,scrollbars=1,status=1,toolbar=0";
  window.open('show_catalog.php?mark_id='+mark_id, 'catalog', options);
}

function search(form)
{
  if( $('#search_for').val() != '' )
  {
    form.submit();
  }
}

function fixPageHeight()
{
  var body_height = ( jQuery('td.body').length > 0 ) ? jQuery('td.body').height() : 0;
  var header_height = ( jQuery('div.header').length > 0 ) ? jQuery('div.header').height() : 0;

  if( jQuery('div.left_bar').length > 0 )
  {
    var leftbar_height = jQuery('div.left_bar').height();
    if( leftbar_height < (body_height - header_height) )
    {
      jQuery('div.left_bar').height(jQuery('td.body').height() - jQuery('div.header').height());
    }
  }

  if( jQuery('div.content').length > 0 )
  {
    var content_height = jQuery('div.content').height();
    if( content_height < (body_height - header_height) )
    {
      jQuery('div.content').height(jQuery('td.body').height() - jQuery('div.header').height());
    }
  }

  if( jQuery('div.right_side').length > 0 )
  {
    var rightside_height = jQuery('div.right_side').height();
    if( rightside_height < body_height )
    {
      jQuery('div.right_side').height(jQuery('td.body').height());
    }
  }
}