/**
 * Init file for Koreos 2012
 *
 * @author smanu85
 * @version 1.1
 * @package koreos
 */

/* 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=!1;cons={log:function(a){debug&&console.log(a)},error:function(a){debug&&console.error(a)},info:function(a){debug&&console.info(a)},warn:function(a){debug&&console.warn(a)}}

/* jQuery DOM ready */
$(function() {

// Instanzia widget orologio/data
var clock = new KoreosClock();

// Array di tutte i possibili effetti cycle
var cycleTransitions = ['blindX', 'blindY', 'blindZ','cover','curtainX','curtainY','fade','fadeZoom','growX','growY','none','scrollUp','scrollDown','scrollLeft','scrollRight','scrollHorz','scrollVert','shuffle','slideX','slideY','toss','turnUp','turnDown','turnLeft','turnRight','uncover','wipe','zoom'];

// jQuery UI buttons
$("section").find(".button, a.button_readmore").button();
$("section").find(".nav").find("a.prev").button({'icons': {primary:'ui-icon-circle-triangle-w'}});
$("section").find(".nav").find("a.next").button({'icons': {secondary:'ui-icon-circle-triangle-e'}});

// Nella pagina lista corsi imposta i box pari e dispari e associa le azioni
$('#lista_corsi').find('.box').each(function(index) {
    if (index%2 === 0) {
        // Se dispari
      	$(this).addClass("alpha");
    } else {
        // Se pari
        $(this).addClass("omega");
    }
    // Rendi cliccabile il box
    $(this).on('click', function() {
        location.href = filter_href($(this).find('.title').find("a").attr("href"));
        return false;
    });
});

// #BOX_PRESENTAZIONE
$("#box_presentazione").find(".content").cycle({
    'fx': 'fade',
    'timeout': 3000,
    'delay': 1000,
    'width': 295,
    'fit': 1
});

// #CORSO e #NEWS
$('#corso, #news').find('.cycle').cycle({ 
    'fx': 'fade',
    'speed': 1000,
    'timeout': 3000
});

// #BOX_CORSI
$('#box_corsi').find('.cycle').cycle({ 
    "fx":       "scrollLeft",
    "speed":    1000,
    "timeout":  3000,
    "pause": 1,
    "before": function() {
        $("#box_corsi").children(".box-inner").children(".cycle-alt").children("span").hide().text(this.title).delay(1000).fadeIn();
    },
    "delay": 500
});

// Se una news non ha immagine di anteprima elimina l'emento <img>
$("#lista_news").find('.box-news').each(function(index) {
    var el = $(this).find('img');
    if (el.attr('src') === "") { el.remove(); }
});

// NEWS
// Se non esite un cycle immagini rimuovi l'elemento e imposta il box info a grid_16
if ($('#news').find('.box-slideshow').find('.cycle').length == 0) {
    $('#news').find('.box-slideshow').remove()
    .end()
    .find('.box-info').removeClass('grid_8').addClass('grid_16');
};

}); // end jQuery DOM ready

/**
 * Return a random number within a given range
 *
 * @param string min Start number.
 * @param string max End number.
 * @return int Random integral.
 */
function randRange(min, max) {
    var randomNum = Math.round(Math.random()*(max-min))+min;
    return randomNum;
};

/**
 * 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);
};

/**
 * Mostra un box di errore con il testo specificato
 * @param string str - messaggio di errore
 */
function showMessage(str, error, form) {
    if (typeof error === 'undefined') {
        error = true;
    };
    if (typeof form === 'undefined') {
        form = $('form');
    } else {
        console.log("Form specificato");
    };
    console.log("Form scelto: "+form.attr('id'));
    var el = form.find('.form-alert');
    if (error) {
        el.removeClass('form-alert-success').text(str).stop(true, true).fadeIn(500).delay(1500).fadeOut(500);
    } else {
        el.addClass('form-alert-success').text(str).stop(true, true).fadeIn(500).delay(1500).fadeOut(500);
        form[0].reset();
    };
};

/**
 * Deferred wait (timeout like)
 * @extend jQuery
 */
jQuery.wait = function(time) {
	var dfd = $.Deferred();
	setTimeout(function() {
		dfd.resolve();
	}, time);
	return dfd;
};

/**
 * Check if user is using an iPhone
 */
function isIphone() {
    if((navigator.userAgent.match(/iPhone/i))/* || (navigator.userAgent.match(/iPod/i))*/) {
        return true;
    };
}

/**
 * Filter document base when redirecting with javascript
 */
function filter_href(loc) {
    // loc is the relative path your wish to redirect to
    var b = document.getElementsByTagName('base');
    if (b && b[0] && b[0].href) {
        if (b[0].href.substr(b[0].href.length-1) == '/' && loc.charAt(0) == '/')
        loc = loc.substr(1);
        loc = b[0].href + loc;
    };
    return loc;
}        

/**
 * Koreos Clock
 *
 * @author smanu85
 * @version 1.0
 * @package koreos
 */

function KoreosClock() {

    var _class = this;
    var _el = jQuery("#clock_date").find(".cont");
    var _months = ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"];
    var _dateInterval;
    var _delay = 60000;

    /**
     * Constructor
     */
    (function() {
        date();
        _dateInterval = setInterval(date, _delay);
    })();

    /**
     * Print current date
     */
    function date() {  
        var myDate = new Date();
        var hours = myDate.getHours();
        var mins = myDate.getMinutes();
        if (hours < 10) {
            hours = "0"+hours;
        }
        if (mins < 10) {
            mins = "0"+mins;
        }
        var output = '<div class="date">'+myDate.getDate()+' '+_months[myDate.getMonth()]+' '+myDate.getFullYear()+'</div><div class="clock">'+hours+':'+mins+'</div';
        _el.html(output);
    }

}; // end of Class
