var addEvent = function(elem, type, eventHandle) {
    if (elem == null || elem == undefined) return;
    if ( elem.addEventListener ) {
        elem.addEventListener( type, eventHandle, false );
    } else if ( elem.attachEvent ) {
        elem.attachEvent( "on" + type, eventHandle );
    }
};

var isMobile = false;

var agent=navigator.userAgent.toLowerCase();
if((agent.indexOf('iphone')!=-1) || (agent.indexOf('ipod')!=-1) || (agent.indexOf('ipad')!=-1) || (agent.indexOf('android')!=-1)){
    isMobile = true;
}


var myScroll;


var wh;
var ww;
var mtop;
var id0 = 'pic';
var id = '_';
var limMax;
var picsize;
var currentYear = (new Date).getFullYear();
var count = 0;
var tot_riga = 0;

var thisPos = 1;
var nBlocchi;
var spazioBlocco = 196;

var t;
var i=0;
var st;
var cipp = 0;

$(document).ready(init);

addEvent(window, "load", function() { resize(); loaded(); } );
addEvent(window, "resize", function() { resize(); } );
addEvent(window, "orientationchange", function() { resize(); } );

function init(){
    limMax = $('.foto .'+id0).length;
    $('.pic').attr('rel', 'gall');
    $(".year").text( (new Date).getFullYear() );
    $('#opentags').click(function(){
        $('.tags_cont').slideToggle(400, "easeInQuad");
    });
    $('#pic').addClass('active');
    $('.categorie a').click(function(){
        $('.categorie a').removeClass('active');
        $('.pic').removeAttr('rel');
        $(this).addClass('active');
        id0 = $(this).attr('id');
		id = '_';
		tot_riga = 0;
		$('.tag a').fadeOut(400);
		$('.tag a').removeClass('active');
        loading();
    });
    $('.tag a').click(function(){
        $('.tag a').removeClass('active');
        $('.pic').removeAttr('rel');
        $(this).addClass('active');
        id = $(this).attr('id');
		tot_riga = 0;
        loading();
    });
    $('.pic').fancybox({
        padding:0,
        margin:0,
        scrolling:'no',
        overlayColor:'#fff',
        overlayOpacity:0.75,
        titlePosition:'over',
        titleFormat: formatTitle
    });
}
function formatTitle(title) {
    return '<div class="fancytitle">' + title + '</div>';
}
function resize(){
    $('body').css('overflow-x','hidden');
    wh = $(window).height();
    mtop = (wh-657)/4;
    if (wh<657){
        $('.footer_cont').css({position:'static'});
    } else {
        $('.footer_cont').css({position:'absolute', bottom:0});
        $('.fascia').css({marginTop:mtop});
    }
    
    ww = $(window).width();
    if (ww<=980){
        $('body').css('overflow-x','auto');
        $('.fascia').width(980);
        nBlocchi = 5;
    } else {
        $('body').css('overflow-x','hidden');
        $('.fascia').width('100%');
        nBlocchi = ww/196;
    }
    
    if (picsize<=ww){
        $('.foto').width(picsize);
        $('.arrow_sx').fadeOut(400);
        $('.arrow_dx').fadeOut(400);
        if((ww-picsize) > $('.foto').offset().left){
            $('.foto').css({'position':'static','left':'auto','margin':'auto'});
        } 
    } else {
        $('.foto').width(picsize);
	    if(ww>=980 && !isMobile){
            $('.arrow_dx').fadeIn(400);
        }
        if((ww-picsize) > $('.foto').offset().left){
            $('.foto').css({left:(ww-picsize)});
			cipp = cipp;
        } 
    }
}
jQuery.fn.cleanWhitespace = function() {
    textNodes = this.contents().filter(
        function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); })
        .remove();
    return this;
}

function loaded(){
    $('.loading').fadeOut(400);
    $('.foto').cleanWhitespace();
    $('.foto').css({'display':'block','opacity':'0'});
	$('.foto a').each(function(index) {
		tot_riga+=$(this).width()
	});
	picsize = tot_riga;
	$('.foto').width(picsize);
    if(isMobile){
        myScroll = new iScroll('wrapper', { useTransition:true, hScrollbar: false, vScrollbar: false, vScroll: false});
        //document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    } else {
        gallery();
    }
	
    $('.foto').animate({opacity:1}, 400, "linear");
	
}
function filtro(){
    ww = $(window).width();
	picsize=tot_riga;
	cipp = 0;
    if (picsize<=ww){
        $('.arrow_sx').fadeOut(400);
        $('.arrow_dx').fadeOut(400);
		$('.foto').css({'position':'static','left':'auto','margin':'auto'});
        if(isMobile){
            setTimeout(function () {
                myScroll.refresh();
            }, 0);
        }
    } else {
		$('.foto').css({'position':'absolute','left':'0','margin':'none'});
		$('.foto').css({'display':'block','opacity':'0'});
        $('.foto').width(picsize);
        if(ww>=980 && !isMobile){
            $('.arrow_dx').fadeIn(400);
        }
        if(isMobile){
            setTimeout(function () {
                myScroll.refresh();
            }, 0);
        }
        
    }
	$('.foto').width(tot_riga);
    $('.loading').fadeOut(400);	
	$('.foto').animate({opacity:1}, 400, "linear");
    $('.foto').cleanWhitespace();
}


function loading(){
    $('.loading').fadeIn(400);
    $('.arrow_sx').fadeOut(400);
    $('.arrow_dx').fadeOut(400);

	$('.foto').animate({'opacity':0},400, function(){
        $('.tag a').each(function(){
			if(id0=='pic'){
				$('.tag a').fadeIn(400);
			}else if($(this).hasClass(id0)){
				$(this).fadeIn(400);							
			}
		});
        count = 0;
        $('.foto').css({left:0});
        if(isMobile){
            setTimeout(function () {
                myScroll.refresh();
            }, 0);
        }
        $('.pic').hide();
        $('.pic').each(function(){
            if (id != '_'){
                if ($(this).hasClass(id) && $(this).hasClass(id0)){
					$(this).attr('rel', 'gall');
					$(this).css({'display':'block','opacity':'0'});
					tot_riga+=$(this).width();
                    count++;
					$(this).animate({opacity:1}, 400, "linear");
                }
            } else {
                if ($(this).hasClass(id0)){
                    $(this).attr('rel', 'gall');
					$(this).css({'display':'block','opacity':'0'});
					tot_riga+=$(this).width();
                    count++;
					$(this).animate({opacity:1}, 400, "linear");
                }
            }
        });
    });
    st = setTimeout(filtro, 1000);
}



function gallery()
{
	$('#prev').hide();
    if(limMax <= nBlocchi){
        $('#next').hide();
    }
	$('#next').hover(function () {
		t = setInterval(moveGalleryNext, 36);
	},
	function () {
	  clearInterval(t);
	});
	$('#prev').hover(function () {
		t = setInterval(moveGalleryPrev, 36);
	},
	function () {
	  clearInterval(t);
	});
}

function moveGalleryNext()
{
	var p = $(".foto");
	var position = p.position();
	if(position.left<=-(picsize-ww)+11){
		$('#next').hide();
		clearInterval(t);
		$('.foto').css({'left':-(picsize-ww)+'px'})
	}
	else{
		cipp-=10;
		$('.foto').css({left:cipp})
		if(cipp < 1){
			$('#prev').show();
		}
	}
}
function moveGalleryPrev()
{
	var p = $(".foto");
	var position = p.position();

	if(position.left==0){
		$('#prev').hide();
		clearInterval(t);
	}else{
		$('#next').show();
		cipp+=10;
		$('.foto').css({left:cipp})
	}
}
