// config

//var forum_url = "http://forum.tribelabs.com/";
//var post_per_page = 10;

// Non editare qui sotto

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        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;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});


//estrae i parametri dall'uri in base al nome
function getParameterByName(name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

// converte un formato data unixtime in una data secondo il formato specificato
// ci sono 2 modalita':
// - elapsed mostra il countdown
// - datetime mostra il formato gg / mm / YYYY HH:mm
//function fromUnixtimeToDate(unixtime,formato){
//    data = new Date(unixtime*1000);
//    if (formato == 'datetime'){
//        return data.getDate() + '/' + data.getMonth() + '/' + data.getFullYear() + " " + data.getHours() + ":" + data.getMinutes();   
//    } else if (formato=='elapsed') {
//        now = new Date();
//        oneday = 1000 * 60 * 60 * 24;
//        difference = Math.ceil((now.getTime()-data.getTime())/oneday);
//        if (difference > 1) {
//            return difference + " giorni fa";
//        } else if (difference == 1) {
//            return difference + " giorno fa";
//        } else {
//            return "alle " + data.getHours() + ":" + data.getMinutes();
//        }
//    } else {
//        return data.getDate() + '/' + data.getMonth() + '/' + data.getFullYear();
//    }
//}


//genera la paginazione dell'area commenti
//function generatePagination(cur,totcommenti){
//    var tot = Math.ceil(totcommenti/post_per_page);
//    this.tot_pagine = tot;
//    if (cur<=tot){
//        this.paginator = new Array();
//        for (i=1; i<=tot; i++)
//        {
//            if (i==cur){
//                this.paginator[i]='current';
//            } else {
//                this.paginator[i]='link';
//            }
//        }
//        if (cur != 1){
//            this.prev=cur-1;
//        }
//        if (cur !=tot){
//            this.next=cur+1;
//        }
//        if ((tot !=1 )&&(cur!=tot))
//        {
//            this.last = tot;
//        }
//    }
//}

// funzione per link agli anchor
jQuery.fn.anchorAnimate = function(settings) {
 	settings = jQuery.extend({
		speed : 1100
	}, settings);	
	return this.each(function(){
		var caller = this;
		$(caller).click(function (event) {	
			event.preventDefault();
			//var locationHref = window.location.href;
			var elementClick = $(caller).attr("href").substring(1);
                        console.log(elementClick);
			var destination = $('a[name='+elementClick+']').offset().top;
                        console.log(destination);
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
				window.location.hash = elementClick;
			});
		  	return false;
		})
	})
}



// funzione per la gestione dei submit dei commenti via ajax
//function bindPostCommentHandler(url) {
//    var target = url;
//    $('#comment-input-block form input.submit-preview').remove();
//    $('#comment-input-block form').submit(function() {
//        tinyMCE.triggerSave();
//        data = $('#comment-input-block form').serialize();
//        console.log(target);
//        $.ajax({
//            type: "POST",
//            data: data,
//            url: target,
//            cache: false,
//            dataType: "html",
//            success: function(html, textStatus) {
//                //$('#comment-input-block form').replaceWith(html);
//                $('#status-submit').replaceWith(html);
//                bindPostCommentHandler(target);
//            },
//            error: function (XMLHttpRequest, textStatus, errorThrown) {
//                $('#comment-input-block form').replaceWith('Al momento non siamo in grado di elaborare il tuo commento. Ci scusiamo per il disagio.');
//            }
//        });
//        return false;
//    });
//}


$(document).ready(function() {
    //gestione barra login
    // if guest
    $('#login-form form').jqTransform();
    $('#guestbar').appendTo('#login_bar');
    $('#guestbar').show();
    // if logged
    $('#loggedbar').appendTo('#login_bar');
    $('#loggedbar').show();
    
    $('.opencoso').click(function(){
        $('#login_bar').toggle("blind");
    });

    //codice per la gestione del text resize
    $('.resize-btn').click(function(){
            var ourText = $('.testo');
            var currFontSize = ourText.css('fontSize');
            var finalNum = parseFloat(currFontSize, 10);
            var stringEnding = currFontSize.slice(-2);
            if(this.id == 'large') {
                    finalNum *= 1.2;
            }
            else if (this.id == 'small'){
                    finalNum /=1.2;
            }
            ourText.css('fontSize', finalNum + stringEnding);
    });    

    // codice per la gestione dei pup
    $('.pup-btn').click(function(){
        var data_form = $("#pup-form").serializeArray();
        var pups_count = $('.pups-count').html();
        $.ajax({
            url: '/ajax/pup/',
            dataType: "json",
            cache: false,
            type: "POST",
            data: data_form,
            success: function(data) {
                if (data['done'] == true) {
                    $('.pup-big-icon').toggleClass('pup-big-icon-on', data['action'] == 'add');
                    if (data['action']=='add'){
                        $('.pups-count').html(parseInt(pups_count)+1);
                        $('#pup-form > input[name="action"]').val('remove');
                        puptip.data('tooltip').getTip().html("Grazie per aver puppato l'articolo!");
                    } else if (data['action']=='remove') {
                        $('.pups-count').html(parseInt(pups_count)-1);
                        $('#pup-form > input[name="action"]').val('add')
                        puptip.data('tooltip').getTip().html("Hai depuppato l'articolo!");
                    }
                }
            }
            //error: function() { alert("error"); },
        });
    });
    
    // codice per la gestione dei game tools
    $('.game-tools-btn').click(function(){
        var clicked_form = $("form", this);
        img = $("img", this);
        var data_form = clicked_form.serializeArray();
        $.ajax({
            url: '/ajax/game_funct/',
            dataType: "json",
            cache: false,
            type: "POST",
            data: data_form,
            success: function(data) {
                if (data['done'] == true) {
                    img.toggleClass(data_form[3].value+'-big-icon-on', data['action'] == 'add');
                    if (data['action']=='add'){
                        $('input[name="action"]', clicked_form).val('remove');
                    } else if (data['action']=='remove') {
                        $('input[name="action"]', clicked_form).val('add');
                    }
                }
            }
            //error: function() { alert("error"); },
        });
    });
    
    // codice gestione like
    // gestione della barra like
    //var toolbar = $('.up-dn-toolbar');
    //$('.commento-item').hover(
    //    function(){
    //        id = $(this).attr("id").match(/\d+/g);
    //        $('.like-btn', toolbar).each(function(i,elem){
    //            $(elem).attr("name",function(i,attr){ return attr+"&id="+id });
    //        });
    //        $('.testo-commento',this).before(toolbar);
    //        $(toolbar).show();
    //    },
    //    function(){
    //        $('.like-btn', toolbar).each(function(i,elem){
    //            $(elem).attr("name",function(y,attr){return attr.match(/action=\w{2}&type=\w+/)});
    //        });
    //        $(toolbar).hide();
    //    }
    //);
    ////submit del like
    //$('.like-btn').click(function(){
    //    $.ajax({
    //        type: "POST",
    //        data: $(this).attr('name'),
    //        url: '/ajax/like/',
    //        cache: false,
    //        dataType: "json",
    //        success: function(data){
    //            if (data['done']){
    //                $("#c_"+data['id']+" span."+data['action']+".counter").html(function(i,val){ return +val+1});
    //                console.log(data);
    //            }
    //        }
    //    });
    //});
    
});
