/* If browser doesn't support console command */
typeof console=="undefined"&&(console={log:function(){},debug:function(){},error:function(){},info:function(){},warn:function(){},assert:function(){},trace:function(){},group:function(){},groupEnd:function(){},profile:function(){},profileEnd:function(){},time:function(){},timeEnd:function(){}})
/* Custom console command */
var debug = true;
cons = {
    log: function(str) {
        if (debug) { console.log(str); }
    },
    error: function(str) {
        if (debug) { console.error(str); }
    },
    info: function(str) {
        if (debug) { console.info(str); }
    },
    warn: function(str) {
        if (debug) { console.warn(str); }
    }
}

var resizeTimeout;

// jQuery DOM ready
$(document).ready(function() {
    cons.log("jQuery ready...");
    
    // Apply Sencha's PIE.js
    if (window.PIE) {
        $('.css3').each(function() {
            PIE.attach(this);
        });
    }

    // Background resize
    bgResize();
    $(window).on("resize", function(event) {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(function() {
            console.log(event.type+" "+event.target);
            bgResize();
        }, 50);
    });
    
    // Cycle image setup
    $('#cycle').find('img').attr({
        width: 366,
        height: 274
    })/*.parent().attr('rel', 'gallery');*/
    
    // Cycle
    $('#cycle').cycle({
        fx:    'scrollLeft',
        sync:   1,
        delay: 2000,
        timeout: 3000
    });
    
    // Fancybox gallery
    $('#cycle').find('a[rel="gallery"]').fancybox({
		'transitionIn'		: 'easeOutBack',
		'transitionOut'		: 'easeInBack'
	});

    // Characters counter
    $('#message').jqEasyCounter({
		'maxChars': 360,
		'maxCharsWarning': 358,
        'msgFontSize': '11px',
        'msgFontColor': '#000'
    });
    
    // Info privacy
    $('#privacy').click(function(){
        showBox($(this).attr('id')+"_info");
    });
    
    // Mostra Fancybox
    function showBox(el){
        $.fancybox({
            'width'				: 620,
            'height'			: 360,
            'autoDimensions'    : false,
            'transitionIn'		: 'elastic',
            'transitionOut'		: 'elastic',
            'overlayOpacity'    : .7,
            'overlayColor'      : '#000',
            'content'           : $('#'+el).html(),
            'centerOnScroll'    : true
        });
    }
    
    // Azione pulsante di invio del form
    $('#richiesta').find('.btn-send').click(function() {
        console.log("Invio form...");
        sendEmail();
        return false; 
    });
    
    /**
     * Controlla ed invia Email
     */
    function sendEmail() {
        console.log("Checking Email...");
        var name = $('#name');
    	if (trim(name.val()).length === 0) {
    	    showError("Inserisci il tuo nome.");
            name.focus();
    	    return false;
    	}
        var email = $('#email');
    	var email_filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    	if (!email_filter.test(email.val())) {
    	    showError("Inserisci un'Email valida.");
    	    email.focus();
    	    return false;
    	}
        var phone = $('#phone');
        if (trim(phone.val()).length === 0) {
    	    showError("Inserisci un numero di telefono.");
            phone.focus();
    	    return false;
    	}
        var phone_filter = /^([0-9\+]{1})([0-9])*$/;
        if (!phone_filter.test(phone.val())) {
            showError("Inserisci un numero di telefono valido.");
    		phone.focus();
    		return false;
	    }
        var message = $('#message');
    	if (trim(message.val()).length === 0) {
    	    showError("Scrivi un messaggio.");
            message.focus();
    	    return false;
    	}
    	$.ajax({
    		url: 'email/sendEmail.php',
    		type: 'POST',
    		data: {'name': name.val(), 'email': email.val(), 'phone': phone.val(), 'message': message.val()},
    		dataType: 'json',
    		error: function(xhr, desc, exceptionobj) {
    			alert(xhr.responseText);
    		},
    		success : function(json) {
    			ajaxOK(json.response);
    		}
    	});
    	
    	function ajaxOK(response)
    	{
    		switch(response)
    		{
    			case "error":
    				alert("Errore nell'Invio dell'Email, si prega di riprovare.");
    			break;
    			case "ok":
    				alert("Email inviata con successo. Riceverati presto una risposta.");
                    resetForm();
    			break;
    		}
    	}
        return false;
    }
    
    /**
     * Mostra un box di errore con il testo specificato
     * @param string str - messaggio di errore
     */
    function showError(str) {
        var el = $('#richiesta').find('.error');
        el.text(str).stop(true, true).fadeIn(500).delay(1500).fadeOut(500);
    };
    
    /**
     * Controlla la presenza di spazi bianchi in una stringa
     * @param string str
     * @retun boolean
     */
    function trim(str) {
        var str = str.replace(/^\s\s*/, ''),
        ws = /\s/,
        i = str.length;
        while (ws.test(str.charAt(i = i-1)));
        return str.slice(0, i + 1);
    };
    
    function resetForm() {
        var form = $('#richiesta');
        form[0].reset();
    }
    
    function bgResize() {
        console.log("Background resize...");
        var el = $('#body_bg');
        var img = $('#body_bg').children('img');
        img.width($(window).width()).height($(window).height());
        /*
        var img = $('#body_bg').children('img');
        var imgRatio = img.width()/img.height;
        el.width($(window).width()).height($(window).height());        */
        //.height(Math.round($(window).width()/imgRatio));
    };
    
});
