/*
 *
 */
function resetForm(id) {
	$('#'+id).each(function(){
		this.reset();
	});
}
$(document).ready(function() {

	$('input:submit').button();
	$('a.button').button();

	if ($('.noStyleAndSubmit').length > 0) {
		$('.noStyleAndSubmit').each(function() {
			var form = $(this).parents('form');
			$(this).click(function() {
				form.submit();
				return false;
			});
		});
	}
	if ($('.noStyleAndReset').length > 0) {
		$('.noStyleAndReset').each(function() {
			var form = $(this).parents('form');
			$(this).click(function() {
				resetForm(form.attr('id'));
				return false;
			});
		});
	}

	// Inizialize GoogleMap -> googleMap.js
	if ($(".menuTabs").size() > 0) {
		initialize();
	};

	// gestione custom SELECT
	/*
	$("#immobile").selectbox();	
	$("#regione").selectbox();
	$("#provincia").selectbox();
	$("#comune").selectbox();	
	*/
	
	// gestione barra STAGE
	if ($("#iStage").length > 0) {
		var hStage  = $("#iStage").height();
		var cssBt   = { position: "absolute"
					  , display: "none"
					  , top: hStage + "px"
					  , left: "22px"
					  , cursor: "pointer"
					  };
		var cssTxt  = { position: "absolute"
					  , display: "none"
					  , top: hStage + "px"
					  , left: "50px"
					  , fontSize: "9px"
					  };
		var imgOut  = '/skinAdmin/entigo/widgets/ico-stage.gif';
		var imgOver = '/skinAdmin/entigo/widgets/ico-stage2.gif';
		var htmlImg = '<img src="' + imgOut + '" width="20" height="14" alt="apri/chiudi stage" id="btStage" />';
		var htmlTxt = '<p id="btStageTxt">&lt; Barra di stage</p>';

		$("#iStage").css("top", "-" + hStage + "px");
		$(".iStageDx").after(htmlImg);
		$("#btStage").css(cssBt).fadeIn("slow");
		$(".iStageDx").after(htmlTxt);
		$("#btStageTxt").css(cssTxt).fadeIn(500).fadeOut(2000);

		$("#btStage").click(function() {
			if ($("#iStage").css("top") == '0px') {
				$("#iStage").animate({top: "-" + hStage + "px"}, 500);
				$(this).attr("src", imgOut);
			} else {
				$("#iStage").animate({top: "0px"}, 300);
				$(this).attr("src", imgOver);
			}
		});
	};
	
	 /* TEST SELECT 
	$('#regione').change(function() {
		var aaa = $('#regione').text();
		var bbb = $('#regione option:selected').val();
		alert('select opt regione: ' + aaa);
		alert('selected regione: ' + bbb);
	})
	$('#provincia').change(function() {
		var ccc = $('#provincia').text();
		var ddd = $('#provincia option:selected').val();
		alert('select opt provincia: ' + ccc);
		alert('selected provincia: ' + ddd);
	})
	*/
	
	// gestione popolamento select
	$('#regione').change(function() {
		provinciaDynamic();
	})
	if ($('#regione option:selected').val()) {
		provinciaDynamic();
	};	
	$('#provincia').change(function() {
		comuneDynamic();
	})
	if ($('#provincia option:selected').val()) {
		comuneDynamic();
	};
	
	// gestione background voci lista immobili
	/*$(".voceLista").each(function() {
		$(this).mouseover(function() {
			//$(this).css('background-color','#fafafa').fade();
			$(this).fadeTo(100, 1);
		});
		$(this).mouseout(function() {
			//$(this).css('background-color','#ffffff');
			$(this).fadeTo(100, 0.8);
		});
	});*/
	
	// gestione TABS dettaglio Immobili
	if ($(".menuTabs").length > 0) {	
		// chiudo tutti i tab
		$(".datiScheda").each(function (i) {
			$(this).hide();
		});
		
		if ($("p.txtError").length > 0) {
			// apro il form
			var toOpen = $(".datiScheda:last");
			$(toOpen).fadeIn('slow');
			var toCurrent = $(".menuTabs li:last");
			$(toCurrent).addClass("current");
		} else if ($(".sendOk").length > 0) {
			// apro il form
			var toOpen = $(".datiScheda:last");
			$(toOpen).fadeIn('slow');
			var toCurrent = $(".menuTabs li:last");
			$(toCurrent).addClass("current");
			$(".sendOk").each(function() {
				$(this).hide();
				$(this).fadeIn(2000);
			});
		} else {
			// apro il primo
			var toOpen = $(".datiScheda:first");
			$(toOpen).fadeIn('slow');
			var toCurrent = $(".menuTabs li:first");
			$(toCurrent).addClass("current");
		}
		
		// click sul tab
		$(".menuTabs a").click(function (i) {
			$(".menuTabs li").removeClass("current");
			var parentTag = $(this).parent().get(0);
			$(parentTag).addClass("current");			
			$(".datiScheda").each(function (i) {
				$(this).hide();
			});
			var title = $(this).attr("class");
			$(".datiScheda."+title).each(function (i) {
				$(this).fadeIn('slow');
			});
		});
		
		// click su dati->contattaci
		$(".foto a.contattaci").click(function (i) {
			$(".menuTabs li").removeClass("current");
			var parentTag = $(".menuTabs li a.tab4").parent().get(0);
			$(parentTag).addClass("current");	
			$(".datiScheda").each(function (i) {
				$(this).hide();
			});
			//var title = $(this).attr("class");
			var title = "tab4";
			$(".datiScheda."+title).each(function (i) {
				$(this).fadeIn("slow");
			});
		});
		
	};
	
		// lightbox img gallery
	if ($(".lightbox").length > 0) {
		$(".lightbox").lightbox();		
		//$(".lightbox").lightBox({fixedNavigation:true});
	}
	
	// gestione IMG HOVER
	$(".mouseOver").each(function() {
		var src = $(this).attr('src');
		var extension = src.substring(src.lastIndexOf('.'),src.length);
		$(this).mouseover(function() {
			$(this).attr('src',src.replace(extension,'-on' + extension));
		});
		$(this).mouseout(function() {
			$(this).attr('src',src);
		});
	});
	
	// gestione showError form
	$(".showError").each(function() {
		var href = $(this).attr('href');
		var href = href.replace('#', '');
		$(this).click(function() {
			$("label[for='" + href + "']").css("background","#ffffcc").css("color","#ff0000");
			return false;
		});
	});
	
	// gestione righe news
	/*$(".news li").each(function() {
		alert($(this).children().attr('id'));
		$(this).children().css('color', '#000000').css('opacity', '0.7');
		$(this).mouseover(function (i) {
			//$(this).children().fadeTo("slow", 1);
			$(this).children().animate({opacity: "1"}, 250).animate({opacity: "0.7"}, 1000).stop();
		});
	});*/
	
	// gestione messaggio ok
	/*$(".sendOk").each(function() {
		var txtColor = $(this).css('color');
		$(this).hide();
		$(this).fadeIn(2000);
	});	*/
	
	// gestione mappa interattiva homepage
	/*if ($("#mappaHome").length > 0) {
		$(function() {
			$("#mappaHome").maphilight();
		});
		$("area").each(function() {
			var regione = $(this).attr('alt');
			/*
			$(this).mouseover(function() {
				$(".regione").text(regione).fadeIn();
			});
			$(this).mouseout(function() {				
				$(".regione").hide();
			});
			*/
	/*
			$(this).click(function() {
				if ($('#regione option[value=' + regione + ']').text()) {
					var toSelect = $('#regione option[value=' + regione + ']').attr('selected', 'selected');
					$('#regione').change();					
					$('#ricerca').before('<p>Loading data...</p>').fadeOut().submit();
					return false;
				} else {
					var toSelect = $('#regione option[value=""]').attr('selected', 'selected');
					$('#regione').change();
				};
			});
		});
	};*/
	
	// gestione mappa interattiva
	if ($("map").attr("id") == "mappa") {
		$(function() {
			$(".mappaIt").maphilight();
			$(".regione").hide();
		});
		$("area").each(function() {
			var regione = $(this).attr('alt');
			$(this).mouseover(function() {
				$(".regione").text(regione).fadeIn();
			});
			$(this).mouseout(function() {				
				$(".regione").hide();
			});
			$(this).click(function() {
				if ($('#regione option[value="' + regione + '"]').text()) {
					var toSelect = $('#regione option[value="' + regione + '"]').attr('selected', 'selected');
					$('#regione').change();					
					$('#ricerca').before('<p>Loading data...</p>').fadeOut().submit();
					return false;
				} else {
					var toSelect = $('#regione option[value=""]').attr('selected', 'selected');
					$('#regione').change();
				};
			});
		});
	};

	/*
	if ($('.noresults').length > 0) {
		var values = $('.noresults').attr('title');
		var url = 'http://ucrea.intesys.net/Vetrina-delle-opportunita-ucrea/' + '?' + values;

		window.open(url, 'Ricerca', 'width=960,height=700,resizable=1,scrollbars=1,toolbar=1,location=1,directories=1,status=1,menubar=1');
	}
	*/

	// gestione menu Print/Add/Send
	$("a.icoPrint").click(function() {
		window.print();
	});
	$("a.icoAdd").click(function() {
		var data = $(this).attr("title");
		var data_array = data.split(" // ");
		createBookmarkLink(data_array[0], data_array[1])
	});

});


/*
 * funzioni popolamento select
 */
function fCheck(o) {
	//alert('fCheck() su '+o.id);
}

function provinciaDynamic() {
	$("#provincia").load('/returnOpt/dynamicOptions'
			, {    
					'fieldID': 'provincia' 
				  , 'tipo': 'Immobili' 
				  , 'default': 'VR' 
				  , 'value': $('#provincia option:selected').val() 
				  , 'xxxx': $('#regione option:selected').val()
			  }
			, function() {
				$("#provincia").change();
				//$("#provincia2").selectbox();
			  }
			);
}

function comuneDynamic() {
	$('#comune').load('/returnOpt/dynamicOptions'
			, {    
					'fieldID': 'citta' 
				  , 'tipo': 'Immobili' 
				  , 'default': 'L949'
				  , 'value': $('#comune option:selected').val()  
				  , 'xxxx': $('#provincia option:selected').val() 
			  }
			, function() {
				$("#comune").change();
				//$("#comune2").selectbox();
			  }
			  );
}


/*
 * Gestione bookmark
 */
/*function bookmarksite(title, url){
	if (document.all)
		window.external.AddFavorite(url, title);
	else if (window.sidebar)
		window.sidebar.addPanel(title, url, "")
}*/
function createBookmarkLink(title, url) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title);
	} else if(window.opera && window.print) { // Opera Hotlist
		return true;
	}
}








jQuery.validator.addMethod("require_from_group", function(value, element, options) {
    numberRequired = options[0];
    selector = options[1];
    //Look for our selector within the parent form
    var validOrNot = $(selector, element.form).filter(function() {
         // Each field is kept if it has a value
         return $(this).val();
         // Set to true if there are enough, else to false
      }).length >= numberRequired;

    //The elegent part - this element needs to check the others that match the
    //selector, but we don't want to set off a feedback loop where all the
    //elements check all the others which check all the others which
    //check all the others...
    //So instead we
    //  1) Flag all matching elements as 'currently being validated'
    //  using jQuery's .data()
    //  2) Re-run validation on each of them. Since the others are now
    //     flagged as being in the process, they will skip this section,
    //     and therefore won't turn around and validate everything else
    //  3) Once that's done, we remove the 'currently being validated' flag
    //     from all the elements
    if(!$(element).data('being_validated')) {
    var fields = $(selector, element.form);
    //.valid() means "validate using all applicable rules" (which 
    //includes this one)
    fields.data('being_validated', true).valid();
    fields.data('being_validated', false);
    }
    return validOrNot;
    // {0} below is the 0th item in the options field
    }, jQuery.format("Please fill out at least {0} of these fields.")
);

