document.documentElement.className += ' hasJS';

/*
 * fixes jquery-webkit warning
 */
if (jQuery.event.props[17] === "layerX" ) {
    jQuery.event.props.splice(17,2);
}

var currentProdCategory = null;

var kmoto = {

	_config : {
		skin_folder : '/skin/website/',
		home_desaturate_enabled : false,
		desaturate_speed : 4000,
		teaser_timeout : 4000,
		teaser_speed : 1000,
		search_box : '.search_box .input_search'
	},

	//Loader
	load : function(param) {
		switch(param) {
			case 'bindings':
				$('.search_box .search').click(function() {
					kmoto.search.show();
				});
				break;
			case 'desaturate' :
				$('.desaturate').each(function() {
					$(this).bind("load", function () {
						kmoto.desaturate($(this), true);
					});
				});
				$('.desaturate-self').each(function() {
					$(this).bind("load", function () {
						if (kmoto._config.home_desaturate_enabled) {
							kmoto.desaturate($(this), false);
						}
					});
				});
				break;
			case 'teasers' :
				kmoto.teasers.start();
				break;
			case 'lightbox':
				/*$('.lightbox').lightBox({
					imageLoading:	kmoto._config.skin_folder+'widgets/lightbox/lightbox-ico-loading.gif',
					imageBtnClose:	kmoto._config.skin_folder+'widgets/lightbox/lightbox-btn-close.gif',
					imageBtnPrev:	kmoto._config.skin_folder+'lightbox/lightbox-btn-prev.gif',
					imageBtnNext:	kmoto._config.skin_folder+'lightbox/lightbox-btn-next.gif',
					imageBlank:		kmoto._config.skin_folder+'lightbox/lightbox-blank.gif'
				});*/
				$('.lightbox').fancybox();
				if ($.browser.msie) {
					$('.lightbox-video').fancybox({
						width : 767,
						height: 445,
						scrolling: 'no'
					});
				} else {
					$('.lightbox-video').fancybox({
						width : 764,
						height: 430,
						scrolling: 'no'
					});
				}
				break;
			case 'loadVariantiCodice':
				kmoto.loadVariantiCodice();
				break;
			case 'emptyProvincia':
				kmoto.emptyProvincia();
				break;
			case 'showFotoLista':
				kmoto.showFotoLista();
				break;
			case 'showHomeProducts':
				kmoto.showHomeProducts();
				break;
			case 'rainEffect':
				kmoto.rainEffect();
				break;
		}
		return kmoto;
	},

	desaturate : function(imgObj, fader) {
		var jImg = imgObj;
		imgObj = imgObj[0];

		if($.browser.msie){
		    return;
		}
		var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');

        var imgW = imgObj.width;
        var imgH = imgObj.height;

        if (imgW < 1 || imgH < 1) return;

        canvas.width = imgW;
        canvas.height = imgH;
        canvasContext.drawImage(imgObj, 0, 0);

        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);

        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg;
                imgPixels.data[i + 1] = avg;
                imgPixels.data[i + 2] = avg;
            }
        }

        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);

		if (fader) {
			var newImg = document.createElement('img');
			newImg.src = canvas.toDataURL();

			jImg.before(newImg);
			jImg.fadeOut(kmoto._config.desaturate_speed);
		}else{
			imgObj.src = canvas.toDataURL();
		}
	},

	teasers : {
		start : function() {
			var obj = $('#content .teaser > .img_mask, .image_below .the_image');
			if (obj.length < 2) return;
			obj.cycle({
				fx: 'fade',
				next: '.arrow_right',
				prev: '.arrow_left',
				//pause: 1,
				timeout: kmoto._config.teaser_timeout,
				speed: kmoto._config.teaser_speed
			});
		}
	},

	search : {
		show : function() {
			if ( $(kmoto._config.search_box).css('display') == 'block' ) {
				kmoto.search.go();
			}else{
				$(kmoto._config.search_box).fadeIn(200);
			}
		},
		go : function() {
			var s = $(kmoto._config.search_box+' input').val();
			if (s.length > 0) {
				window.location.href = '/search?q=' + s;
			}
		}
	},
	rel_fix : function() {
		$('a[rel="external"]').click(function(){
			this.target = "_blank";
		});
		return kmoto;
	},
	
	Resellers : {
		
		dfrGmaps : null,
		
		init : function () {
			var $container = $('#distributori_gmaps') || [],
				$filters,
				that = this;
			
			if (!$container.length) {
				return;
			}
			$filters = $('#distFiltri');
			$filters.bind('submit', function (e) {
				var $this = $(this),
					action = $this.attr('action'),
					nationFilter = $this.find('#filtroNazione').val() || '',
					areaFilter = $this.find('#filtroArea').val() || '',
					regioneFilter = $this.find('#filtroRegione').val() || '',
					provinciaFilter = $this.find('#filtroProvincia').val() || '',
					data = $this.serialize(),
					opts = {};
				
				e.preventDefault();
				
				$('#gmap_preloader').show();
				
				if (nationFilter == 'ITALIA') {
					mappa.currentOpts = mappa.params.ITALIA;
				}
				if (nationFilter == 'FRANCIA') {
					mappa.currentOpts = mappa.params.FRANCIA;
				}
				if (areaFilter == 'EUROPA') {
					mappa.currentOpts = mappa.params.EUROPA;
				}
				if (regioneFilter != '') {
					mappa.currentOpts = mappa.params.REGIONE;
				}
				if (provinciaFilter != '') {
					mappa.currentOpts = mappa.params.PROVINCIA;
				}
				var loadResellers = $.when(that.getContentList(action, data),that.loadGMaps.call(that));
				
				if (provinciaFilter != '') {
					loadResellers.then(function(response) {
						if (response[0] != null & response.length>0) {	
							$('.hasJS #gmap.opened').css({
								'height': '550px',
								'width': '450px',
								'float': 'left'
							});
							$('#listaRivenditoriProvincia').remove();
							$('#distributori_gmaps').append('<div id="listaRivenditoriProvincia"></div>');
							var i = 0; 
							$.each(response[0].results,function(i,el) {
								var last = ''; 
								if (i == response[0].results.length - 1) {
									last = 'last';
								}
								$('#listaRivenditoriProvincia').append(
									'<div class="rivenditoreProvincia ' + last + '"><p>' + el.text
									+ '<br>Telefono: ' + el.telefono
									+ '<br>Fax: ' + el.fax
									+ '<br><a href="mailto:'+ el.email + '">' + el.email + '</a>'
									+ '</p></div>'
								);
								$('#listaRivenditoriProvincia .rivenditoreProvincia .teldist').remove();
								$('#listaRivenditoriProvincia .rivenditoreProvincia .emaildist').remove();
								$('#listaRivenditoriProvincia .rivenditoreProvincia .rivenditori_info br').last().remove();
								i++;
							});	
						}
						kmoto.Resellers.showList(response);				
					});
				} else {
					loadResellers.then(function(response) {
						$('#listaRivenditoriProvincia').remove();
						$('#clearer').remove();
						$('.hasJS #gmap.opened').css({
							'height': '550px',
							'width': 'auto',
							'float': 'none'
						});
						kmoto.Resellers.showList(response);
					});
				}
			}).triggerHandler('submit');
		},
		
		loadGMaps : function () {
			var lang = (document.documentElement.lang || 'EN');
			if (kmoto.Resellers.dfrGmaps === null) {
				kmoto.Resellers.dfrGmaps = $.Deferred();
				$.getScript("http://maps.google.com/maps/api/js?sensor=true&async=2&language=" + lang + "&callback=kmoto.Resellers.loadGMapsPlugins");
				return kmoto.Resellers.dfrGmaps.promise();	
			}
			return true;
		},
		
		loadGMapsPlugins : function () {
			if (kmoto.Resellers.dfrGmaps === null || !kmoto.Resellers.dfrGmaps.isResolved()) {
				$.getScript("/js/desktop/marker_manager.js", function () {
					kmoto.Resellers.dfrGmaps.resolve();
				});
			}
			return true;
		},
		
		getContentList : function (action, data) {
			return $.getJSON(
				action,
				data || {}
			);
		},
		
		showList : function (response) {
			var r = response[0];
			
			if (!r) {
				alert($('#gmap_error_message').text());
				$('#gmap_preloader').hide();
				return;
			}
			mappa.loadMap(response[0]);
		}
	},
	loadVariantiCodice: function(){
		  // Gestione verianti colori per immagine principale prodotto
		  if ($('ul.prodColoriList').length > 0) {
		    var oldSrc  = $('img.mainImg').attr('src');
		    var oldHref = $('a.mainImg').attr('href');
		    $('ul.prodColoriList li a').each(function() {
		      $(this).click(function() {
		        //console.debug('Before >>> ' + $('img.mainImg').attr('src'));
		        var title = $(this).attr('title');
		        if ($('ul.listVars li img[alt=' + title + ']')) {
		          var newSrc  = $('ul.listVars li img[alt=' + title + ']').attr('src');
		          var newHref = $('ul.listVars li img[alt=' + title + ']').attr('title');
		          if (newSrc != undefined) {
		            $("#myLoading").stop().hide();
		            $('img.mainImg').attr('src', newSrc);
		            $('a.mainImg').attr('href', newHref);
		            //console.debug('After  >>> ' + $('img.mainImg').attr('src'));
		          } else {
		            $("#myLoading").stop();
		            $("#myLoading p").text('Preview not available');
		            var css = {
		              left: "730px",
		              top: "530px"
		            };
		            $("#myLoading").css(css);
		            $("#myLoading").stop()
		              .fadeIn()
		              .animate({opacity: 1.0}, 1000)
		              .fadeOut()
		              ;
		            $('img.mainImg').attr('src', oldSrc);
		            $('a.mainImg').attr('href', oldHref);
		          }
		        }
		        return kmoto;
		      });
		    });
		  }			
	},
	emptyProvincia: function() {
		$('#filtroRegione').change(function(){
			var empty_option = $('#filtroProvincia option:first').detach();
			$('#filtroProvincia')[0].innerHTML = '';
			$('#filtroProvincia').append(empty_option);
			$('#distFiltri').submit();
		});
	},
	showFotoLista: function() {
		$('ul.fotoLista li a').click(function(){
			var imgLink = $(this).attr('href');
			if (imgLink != '#video') {
				var imgTitle = $(this).attr('title');
				var imgAlt = $('img',this).attr('alt');
				$('.product_image>a').attr('href',imgLink);
				$('.product_image>a').attr('title',imgTitle);
				$('.product_image>a img').attr('src',imgLink);
				$('.product_image>a img').attr('alt',imgAlt);
				return false;
			} else {
				if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
		            var $target = $(this.hash);
		            $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
		            if ($target.length) {
		                var targetOffset = $target.offset().top;
		                $('html,body').animate({scrollTop: targetOffset}, 1000);
		                return false;
		            }
		        }
			}
		});
	},
	showHomeProducts: function() {
		$('.home .lista_categorie_prodotti .lista_prodotti_container .close_products_home').click(function(e){
			$('.home .lista_categorie_prodotti li.active').removeClass('active');
			$('.home .lista_prodotti_container').slideUp();
			currentProdCategory = null;
			e.preventDefault();
		});
		$('.home .lista_categorie_prodotti li').mouseover(function() {
			showHomeProductBox($(this));
		});
		$('.home .lista_categorie_prodotti li').click(function() {
			showHomeProductBox($(this));
		});
	},
	
	rainEffect: function() {
		if ($.browser.msie) {
			if ($('.effect').length > 0) {
				$('.effect').animate({},1,function(){
					rainLoop();
					function rainLoop() {
						$('.effect.first').animate({
							top: '87px'
						},1,function() {
							$('.effect.first').animate({
								top: '94px'
							},150,function() {
								$('.effect.first').animate({
									top: '100px'
								},150,function(){
									$('.effect.second').animate({},1,function(){
										$('.effect.second').animate({
											top: '87px'
										},150,function(){
											$('.effect.second').animate({
												top: '100px'
											},150, function() {
												rainLoop();
											});
										});
									});
								});
							});
						});
					}
				});
			}
		}
	}
};

var mappa = {
		infoWindow : null,
		map: null,
		markers: null,
		mgr: null,
		currentOpts : {},
		params : {
			'ITALIA' : {
				latlng : [42.779275, 12.824706],
				zoom: 5
			},
			'FRANCIA' : {
				latlng: [46.619261,2.351074],
				zoom: 5
			},
			'EUROPA' : {
				latlng : [51.618421103286664, 17.921106874999946],
				zoom: 4
			},
			'REGIONE' : {
				latlng : [42.779275, 12.824706],
				zoom: 8
			},
			'PROVINCIA' : {
				latlng : [42.779275, 12.824706],
				zoom: 9
			}
		},
		loadMap: function(response){
			var mapDiv = $('#gmap').addClass('opened')[0],
				options = $.extend({
					latlng: [43.9611909632867, 5.178221874999962],
					zoom: 2,
					mapTypeId: google.maps.MapTypeId.ROADMAP
				}, mappa.currentOpts),
				province = response.province,
				lista_province = response.lista_province || [],
				provincia_selected = response.provincia || null,
				agenzie = $.makeArray(response.results),
				cities = [],
				states = []
				;
				
			options.center = new google.maps.LatLng(options.latlng[0], options.latlng[1]);
			
			mappa.infoWindow = new google.maps.InfoWindow();
			
			mappa.map = new google.maps.Map(mapDiv, options);
			mappa.mgr = new MarkerManager(mappa.map);
			
			for(var i = 0, len = agenzie.length; i < len; i = i+1 ) {
				cities.push(mappa.createMarker(agenzie[i]));
			}
			
			for(provincia in province) { 
				states.push(mappa.createMarker(province[provincia]));
			}
			if (!!states.length) {
				if (options.zoom == mappa.params.REGIONE.zoom ) {
					mappa.map.setCenter(states[0].getPosition());
				}
				if (options.zoom == mappa.params.PROVINCIA.zoom ) {
					google.maps.event.trigger(mappa.map,'resize');
					mappa.map.setCenter(cities[0].getPosition());
				}
				google.maps.event.addListener(mappa.mgr, 'loaded', function() {
					mappa.mgr.addMarkers(states, 1, 7);
					mappa.mgr.addMarkers(cities, 8);
					mappa.mgr.refresh();
				});
				
				var lista_province = $.map(lista_province,function(el) {
					var provincia_option_selected = (provincia_selected == el) ? 'selected="selected"' : '';
					return '<option value="' + el + '" ' + provincia_option_selected + '>' + el + '</option>';
				});
				var empty_option = $('#filtroProvincia option:first').detach();
				$('#filtroProvincia')[0].innerHTML = '';
				$('#filtroProvincia').append(empty_option).append(lista_province.join(''));
			
			} else {
				if ( $('#filtroNazione option:selected').val() != '' ) {
					mappa.map.setCenter(cities[0].getPosition());
				}
				google.maps.event.addListener(mappa.mgr, 'loaded', function() {
					mappa.mgr.addMarkers(cities, 1, 14);
					mappa.map.setZoom(options.zoom);
					//mappa.map.setCenter(cities[0].getPosition());
					mappa.mgr.refresh();
				});
			}
			$('#gmap_preloader').hide();
		},
		
	/*	centra : function (lat, lng) {
			var latlng = new google.maps.LatLng(lat, lng);
			mappa.map.setCenter(latlng);
		},*/
		createMarker: function (marker){
			var lat = marker.latitudine || 0,
				lng = marker.longitudine || 0,
				icon = /*marker.icon || */'/skin/website/widgets/desktop/small_marker_a.png',
				text = marker.text || '',
				mark = null;
			mark = new google.maps.Marker({
				position: new google.maps.LatLng(lat, lng),
				icon: icon
			});
			
			if (text != '') {
				google.maps.event.addListener(mark, 'click', function() {
					var infowindow = mappa.infoWindow;
					
					infowindow.setContent(text);
					infowindow.open(mappa.map, mark);
					mappa.map.setCenter(mark.getPosition());
				});
			} else {
				google.maps.event.addListener(mark, 'click', function() {
					mappa.map.setZoom(10);
					mappa.map.setCenter(mark.getPosition());
				});
			}
			return mark;
		}		
		
	};
/*
 * Drop-down menu lingue
 */

$(document).ready(function($) {
	kmoto
		.load('bindings')
		.load('desaturate')
		.load('teasers')
		.load('lightbox')
		.load('loadVariantiCodice')
		.load('emptyProvincia')
		.load('showFotoLista')
		.load('showHomeProducts')
		.load('rainEffect')
		.rel_fix()
		.Resellers.init();
	;

	if ($.browser.msie && parseInt($.browser.version, 10) < 8) {
		$('.header .menu ul ul li').live('click', function (e) {
			var $a = $('a', this);
			e.preventDefault();
			window.location.href = $a.attr('href');
			return false;
		});
	}
	
});

function showHomeProductBox(el) {
	$('.home .lista_categorie_prodotti li.active').removeClass('active');
	el.addClass('active');
	var id = el.attr('id');
	id = id.substring(3,id.length);
	if (currentProdCategory == null || currentProdCategory != id) {
		$('#loader_overlay').show();
		currentProdCategory = id;
		$.get('/return/listaprodotti/', {
			'id_content': id
		}, function(data) {
			$('.home .lista_prodotti').html(data);
			$('.home .lista_prodotti_container .arrow_left_prod').css('display','block');
			$('.home .lista_prodotti_container .arrow_right_prod').css('display','block');
			setTimeout(function() {
				var obj = $('.home .lista_prodotti_container');
				obj.slides({
					container: 'lista_prodotti',
					prev: 'arrow_left_prod',
					next: 'arrow_right_prod',
					pagination: false,
					generatePagination: false
				});
			}, 0);
		});
	 	$('.home .lista_prodotti_container').slideDown();
	 	setTimeout(function(){
	 		$('#loader_overlay').fadeOut();
	 	}, 800);
	}
}
