//In caso vengano utilizzati dei log o debug con la console di firebug,
//evita errori in caso firebug non sia installato o estende console in
//modo da essere usato su opera dragonfly
if ( typeof window.loadFirebugConsole == 'function' ) {
  window.loadFirebugConsole();
} else {
  if ( !(window.console && window.console.log) ) {
    if ( window.opera && window.opera.postError ) {
      fConsole = window.opera.postError;
    } else {
      fConsole = function() {};
    }
    window.console = {
      log:    fConsole,
      debug:  fConsole,
      info:   fConsole,
      warn:   fConsole,
      assert: fConsole
    }
  }
}

(function ($) {
  $.fn.vAlign = function() {
    $(this).each(function(i) {
      var ah = $(this).height();
      var ph = $(this).parent().height();
      var mh = parseInt((ph - ah) / 2);
      $(this).css('padding-top', mh+'px');
    });
  };
})(jQuery);

var rv = 9;
var h_div = 0;

if (navigator.appName == 'Microsoft Internet Explorer')
{
  var ua = navigator.userAgent;
  var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
  if (re.exec(ua) != null)
    rv = parseFloat( RegExp.$1 );
}


$(document).ready(function() {

  var slide = '';
  $('#itemBox').after('<ul id="nav">').cycle({
    fx:     'fade',
    speed:  'fast',
    timeout: 0,
    pager:  '#nav',
    pagerAnchorBuilder: function(idx, slide) {
      return '<li><a href="#"><img src="' + slide.src + '" /></a></li>';
    }
  });

  $("#slider").easySlider({
    auto: true,
    continuous: true,
    speed:  500,
    pause:  5000
  });

  $("#dialog_data").css("z-index","99999");
  $(".iframe").css("z-index","1");
  
  $("#dialog_login").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 300,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[1080].substr(0,1).toUpperCase()+lingua[1080].substr(1),
      text: 'Annulla',
      click: function() {
        $(this).dialog('close');
      },
      //text: lingua[420].substr(0,1).toUpperCase()+lingua[420].substr(1),
      text: 'Accedi',
      click: function() {
        if (validateMyLogin())
          $("#my_login").submit();
      }
    }]
  });

  $("#dialog_rescue").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 180,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[1080].substr(0,1).toUpperCase()+lingua[1080].substr(1),
      text: 'Annulla',
      click: function() {
        $(this).dialog('close');
      },
      //text: lingua[1417].substr(0,1).toUpperCase()+lingua[1417].substr(1)
      text: "Recupera",
      click: function() {
        $("#rescue_username_err").hide();
        if (!$("#rescue_username").attr("value")){
          $("#rescue_username_err").fadeIn();
        }else{
          $("#rescue_username_err").fadeOut();
          $("#rescue").submit();
          $(this).dialog('close');
        }
      }
    }]
  });

  $("#dialog_msg_rescue").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 100,
    width: 400,
    modal: true,
    buttons: [{
//      text: lingua[841].substr(0,1).toUpperCase()+lingua[841].substr(1),
      text: 'Ok',
      click: function() {
        if (validateMyRegister())
          $("#dialog_msg_rescue").dialog('close');
      }
    }]
  });

  $("#dialog_data").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 600,
    width: 800,
    modal: true,
    buttons: [{
      //text: lingua[1080].substr(0,1).toUpperCase()+lingua[1080].substr(1),
      text: 'Annulla',
      click: function() {
        $(this).dialog('close');
      },
      //text: lingua[623].substr(0,1).toUpperCase()+lingua[623].substr(1),
      text: 'Modifica',
      click: function() {
        if (validateMyRegister())
          my_register(document.my_registerForm);
      }
    }]
  });

  $("#dialog_msg_data").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 100,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[841].substr(0,1).toUpperCase()+lingua[841].substr(1)
      text: 'Ok',
      click: function() {
        $(this).dialog('close');
      }
    }]
  });

  $("#my_rescue_password").click(function(){
    $("#dialog_rescue").dialog("open");
    return false;
  });

  $("#dialog_login").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 300,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[1080].substr(0,1).toUpperCase()+lingua[1080].substr(1),
      text: 'Annulla',
      click: function() {
        $(this).dialog('close');
      },
      //text: lingua[420].substr(0,1).toUpperCase()+lingua[420].substr(1),
      text: "Accedi",
      click: function() {
        if (validateMyLogin())
          $("#my_login").submit();
      }
    }]
  });

  $("#dialog_rescue").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 180,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[1080].substr(0,1).toUpperCase()+lingua[1080].substr(1),
      text: 'Annulla',
      click: function() {
        $(this).dialog('close');
      },
      //text: lingua[1417].substr(0,1).toUpperCase()+lingua[1417].substr(1)
      text: "Recupera",
      click: function() {
        $("#rescue_username_err").hide();
        if (!$("#rescue_username").attr("value")){
          $("#rescue_username_err").fadeIn();
        }else{
          $("#rescue_username_err").fadeOut();
          $("#rescue").submit();
          $(this).dialog('close');
        }
      }
    }]
  });

  $("#dialog_msg_rescue").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 100,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[841].substr(0,1).toUpperCase()+lingua[841].substr(1),
      text: 'Ok',
      click: function() {
        $(this).dialog('close');
      }
    }]
  });

  $("#dialog_data").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 600,
    width: 800,
    modal: true,
    buttons: [{
      //text: lingua[1080].substr(0,1).toUpperCase()+lingua[1080].substr(1),
      text: 'Annulla',
      click: function() {
        $(this).dialog('close');
      },
      //text: lingua[623].substr(0,1).toUpperCase()+lingua[623].substr(1),
      text: "Modifica",
      click: function() {
        if (validateMyRegister())
          my_register(document.my_registerForm);
      }
    }]
  });

  $("#dialog_msg_data").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 100,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[841].substr(0,1).toUpperCase()+lingua[841].substr(1),
      text: 'Ok',
      click: function() {
        $(this).dialog('close');
      }
    }]
  });

  $("#my_rescue_password").click(function(){
    $("#dialog_rescue").dialog("open");
    return false;
  });

  $(function() {
    $("a[rel='_blank']").attr("target","_blank");
  });
	
  // INIZIO JQUERY CSS FIX & ADJUST
  $('#mainMenu li').find('a').before('<span class="roundLeft"></span>').after('<span class="roundRight"></span>');
  //$('#subMenu li a:last').css('background-image','none');
  $('#subMenu li.current').find('a').before('<span class="roundLeft"></span>').after('<span class="roundRight"></span>');
  $('.topMenu a:first-child').css('background-image','none');
  $('#footer p a:last-child').css('border-right','none');
  //$('.liquid_box.w703').find('.boxInner').before('<span class="w703_top"></span>').after('<span class="w703_bottom"></span>');
  $('.liquid_box.w400').children('.boxInner').before('<span class="w400_top"></span>');
  $('.liquid_box.w600').children('.boxInner').before('<span class="w600_top"></span>');
  $('.liquid_box.w703').children('.boxInner').before('<span class="w703_top"></span>');
  $('.liquid_box.w735').children('.boxInner').before('<span class="w735_top"></span>');
  $('.liquid_box.w223').children('.boxInner').before('<span class="w223_top"></span>');
  $('.liquid_box.w237').children('.boxInner').before('<span class="w237_top"></span>').after('<span class="w237_bottom"></span>');
  $('.liquid_box.w237_bianco').children('.boxInner').before('<span class="w237_bianco_top"></span>').after('<span class="w237_bianco_bottom"></span>');
  $('.liquid_box.w692').children('.boxInner').before('<span class="w692_top"></span>').after('<span class="w692_bottom"></span>');
  $('.liquid_box.w692').children('.boxInner2').before('<span class="w692_top"></span>').after('<span class="w692_bottom"></span>');
  $('.liquid_box.w692_bianco').children('.boxInner').before('<span class="w692_bianco_top"></span>').after('<span class="w692_bianco_bottom"></span>');
  $('.wrapper.w970').children('.boxInner').before('<span class="w970_top"></span>').after('<span class="w970_bottom"></span>');
  $('ul.categorie li:last-child').css('padding-bottom','0px');
  $('.td_distanza p:last-child').css('background-image','none');

  //$('#leftNav, #rightContent').equalHeight();
  //$('#wideContent, #container').equalHeight();
  // FINE JQUERY CSS FIX & ADJUST
	
  // INIZIO FUNZIONI SIDEBAR AFFINA RICERCA
  $('#filterBoxes div ul').hide();
  $('#filterBoxes div:first-child').find('ul').show();
  $('#filterBoxes div:first-child').find('h3').addClass('open')
  $('#filterBoxes div h3').find('a').click(function() {
    $(this).parent().toggleClass('open');
    $(this).parent().parent().find('ul').slideToggle();
    return false
  });
  // FINE FUNZIONI SIDEBAR AFFINA RICERCA
	
  $('p.dettagli').hide();
  $('a#dettagliToggler').click(function() {
    $('p.dettagli').slideToggle();
    return false
  });
	
  $('.just_online_pren a').click(function() {
    $(this).toggleClass('checked');
    return false
  });
	
  // EFFETTI MENU AL CMABIO PAGINA
  $('#mainMenu li a').click(function() {
    $('#subMenu').hide();
    $('#mainMenu li').removeClass('current');
    $(this).parent().addClass('current');
  });

  $("#email_exist_err").addClass("formAlert");

  $("#dialog_email_exist_err").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 140,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[841].substr(0,1).toUpperCase()+lingua[841].substr(1),
      text: 'OK',
      click: function() {
        $(this).dialog('close');
      }
    }]
  });
	
  $("#send_err").addClass("formAlert");

  $("#dialog_send_err").dialog({
    bgiframe: true,
    autoOpen: false,
    height: 140,
    width: 400,
    modal: true,
    buttons: [{
      //text: lingua[841].substr(0,1).toUpperCase()+lingua[841].substr(1),
      text: 'OK',
      click: function() {
        $(this).dialog('close');
      }
    }]
  });

  $("#box-claim-font").vAlign();

  $('.corner').corner("round 8px").parent().css('padding', '1px').corner("round 10px");
  $('.menu_corner').corner("top round 3px").parent().css('padding', '1px 1px 0 1px').corner("top round 5px");
  $('.corner-orange').corner("round 8px").parent().css('padding', '0px').corner("round 10px");
  $('.corner-orange-home').corner("round 8px").parent().css('padding', '22px').corner("round 10px")
  $('.special-red-liquid-box').corner("round 8px").parent().css({
    'padding': '1px',
    'background-color': '#000000'
  }).corner("round 10px");
  ;
  
  if (rv > 7) {
    var h_spalla = $('#spalla_destra_2').outerHeight() + 7 + $('#spalla_destra_1').outerHeight();
    var h_corpo = $('#content').outerHeight();
      
    if(h_spalla > h_corpo) {
      h_coprente = h_spalla;
      h_div = h_spalla - h_corpo;
    } else {
      h_coprente = h_corpo;
    }

//    $('#coprente_ricerca').css({
//      width: '100%',
//      height: h_coprente+6+$('#box_fornitori').height()+'px',
//      position: 'absolute',
//      top: 219,
//      left: 0,
//      backgroundColor: '#555555',
//      opacity: 0.6,
//      'z-index': 100
//    });
//    $('#coprente_ricerca').addClass('coprente_ricerca');

    

    $('#altezza_pagina').css({
      'height': h_div +'px'
    });

    $('.z-index200-1').css('z-index', 200);
    $('.z-index200').css('z-index', 200);

  }

  $('#subMenu li').each( function() {
    $(this).mouseenter( function () {
      me = $(this);
      me.find('a.nonselezionato').each( function() {
        $(this).css({
          'background-image': 'url('+$(this).attr('srcnormale')+')'
        });
        me.css('padding-top', '9px');
      });
    });
    $(this).mouseleave( function () {
      me = $(this);
      me.find('a.nonselezionato').each( function() {
        $(this).css({
          'background-image': 'url('+$(this).attr('srcopaco')+')'
        });
        me.css('padding-top', '0');
      });
    });
  });
});
        
$('.img_slide').each(function(){
  width = $(this).outerWidth();
  height = $(this).outerHeight();
  new_height = Math.round(height * ( 80 / width ));
  $(this).css('height', new_height+'px');
  $(this).css('width', '80px');
});


function isValidEmail(email){
  var expr = /^[_a-z0-9+-]+(\.[_a-z0-9+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)+$/;
  if (!expr.test(email))
  {
    return false;
  }
  return true;
}

function isTelefono(tel){
  var expr = /^[_0-9 +-]+$/;
  if (!expr.test(tel))
  {
    return false;
  }
  return true;
}

function isCap(cap){
  var expr = /^[_0-9+-][_0-9+-][_0-9+-][_0-9+-][_0-9+-]$/;
  if (!expr.test(cap))
  {
    return false;
  }
  return true;
}
// imposta il cookie sNome = sValore
// per la durata di iGiorni
function setCookie(sNome, sValore, iGiorni) {
  var dtOggi = new Date()
  var dtExpires = new Date()
  dtExpires.setTime
  (dtOggi.getTime() + 24 * iGiorni * 3600000)
  document.cookie = sNome + "=" + escape(sValore) +
  "; expires=" + dtExpires.toGMTString();
}

// restituisce il valore del cookie sNome
function getCookie(sNome) {
  // genera un array di coppie "Nome = Valore"
  // NOTA: i cookies sono separati da ';'
  var asCookies = document.cookie.split("; ");
  // ciclo su tutti i cookies
  for (var iCnt = 0; iCnt < asCookies.length; iCnt++)
  {
    // leggo singolo cookie "Nome = Valore"
    var asCookie = asCookies[iCnt].split("=");
    if (sNome == asCookie[0]) {
      return (unescape(asCookie[1]));
    }
  }

  // SE non esiste il cookie richiesto
  return("");
}

// rimuove un cookie
function delCookie(sNome) {
  setCookie(sNome, "");
}
function GetXmlHttpObject(){
  var objXMLHttp=null

  if (window.XMLHttpRequest){
    objXMLHttp=new XMLHttpRequest();
  }else if (window.ActiveXObject){
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
  }
  return objXMLHttp;
}

function makePOSTRequest(url, parameters, type) {
  http_request = false;
  http_request=GetXmlHttpObject();
  if (http_request==null){
    alert ("Browser does not support HTTP Request");
    return false;
  }
  if (type == "register")
    http_request.onreadystatechange = alertContentsRegister;

  if (type == "rescue")
    http_request.onreadystatechange = alertContentsRescue;

  if (type == "update")
    http_request.onreadystatechange = alertContentsUpdate;

  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.send(parameters);
}

function alertContentsRegister() {
  if (http_request.readyState == 4 || http_request.readyState=="complete") {
    if (http_request.status == 200) {
      result=http_request.responseText;
      if (result){
        //success = result.getElementsByTagName("success")[0].childNodes[0].nodeValue;
        success = $(result).find("success").text();
        if (success == 1){
          //$("#id_cliente").attr("value", result.getElementsByTagName("id_cliente")[0].childNodes[0].nodeValue);
          $("#id_cliente").attr("value", $(result).find("id_cliente").text());
          $("#username").attr("value", $(result).find("username").text());
          $("#password").attr("value", $(result).find("password").text());
          $("#login").submit();
        //$("#dialog_conferma_prenotazione").dialog("open");
        }else{
          //if (success == "CAPTCHA_ERR"){
          //	$("#dialog_captcha_err").dialog("open");
          //}else{
          if (success == "SEND_ERR"){
            $("#dialog_send_err").dialog("open");
          }else{
            if (success == "EMAIL_EXIST"){
              $("#dialog_email_exist_err").dialog("open");
            }else{
              $("#dialog_registrazione_fallita").dialog("open");
            }
          }
        //}
        }
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
}

function alertContentsRescue() {
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
      result=http_request.responseText;
      $("#msg_rescue").html(result);
      $("#dialog_msg_rescue").dialog("open");
    } else {
      alert('There was a problem with the request.');
    }
  }
}

function alertContentsUpdate() {
  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
      result=http_request.responseText;
      $("#msg_data").html(result);
      $("#dialog_data").dialog("close");
      $("#dialog_msg_data").dialog("open");
    } else {
      alert('There was a problem with the request.');
    }
  }
}


// IWS AJAX LIB
function createXMLHttpRequest()
{
  var ua;
  if(window.XMLHttpRequest)
  {
    try
    {
      ua = new XMLHttpRequest();
    }
    catch(e)
    {
      ua = false;
    }
  }
  else if (window.ActiveXObject)
  {
    try
    {
      ua = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e)
    {
      ua = false;
    }
  }
  return ua;
}

var req = createXMLHttpRequest();
var divID = "testdiv";

function sendRequest(_url, _divID)
{
  var chpar = '';
  divID = _divID;
  if (_url.indexOf('?')!=-1)
  {
    chpar = '&';
  }
  else
  {
    chpar = '?';
  }
  req.open('post', _url+chpar+"rand="+escape(Math.random()));
  req.onreadystatechange = handleResponse;
  req.send(null);
}

function sendShadowBoxRequest(_url, _divID)
{
  var chpar = '';
  divID = _divID;
  if (_url.indexOf('?')!=-1)
  {
    chpar = '&';
  }
  else
  {
    chpar = '?';
  }
  Shadowbox.setup();
  req.open('post', _url+chpar+"rand="+escape(Math.random()));
  req.onreadystatechange = handleResponse;
  req.send(null);
}

function handleResponse()
{
  if(req.readyState == 4)
  {
    var response = req.responseText;
    var update = new Array();
    var search = req.responseText;
    if(response.indexOf('||' != -1))
    {
      update = response.split('||');

      while( script = search.match(/(<script>)/i)) //[^>]+javascript[^>]+>\s)/i))
      {
        search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length);

        if (!(endscript = search.match(/(<\/script>)/i))) break;

        block = search.substr(0, search.indexOf(RegExp.$1));
        search = search.substring(block.length + RegExp.$1.length);

        eval(block);
      }
      document.getElementById(divID).innerHTML = req.responseText;
    }
  }
  else
  {
    strloading = "Loading (";
    switch (req.readyState)
    {
      case 1:
        strloading = strloading + "25%)";
        break;
      case 2:
        strloading = strloading + "50%)";
        break;
      case 3:
        strloading = strloading + "75%)";
        break;
      default:
        strloading = "Loading ...";
        break;
    }
    val2 = getElementsByClassName(document, "div", divID);
  //document.getElementById("testdiv").innerHTML = strloading;

  }
}

function getElementsByClassName(oElm, strTagName, strClassName)
{
  var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
  var arrReturnElements = new Array();
  strClassName = strClassName.replace(/\-/g, "\\-");
  var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  var oElement;
  for(var i=0; i<arrElements.length; i++)
  {
    oElement = arrElements[i];
    if(oRegExp.test(oElement.className))
    {
      arrReturnElements.push(oElement);
    }
  }
  return (arrReturnElements)
};


//Create the tinoleggio namespace, if doesn't exist
if ( typeof $.ui.tinoleggio == 'undefined' ) {
  $.tinoleggio = {};
}

$.widget("ui.resultBox", {
  // default options

  options1: {
    elements: {
      table:  '.resultsHolder .results'
    }
  },

  _init: function() {
    this.startResultFetch();
  },

  startResultFetch: function() {
    var self = this;
    $(this).everyTime( this.options.fetchWaitTime, 'resultFetch', function () {
      $.post( 'ajax/getArticlesCount.php',
      {
        sessionId: self.options.sessionId,
        lastCreationTime: self.options.lastCreationTime,
        q: self.options.q
      },
      function( data ){

        if ( typeof data.result != 'object' )
        {
          //There must be some kind of error, let's block the fetch
          self.stopResultFetch();
          self.options.onResult( {
            searchStatus: {
              isComplete: true
            }
          } );
          return;
        }

        var result = data.result;

        if ( result.newResults ) {
          self.options.lastCreationTime = result.lastCreationTime;
          self.options.resultCount = result.articleCount;
          $(self.element).find('#resultsHolder').html( result.resultTable );
          $(self.element).find('#resultCount').html( self.options.resultCount );
          $(self.element).find('#pager').html( result.pager );
        }

        //Call the optional callback
        self.options.onResult( result );

        //The search is finished, let's stop the process
        if ( result.searchStatus.isComplete ) {
          self.stopResultFetch();
        }
        if(result.zeroResults) {
          $(self.element).find('#resultsHolder').html( '<div style="width:720px; text-align:center"><p><font class="msg_err"><br><br><br><br><br><br>'+result.zeroResults+'</font></p></div>' );
        }
      }
      ,'json'
      );
    });
  },

  stopResultFetch: function() {
    $(this).stopTime( 'resultFetch' );
  },

  resultFetch: function() {

  }
});

$.ui.resultBox.defaults = {
  resultCount: 0,
  lastCreationTime: 0,
  fetchWaitTime: 1000,
  q: '',
  onResult: function(result) {},
  sessionId: ''
};

