////////////////////////////////////////////////////////////

(function($) {
	//ARRAY - LAST
	$.fn.last = function() {
	   return this[this.length-1];
	}
	
	//FORM - FORM ELEMENTS ENABLE
	$.fn.enable = function() {	
		if (this.get(0).tagName=='FORM')
			$(':input', this).removeAttr('disabled');
		else
			$(this).removeAttr('disabled');
	};
	
	//FORM - FORM ELEMENTS DISABLE
	$.fn.disable = function() {
		if (this.get(0).tagName=='FORM')
			$(':input', this).attr('disabled', 'disabled');
		else
			$(this).attr('disabled', 'disabled');
	};
	
	//FORM CHECK REQUIRED FIELDS
	$.fn.checkRequired = function() {
		var _required=true;
		$('.required', this).each (function () {
			$(this).removeClass('input_error');
			if ($(this).val()=='') {
				$(this).addClass('input_error');
				_required=false;
			}
		});
		return _required;
	}
	
})(jQuery);

function printMessage (txt) {
	alert (txt);
}


/* ------------------       passion cocoa      */

function sendMail(){

 var emailREG = /^(\w+[\.\-\_\s])*\w+@(\w+[\.\-\_\s])+[A-Za-z]+$/;


  if ($('#nome').val() == "" || $('#nome').val() == "Nome*" ) {     
    alert("e' necessario inserire il nome");     
    return false;   
  }
  
  if ($('#cognome').val() == "" || $('#cognome').val() == "Cognome*" ) {     
    alert("e' necessario inserire il cognome");     
    return false;   
  }

  if ($('#telefono').val() == "" || $('#telefono').val() == "Telefono*" ) {     
    alert("e' necessario inserire il telefono");     
    return false;   
  }

  if ($('#email').val() == "" || $('#email').val() == "Email*" ) {     
    alert("e' necessario inserire la mail");     
    return false;   
  }

  if ( !emailREG.test($('#email').val()) ) {  
   alert("l'email inserita non è in formato valido");   
   return false;
  }

  if (!$('input[name=utente]').is(':checked') && !$('input[name=rivenditore]').is(':checked') ) {
		alert ('Scegli la tipologia di utenza');
		return false;
	}
	
	if($('input[name=utente]').is(':checked')){
    $('#user').val('utente');
  }
  if($('input[name=rivenditore]').is(':checked')){
    $('#user').val('rivenditore');
  }


  if ($('#richiesta').val() == ""  ) {     
    alert("e' necessario inserire una richiesta");     
    return false;   
  }

	if (!$('input[name=privacy]').is(':checked')) {
		alert ('Leggi e accetta l\'informativa sulla privacy');
		return false;
	}

  $('#f_mail').submit(); 

  
  return true;
}

function initForm(){

  $('input').click(function() {

    $(this).val('');
  });

}


/* ------------------       fine passion cocoa */



/* ------------------       generali     */

function initPage() {
	$('#doLogin, #doLogout').click(doLogin);
}		

function doLogin () {
  
	if ($(this).attr('id')=='doLogout') {
		window.location.href='/logout.php';
	} else {
	   
		if ($('#loginPannel').is(':visible'))
			$('#loginPannel').hide();
		else
		{
    	$('#loginPannel').show();
			$('#email').val('');
		}	
	}
	return false;
}


/*  da fermare l'observe sul click mentre è in atto l'animazione  */
function initGalleries (){
	//TODO click
	$('#right_arrow').click(function () {
		var cnt=$('#gallery').children();		
		var ml=parseInt(cnt.css('margin-left').replace('px',''));
		if (ml<=$('#gallery').width()-cnt.width()+184)
			return false;
		
		cnt.stop().animate({'margin-left':(ml-184)+'px'},200);
		
		return false;
	});


	$('#left_arrow').click(function () {
		var cnt=$('#gallery').children();
		var ml=parseInt(cnt.css('margin-left').replace('px',''));
		if (ml>=0)
			return false;
			
		cnt.stop().animate({'margin-left':(ml+184)+'px'},200);
		
		return false;
	});

	$('#right_arrow2').click(function () {
		var cnt=$('#gallery2').children();		
		var ml=parseInt(cnt.css('margin-left').replace('px',''));
		if (ml<=$('#gallery2').width()-cnt.width()+184)
			return false;
		
		cnt.stop().animate({'margin-left':(ml-184)+'px'},200);
		
		return false;
	});

	$('#left_arrow2').click(function () {
		var cnt=$('#gallery2').children();
		var ml=parseInt(cnt.css('margin-left').replace('px',''));
		if (ml>=0)
			return false;
			
		cnt.stop().animate({'margin-left':(ml+184)+'px'},200);
		
		return false;
	});
	
  return false;
}



function appear(){

	                                                
	if($('#fade')){
	 $('#fade').fadeOut(1000,callPromo);
	 //$('.immagine').fadeIn(1000);
   //$('.cont_int').fadeOut(1000,callPromo);
	} 
	else
	 callPromo();
	
	return false;
}

function callPromo(){
 
  var cat;

  if($('#menu').length >0)
    cat = $('#menu').attr('class').split('_');
  else
    cat = 0;
  
  var objHash={};
  objHash.action='SHOW';
  objHash.cat=cat[1];
  
 	$.ajax({
  	url: '/include/general_process.php',
  	data: objHash,
  	type: 'POST', 
  	dataType: 'json', 
  	success: function (data) {
 	
  		if (!data.res) {
  			printMessage(data.msg);  		
  		} else {

  		  $('#fade').hide().html(data.cnt).fadeIn(1000);
  		  $('#fade').remove();
  		  $('.show').html(data.cnt);
  		  $('#fade').hide().fadeIn(1000);
        //$('.immagine').hide().html(data.image).fadeIn(1000);
  		  //$('.cont_int').hide().html(data.text).fadeIn(1000);
  		  //alert(data.cnt);
  		}
  	},
  	error: function(XMLHttpRequest, textStatus){printMessage('Error:\n'+XMLHttpRequest.responseText)}
	});
  
}


/*------------detail---------------*/


function initProductThumbs () {

  $('.selected').fadeTo('fast', 0.5);
  $('.thumb').click(loadMediumImage);
	
	$('#richiedi').click(doRichiedi);
}

function loadMediumImage () {
	
	
	var id= $(this).attr('id').split('_');
	
	
	if ($(this).hasClass('selected'))
		return false;
	
 
  var old = $('.selected').attr('id').split('_');
   
  $('.selected').fadeTo('fast', 1);
  $('.selected').removeClass('selected');
  
 
  $('#item_medium_image_'+old[3]).hide();
  $('#item_medium_image_'+id[3]).show();
  $(this).addClass('selected');
   $(this).fadeTo('fast', 0.5);		
	
	/*var src=Event.findElement(event,'A');
	var id=src.id.split('_').last();

	if ($('item_medium_image_'+id).visible())
		return false;
		
	var old=$$('#item_thumbs a.selected')[0];
	old.down('img').setOpacity(1);
	old.removeClassName('selected');
	$('item_medium_image_'+old.id.split('_').last()).hide();
	
	src.down('img').setOpacity(.5);
	$('item_medium_image_'+id).show();
	src.addClassName('selected');
	*/
	return false;
}


function doRichiedi()
{
  
  var objHash={};
  objHash.action='SHOWRICHIEDI';
 	objHash.id_prodotto=$(this).attr('rel');
  

  
	$.ajax({
  	url: '/include/general_process.php',
  	data: objHash,
    dataType: 'json',	
  	success: function (data) {
  	
  	if (!data.res) { //ERROR
  			alert(data);
  		} else { //OK
  			showOver();
  			$('#wOverContainer').html(data.msg);
  			$('#sendRequest').click(sendInvite);
  		//	$('#hide_lang').val($('#lang').val());
  		}
  	},
  	error: function(XMLHttpRequest, textStatus){printMessage('Error:\n'+XMLHttpRequest.responseText)}
	}); 
  return false;
}

function sendInvite(){
   var emailREG = /^(\w+[\.\-\_\s])*\w+@(\w+[\.\-\_\s])+[A-Za-z]+$/;
   
   if (!$('#FI').checkRequired()) {
		alert ('Devi completare tutti i campi');
		return false;
	 }
	 
	 if (!emailREG.test($('#email').val())) {
		$('#email').addClass('input_error');
		alert ('FORMATO EMAIL NON VALIDO');
		return false;
	 }
	//
	var objHash={};
    objHash = $('#FI').serialize();
  $.ajax({
  	url: '/include/general_process.php',
  	data: objHash,
    dataType: 'json',	
  	success: function (data) {

    if (!data.res) { //ERROR
  			alert(data);
  		} else { //OK
          
        var testo = '<div id="reg_panel">La tua richiesta &egrave; stata inoltrata<br /><br /><a onclick="closeOver(); return false;" href="" class="shopButton conferma">Chiudi</a></div>';
        $('#wOverContainer').html(testo);
     }      
  	},
  	error: function(XMLHttpRequest, textStatus){printMessage('Error:\n'+XMLHttpRequest.responseText)}
	});	
  
  return false;

}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}

function initUserForm (){
	$('#saveUser').click(saveUser);
	lookType();
}

function initUserForm (){
	$('#saveUser').click(saveUser);
	lookType();
}

function saveUser (event) {

   var emailREG = /^(\w+[\.\-\_\s])*\w+@(\w+[\.\-\_\s])+[A-Za-z]+$/;
   
   if (!$('#FER').checkRequired()) {
		alert ('Devi completare tutti i campi');
		return false;
	 }
	 
	 if (!emailREG.test($('#email').val())) {
		$('#email').addClass('input_error');
		alert ('FORMATO EMAIL NON VALIDO');
		return false;
	 }

	$('#FER').target='PRF';
	$('#FER').submit();	
	setForm (false);
	
	return false;
}

function lookType(){
  if($('#tipo').val() == 'P')
  {
    $('#tr_azienda').hide();
    $('#tr_piva').hide();
    $('#azienda').removeClass('required');
    $('#piva').removeClass('required');  
  }
  else
  {
    $('#tr_azienda').show();
    $('#tr_piva').show(); 
    $('#azienda').addClass('required');
    $('#piva').addClass('required'); 
  }
}



