function svuotaCampo(campo, rimpiazza) {
	$(campo).click(function(){
		var value = $(this).val();
		if(value == rimpiazza) {
			$(this).val("");
		}
	});
	$(campo).blur(function(){
		var value = $(this).val();
		if((value == "") && rimpiazza != "" ) {
			$(this).val(rimpiazza);
		}
	});
}

jQuery.fn.extend({

getUrlParam: function(strParamName){
	  strParamName = escape(unescape(strParamName));

	  var returnVal = new Array();
	  var qString = null;

	  if ($(this).attr("nodeName")=="#document") {
	  	//document-handler

		if (window.location.search.search(strParamName) > -1 ){

			qString = window.location.search.substr(1,window.location.search.length).split("&");
		}

	  } else if ($(this).attr("src")!="undefined") {

	  	var strHref = $(this).attr("src")
	  	if ( strHref.indexOf("?") > -1 ){
	    	var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	  		qString = strQueryString.split("&");
	  	}
	  } else if ($(this).attr("href")!="undefined") {

	  	var strHref = $(this).attr("href")
	  	if ( strHref.indexOf("?") > -1 ){
	    	var strQueryString = strHref.substr(strHref.indexOf("?")+1);
	  		qString = strQueryString.split("&");
	  	}
	  } else {
	  	return null;
	  }


	  if (qString==null) return null;


	  for (var i=0;i<qString.length; i++){
			if (escape(unescape(qString[i].split("=")[0])) == strParamName){
				returnVal.push(qString[i].split("=")[1]);
			}

	  }


	  if (returnVal.length==0) return null;
	  else if (returnVal.length==1) return returnVal[0];
	  else return returnVal;
	}
});

//==========================================
// A J A X
//==========================================

// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address

// when set to true, display detailed error messages
var showErrors = false;
// initialize the validation requests cache
var cache = new Array();

// creates an XMLHttpRequest instance
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 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) {} // ignore potential error
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    displayError("Error creating the XMLHttpRequest object.");
  else
    return xmlHttp;
}

// function that displays an error message
function displayError($message)
{
  // ignore errors if showErrors is false
  if (showErrors)
  {
    // turn error displaying Off
    showErrors = false;
    // display error message

    alert("Error encountered: \n" + $message);
    // retry validation after 10 seconds
    setTimeout("validate();", 10000);
  }
}

// the function handles the validation for any form field
function validate(inputValue, fieldID, fieldArray, serverAddress)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // if we received non-null parameters, we add them to cache in the
    // form of the query string to be sent to the server for validation
    if (fieldID)
    {
      // encode values for safely adding them to an HTTP request query string
      inputValue = encodeURIComponent(inputValue);
      fieldID = encodeURIComponent(fieldID);
      fieldArray = encodeURIComponent(fieldArray);
      // add the values to the queue
      cache.push(fieldID+"=" + inputValue + "&fieldArray=" + fieldArray);
    }
    // try to connect to the server
    try
    {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
         && cache.length > 0)
      {
        // get a new set of parameters from the cache
        var cacheEntry = cache.shift();
        // make a server request to validate the extracted data
        xmlHttp.open("POST", serverAddress, true);
        xmlHttp.setRequestHeader("Content-Type",
                                 "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleRequestStateChange;
        xmlHttp.send(cacheEntry);
      }
    }
    catch (e)
    {
      // display an error when failing to connect to the server
      displayError(e.toString());
    }
  }
}

// function that handles the HTTP response
function handleRequestStateChange()
{
  // when readyState is 4, we read the server response
  if (xmlHttp.readyState == 4)
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200)
    {
      try
      {
        // read the response from the server
        readResponse();
      }
      catch(e)

      {
        // display error message
        displayError(e.toString());
      }
    }
    else
    {
      // display error message
      displayError(xmlHttp.statusText);
    }
  }
}

// read server's response
function readResponse(){

  // retrieve the server's response
  var response = xmlHttp.responseText;
  // server error?
  if (response.indexOf("ERRNO") >= 0
      || response.indexOf("error:") >= 0
      || response.length == 0)
    throw(response.length == 0 ? "Server error." : response);
  // get response in XML format (assume the response is valid XML)
  responseXml = xmlHttp.responseXML;
  // get the document element
  xmlDoc = responseXml.documentElement;
  var result = xmlDoc.getElementsByTagName("errInt")[0].firstChild.data;
  var fieldID = xmlDoc.getElementsByTagName("field")[0].firstChild.data;
  var errorMsg = xmlDoc.getElementsByTagName("errMsg")[0].firstChild.data;

  if(xmlDoc.getElementsByTagName("jSelect")[0]){

  	leng = xmlDoc.getElementsByTagName("jSelect")[0].childNodes.length;
  	mySelect = xmlDoc.getElementsByTagName("jSelect")[0].getAttribute("id");
  	opt = "";
	for(i=0; i<leng; i++) {
		var myVa = xmlDoc.getElementsByTagName("myOpt")[i].childNodes[0].nodeValue;
		var myId = xmlDoc.getElementsByTagName("myOpt")[i].getAttribute("id");
		opt += "<option value='"+myId+"'>"+myVa+"</option>";
	}
	//alert(opt);
	$("#"+mySelect).html(opt);
  }

  if(xmlDoc.getElementsByTagName("jTags")[0]) {
  	var jTags = xmlDoc.getElementsByTagName("jTags");
  	lgt = jTags.length;
  	for(i=0; i<=lgt; i++) {
		var jFunct = jTags[0].getElementsByTagName("jQuery")[i].firstChild.data;
		var jElement =jTags[0].getElementsByTagName("element")[i].firstChild.data;
		var jValue = jTags[0].getElementsByTagName("value")[i].firstChild.data;
		switch(jFunct) {
			case "html" :
				$(jElement).html(jValue);
				break;
			case "addClass" :
				$(jElement).addClass(jValue);
				break;
			case "removeClass" :
				$(jElement).removeClass(jValue);
				break;
			case "removeAttr" :
				$(jElement).removeAttr(jValue);
				break;
		}
	}

  }

  // find the HTML element that displays the error
  message = document.getElementById(fieldID + "_msg");
  fieldLabel = document.getElementById(fieldID + "_lbl");
  tooltip = document.getElementById(fieldID + "_tt");
  // show the error or hide the error
  //fieldLabel.className = (result == "1") ? "frmLabel labelErr" : "frmLabel";
  //tooltip.className = (result == "1") ? "toolhelp toolErr" : "toolhelp";
  if(result == "1"){
	fieldLabel.className = "frmLabel labelErr";
	tooltip.className = "toolhelp toolErr";
	message.className = "error";
	message.innerHTML = errorMsg;
  } else if(result == "0") {
	fieldLabel.className = "frmLabel";
	tooltip.className = "toolhelp toolOk";
	message.className = "hidden";
	message.innerHTML = "";
  }	else {
	fieldLabel.className = "frmLabel";
	tooltip.className = "toolhelp";
	message.className = "hidden";
  }
  //message.className = (result >= "1") ? "error" : "hidden";
  //message.innerHTML = errorMsg;
  // call validate() again, in case there are values left in the cache
  setTimeout("validate();", 500);
}

	$(function() {
		$("#tabs").tabs();
	});

//==========================================
// ...A DOCUMENTO PRONTO...
//==========================================

$(document).ready(function(){

	$('.debugHead').click(function() {
		$(this).next().slideToggle('fast');
		return false;
	}).next().hide();

	$('#dbgMax').click(function() {
		var hScreen = $(window).height() - 20;
		$('#debug, .ui-tabs .ui-tabs-panel').height(hScreen);
	});
	$('#dbgMin').click(function() {
		$('#debug, .ui-tabs .ui-tabs-panel').height(300);
	});
	$('#dbgClo').click(function() {
		$('#debug, .ui-tabs .ui-tabs-panel').height(0);
	});

	// ACCORDION BOX NOTIZIE
	// ===================

	$(".silverheader").accordion({
		event: "mouseover",
		animated: 'slow',
		active: false
	});

	// SVUOTA CAMPI
	// ===========================

	svuotaCampo("#fld1", "ricerca testuale");
	svuotaCampo(".popNl #mail", "la tua email");
	svuotaCampo(".boxNl #nl-mail", "inserisci la tua e-mail");
	svuotaCampo(".boxNl #quantita", "numero annunci");


	// PANNELLO AD APERTURA SLIDE
	// ==========================

	/*$("#panel").slideToggle(2000);
	var jolSitoWeb		= $("a:contains('Sito web')");
	jolSitoWeb.attr("target","_blank");*/

	// PANNELLO SLIDE A SCOMPARSA
	if($(document).getUrlParam("frm")) {
		if(document.location.hash.indexOf('#&v') == -1) {
			alertValue 	= $(document).getUrlParam("frm");
			$("p.close a").click(function(){
				$('#alertPanel').slideUp("slow");
			});
			$(document).keypress(function(e) {
				if (e.keyCode == 27) {
					$('#alertPanel').slideUp("slow");
				}
			});
			$('#alertPanel').slideDown("slow");
			window.location.hash = "&v";
			if($(document).getUrlParam("time") && $(document).getUrlParam("time") > 0) {
				time = $(document).getUrlParam("time") * 1000;
				setTimeout(function() {
					$('#alertPanel').slideUp("slow");
				}, time);
			}
		}
	}

	// PANNELLO POPUP
	// ==========================

	if($(document).getUrlParam("pop")) {
		if(document.location.hash.indexOf('#&v') == -1) {
			alertValue 	= $(document).getUrlParam("pop");
			$(".pTitle a, .pClose a").click(function(){
				$('#popUp').fadeOut("slow");
			});
			$(document).keypress(function(e) {
				if (e.keyCode == 27) {
					$('#popUp').fadeOut("slow");
				}
			});
			$('#popUp').fadeIn("slow");
 			window.location.hash = "&v";
			if($(document).getUrlParam("time") && $(document).getUrlParam("time") > 0) {
				time = $(document).getUrlParam("time") * 1000;
				setTimeout(function() {
					$('#popUp').fadeOut("slow");
				}, time);
			}
		}
	}

	// ===================
	// INDICE DELLE PAGINE

	$('#draggable p').draggable({ containment: 'parent', axis: 'x'});
	var ni = 0;
	$('.index p').hover(function(){
		if(ni == 0) {
			$('.alertIndex span').fadeIn(300);
			setTimeout(function() {
				$('.alertIndex span').fadeOut(4000);
			}, 3000);
			ni++;
		}
	});

	// ===================
	// SUBMENU DI CANALE

	$("ul#navigation > li").hover(function() { //Hover over event on list item
		if(!$('a',this).hasClass('act')) {
			$("ul#navigation > li > a.act").css('background',"none");
			$("ul#navigation > li > a.act").parent().find('ul').hide();
		}
		$('a',this).css({ 'background' : 'transparent url(/0-HTML/pic/tribianco.gif) center 53px no-repeat'});
		$(this).find("ul").show();
	} , function() { //on hover out...
			$('a',this).css({ 'background' : 'none'}); //Ditch the background
			$(this).find("ul").hide(); //Hide the subnav
			$("ul#navigation > li > a.act").css('background',"transparent url('/0-HTML/pic/tribianco.gif') center 53px no-repeat");
			$("ul#navigation > li > ul.subactive").show();
	});

	// ===================
	// MAPPA DEL SITO
	var i = 1
	$('#sitemap').click(function(){
		if((i%2)) {
			$('.footer-menu').css('display', 'none');
			$('.sitemap-menu').css('display', 'block');
			$(this).html('Chiudi mappa');
		} else {
			$('.sitemap-menu').css('display', 'none');
			$('.footer-menu').css('display', 'block');
			$(this).html('Mappa del sito');
		}
		i++;
	});

	// ===================
	// TOOLTIPS

	$('.icoHelp, .toolhelp').tooltip({
		fixPng: true,
		delay: 500,
		showURL: false,
		showBody: " - ",
		opacity: 0.85,
		top: -15,
		fade: 250,
		track: true
	});

	// div diverso destinatario su shop
	/*if ($('#spStessi').attr('checked')) {
		$('#hideIt').hide();
	} else {
		$('#hideIt').show();
	}*/

	$('#alertPanel').bgiframe();
	$('#popUp').bgiframe();
	$('.aButton').corner("5px");
	$('#tooltip').corner("5px");
	$('.pMsg').corner("5px");
	$('.icoHelp p').corner("5px");
	$('.pTitle').corner("5px");

	/// ===================
	/// LJ AJAX FORMS

	// offerta speciale aziende, n° annunci
	$('#quantita').keyup(function(){
		//alert($('#quantita').val());
		var qty = $('#quantita').val();
		$('#qannunci').val(qty);
	});

	$(":input").blur(function(){
		var myForm = $(this).parents('form:first');
		var serverAddress = myForm.attr("action").replace(/\?validation=php/, "");
		var fieldArray = $(":input").serialize();
		switch(this.type) {
			case "checkbox" :
				var myValue = this.checked;
			break;
			default :
				var myValue = this.value;
			break;
		}
		validate(myValue, this.id, fieldArray, serverAddress);
	});

	$(":input[alt|=change]").change(function(){
		var serverAddress = $(this).attr("alt").replace("change-", "");
		var fieldArray = $(":input").serialize();
		switch(this.type) {
			case "checkbox" :
				var myValue = this.checked;
			break;
			default :
				var myValue = this.value;
			break;
		}
		validate(myValue, this.id, fieldArray, serverAddress);
	});

	$(":input[alt|=keyup]").keyup(function(){
		var myForm = $(this).parents('form:first');
		$(myForm).keypress(function(event) {
  			if (event.which == '13') {
     			event.preventDefault();
   			}
   		});
		var serverAddress = $(this).attr("alt").replace("keyup-", "");
		var fieldArray = $(":input").serialize();
		var myValue = $(this).val();
		if(myValue == "") {
			myValue = 0;
		}
			validate(myValue, this.id, fieldArray, serverAddress);
	});

});
