$(document).ready(function() {

	// Gestione target blank links con doctype strict
	// This is how it works:
	// <a href="http://www.tripwiremagazine.com/" rel="external">tripwiremagazine.com</a>
	$('a[rel="external"]').click(function(){
		this.target = "_blank";
	});

	// gestione IMG HOVER
	$(".mHover").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));
		}).mouseout(function() {
			$(this).attr('src', src);
		});
	});
	
	$('ul.viniMenuInterno').find('ul:not(:has(li))').remove();
	$('#contentSpace .section .text .newsContainer .news ul:first li:last').css('border', 0);
	
	riondo.menuHome();
	
	var config = { over : menu, timeout : 500, out : menu };
	riondo.according(config);
	
	riondo.carousel();
	
	riondo.mappa();
	
	riondo.getFlash();
	
	riondo.setComuneNascita();
	
	/*if (jQuery.browser.msie) {
		var ie = parseInt(jQuery.browser.version);
		if (ie == 7) {
			jQuery.each($('.iCmsPag .iCmsPagNum'), function(i, val) {
				$(this).attr('style', 'display: block').css('paddingTop', 10);
		    });
			$('.homeA, .homeA2, .areaA').css({'top' : '8px', 'background-position' : 'right 3px'});
			$('.loginA, .logoutA').css({'top' : '8px'});
		}
	}*/
	
	riondo.overlay();
	
	riondo.showLogin();
	
	riondo.doLogin();
	
	riondo.carouselNews();
	
	riondo.layout();
	
	riondo.noBorder();
	
	riondo.privacy();
	
	if ($('body').attr('class') == '') {
		$('.sfumatura').remove();
	}
	
});

$(window).resize(function() {
	riondo.resizeOverlay();
});

var riondo = {
	menuHome : function () {
		var aList = $('ul.vini li a');
		
		aList.removeClass('open');
		
		aList.mouseover(function () {
			
			var currentClass = $(this).attr('class');
			
			aList.each(function(index) {
				if (currentClass != $(this).attr('class')) {
					var newClass = $(this).attr('class');
					$(this).removeClass($(this).attr('class'));
					$(this).addClass(newClass+'Off');
					if($(this).parent().hasClass('current')) {
						$(this).parent().removeClass('open');
					}
				}
			});
		}).mouseout(function () {		
			aList.each(function(index) {
				var newClass =  riondo.strReplace('Off', '', $(this).attr('class'));
				$(this).removeClass($(this).attr('class'));
				$(this).addClass(newClass);
				if($(this).parent().hasClass('current')) {
					$(this).parent().addClass('open');
				}
			});
		});
	},
	
	according : function (config) {
		if ($('.viniMenuInterno').length > 0) {
			$('.viniMenuInterno li.level2 a').hoverIntent(config);
		}
	},	
	
	strReplace : function (search, replace, subject, count) {
		var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
        f = [].concat(search),
        r = [].concat(replace),
        s = subject,
        ra = r instanceof Array, sa = s instanceof Array;
		s = [].concat(s);
		if (count) {
		    this.window[count] = 0;
		}
		
		for (i=0, sl=s.length; i < sl; i++) {
		    if (s[i] === '') {
		        continue;
		    }
		    for (j=0, fl=f.length; j < fl; j++) {
		        temp = s[i]+'';
		        repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
		        s[i] = (temp).split(f[j]).join(repl);
		        if (count && s[i] !== temp) {
		            this.window[count] += (temp.length-s[i].length)/f[j].length;}
		    }
		}
		return sa ? s : s[0];
	},
	
	carousel : function () {
		if ($('#viniList').length > 0) {
			$('#viniList').jcarousel({scroll: 2});
		}
	},
	
	carouselNews : function () {
		if ($('#imgNewsList').length > 0) {
			$('#imgNewsList').jcarousel({scroll: 3});
			$("#imgNewsList > li").find('a').fancybox();
		}
	},
	
	mappa : function () {
		if ($('#map').length > 0) {
			// fornisce latitudine e longitudine
			var latlng = new google.maps.LatLng(45.4120453,11.27637260);	   
			// imposta le opzioni di visualizzazione
			var options = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.HYBRID };
			// crea l'oggetto mappa
			var map    = new google.maps.Map(document.getElementById('map'), options);
			var marker = new google.maps.Marker({ position: latlng, map: map, title: '' });
		}
	},
	
	getFlash : function () {
		
		if ($('.flash').length > 0) {
			
			var bodyClass = $('body').attr('class');
			var section   = (bodyClass == '') ? 'home' : bodyClass;
			
			var flashMovie = $('.flash');
			flashMovie.flash(
				{
					swf: '/skin/website/flash/header.swf'
				  , height: 196
				  , width: 1000
				  , wmode: 'transparent'
				  , scale: 'no-scale'
				  , hasVersion: 9
				  , flashvars: { gateway : '/amf/' + section + '/' }
				}
			);
			
		}
	},
	
	setComuneNascita : function () {
		if ($('#comune_nascita').length > 0) {
			$('#comune_nascita').attr('disabled', 'disabled').css('background-color', '#EEE');
			riondo.getComuni();
			if ($('#prov_nascita option:selected').val()) {
				riondo.ajax($('#prov_nascita'));
			}
			riondo.generaCf();
			riondo.checkForm();
			
			$('#data_nascita').datepicker({
				changeYear: true,
				changeMonth: true,
				yearRange: '1910:2010'
			});
			$.datepicker.setDefaults($.datepicker.regional['it']);
			
		}
	},
	
	getComuni : function () {
		$('#prov_nascita').change(function () {
			var $sel;
			$sel = this;
			riondo.ajax($sel);
		});
	},
	
	ajax : function (obj) {
		
		$.ajax({
			type: "POST",
		    url: "/ajax/",
		    data: { 'value' : $('option:selected', obj).val() },
		    success: function(data){
		    	if(jQuery.trim(data) != ''){
		    		$('#comune_nascita').attr('disabled', '').css('background-color', '#FFF');
		    		$('#comune_nascita').html(data);
		    	} else {
		    		$('#comune_nascita').attr('disabled', 'disabled').css('background-color', '#EEE');
		    		$('#comune_nascita').html('<option value=""></option>');
		    	}
		   }
		});
		
	},
	generaCf : function () {
		$('#genera').click(function () {
			
			$('.message_error').remove();
			$('div').removeClass('errorField');
			
			var error = false;
			
			$.each($('.forCf'), function(index, value) {
				if (jQuery.trim($(this).val()) == '') {
					$(this).parent().addClass('errorField');
					error = true;
				} else {
					$(this).parent().removeClass('errorField');
				}
			});
			var checked = $("input[name=sesso]:checked").length;
			if (checked == 0) {
				$("input[name=sesso]:radio").parent().addClass('errorField');
				error = true;
			} else {
				$("input[name=sesso]:radio").parent().removeClass('errorField');
			}
			
			if (error) {
				$('.icms_form').before('<div class="message_error">E\' necessario compilare i campi sottostanti per calcolare il codice fiscale</div>');
			} else {
				$('#cf').val(generaCF($('#cognome').val()
					                , $('#nome').val()
					                , $('#data_nascita').val()
					                , $('input[name=sesso]:checked').val()
					                , $('#comune_nascita').val()));
			}
			
		});
	},
	
	checkForm : function () {
		$('#invio').click(function () {
			
			$('.message_error').remove();
			$('div').removeClass('errorField');
			var error = false;
			
			$.each($('.detail .icms_form input, .detail .icms_form select'), function(index, value) {
				if (jQuery.trim($(this).val()) == '') {
					$(this).parent().addClass('errorField');
					error = true;
				} else {
					$(this).parent().removeClass('errorField');
				}
			});
			var checked = $("input[name=sesso]:checked, input[name=privacy]:checked").length;
			
			if (checked == 0) {
				$("input:radio, input:checkbox").parent().addClass('errorField');
				error = true;
			} else {
				$("input:radio, input:checkbox").parent().removeClass('errorField');
			}
			if (error) {
				$('.icms_form').before('<div class="message_error">Errore nella compilazione del form. Tutti i campi sono obbligatori</div>');
				return false;
			}
			if (isNaN(jQuery.trim($('#cap').val()))) {
				$('#cap').parent().addClass('errorField');
				$('.icms_form').before('<div class="message_error">Errore nella compilazione del form. Il campo CAP deve contenere caratteri numerici</div>');
				return false;
			}
			
			return true;
			
		});
	},
	
	overlay : function () {
		
		if (!riondo.checkCookie()) {
			
			var w = $( window );
			var H = w.height();
			var W = w.width();
			$('.overlay').show().css({width: W, height: H, opacity: 0.7});
			
			var w = $('.modalContainer').width();
			var h = $('.modalContainer').height();
			var left = Math.floor((W-w)/2);
			var top = Math.floor((H-h)/2);
			$('.modalContainer').show().css({top: top - 100, left: left});
			$('.inputButton span').click(function () {
				
				$('.errorIns').hide();
				$('.errorYear').hide();
				
				error = false;
				$.each($('.inputDate select'), function(index, value) {
					if (jQuery.trim($(this).val()) == '0') {
						error = true;
					}
				});
				
				if (error) {
					$('.errorIns').show();
					return false;
				}
				
				var day   = parseInt($('#day').val());
				var month = parseInt($('#month').val());
				var year  = parseInt($('#year').val());
				
				var objDate = new Date();
				var todayDate = new Date(objDate.getFullYear() - 18, objDate.getMonth() + 1, objDate.getDate());
				var inputDate = new Date(year, month, day);
				
				if (todayDate < inputDate) {
					$('.errorYear').show();
					return false;
				}
				
				$.cookie('riondo', 'go', { path: '/', expires: 90 });
				
				$('.overlay').hide();
				$('.modalContainer').hide();
				
				return true;
			});
		
		}
	},
	
	checkCookie : function () {
		var issetCookie = false;
		if ($.cookie('riondo') && $.cookie('riondo') == 'go') {
			issetCookie = true;
		}
		return issetCookie;
	},
	
	resizeOverlay : function () {
		var w = $( window );
		var H = w.height();
		var W = w.width();
		$('.overlay').css({width: W, height: H});
		
		var w = $('.modalContainer').width();
		var h = $('.modalContainer').height();
		var left = Math.floor((W-w)/2);
		var top = Math.floor((H-h)/2);
		$('.modalContainer').css({top: top, left: left});
	},
	
	showLogin : function () {
		$('#aLogin').toggle(
			function () { $('.login').show(); },
			function () { $('.login').hide(); }
		);
	},
	
	doLogin : function () {
		if ($('#dLogin').length > 0) {
			
			$('#dLogin').click(function () {
				
				$('.errorSpan').css({'visibility' : 'hidden'});
				
				$.ajax({
					type: "POST",
				    url: "/login/",
				    data: $('.login > form').serializeObject(),
				    success: function(data){
						//$('.login > form').after(data);
						
						data = jQuery.trim(data); 
						
				    	if(data != ''){
				    		if (data == 'si') {
				    			location.href = ($('input[name=page]').val());
				    		} else {
				    			$('.errorSpan').css({'visibility' : 'visible'});
				    		}
				    	} 
				   }
				});
				return false;
			});
		}
	},
	
	layout : function () {
		if ($('.loginA').length > 0) {
			var offset = $('.loginA').offset();
			var left   = offset.left - 173;
			$('.login').css({'left' : left});
		}
	},
	
	noBorder : function () {
		$('a').has('img').css('border', 0);
		$('.back a, .title, .iCmsPag a').css({'border-bottom' : 0});
	},
	
	privacy : function (){
		if ($('.privacy').length > 0) {
			$('.privacy').jScrollPane({scrollbarWidth : 4 });
		}
	}
};


function menu () {
	var checkElement = $(this).next();
	if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
		return false;
	}
	if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
		$('.viniMenuInterno li.level2 ul:visible').slideUp('normal').prev().removeClass('open');
		checkElement.slideDown('normal');
		checkElement.prev().addClass('open');
		return false;
	}
}

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
