var urlAjaxHandler=serverPath+'functions/ma_common_helper.php'; // percorso  del contenuto del  dialog
var fill="";
var oldObjAcco="";
$(document).ready(function(){
	
	
	
	     //  swap    
		   swapValues = [];
	       $(".swap_value").each(function(i){
		        swapValues[i] = $(this).val();
		        $(this).focus(function(){
		            if ($(this).val() == swapValues[i]) {
		                $(this).val("");
		            }
		        }).blur(function(){
		            if ($.trim($(this).val()) == "") {
		                $(this).val(swapValues[i]);
		            }
		        });
	       });
		   
		   /*
		   var msgOpts = {
			modal: true,
			autoOpen: false,
			width: 300,
			height:150,
			closeOnEscape:true,
		    draggable: true,
			resizable: false,
			
			overlay: {	
				backgroundColor: '#000',
				opacity: 0.7
			}		
		};
		
		$("#msgBox").dialog(msgOpts);	//end dialog
		*/
		
		
		
        $(".optionsProdotti").each(function(i){
            $(this).click(function(){
				    curObj = this.id
				    if(oldObjAcco!='') {
                  if(curObj!= curObj)  {
                      $('#sub_' + oldObjAcco).slideToggle('slow');
                      $('#desc_' + oldObjAcco).toggleClass("highlighteasy");
                  }
                    
                    
                    
                    
                
                };
				        
                $('#desc_' + curObj).toggleClass("highlighteasy");
                $('#sub_' + curObj).slideToggle('slow');
                
                oldObjAcco=curObj
            });
        });
		
		 $("div.lista").each(function(i){
		    
            $(this).click(function(){
				    curObj = this.id
				    if(oldObjAcco!='') {
                    if(curObj!= curObj)  {
                      $('#sub_' + oldObjAcco).slideToggle('slow');
                      $('#desc_' + oldObjAcco).toggleClass("highlighteasy");
                  }
                
                };
				        
                $('#desc_' + curObj).toggleClass("highlight");
                $('#sub_' + curObj).slideToggle('slow');
                
                oldObjAcco=curObj
            });
        });
		 
		 
		 $(".boxEspandi").each(function(i){
	            $(this).click(function(){
	                curObj = this.id
	                
	                
	                $('#Lista_'+curObj).toggleClass("schedaprodottilista");
					$('#'+curObj).toggleClass("boxChiudi");
					if($('#'+curObj).hasClass('boxChiudi')) $('#'+curObj).html('Chiudi');
					else $('#'+curObj).html('Mostra tutti');
	                return false;
	            });
	        });
		 
		 
		 
		 
		
		$("#privacy").fancybox({
		'width'				: '75%',
		'height'			: 400,
		'padding'			: 10,
        'autoDimensions'     	:true,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'

	    });
    
		$("#credits").fancybox({
		'width'				: 400,
		'height'			: 300,
		'padding'			: 10,
        'autoDimensions'     	:true,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'

	});
	
	$("#richiesta").fancybox({
    'width'       : 490,
    'height'      : 500,
    'padding'     : 10,
    'autoDimensions'      :true,
    'transitionIn'    : 'none',
    'transitionOut'   : 'none',
    'type'        : 'iframe'
    });
  

  $(".contattiPop").click(function() {
     curObj=this.id.split('_');
         $.fancybox({
          //'orig'      : $(this),
          'padding'   : 0,
          'href'      : serverPath+'richieste.php/it/'+curObj[0]+'/1?IdTipo='+curObj[1]+'&cat='+curObj[2]+'&item='+curObj[3]+'&itemName='+curObj[4]+'&decoroImg='+curObj[4]+'_'+curObj[5],
          'width'       : 490,
          'height'      : 500,
          'padding'     : 10,
          'autoDimensions':true,
          'transitionIn'  : 'none',
          'transitionOut' : 'none',
          'type'          : 'iframe'
    });
    });
	
	
	
	$("#creaPosa").fancybox({
	    	 'width'				: 770,
		 		'height'			: 620,
		 		'padding'			: 0,
		        'autoDimensions'     	:true,
		         'transitionIn'		: 'none',
		 		'transitionOut'		: 'none',
		 		'type'				: 'iframe'
		 	});
    
  /*
   $(".contattiRegistrazione").click(function() {
	  apri_contatto_registrazione();
      return  false;
    });
	*/
    
	$("select.box").change(ricercaHelper);
	
	//slide  show  
	
	 $("a[rel=example_group]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
		}
	});
	
	if(isNewsletterActived==1)showConfermaIscrizione();
	
	$("a.ckLogin").fancybox({
		'scrolling'		: 'no',
		'titleShow'		: true,
		'onStart'		: function() {
		       ckLogin();
		},
		'onClosed'		: function() {
		    $("#msgBox").hide();
		}
	});
	
	
	
	
	
});

/*********************** ajax  and    modal  window  handler *******************/

function ckLogin(){
	 pageUrlLink=location.href;
	 location.href=serverPath+'reserved.php';
	 return false;
}



function  logout(){
    $.getJSON( urlAjaxHandler, 
  		 {actionType:'logout'}
		 
		 ,function(xml){
		 	if (xml.match('OK')) {
                location.href=serverPath+'index.php'
            }
            else erroreMessage('Si e\' verificato un Errore');
		   //alert(xml);
	     }
		 
     );
 
}

function  authUser(){

	  if($('#username').val()!='' && $('#password').val()!='') {
	   	     $.getJSON( urlAjaxHandler, 
	  		 {username: $('#username').val(),password:$('#password').val() ,actionType:'auth',isModal:$('#isModal').val()}
			  ,function(xml){
			 	 if (xml.status != 'KO') {
				     if(xml.message!=''){
			 			      erroreMessage(xml.message);
			 		 }
				     else  location.href=serverPath+'reserved.php';
			 		 }	           
	            else alert(xml.message)
			   
		     }	 
	     );
	  }
	  else alert('\n Prego inserire Username e Password	');
} 



function  sendPwd(){
	  
	  if($('#emailPwd').val()!='') {
	  	     showWait();
			 curEmail=$('#emailPwd').val();
			 //if(checkEmailValue(curEmail)==true){
				var url = serverPath+'functions/ma_common_helper.php';
				$.post( urlAjaxHandler, 
				 		 {email: curEmail,actionType:'sendPwd'}
					 ,function(xml){
					 	erroreMessage(xml);
					 	
					  }
					 
				  );
			  //}
			  //else erroreMessage('<?php echo MSG_ERROR_EMAIL_INVALID?>')
	  }
	  else   erroreMessage('<br><br>Inserire Email')
} 


function  aggiungiPreferiti(Id,titolo,IdObject){
    
	msg='';
  	//alert(location.href) 
	 showWait();
	 pageUrlLink=location.href;
	 if(msg=='') {
		 $.getJSON( urlAjaxHandler, 
  		 {IdUser: Id,pageTitle:titolo,pageUrl:pageUrlLink,actionType:'aggiungiPreferiti',IdObject:IdObject}
		 
		 ,function(xml){
		 	
                //location.href='profilo.php'
            
		   erroreMessage(xml.message);
	     }
		 
     );
  }
  else erroreMessage(msg);
}
//updateItem è l'id  del tracker che salvo in IdObject
function  aggiungiPreferitiDecoro(Id,titolo,IdObject,updateItem,type){
    msg='';
    showWait()
    //$("#" + updateItem).fadeIn('10').html('....adding....')
  	
	  pageUrlLink=location.href;
   
	 if(msg=='') {
		 $.post( urlAjaxHandler, 
  		 {IdUser:Id,pageTitle:titolo,pageUrl:pageUrlLink,actionType:type,IdObject:IdObject,Article:updateItem}
		 
		 ,function(xml){
			 if(xml.length<150){
			 var objJSon = jQuery.parseJSON(xml);
			      erroreMessage(objJSon.message);
			 }
			 else  erroreMessage(xml);
			 //$("#" + updateItem).fadeIn(200).html(xml.message).delay(1000).fadeOut(6000)
	     }
		 
     );
  }
  else erroreMessage(msg);
}

function apri_contatto_registrazione()
{
	curObj='';
	  
      $.fancybox({
   //'orig'      : $(this),
   'padding'   : 0,
   'href'      : serverPath+'registrazione.php?IdTipo='+curObj[1]+'&cat='+curObj[2]+'&item='+curObj[3]+'&itemName='+curObj[4],
   'width'       : 490,
   'height'      : 530,
   'padding'     : 10,
   'autoDimensions':true,
   'transitionIn'  : 'none',
   'transitionOut' : 'none',
   'type'          : 'iframe'
 });
}

function  iscivitiNewsletter(){
	    
		msg='';
	  //Email
	     
	     if(msg=='') {
	     showWait();
		 
		
	     $.post( urlAjaxHandler, 
	  		 {email: $('#email').val(),Firstname:$('#nome').val(),actionType:'newsletter'}
			 
			 ,function(xml){
			 	
	                //location.href='profilo.php'
	            erroreMessage(xml);
		     }
			 
	     );
	  }
	  else erroreMessage(msg);
	}  

/******************* start  ajax helper ***************************/
// funzione generica 
function  ma_ajax_helper(nome_form,actionTypeName){
  
  if(nome_form!='')para=$('#'+nome_form).serialize();
  else para="logout:1";
  $.post( urlAjaxHandler, 
  		 $('#'+nome_form).serialize()
		 
		 ,function(xml){
		 	if (xml.match('OK')) {
               erroreMessage(xml); 
            }
            else erroreMessage(xml);
		   //alert(xml);
	     }
		 
     );
  
} 




function  ma_ajax_updater(nome_form,actionTypeName,updateItem){
   $.ajax({
       url: urlAjaxHandler+'?actionType='+actionTypeName, 
       data:$('#'+nome_form).serialize(),
       type: 'POST',
       dataType: 'json',
       cache: false,
        success: function(risposta){
        if (risposta.status == 'OK') {
		
          $("#" + updateItem).html(risposta.message);
          
        }
        else alert(risposta.message);
      } 
     }
     );
} 

function  ma_ajax_updater_html(nome_form,actionTypeName,updateItem){
  $("#" + updateItem).html('<div id="loading">&nbsp;</div>');
   $.ajax({
       url: urlAjaxHandler+'?actionType='+actionTypeName, 
       data:$('#'+nome_form).serialize(),
       type: 'POST',
      
       cache: false,
        success: function(risposta){
		if (risposta) {
		
          $("#" + updateItem).html(risposta);
          
        }
        else alert(risposta.message);
      } 
     }
     );
} 


function  ma_ajax_load_html(page,updateItem){
  $("#" + updateItem).html('<div id="loading">&nbsp;</div>');
  $("#" + updateItem).load(page)
} 

 
function setDescrizione(){
  var p = $("#contentDescrizione");
  var t = $("#contentDescrizioneBox");
  var h=$(t).height();
  if(isFinito==false)$(t).slideToggle('slow', function(){isFinito=false} );
  isFinito=true
}
  
  /*
  $(t).animate({
       height:bh}, 
	   1000, "linear", function(){alert("all done");} );

}
*/
function ricercaHelper(){
  ma_ajax_updater_html('adv_search','getProduct','galleryBox')
}
function showSocial(){

	if($('#social').length>0){
		objSocial=$('#social');
		objSocial.show()
		var t = $(".contenutoSxLong");
		var h=$(t).height();
		var position = $(t).position()
		var hs=$('#social').height();
		posSocial=position.top+(h-hs)+8;
		objSocial.css({ position: "absolute",
              marginLeft: 0, marginTop: 0,
              top: posSocial });
	}
}
function setDescrizioneOn(){
  var p = $("#contentDescrizione");
  var t = $("#contentDescrizioneBox");
  var h=$(t).height();
  if(isFinito==false) $(t).slideDown('slow', function(){isFinito=false} );
}

// ricerca  avanzata  categorie
function ricercaAvanzata(nome_form){
	
	msg='';
   
	if ($('#sword').length > 0) {
		if($('#sword').val()=='Ricerca rapida' || $('#sword').val()=='') msg="Prego inserire un  parola"
	}
	

   

	if(msg!=''){
		erroreMessage(msg)
	}
	else {
		showWait()
	    document.forms[nome_form].submit()
	}
	
}

/***********************************  gestione  messaggi ***********************************/
function erroreMessage(msgContent){
	  $.fancybox(
			'<p>'+msgContent+'</p>',
			{
	        	'autoDimensions'	: false,
				'width'         		:'auto',
				'height'        		: 'auto',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			}
		);

}

function showWait(){
	
	 $.fancybox(
				$('#msgBox').html(),
				{
		        	'autoDimensions'	: false,
					'width'         	: 200,
					'height'        	: 'auto',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
				}
			);
}

function closeDialog(box){
   $(box).dialog('close');
  
}


/***************************** cancella  favoriti *************************/

//cancella  gli item
function deleteItem(obj){
   curObjToDel=obj
   showWait()
   cancellaOggetto(curObjToDel);
}

function cancellaOggetto(curObjToDel) {
    dataItem=curObjToDel.split('_');
    curId=dataItem[1];
    curTableItem=dataItem[0];
  //curItem='#item_'+curTableItem+'_'+curId;
    curItem=$('#item_'+curTableItem+'_'+curId)
    $.post( urlAjaxHandler, 
         {actionType:'deleteItem',
          Id:curId,
          dataType: 'json',
          mainTab:curTableItem
       },
       function(xml){
    	   var obj = jQuery.parseJSON(xml);

    	   erroreMessage(obj.message);
           if($(curItem))$(curItem).hide();
       }
     
     );
}



/****************************** fine  cancellazione ***********************/   



/*********************************funzioni ricerca negozi ********************************/
var curNazione
function ricercaNegozi(Obj,Campo,Valore) {
	//scoloro
	$('#'+Obj).parent().parent().children().each(function(index) {
	   $(this).children().css("color","#fff");
	});
	//coloro
	$('#'+Obj).css("color","#FFFF04");
    if(Campo=='IdCountry'){
    	$("#boxListaNegozi").html('');
    	curNazione=Valore;
    	ma_ajax_updater_ricerca(Campo,Valore,'select_citta','boxListaCitta');
 	};
    if(Campo=='City')ma_ajax_updater_ricerca(Campo,Valore,'select_negozi','boxListaNegozi');
    if(Campo=='Id')ma_ajax_updater_ricerca(Campo,Valore,'select_negozio','boxNegozio');
    else $("#boxNegozio").html('');
}

function ma_ajax_updater_ricerca(Campo, Valore, actionTypeName, updateItem) {
	    $("#" + updateItem).html('...loading...');
	    $.ajax( {
		url : urlAjaxHandler + '?actionType=' + actionTypeName+"&Campo="+Campo+"&Valore="+Valore+"&IdCountry="+curNazione,
		cache : false,
		success : function(code) {
			$("#" + updateItem).html(code);
			//closeDialog("#msgBox");
		}

	});

} 


function showConfermaIscrizione(){
	
	   alert('Gentile utente,\n\n\Ti ringraziamo per aver confermato la tua iscrizione.');
	   
}

function showDecoro(item) {
}
 

