/******************************************************
 /*
 /*  		File:    common.js version 1.0
 /*  		Author:  Francesco Bertelli, francescobertelli.com
 /*  		Website: http://www.francescobertelli.com/
 /*
 /*****************************************************/

var webkit = true;
var FF = /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent);
var OO = /Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent);
var IE = /MSIE[\/\s](\d+\.\d+)/.test(navigator.userAgent);

if (FF || OO || IE) {
    //test for Firefox and OPERA and IE
    webkit = false;
}

var winWidth = 0;
var winHeight = 0;
var isOpen = false;
var idleInterval;
var idleInterval2;
var isarchive = 0;
var hashindex = 0;
var totalItem = 0;
var q = 0;
var first = true;
var myScroll;
var currCols = 0;
var current = '';
var currentSlide = 1;
var currentMax = 0;
var totalCurrentImages = 0;
var oldWidth = 0;
var startWidth = 196;
var dividendo = 0;
var works_id = new Array();
var works_client = new Array();
var works_year = new Array();
var works_name = new Array();
var works_dark = new Array();
var works_url = new Array();
var works_description = new Array();
var images_array = new Array();
var images_array_title = new Array();
var works_css = new Array();
var works_website = new Array();
var works_quote = new Array();
var foto = new Array();
var imgfile = new Array();
var desktopCompat = true;
var client = '';
var totLi = 0;
var ishover = false;
var photo = new Array();
var isiPad = navigator.userAgent.match(/iPad/i) != null;
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;

idleTime = 0;


 


function stripslashes(str) {
    str = str.replace(/\\'/g, '\'');
    str = str.replace(/\\"/g, '"');
    str = str.replace(/\\0/g, '\0');
    str = str.replace(/\\\\/g, '\\');
    return str;
}

function imgresize() {

    winWidth = $(window).width();
    winHeight = $(window).height();

    var scarto = winWidth % startWidth
    currCols = Math.floor(winWidth / startWidth);
    dividendo = Math.floor(scarto / currCols);

    $('.li-box').width(startWidth + dividendo).height(startWidth + dividendo);
    $('.ex').width(startWidth + dividendo).height(startWidth + dividendo);
    $('.dummy').width(startWidth + dividendo).height(startWidth + dividendo);
    $('.bg').width(startWidth + dividendo).height(startWidth + dividendo);

    if (isOpen == true) {
	
		var idn = current;
		var s = idn % currCols;
		var rows = parseInt(totalItem / currCols);
		var res = idn + 1 > rows * currCols;
		if (res == true) {
		    newId = totalItem - 1;
		} else {
		    newId = (idn - 1 + currCols - s);
		}
		var div = $('#temp').remove();
		$('#box' + newId).after(div);
	
	
	
	var n = $('#scroller .inner').size();
 
	
        $('.full').width(winWidth).height(winHeight);
        $('#scroller').width(winWidth*n).height(winHeight);
        $('.inner').width(winWidth).height(winHeight);
        if (current > 0) {
	
            if (webkit == false) {
                $('#temp').scrollTo('.inner:eq(' + currentSlide + ')', 0);
            } else {
				myScroll.refresh();
                $('#scroller').css('-webkit-transform', 'translate3d(-' + currentSlide * winWidth + 'px, 0px, 0px)')
            }
        }
        var pos = $('#temp').position().top;
        $(window).scrollTop(pos);
    }
}

$(window).resize(function() {
    imgresize();
});

$(window).scroll(function() {
	var e=$(window).scrollTop();
	var pos = $('#temp').position().top;
 
	if(e==pos){
		ishover==true;
	}else{
	  ishover== false;
	}

});

function createHash(i) {
    window.location.hash = works_url[i] + '/';
}

function detectHash() {

    var hs = window.location.hash;

    if (hs && hs !== "#-") {
        hs = hs.replace('#', '');
        hs = hs.replace('/', '');
        hs = hs.replace(' ', '');
        hs = hs.replace(' ', '');
        hashindex = works_url.indexOf(hs);
        openWork(hashindex);
        setOpen(true);
    }

}

function writeWork(id) {
    current = id;
currentSlide = 1;
    var winWidth = $(document).width();
    var winHeight = $(window).height();
    var str;

    if (works_css[id] == '') {
        addstyle = "";
    } else {
        addstyle = "background-color:#" + works_css[id] + ";";
    }

    if (works_dark[id] == 0) {
        style = "";
    } else {
        style = " dark ";
    }

    if (id > 0) {
        n = 2;
    } else {
        n = 1;
    }

    if (images_array[current]) {
        if (images_array[current].length > 0) {
            i = images_array[id].length - 1;
        } else {
            i = 1;
        }
    } else {
        i = 1;
    }

    currentMax = (i + n) - 1;

totalCurrentImages = (i + n);

    str = '<li  class="full ' + style + '" id="temp"  style=" ' + addstyle + ' width:' + (winWidth) + 'px;">';
    str += '<div id="scroller" style="width:' + winWidth * (i + n) + 'px;" >';

    if (id > 0) {
        str += '<div  id="subtemp0"   class="inner last" style="width:' + winWidth + 'px;height:' + winHeight + 'px;    "  >';
        str += "<div class='prevprojbig' onclick='openNext()'><span class='span'>Previous Project:</span>" + works_name[id - 1].replace("\\","") + "</div>";
        str += "<div class='prevproj'  onclick='openPrev()' >Prev</div>";
        str += "<div class='nextproj' onclick='openNextImg()'>Next</div>";
        str += "</div>";
    }
    if (images_array[id]) {
        var imgw = images_array[id][1];
    }


    str += '<div id="subtemp1" class="inner" style="width:' + winWidth + 'px;height:' + winHeight + 'px;background-repeat:no-repeat; background-position:50% 50%; background-image:url(admin/works/' + works_id[id] + '/images/' + imgw + ')"  >';
    if (id > 0) {
        str += "<div class='previmg' onclick='openPrevImg()'>Prev</div>";
    }
    if (id < totalItem - 1) {
        if (id > 0) {
            str += "<div class='nextimg' onclick='openNextImg()'>Next</div>";
        } else {
            currentSlide = currentSlide - 1;
            str += "<div class='nextimg' onclick='openNextImg()'>Next</div>";
        }
    }
    str += "<div class='quote'>" + works_quote[id] + "</div>";

    str += "<div class='client'>" + works_description[id] + "</div>";
    if (id < totalItem - 1) {
        str += "<div class='client'>Project: " + works_name[id].replace("\\","") + "</div>";
        str += "<div class='client'>Year: " + works_year[id] + "</div>";
    }

    str += "<div class='web'><a href='" + works_website[id] + "' target='_blank'>" + works_website[id] + "</a></div>";
    str += "<div onclick=\"closeAll()\" id=\"close\">x</div> </div>";

    if (images_array[id]) {
        for (var w = 2; w < images_array[id].length; w++) {
            var imgw = images_array[id][w];
            str += '<div id="subtemp' + (2 + w) + '" class="inner" style="width:' + winWidth + 'px;height:' + winHeight + 'px;background-repeat:no-repeat; background-position:50% 50%; background-image:url(admin/works/' + works_id[id] + '/images/' + imgw + ')"  >';
            str += "<div class='previmg' onclick='openPrevImg()'>Prev</div>";
            str += "<div class='nextimg' onclick='openNextImg()'>Next</div>";
            if (images_array_title[id][w]) {

                str += "<div class='caption'>" + images_array_title[id][w] + "</div>";

            }
            str += "</div>";
        }
    }
    if (id < totalItem - 1) {
        str += '<div id="subtemp_last" class="inner last" style="width:' + winWidth + 'px;height:' + winHeight + 'px;"  >';
        str += "<div class='nextprojbig' onclick='openNext()'><span class='span'>Next Project:</span>" + works_name[id + 1].replace("\\","") + "</div>";
        str += "<div class='prevproj' onclick='openPrevImg()'>Prev</div>";
        str += "<div class='nextproj' onclick='openNext()'>Next</div>";
        str += "</div>";
    }
    str += '</div>';

    str += "</li>";

    return str;

}

function openNextImg() {
	
//
if(currentSlide < totalCurrentImages-1){
	currentSlide++;
    if (webkit == true) {
        myScroll.scrollToPage('next', 0);
    } else {
        $('#temp').scrollTo('.inner:eq(' + currentSlide + ')', 600);
    }
}else{
	openNext()
}
    var pos = $('#temp').position().top;

    $('html, body').animate({
        scrollTop: pos
    },
    'slow');
}

function openPrevImg() {
 

 
if(currentSlide>0){
		currentSlide--;
    if (webkit == true) {
        myScroll.scrollToPage('prev', 0);
    } else {
        
        $('#temp').scrollTo('.inner:eq(' + currentSlide + ')', 600);
    }
}else{
		openPrev()
}
	
    var pos = $('#temp').position().top;

    $('html, body').animate({
        scrollTop: pos
    },
    'slow');
}

function openNext() {
    if (current < totalItem - 1) {
        openWork(current + 1)
    }
    createHash(current);
}

function openPrev() {
    if (current > 0) {
        openWork(current - 1)
    }
    createHash(current);
}





function openWork(idn) {
	
	$('.li-box').not('#box' + idn).animate({'background-color': '#f5f5f5'},300);
	$('.title').not('#title' + idn).animate({'color': '#00c2d9'},300);
	$('.dummy').show();            
	$('.bg').fadeTo(300, 1);
	$('.numbers').fadeTo(150, 1);

    var idn = idn;
    createHash(idn);

    var s = idn % currCols;
    var rows = parseInt(totalItem / currCols);
    var res = idn + 1 > rows * currCols;
    if (res == true) {
        newId = totalItem - 1;
    } else {
        newId = (idn - 1 + currCols - s);
    }

    var div = writeWork(idn);
    var img = imgfile[idn];

	
 
    $('#box' + idn).css('background-image', 'url(ajax-loader.gif)').css('background-color', '#00c2d9');
    $('#box' + idn).children('.bg').fadeTo(300, 0);
    $('#box' + idn).children('.ex').fadeTo(300, 0);

//	$('.title').not(':eq('+idn+')').fadeTo(300, 0);

	$('#box' + idn).children('.title').css('color', '#fff').css('opacity', '1')
	
    $('.title2').fadeTo(300, 0);
    $('#box' + idn).children('.numbers').fadeTo(300, 0);

    //	$('#box' + newId).after('<div id="loading">loading</div>');
    $('#temp').animate({
        height: '0px'
    },
    'slow',
    function() {

        var pos = $('#box' + idn).position().top;

        $('html, body').animate({
            scrollTop: pos
        },
        'slow');

        $('#temp').delay(1200).animate({
             height: '0px'
        },
        'slow',function() {

			//enable loading then remove then open again

		        $('#temp').remove();

		        //	$('#loading').remove();
		        $('#box' + newId).after(div);
		        var pos = $('#temp').position().top;
		        var winWidth = $(window).width();
		        var winHeight = $(window).height();

		        if (idn > 0) {
		            if (webkit == false) {
		                $('#temp').scrollTo('.inner:eq(1)', 0);
		            } else {
						//myScroll.scrollToElement('#subtemp1', '4ms');
		                $('#scroller').css('-webkit-transform', 'translate3d(-' + winWidth + 'px, 0px, 0px)')
		            }
		        }

		        $('html, body').delay(300).animate({
		            scrollTop: pos
		        },
		        'slow',function(){
		 			$('.dummy').hide();
					$('#box' + idn).children('.dummy').show();
		       		$('#box' + idn).css('background-image', 'url( )');
					$('#box' + idn).children('.ex').fadeTo(300, 0.3);
				 	$('.title2').fadeTo(300, 1);
				});


		        $('#temp').animate({
		            height: winHeight + 'px'
		        },
		        'slow',
		        function() {
		            if (webkit == true) {
		                myScroll = new iScroll('scroller', {
		                    snap: true,
		                    desktopCompatibility: desktopCompat,
		                    momentum: false,
		                    vScrollbar: false,
		                    hScrollbar: false,
		                    onScrollEnd: function() {
		                        setcurrentSlide(this.pageX);
		                         
		                        var pos = $('#temp').position().top;
		                        $(window).scrollTop(pos);
		                    }
		                });
		            }
		            if (idn > 0) {
		                if (webkit == false) {
		                    $('#temp').scrollTo('.inner:eq(1)', 0);
		                } else {
							// myScroll.scrollToElement('#subtemp1', '4ms');
			
		                   $('#scroller').css('-webkit-transform', 'translate3d(-' + winWidth + 'px, 0px, 0px)')
		                }
		            }

		        });
				/////////

	
		});
	


    });

}

function closeAll() {
	$('.bg').fadeTo(300, 1);
	$('.numbers').fadeTo(150, 1);
 //   $('.title').css('color', '#00c2d9').fadeTo(300, 0);
  $('.li-box').animate({'background-color': '#f5f5f5'},300);
 $('.title').animate({'color': '#00c2d9'},300);

 	$('.dummy').hide();
    $('li').css('background-image', 'url( )');


    var pos = $('#temp').position().top - dividendo - startWidth;

    $('html, body').animate({
        scrollTop: pos
    },
    'slow');

    $('#temp').animate({
        height: '0px'
    },
    'slow',
    function() {

        $('#temp').html(' ').hide();
        $('.numbers').fadeTo(150, 1);
        setOpen(false);
        window.location.hash = '-';
        return false;
    });

}

function setcurrentSlide(n) {

    currentSlide = n;

}

function setOpen(val) {

    isOpen = val;

}

function loaded() {

    Cufon.replace('.numbers', {
        hover: true,
        fontFamily: 'numbers'
    });
    imgresize();

    $('.ex').hover(function() {
	var thisguy = $(this).parent();
        var id = thisguy.attr('id');
        var idn = parseInt(id.replace('box', ''));
        $('#box' + idn).children('.title').animate({'color': '#FFF'},30).fadeTo(300, 1);
        $('#box' + idn).animate({'background-color': '#00c2d9'},300);
       //  $('#box' + idn).children('.bg').fadeTo(300, 0.0);

    },
    function() {
	var thisguy = $(this).parent();
        var id = thisguy.attr('id');
        var idn = parseInt(id.replace('box', ''));
			if(idn!==current){
			 //   $('#box' + idn).children('.title').fadeTo(300, 0);	
	        $('#box' + idn).animate({'background-color': '#f5f5f5'},300);
 	        $('#box' + idn).children('.title').animate({'color': '#00c2d9'},300);
			}
	       // $('#box' + idn).children('.bg').fadeTo(300, 1);
    });




    $('.ex').click(function() {
        $('#box' + idn).children('.bg').fadeTo(300, 1);
        isOpen = true;
        var thisguy = $(this).parent();
        var newId = 0;
        var addcol = 0;
        var id = thisguy.attr('id');
        var idn = parseInt(id.replace('box', ''));
        openWork(idn);
    });


}



function loadWorks() {

    $.ajax({

        type: "POST",
        dataType: "json",
        url: "list.php",
        success: function(data) {
            totalItem = data.length + 1;
            for (i = 0; i < data.length; i++) {
                works_id[i] = data[i].works_id;
                works_css[i] = data[i].works_css;
                works_dark[i] = data[i].works_dark;
                works_url[i] = data[i].works_safeurl;
                works_name[i] = data[i].works_name;
                works_description[i] = data[i].works_description;
                works_year[i] = data[i].works_year;
                works_website[i] = data[i].works_website;
                works_quote[i] = data[i].works_quote;
                if (data[i].images.length > 0) {
                    var img = data[i].images[0].works_images_file
                    imgfile[i] = 'admin/works/' + works_id[i] + '/images/' + img;
                    images_array[i] = new Array();
                    images_array_title[i] = new Array();
                    for (var w = 0; w < data[i].images.length; w++) {
                        var imgw = data[i].images[w].works_images_file;
                        images_array_title[i][w] = data[i].images[w].works_images_title;
                        images_array[i][w] = imgw;
                    }

                }

                var r = i / 236 ;

                var list = '<li class="li-box works"  id="box' + i + '" style="background-repeat:no-repeat;background-position:50% 50%; "  >';
                list += '<div class="dummy"> </div>';
				list += '<div class="ex"> </div>';
                list += '<div class="numbers">' + (data.length - i) + '</div>';
                list += '<div class="title" id="title' + i + '">' + data[i].works_name.replace("\\","") + '<br/>' + data[i].works_year + '</div>';
				list += '<div class="bg" style="background:rgba(0,0,0,' + r + '); background-repeat:no-repeat;background-position:50% 50%; "  > </div>';
                list += '</li>';

                $('#wrapper').append(list);

            }

            i = data.length;
            imgfile[i] = 'fb.jpg';
            images_array[i] = new Array();
            images_array[i][0] = "fb.jpg";
            works_id[i] = "0";
            works_css[i] = "";
            works_dark[i] = "0";
            works_url[i] = "about";
            works_name[i] = "Francesco Bertelli";
            works_description[i] = "I'm a Design Director living in NYC, and currently working for Huge Inc. Brooklyn. <br/> I've been working as external consultant and web art director for the New York Times, and many major italian advertising agencies, small design boutiques since 2001.<br/><br/>PS. And yes, I'm also the founder of <a target='_blank' href='http://www.bertellibici.com'>Bertelli Bici</a>, but that's my hobby. <br/><br/> <a href='http://www.twitter.com/_ll_l'  target='_blank' >Twitter me</a>";
            works_website[i] = "mailto:francesco.bertelli@gmail.com";
            works_quote[i] = "About";

            var list = '<li style="background-position:50% 50%;background-repeat:no-repeat;background-image:url(bertelli.jpg)"  class="li-box works"  id="box' + i + '" >';
            list += '<div class="dummy"> </div>';
            list += '<div class="ex"> </div>';
            list += '<div class="title2">About</div>';
            list += '<div class="title">Francesco Bertelli</div>';
			list += '<div class="bg" style="background:rgba(0,0,0,' + r + '); background-repeat:no-repeat;background-position:50% 50%; background-image:url(bertelli.jpg)" > </div>';
            list += '</li>';

            $('#wrapper').append(list);

            loaded();
            detectHash();

        },
        error: function(data) {
        }
    });

}

$(document).ready(function() {
	
    loadWorks();

    shortcut.add("Down",
    function() {
        openNext();
    });

    shortcut.add("n",
    function() {
        openNextImg();
    });

    shortcut.add("p",
    function() {
        openPrevImg();
    });

    shortcut.add("Up",
    function() {
        openPrev();
    });

    shortcut.add("Left",
    function() {
        openPrevImg();
    });

    shortcut.add("Right",
    function() {
        openNextImg();
    });

})

