var fpw,fph,tp,cp;

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

//Mostro la index-esima foto
function mostra_foto(index){
	//Seleziono la prossima foto, la clono e la copio per la visualizzazione
	$('#foto_prodotto').empty();
	$('img#foto_'+ index,'#mContent').clone().appendTo('#foto_prodotto').attr('id',$('img#foto_'+ index,'#mContent').attr('id')+'_current');				
	
	var curimg = $('img#foto_'+ index+'_current','#foto_prodotto');
	//Calcolo il centro dell'immagine grande
	var iw = parseInt(curimg.width());
	var ih = parseInt(curimg.height());						
	//centro la foto
	curimg.css({'top':((fph-ih)/2)+'px','left':parseInt((fpw-iw)/2)+'px'});
}



//Crea il pannello sopra il div foto_prodotto con i tasti per passare da una foto all'altra
function show_pics_toolbar(tp){
	if(tp > 1){

		var toolbar = document.createElement('div');
		$(toolbar).attr('id','toolbar')
	
		var prev_pic = document.createElement('a');
		$(prev_pic).attr({'id':'prev_pic','href':'#'}).appendTo(toolbar).click(function(e){
			e.preventDefault();
			//Seleziono la foto precedente foto, la clono e la copio per la visualizzazione
			cp-=1;
			if(cp <= 0) cp=tp;
				
			mostra_foto(cp);
			
		});//click prev handler
			
	
		var next_pic = document.createElement('a');
		$(next_pic).attr({'id':'next_pic','href':'#'}).appendTo(toolbar).click(function(e){
			e.preventDefault();
			//Seleziono la prossima foto foto, la clono e la copio per la visualizzazione
			cp+=1;
			if(cp > tp) cp=1;
				
			mostra_foto(cp);

		});//click next handler
	
		$(toolbar).appendTo('#slider_content').fadeIn();
	}
}

//Gestione dello zoom quando clicco sopra la foto
function zoom_handler(){
	//gestione dello zoom
	$('#foto_prodotto').click(function(e){
		e.preventDefault();
		if($('img:animated',this).length) return false;	
	
		var img = $('img',this);			
	
		var sw = parseInt(img.width());
		var sh = parseInt(img.height());
		var sl = parseInt(img.css('left'));
		var st = parseInt(img.css('top'));
		
		
		$('div.overlay_menu','div.slider').fadeIn();
		
		var id=img.attr('id');
		var zoom = $('img#zoom_'+parseInt(id.substr(5)),'#mContent');
		
		var w = parseInt(zoom.width());
		var h = parseInt(zoom.height());
		
		$('#toolbar','#slider_content').fadeOut('fast');				
	
		//ZOOM-IN Animazione zoom fino alla dimensione della foto zoom
		
		var cw,ch;
		

		//Containment
		ch = (fph-h)/2;
		cw = (fpw-w)/2;
		
		img.animate({width:w+'px',height:h+'px',top:ch+'px',left:cw+'px'},1000,function(){
	
			var zoomPanel = document.createElement('div');
			$(zoomPanel).attr('id','zoomPanel').width($('#foto_prodotto').width()).height($('#foto_prodotto').height());
	
			$('div#slider_content').append(zoomPanel);
			
			//Ho appena finito l'animazione dello zoom..
			var zpo = $(zoomPanel).offset();
			
			zoom.css({top:ch+'px',left:cw+'px'}).clone().appendTo(zoomPanel).attr('id',zoom.attr('id')+'_current')
			.draggable({ scroll:false, containment: [parseInt(zpo.left)-w/2,parseInt(zpo.top)-h/2,parseInt(zpo.left)+parseInt($(zoomPanel).css('width'))-w/2,parseInt(zpo.top)+fph-h/2]});
	
			var ripristina = document.createElement('button');
			$(ripristina).attr('id','ripristina').click(function(){
				//ZOOM-OUT Handler per tornare alla foto originale. Cancello zoomPanel e facccio l'animazione all'indietro
				$('img',zoomPanel).draggable('destroy');
				$(this).fadeOut('fast',function(){
					$('img',zoomPanel).animate({width:sw+'px',height:sh+'px',top:st+'px',left:sl+'px'},1000,function(){
						$(zoomPanel).remove();
						img.css({width:sw+'px',height:sh+'px',top:st+'px',left:sl+'px'});
						$('#toolbar','#slider_content').fadeIn('fast');											
						$('#foto_prodotto').trigger('zoomOut');
					})
				});
				
			});
	
			$('#zoomPanel','div#slider_content').append(ripristina);				
			
		});
				
		return false;
	})	
}


//Funzione che legge l'xml di risposta dal server per visualizzare il prodotto
function mostraProdotto(xml){
	var pics_loaded=0;
	var pics_to_load = 0;
	

	function endPreload(){		

		//La foto correntemente visualizzata è la prima foto
		cp=1;

		$('#foto_prodotto').removeClass('loading').empty();
	
		//Seleziono la prima foto, la clono e la copio per la visualizzazione			
		$('img#foto_'+cp,'#mContent').clone().appendTo('#foto_prodotto').attr('id',$('img#foto_'+cp,'#mContent').attr('id')+'_current');		
				
		var curimg = $('img','#foto_prodotto');
		//Calcolo il centro dell'immagine grande
		var iw = parseInt(curimg.width());
		var ih = parseInt(curimg.height());						
		
		//sposta la foto grande
		curimg.hide().css({'top':((fph-ih)/2)+'px',left:parseInt((fpw-iw)/2)+'px'});
		
		$('#mContent').trigger('endPreload');	
		
	}
	
	

	var text = $(xml).find('description');
	var price = $(xml).find('price');
	
	
	
	var foto_prodotto = $('#foto_prodotto');		
	foto_prodotto.addClass('loading');
	
	//Conto il numero di foto per questo prodotto
	tp = $(xml).find('img').length ;
	//Conto il numero di foto da caricare dall'xml (zoome e normale quindi * 2)
	pics_to_load=tp*2;
	
	//Carico le foto e le metto nel div temporaneo mcontent che devo svuotare ogni volta
	$('#mContent').empty();
	var imgContainer = $(xml).find('images');
	var image,zoom;
	
	$(imgContainer).find('img').each(function(nr_foto){
		
		var img = document.createElement('img');		
		image = $(this).find('image');

		$(img).attr('alt',$(image).attr('alt')).attr('id','foto_'+(nr_foto+1)).appendTo('#mContent').load(function () {		
			
			pics_loaded++;
			if(pics_loaded >= pics_to_load) endPreload();

		}).error(function () {
			alert('Errore caricamento foto');
		}).attr('src',$(image).attr('src'));

		var img_zoom = document.createElement('img');
		zoom = $(this).find('zoom');
		
		$(img_zoom).attr('alt',$(zoom).attr('alt')).attr('id','zoom_'+(nr_foto+1)).appendTo('#mContent').load(function () {		
			pics_loaded++;
			if(pics_loaded >= pics_to_load) endPreload();
		}).error(function () {
			alert('Errore caricamento foto zoom');
		}).attr('src',$(zoom).attr('src'));

	});
		
	
	$('#testo_prodotto').html($(text).text());
	$('#prezzo_prodotto').html($(price).text());
}
	
function mostra_carrello(){
	if($('#cart_preview:visible').length) return false;
	//nascondo il menu utente
	$('.usermenu',$('#show_cart').parent()).hide();
	$('#cart_preview').addClass('loading').show();
	
	function mostra_risultati(data){
		$('#cart_preview').html(data).css('height','auto').removeClass('loading');	
	}
	
	$.get('../shop/carrello.php?lang='+gup('lang'),{show:'preview'},mostra_risultati);
	$('#cart_preview').mouseleave(function(){
		$(this).fadeOut();
		clearTimeout(nc);
	})
}

function nascondi_menuutente(){
	$('.usermenu').fadeOut();
}


function nascondi_carrello(){
	$('#cart_preview').fadeOut();
}


function carica_select(data){
	
	var selected = 0;
	if($('#id_sottocategoria').length){
		selected =  $('#id_sottocategoria').val();
	}
	
	var html = '<option value="0">sottocategoria...</option>';
	$(data).find('sottocategoria').each(function(){
		if(selected == $(this).attr('id')){
			html+='<option value="'+$(this).attr('id')+'" selected="selected">'+$(this).text()+'</option>';		
		}else{
			html+='<option value="'+$(this).attr('id')+'">'+$(this).text()+'</option>';			
		}
	});
	
	$('div.menu_categorie  #select_sottocategoria').html(html).removeAttr('disabled');
	$('div.menu_categorie  #select_sottocategoria').select_replacement_update();
}

function popola_select(data){

	carica_select(data);
	$('div.menu_categorie  #select_sottocategoria').select_replacement_update();

	
}

var nc,nmu,timeout=1000;

$(document).ready(function(){

	//Mi prendo la grandezza del div per mostrare i prodotti
	fpw = parseInt($('#foto_prodotto').width());
	fph = parseInt($('#foto_prodotto').height());

	zoom_handler();
	

	if($('#id_categoria').length){
		$('#select_categoria option').each(function(){
			if($(this).attr('value') == $('#id_categoria').val()){
				$(this).attr('selected','selected');
			}
		})
		
		$.get('../shop/render_products.php',{show:'getsubcat',cat:$('#id_categoria').val()},carica_select,'xml')
		
	}



	$('div.menu_categorie  #select_categoria').select_replacement(); 
	$('div.menu_categorie  #select_sottocategoria').select_replacement(); 

	//Tendine
	$('#show_cart').mouseenter(function() {			
		mostra_carrello();
		clearTimeout(nc);
		nc = setTimeout('nascondi_carrello()',timeout);
	}).mouseover(function(){
		clearTimeout(nc);		
	}).mouseleave(function(){
		nc = setTimeout('nascondi_carrello()',timeout);
	});
		
	$('#cart_preview').click(function(){
		location.href="../shop/carrello.php?lang="+gup('lang');
	}).mouseover(function(){
		clearTimeout(nc);
	}).mouseleave(function(){
		nc = setTimeout('nascondi_carrello()',timeout);
	})
	
	$('#usermenu').mouseenter(function(e) { 
		e.preventDefault();
		$('#cart_preview').hide();
		$('.usermenu',$(this).parent()).show();
		return false;
	}).click(function(e){
		e.preventDefault();
		return false;	
	}).mouseover(function(){
		clearTimeout(nmu);
	}).mouseleave(function(){
		nmu = setTimeout('nascondi_menuutente()',timeout);
	});
	
	$('.usermenu','ul.menu_utente').mouseleave(function(){
		$(this).fadeOut()
		nmu = setTimeout('nascondi_menuutente()',timeout);
	}).mouseover(function(){
		clearTimeout(nmu);
	})
	
	
	//categoria e sotto categoria
				
	$('#select_categoria').change(function(){
		
		if($(this).val() != 0){
			$('div.menu_categorie  #select_sottocategoria').select_replacement_loading()
			$.get('../shop/render_products.php',{show:'getsubcat',cat:$(this).val()},popola_select,'xml')
		}else{
			$('#select_sottocategoria').attr('disabled','').html('<option value="0">sottocategoria...</option>').val(0).attr('disabled','disables');
		}
		
	})
	

	$('#select_sottocategoria').change(function(){
		if($(this).val() != 0){
			$('body').append('<div id="page_loader"><p>caricamento...</p><img src="../img/ajax-loader.gif" /></div>')
			$('#form_categoria').submit();
		}
	});

	
	
	$('div#header div.menu_categorie ul li.search input').focus(function(){

		$(this).parent().css('backgroundPosition','center bottom')

		if($(this).val() == 'cerca'){
			$(this).val('');
		}
	}).blur(function(){
		$(this).parent().css('backgroundPosition','center top')
	})
	

	//centro il menu "artistico" e installo l'handler per il mouseover
	var nli = $('ul.hmenu li').length;
	var wli = parseInt(100/nli);		
	$('ul.hmenu li').css('width',wli+'%');
	 
    $("ul.hmenu li a").before('<img class="btnshadow" src="../img/icons-shadow.jpg" width="152" height="20" alt="" />');


    $("ul.hmenu li").hover(function() {
    	var e = this;
        $(e).find("a").stop().animate({ marginTop: "-14px" }, 250, function() {
        	$(e).find("a").animate({ marginTop: "-10px" }, 250);
        });
        $(e).find("img.btnshadow").stop().animate({ width: "80%", height: "20px", marginLeft: "8px", opacity: 0.25 }, 250);
    },function(){
    	var e = this;
        $(e).find("a").stop().animate({ marginTop: "4px" }, 250, function() {
        	$(e).find("a").animate({ marginTop: "0px" }, 250);
        });
        $(e).find("img.btnshadow").stop().animate({ width: "100%", height: "27px", marginLeft: "0px", opacity: 1 }, 250);
    });


	$("#btn_login").fancybox({
		width:300,
		onComplete: function(){
			
			
				function loginResponse(xml){
					$.fancybox.hideActivity();
					
					var response = $(xml).find("response");
					
					
					if( parseInt(response.text()) == 1){
						window.location.reload();
					}else{
						$("#loginmodal-login-error").show();
						$.fancybox.resize();
						
					}
				}
					
				function loginSubmit(formData, jqForm, options){
				   for (var i=0; i < formData.length; i++) { 
				        if (!formData[i].value) { 
							$("#loginmodal-login-error").show();
							$.fancybox.resize();				             
				            return false; 
				        } 
				    }					
					$.fancybox.showActivity();
				}
				
					
				var options = { 
				    beforeSubmit:  loginSubmit,
				    success:       loginResponse,
				    dataType:  	   'xml'
				  }; 
				  
				$('#user_login_form').ajaxForm(options); 			
		}
	
	});
	
	$(".popup").fancybox({width:450,height:400,type:'iframe'});
	$(".detail_popup").fancybox({autoDimensions:false,width:450,height:400,type:'iframe'});
	
})
