// font replace
Cufon.replace('.replace', {
	hover: true,
	hoverables: { a: true, button: true }
});

function facebook_login(e) {
  window.location = window.location.protocol + '//' + window.location.host + '/fb_user_service.php?action=login';
}

function rollIE(lingua){
 $('button.btn_rosa').live('mouseover', function(){
     $(this).addClass('btnHover').css({'background-image': 'url("img/'+lingua+'/sprite_btn_rosa.png")'
  			});
     });
     $('button.btn_rosa').live('mouseout', function(){
    $(this).removeClass('btnHover').css({'background-image':'url("img/'+lingua+'/sprite_btn_rosa.png")'
 			});
     });
   $('button.btn_stretto').hover(function(){
     $(this).addClass('btnHover').css(
     	{	'background-image': 'url("img/comuni/btn_largo_stretto.png")',
     		'background-position':'-200px -64px'
     		});
     }, function(){
     $(this).removeClass('btnHover').css(
     	{	'background-image': 'url("img/comuni/btn_largo_stretto.png")',
     		'background-position':'0 -64px'
     		});
     });
    $('button.btn_largo').hover(function(){
     $(this).addClass('btnHover').css(
     	{	'background-image': 'url("img/comuni/btn_largo_stretto.png")',
     		'background-position':'-200px 0'
     		});
     }, function(){
     $(this).removeClass('btnHover').css(
     	{	'background-image': 'url("img/comuni/btn_largo_stretto.png")',
     		'background-position':'0 0'
     		});
     });
};

$(function(){

  jQuery.fn.outerHTML = function(s) {
    return (s) ? this.before(s).remove() : jQuery("<p>").append(this.eq(0).clone()).html();
  };

	$('#finestra_modale').ajaxSend(function(evt, request, settings){
			$('#finestra_modale #messaggio').html('<img src="/img/comuni/spinner.gif" />');
		});

		$('a.apriModale').live(
			"click",
			function(el){
				if($(this).attr('href')){
					if($(this).attr('href').length>1 && $(this).attr('href').substr(0, 1) == '#' && !$(this).attr('title')){
						$($(this).attr('href')).show();
						apriModale({message: $($(this).attr('href')).outerHTML(), target_el:this});
						$($(this).attr('href')).hide();
					}else{
						apriModale({url: $(this).attr('href'), target_el:this});
					}
				}else if(this.title){
					apriModale({message: $(this).attr('title'), target_el:this});
				}
				return false;
			}
		);



	// HOME PAGE ////////////////////////////////////////////
		// login hp
		$('#login').ajaxForm({
	    	dataType: 'json',
	    	success: function(data){
	    		if(data.success){
	    			location.href = 'private_page_home.php';
//	    			$('#username_utente_loggato').html(data.response.nickname);
//	    			$('#login').fadeOut();
//	    			$('#utente_loggato').fadeIn();
	    		}else{
	    			apriModale({message:data.response});
	    		}
	    	}
		});
		// switch lovatar
		$('#labelz a').click(function(){
			$('#labelz a').removeClass('active');
			$(this).addClass('active');
			var target= $(this).attr('href');
			$('.lovatar').hide();
			$(target).fadeIn();
			return false;
		});
		// GADGETS vignette /////////////////////////////////////
		function mostraVignetta(data){
		$('#modalBoxOverlay').show();
			$('#popSketch img').load(function(){
				var offset =$('#vignettaModale').outerHeight()/2;
				if(typeof document.body.style.maxHeight == "undefined") {
					// IE6
					var viewportheight = document.documentElement.clientHeight //altezza area visibile
					var scrOfY = document.documentElement.scrollTop; //scroll verticale
					var topIe6 =scrOfY+(viewportheight/2)-offset;	//margin-top
					$('#vignettaModale').css({'top':topIe6+'px'}).fadeIn();
				}else{
				// tutti gli altri
				$('#vignettaModale').css({'top':'50%', 'margin-top':'-'+offset+'px'}).fadeIn();
				};
			});
		};
		$('a').live('click', function(event){ //intercetto il click
		if($(this).attr('rel')=='vignetta'){
			var target = $(this).attr('href');
			$('div#vignettaModale .messaggio').load(target, null, mostraVignetta);
			event.preventDefault();
		};
		if($(this).attr('rel')=='chiudiVignetta'){
			$('div#vignettaModale').hide();
			$('#modalBoxOverlay').hide();
			event.preventDefault();
		}

	});



	// APRI SONDAGGI /////////////////////////////////////
	$('a.apriSondaggio').live('click', function(){
		$.target_url =$(this).attr('href');
		$.get(
				'ajax/login_modale.php',
				null,
				function(data){
					if(data['success']){
						var target=$.target_url;
						var windowLeft = (screen.width - 475) / 2;
				  		var windowTop = (screen.height - 396) / 2;
				      window.open(target, 'popup', 'height=396, width=475, top=' + windowTop + ',left=' + windowLeft + ',scrollbars=no, resizable=0, menubar=0, toolbar=0, location=0, statusbar=0, fullscreen=0');
					}else{
						bloccaInterfaccia({});
						$('#messaggio').fadeIn();
						$('#finestra_modale #messaggio').html(data['response']);
						centraMessaggio();
					}
				},
				'json'
			);
      return false;
	});
	// APRI TEST ////////////////////////////////////////
		$('a.apriTest').live('click', function(){
		$.target_url =$(this).attr('href');
		$.get(
				'ajax/login_modale.php?chk_login_required='+$.target_url,
				null,
				function(data){
					if(data['success']){
						var target=$.target_url;
						var windowLeft = (screen.width - 580) / 2;
  						var windowTop = (screen.height - 380) / 2;
     					window.open(target, 'test', 'height=380, width=580, top=' + windowTop + ',left=' + windowLeft + ',scrollbars=no, resizable=0, menubar=0, toolbar=0, location=0, statusbar=0, fullscreen=0');
					}else{
						bloccaInterfaccia({});
						$('#messaggio').fadeIn();
						$('#finestra_modale #messaggio').html(data['response']);
						centraMessaggio();
					}
				},
				'json'
			);
      return false;
	});
	// APRI TOOLS ///////////////////////////////////////
		$('a.apriTool').live('click', function(){
			$.target_url = $(this).attr('href');
			$.get(
				'ajax/login_modale.php?chk_login_required='+$.target_url,
				null,
				function(data){
					if(data['success']){
						var target=$.target_url;
						var windowLeft = (screen.width - 580) / 2;
				  		var windowTop = (screen.height - 380) / 2;
				  		window.open(target, 'tools', 'height=380, width=580, top=' + windowTop + ',left=' + windowLeft + ',scrollbars=no, resizable=0, menubar=0, toolbar=0, location=0, statusbar=0, fullscreen=0');
					}else{
						bloccaInterfaccia({});
						$('#messaggio').fadeIn();
						$('#finestra_modale #messaggio').html(data['response']);
						centraMessaggio();
					}
				},
				'json'
			);
			return false;
		});

	// MUSICA IN HOME //////////////////////////////////
	$('a#toggleMusic').live('click', function() {
		if ($(this).hasClass('on')) {
			window.suono.location.href = "music_off.php";
			$(this).removeClass('on').addClass('off');
			$.get('services/chkSession.php?audio_ctrl=off', null, null);
		} else {
	    $.get('services/chkSession.php?audio_ctrl=on', null, null);
			window.suono.location.href = "music_on.php";
			$(this).removeClass('off').addClass('on');
		}
		return false;
	});
	
	// TOOLTIPS ////////////////////////////////////////
	$('.tTips').tooltip({
		track: true,
    delay: 0,
    showURL: false,
    showBody: " - ",
    fade: 250
	});
});

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


// CONCORSO JUSTIN BIEBER ============================
function apriBieber(){
   $('body').openModal({
      ovOpacity: 0,
      closeOnOverlay: false,
      extPage : 'bieber_istantwin.php',
      spinner : 'img/comuni/spinner.gif',
      addClose : '.chiudi'
      // callback: initValidation //validateForm      
    });
};
// $('.bieberModal .invitamiche').live('click', function(){
 //    $('#bieber_iw6').fadeIn();
 //    return false;
 // });  
$('a[rel=remote]').live('click', function(e){
  var target = $(this).attr('href');
  $('#modal').load(target);
  e.preventDefault();
});

$('a[rel=feedbackSms]').live('click',function(){
        $(this).openModal({
			ovOpacity: 0,
			addClose : '#chiudi'
		}); 
    });
// valido form invitamiche ------------------------------
   function initValidation(){
      $('#formInvita').validate({
         onfocusout:false,
         onkeyup: false,
         showErrors: function(errorMap, errorList) {
            if (errorList.length > 0){                  
                  alert(errorList[0].message);
               }
             this.defaultShowErrors();          
              },        
         rules:{
            nickname: 'required',
            mail:{
               required: true,
               email: true
            },
            nome1: 'required',            
            email1:{
               required: true,
               email: true
            },   
            nome2: {
               required: function(){
                  return $('#email2').val() != '';
               }
            },      
            email2:{
               required: function(){
                  return ($('#nome2').val() != '' || $('#email2').val() != '');
               },
               email: true
            },
            nome3:{
                  required: function(){
                  return $('#email3').val() != '';
               }                  
            },      
            email3:{
               required: function(){
                  return ($('#nome3').val() != '' || $('#email3').val() != '');
               },
               email: true
            }   
         }, 
         messages:{
            nickname: 'Inserisci il tuo nome',
            mail:{
               required: 'Inserisci la tua mail',
               email: 'Inserisci una mail corretta'
            },
            nome1: 'Inserisci il nome di almeno una amica',
            email1:{
               required: 'Inserisci la mail della tua amica',
               email: 'Inserisci una e-mail corretta'
            },
            nome2: 'Inserisci il nome della tua seconda amica',
            email2:{
               required: 'Inserisci la mail della tua seconda amica',
               email: 'Inserisci la mail della tua seconda amica correttamente'
            },
            nome3: 'Inserisci il nome della tua terza amica',
            email3:{
               required: 'Inserisci la mail della tua terza amica',
               email: 'Inserisci la mail della tua terza amica correttamente'
            }            
         },
         errorPlacement: function(error, element) {
           error.appendTo($('#fake')); //nascondo i messaggi d'errore
         },
         submitHandler: function(form) {
      	$(form).ajaxSubmit({   
      	  target: $('#feedBackLayout p'),       
          success: function(){
             $('#formLayout').hide();
             $('#feedBackLayout').fadeIn();
          }
      	});
      	return false;
         }
      });
   };
   
// funzione per nascondere testo di default nelle Textarea------------------------------  
$(function() {
    $('textarea.defaultText').each(function() {
       //$.data(this, 'default', this.value);
    }).focus(function() {
        if (!$.data(this, 'edited')) {
            this.value = "";
        }
    }).click(function() {
        $.data(this, 'edited', this.value != "");
    }).blur(function() {
        if (!$.data(this, 'edited')) {
            //this.value = $.data(this, 'default');
        }
    });
});
 




