$('<div id="ajaxBusy">Caricamento...</div>').hide().ajaxStart(function() {$(this).show();}).ajaxStop(function() {$(this).hide();}).appendTo('body');
if (!("console" in window) || !("firebug" in console)){
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
  "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
  
  window.console = {};
  for (var i = 0; i < names.length; ++i){
    window.console[names[i]] = function() {};
  }
}
jQuery.extend(
  jQuery.expr[ ":" ], 
  {reallyvisible : function (a) {return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length);}}
);


jQuery.fn.rdy = function(func){
	this.length && func.apply(this);
	return this;
};
function replaceButtons() {
	$('button').filter(function(){if ($(this).find('img[src$="-off.png"]').length>0){ 
		var t=$(this),
				imag = t.find('img');
		var img=new Image();
				img.src = imag.attr('src')
		img.onload=function(e){
			t.css({
				width:img.width,
				height:img.height
			})
		}
		
		 return this; 
		}
	}).addClass('replacedButton');
	
	$('img[src$="-off.png"]').css({cursor:'pointer'}).parent().bind('mouseenter mouseleave', function(e){
		var t=$(this).find('img'),
				src = t.attr('src');
		if(e.type==='mouseenter'){
			t.attr('src', src.replace('-off', '-on'));
		}else {
			t.attr('src', src.replace('-on', '-off'));
		}
	});
} //replaceButtons

//$.getScript('/js/customForms.js');vvv
LazyLoad.js('/js/customForms.js');

$.fn.ntzCorner = function(options) {
	if(!$.browser.msie) {return;}
	$('.roundedTop').parent().remove();
	
        return this.each(function(){
		var t=$(this);
			var temp = $('<div class="rounded"><div class="roundedTop"><div class="topLeft"><div class="topRight"/></div></div><div class="roundedBottom"><div class="bottomLeft"><div class="bottomRight"/></div></div>');
			//t.addClass('isRounded');// Some problems with backgrounds!!!
			//temp.find('.roundedTop, .roundedBottom').width()
			
                        temp.find('.roundedTop').css({
				left:t.offset().left,
				top:t.offset().top-5,
				width:t.innerWidth()
                                
                                
			});
                      
                        
			temp.find('.roundedBottom').css({
				left:t.offset().left,
				top:t.offset().top + t.innerHeight() ,
				width:t.innerWidth()
			});
			temp.appendTo('body');
	});
    
};

$.fn.ntzCornerWhite = function(options) {
	if(!$.browser.msie) {return;}
	$('.roundedTopWhite').parent().remove();
        $(' niceAndRoundedWhite').css('border','none');
	return this.each(function(){
           
		var t=$(this);
			var temp = $('<div><div class="roundedTopWhite"><div class="topLeftWhite"><div class="topRightWhite"/></div></div><div class="roundedBottomWhite"><div class="bottomLeftWhite"><div class="bottomRightWhite"/></div></div>');
			t.addClass('isRoundedWhite');
			//temp.find('.roundedTop, .roundedBottom').width()
			temp.find('.roundedTopWhite').css({
				left:t.offset().left,
				top:t.offset().top-5,
				width:t.innerWidth()+3
                               
			});
			temp.find('.roundedBottomWhite').css({
				left:t.offset().left,
				top:t.offset().top + t.innerHeight()+3 ,
				width:t.innerWidth()+3
			});

                       

			temp.appendTo('body');
	});
};

/* fixing IE 
------------------------------------------------------------- */
if($.browser.msie) {
	if($.browser.version<7){
		$.getScript('/js/ie6.js', function(){
			replaceButtons();
			$('img[src$=".png"]:not([src$="-off.png"]):not(#carPicker a)').filter(function(){return ($(this).closest('#header').length === 0 ? this : '');}).ntzPngFix();
		});
	}
/*=======================================*/

	window.setTimeout(function(){
		$('.niceAndRounded').ntzCorner();
                //$('.rounded').find('.roundedTop').css('z-index',9000);
	}, 200);
     
       window.setTimeout(function(){
		$('.niceAndRoundedWhite').ntzCornerWhite();
	}, 200);
        
}
/* ie fixed!
------------------------------------------------------------- */
function eqCols() {
	maxHeight = 0;
	$('.eqCols').each(function(){
		var t=$(this),
				h = t.height();
		if(h>maxHeight){
			maxHeight = h;
		}
	}).height(maxHeight);
};//eqCols


if( !$('#userArea').hasClass('noAutoHeight') && $('#theContent').height()<$('#userCP').height() ){
	$('#theContent').height($('#userCP').height());
}

/* modal window
------------------------------------------------------------- */

function toggleSelects(show) {
	var show = show || 0;
	if(show){
		$('select.wasVisible').removeClass('wasVisible');
	}else {
		$('select:visible').addClass('wasVisible');
	}
};//toggleSelects - IE6 problem


function modalStuff() {
	$('body').delegate('.async_request, .modal_buttons a, #ajaxMessages a.dismiss', 'click.ntzModal', function(e){
		
		var t = _this = $(this), params = '';
		t.blur();
		if(t.hasClass('dismiss')){
			$('#ajaxMessages, #ajaxOverlay').remove();
			toggleSelects(1);
			$('.niceAndRounded').ntzCorner();
			return false;
		}
                // redirect senza chiamate ajax
		if(t.hasClass('goto'))
		{
			window.location = t[0].href;
			return false;
		}
                 // submit senza chiamate ajax
                 // submit del primo form
		if(t.hasClass('submitNoAjax'))
		{
			$('form:first').submit();
                        return true;
		} // submit senza chiamate ajax
                 // submit del primo form
		if(t.hasClass('back'))
		{
			history.back();
                        return false;
		}

                 // submit di delete X un form
		if(t.hasClass('submitDelete'))
		{
			$('#form1').attr('action','Delete.php');
                        $('#form1').submit()  ;
                       
			return false;
		}

                // submit di delete X un form
		if(t.hasClass('submitAttiva'))
		{
			$('#form1').val('Attiva');
                        $('#form1').submit()  ;

			return false;
		}


		if(t.hasClass('redirect')){
			window.location = t[0].href;
		}
		if(this.nodeName.toLowerCase()==='button'){
			var attrHref = t.closest('form').attr('action');
			params = t.closest('form').serialize();
		}else {
			var attrHref = t.attr('href');
		}
		
	/*=======================================*/
		$.getJSON(attrHref, params, function(data){
			showModalWindow(data, _this);
		});
		return false;
	});
	$('a.autoClick').unbind('click.ntzModal').click();
} //modalStuff


	function showModalWindow(data, _this) {
		var msg = '#ajaxMessages',
				_this = _this || null;
		if($(msg).length) {$('#ajaxMessages, #ajaxOverlay').remove();toggleSelects(1);$('.niceAndRounded').ntzCorner();}

		$('<div id="ajaxMessages"/>').appendTo('body');
		
		
		$('<div id="ajaxOverlay"/>').css({
			height:$(document).height()
		}).appendTo('body');
		if($.browser.msie && $.browser.version<7){
			toggleSelects();
		}
/*=======================================*/		
		$.each(data, function(){
			if(typeof(this.replacements)!=='undefined'){
				var rep = this.replacements;
				for(var i = 0, len = this.replacements.length; i<len; i++){
					$('#'+rep[i].whatToUpdate).html(rep[i].updateWith);
				}
			}
/*=======================================*/
			if(typeof(this.messages)!=='undefined'){
				var tmp = $('<div class="modal_buttons"/>');
				var messages = this.messages;
				$(msg).html('<div class="ajaxMessageContent">'+messages.returnMessage+'</div>').attr('title',messages.dialogTitle);
				$.each(messages.buttons, function(){
					var t=this;
					$('<a/>').attr({
						"href":t[0],
						"class":t[3]
					}).html(t[1]).appendTo(tmp);	
				});
				if(tmp.find('a').length>0){
					$(msg).append(tmp);
				}else {
					$(msg).css('paddingBottom', 0);
				}
			}
/*=======================================*/
			if(typeof(this.inlineMessage)!=='undefined'){
				var inline = this.inlineMessage,
						closest = _this.closest('.'+inline.closestEl),
						message = $('<div class="ajax_inline_message clearfix"/>').addClass(closest[0].className).html('<p>'+inline.message+'</p> <a href="'+inline.undoLink+'" class="undoLink action_async">'+inline.undoText+'</a>'),
						hideAfter = inline.hideAfter || 0;

				if( !closest.prev(0).hasClass('ajax_inline_message') && hideAfter >= 0 && !_this.hasClass('undoLink') ){
					message.hide().insertBefore(closest).slideDown();
					
					if(hideAfter>0){
						window.setTimeout(function(){
							message.slideUp(function(){$(this).remove();});
						}, hideAfter);
					}
				}
			}
/*=======================================*/
			if(typeof(this.classToggler)!=='undefined'){
				_this.data('classToggler', this.classToggler);
			}
		});
		
		_this.trigger('customEvent');
		
		if(typeof(customForms) === 'function') {customForms($('#ajaxMessages'));}
		
		$(msg).append('<a href="#" class="closeModal icons dismiss">X</a>');
		window.setTimeout(function(){
			try{
				$('#ajaxMessages').ntzCorner();
                                $('.rounded').find('.roundedTop').css('z-index',9000);
                                 $('.rounded').find('.roundedBottom').css('z-index',9000);
			}catch(err){}
		}, 200);
		
		$('#ajaxMessages').css({
			top:'50%',
			marginTop : -( Math.ceil($('#ajaxMessages').innerHeight())/2 )
		});
		replaceButtons();
               
                
               
	} //showModalWindow

$('button.async_request[type="submit"]').closest('form').submit(function(e){
	e.stopPropagation();
	$(this).find('button.async_request[type="submit"]:first').click();
});


$(window).bind('resize', function(){
	
	//if($('#ajaxOverlay').length){
	//	$('#ajaxOverlay').css({
	//		height:$(document).height()
	//	});
	//}	
});
/*=======================================*/

/* top nav
------------------------------------------------------------- */
function topNav() {
	$('#topNav li a').filter(function(){return $(this).find('br').length ? this : false;}).addClass('multiline');
	//Cufon.replace($('#topNav>li>a'), { hover: true });	
	
	$('#topNav ul').prepend('<li class="first"/>');
	$('#topNav ul').each(function(){
		var t=$(this);
		t.find('li:first').width(t.parent().innerWidth()).next().addClass('second');
		t.find('li:last').addClass('last');
	});
	
	$('#topNav a').filter(function(){return $(this).next('ul').length>0 ? this : false;}).addClass('hasSubmenu').closest('li').bind('mouseenter mouseleave', function(e){
		var t=$(this),
				siblings = t.siblings('li.s');
		siblings.addClass('isSelected').removeClass('s');
		if(e.type==='mouseleave'){
			t.siblings('.isSelected').addClass('s').removeClass('isSelected');
		}
		t.find('ul li:first').width(t.innerWidth());
	});
};//topNav





function filterPage() {
	$('#stats').rdy(function(){
		$('#stats ul.tabs li a').filter(function(){return $(this).find('br').length ? this : false;}).addClass('multiline');
		var totalTabs = $('#stats ul.tabs li').length,
				wrapWidth = $('#stats').width();
				widthPerTab = Math.floor(wrapWidth/totalTabs)-5;
				console.log(wrapWidth/totalTabs);
		$('#stats ul.tabs li').width(widthPerTab);
		$('#stats ul.tabs li:last').width(widthPerTab+wrapWidth%totalTabs);
		$('#stats ul.tabs li:first').width(widthPerTab+5)
		
	$('#stats .tabContent div.tab').hide();	
	$('#stats ul.tabs').delegate('li', 'click', function(e){
		var t=$(this);
		t.addClass('s').siblings().removeClass('s').trigger('mouseenter');
		$('#stats .tabContent div.tab').eq(t.index()).show().siblings('div.tab').hide();
		$('.niceAndRounded').ntzCorner();
		return false;
	});
	$('#stats ul.tabs li:first').click();
	
	if($.browser.msie && $.browser.version<7){
		$('#stats ul.tabs').height(34)
	}
		
	});
};//filterPage

// ======================
// = Sort by table head =
// ======================
function sortTableHeader() {
	$('.sortable').rdy(function(){
			$('.sortable').each(function(){
			var t=$(this),
					tO = t.offset();
			t.find('thead th').each(function(){
				var th = $(this),
						o = th.offset();
				th.find('a.sortUp, a.sortDown').css({
					left:o.left - tO.left + th.innerWidth()-12,
					top:o.top - tO.top +3
				}).show();
			});
			
			// t.find('tbody').delegate('td', 'click', function(){
			// 	var tr = $(this).closest('tr'),
			// 			check = tr.find('td.check input:checkbox');
			// 	if(check.length===0) return 
			// 	if(!check[0].checked){
			// 		tr.addClass('selected');
			// 		check.attr('checked', true);
			// 	}else {
			// 		tr.removeClass('selected');
			// 		check.attr('checked', false);
			// 	}
			// });
			
			t.find('tbody td.check').delegate('input:checkbox', 'click', function(e){$(this).parent().click();});
			
			t.find('tbody tr').filter(function(){return $(this).find('td.check input:checkbox').attr('checked') ? this : '';}).addClass('selected');
		});
		
		$('.sortableTools').delegate('a.selectAll, a.unselectAll, a.openAll, a.closeAll', 'click', function(){
			var inputs = $('.sortable tbody td.check input'),
					t = $(this);
			if(t.hasClass('unselectAll')){
				inputs.attr('checked', false).closest('tr').removeClass('selected');
			}else if(t.hasClass('selectAll')){
				inputs.attr('checked', true).closest('tr').addClass('selected');
			}else if(t.hasClass('openAll')){
				$('tr.details').show();
			}else if(t.hasClass('closeAll')){
				$('tr.details').hide();
			}
			$('.niceAndRounded').ntzCorner();
			return false;
		});
	});
};//sortTableHeader




$(document).ready(function() {
	
	formChecker();
	modalStuff();
	eqCols();
	topNav();
	sortTableHeader();
	filterPage();
	customTooltips();
	replaceButtons();
	
if($.browser.msie){
	$('img').each(function(){
		var t=$(this),
				img = new Image();
		$(img).load(function(){
			$('.niceAndRounded').ntzCorner();
		}).attr('src', t.attr('src'));
	});
}
});


function IsNumeric(strString) {
  var strValidChars = "0123456789";
  var strChar;
  var blnResult = true;

  if (strString.length == 0) return false;
  //  test strString consists of valid characters listed above
  for (i = 0; i < strString.length && blnResult == true; i++) {
    strChar = strString.charAt(i);
    if (strValidChars.indexOf(strChar) == -1) {
      blnResult = false;
    }
  }
  return blnResult;
}


function customTooltips() {
	$('input[tooltip]').bind('focus blur', function(e){	
		var t=$(this);
		if(e.type==='focus'){
			$('.customTooltip').remove();
			$('<span class="customTooltip"/>').html(t.attr('tooltip')).hide().css({
				left:t.offset().left+t.width()+10,
				top:t.offset().top-3
			}).appendTo('body').fadeIn();
		}else if(e.type==='blur'){
			$('.customTooltip').fadeOut();
		}
	});
} //customTooltips


var emailPattern = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		isNonblank_re = /\S/;

function isNonblank (s) {
	return String (s).search (isNonblank_re) != -1
}
function isEmail(email) {
	return email.search(emailPattern) != -1;
} //isEmail


function formChecker() {
	$('form').submit(function(){
		var t=$(this);
		if( t.find('input[req]') || t.find('textarea[req]') || t.find('select[req]') ){
			var errorsWrapper,
					errors = $('<div><ul class="errorListing"/></div>');
					
			t.find('input[req]').add(t.find('textarea[req]')).add(t.find('select[req]')).each(function(validation){
				var toValidate = $(this),
						el = toValidate[0].nodeName,
						reqType = toValidate.attr('req'),
						val = this.value,
						minLen = toValidate.attr('minlen'),
						maxval = toValidate.attr('maxval'),
						minval = toValidate.attr('minval'),
						emailAttr = toValidate.attr('email'),
						slaveFor = toValidate.attr('slaveFor'),
						master = toValidate.attr('master'),
						preValidate_slaveFlag = 0;
				
				switch (el.toLowerCase()){
					case 'input':
                                        case 'select':
						var numberVal = parseInt(Number( val ), 10) || 0;
						if(typeof(preValidate_slave)==='function'){
							preValidate_slaveFlag = preValidate_slave();
						}
								
						if(reqType == 1){ //required
							if(typeof(toValidate.attr('err')) === 'undefined') {return;}
							if(typeof(slaveFor) !=='undefined'){
								if( !$('input[master="'+slaveFor+'"]').is(':checked') && preValidate_slaveFlag===0) {
									return;
								}
							}
							if( ( val.length < minLen ) || ( numberVal > parseInt(maxval, 10) ) || ( numberVal < parseInt(minval, 10) ) ){
								errors.find('ul').append('<li>'+toValidate.attr('err')+'</li>');
							}else if(!isNonblank(val) || (emailAttr == 1 && !isEmail(val))){
								errors.find('ul').append('<li>'+toValidate.attr('err')+'</li>');
							}else if(toValidate.attr('type') === 'password'){
								var pairWith = $('input[name="'+toValidate.attr('pairwith')+'"]');
								if(pairWith.length && val !== pairWith.val()){
									errors.find('ul').append('<li>'+pairWith.attr('err')+'</li>');
								}	
							}else if(toValidate.attr('type') === 'radio'){
								if( $('input[name="'+toValidate.attr('name')+'"]:checked').length === 0 ){
									errors.find('ul').append('<li>'+toValidate.attr('err')+'</li>');
								}
							}else if(toValidate.attr('type') === 'checkbox'){
								if(!toValidate.is(':checked')){
									errors.find('ul').append('<li>'+toValidate.attr('err')+'</li>');
								}
							}
						}else if((reqType == 0) && isNonblank(val)){ //optional
							if(emailAttr == 1 && !isEmail(val)){
								errors.find('ul').append('<li>'+toValidate.attr('err')+'</li>');
							}
						}
						
					break;
					/*
                                        case 'select':
						console.log(2);
					break;
					*/
                                        case 'textarea':
						if(reqType == 1){ //required
							if(!isNonblank(val)){
								errors.find('ul').append('<li>'+toValidate.attr('err')+'</li>');
							}
						}
					break;
				}
			});
			if(typeof(customFormValidator) === 'function') {var customErrorTitle = customFormValidator(t.attr('id'), errors);}
			if(errors.find('li').length) {
				var errorTitle = '';
				if(typeof(customErrorTitle)!=='undefined'){
					errorTitle = "<h2><img src='/f.php?text="+customErrorTitle+"&amp;size=11' /></h3>";
				}
				errorsWrapper = [
					{
						"messages" : {
							"returnMessage":"<div class='errorPopupWrapper'>" + errorTitle + $(errors).html() + '</div>',
							"dialogTitle":"",
							"buttons" : {
								"closeButton":["#", "<img src=\"/images/buttons/torna-indietro-left-off.png\" />", false, "dismiss"]
							}
						}
					}
				];
				showModalWindow(errorsWrapper, t);
			}else {
				console.log('form is ok');
				return ;
			}
		}else {
			return;
		}
		return false;
	});
} //formChecker


function dateCompare(date1, date2){
  d1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
  d2 = new Date(date2.getFullYear(), date2.getMonth()-1, date2.getDate());

  if (d1.getTime()>=d2.getTime()) {
    return true;
  }
  else{
    return false;
  } 
} //dateCompare


function isDateInFuture(date){
  

  d1 = new Date(date.getFullYear(), date.getMonth(), date.getDate());
  d2 = new Date();
  
  if (d1.getTime()>d2.getTime()) {
    return true;
  }
  else{
    return false;
  } 
} //isDateInFuture


function isDateValid(y, m, d){
	d = parseInt(d, 10);
	m = parseInt(m, 10);
	y = parseInt(y, 10);
	var date = new Date(y,m-1,d);
	var convertedDate = date.getFullYear() + (date.getMonth()+1) + date.getDate();
	var givenDate = y + m + d;
	return ( givenDate == convertedDate && !isNaN(convertedDate));
} //isDateValid

