var pictures = new Array();
var descriptions = new Array();
var visible_thumbs = 0;
var visible_picture = 0;
var thumbs_per_page = 0;
var current_album = '';
var thumbs_page = 1;
var inAnimation = false;
var reseted = false;
var openedOnce = true;

function getDescriptions(){
    var request = new XMLHttpRequest();  
    //request.open('GET', '/vilamarques/gallery/json/getDescriptions.php?album='+current_album);
    request.open('GET', '/gallery/json/getDescriptions.php?album='+current_album);
    request.onreadystatechange = function (aEvt) {  
    if (request.readyState == 4) {  
        if(request.status == 200) {    
            var obj = eval("(" + request.responseText + ")");
            if(obj.status=="success"){
                descriptions = obj.desc;
                getPictures();
            }
            else if(obj.status=="error"){
                console.log(obj.msg);
            }
         }else {
           console.log('Error', request.statusText);  
         }
      }  
    };  
    request.send(null);
}
function getPictures(){
    var request = new XMLHttpRequest();  
    //request.open('GET', '/vilamarques/gallery/json/getPictures.php?album='+current_album);
    request.open('GET', '/gallery/json/getPictures.php?album='+current_album);
    request.onreadystatechange = function (aEvt) {  
    if (request.readyState == 4) {  
        if(request.status == 200) {    
            var obj = eval("(" + request.responseText + ")");
            if(obj.status=="success"){
                pictures = obj.pics_str.split("|");
                pictures = pictures.splice(0,pictures.length-1);
                for (i in pictures){
                    createThumb(i, pictures[i]);
                }              
                showThumbs();
                createGalleryEventListeners();
                for (i in pictures){
                    createPicture(i, pictures[i]);
                }
                setThumbsPerPage();
                if(!inAnimation)
                    showPicture(0);
            }
            else if(obj.status=="error"){
                
            }
         }else {
           console.log('Error', request.statusText);  
         }
      }  
    };  
    request.send(null);
}
function setPictureNumHtml(){
    $('#picture_num').html((parseInt(visible_picture)+1)+'/'+pictures.length);
}
function setPictureDescHtml(){
    $('#picture_desc').html(descriptions[parseInt(visible_picture)+1]);
}                            
function createPicture(id, file_name){
    var picture = document.createElement('div');
    $(picture).attr('id', 'picture'+id);
    $(picture).attr('class', 'picture'); 
    var img = document.createElement('img');
    $(img).attr('src','/gallery/albuns/'+current_album+'/pictures/'+file_name);
    //$(img).attr('src','http://datdesignandthings.com/vilamarques/gallery/albuns/'+current_album+'/pictures/'+file_name);
    $(picture).append($(img)); 
    $('#picture_holder').append($(picture));
}
function showPicture(id){
    //console.log(arguments.callee.caller.toString());
    inAnimation = true;
    thumbToggleClass(id);
    $('#nav_container').fadeOut();
    $('#picture'+visible_picture).fadeOut(function(){
            $('#nav_container').fadeIn();
            visible_picture = id;      
            setPictureNumHtml();
            setPictureDescHtml();
            $('#picture'+id).fadeIn(function(){  
                inAnimation = false;    
            });
    });
}

function thumbToggleClass(id){ 
    $('#thumb'+visible_picture).removeClass('thumb_selected');
    $('#thumb'+id).addClass('thumb_selected');
}

function createThumb(id, file_name){
    var thumb = document.createElement('div');
    $(thumb).attr('id', 'thumb'+id);
    $(thumb).attr('class', 'thumb'); 
    var img = document.createElement('img');
    //$(img).attr('src','http://datdesignandthings.com/vilamarques/gallery/albuns/'+current_album+'/thumbs/'+file_name);
    $(img).attr('src','/gallery/albuns/'+current_album+'/thumbs/'+file_name);
    $(thumb).append($(img)); 
                                                                            
    $(thumb).click(function(){
        if(!inAnimation)
            showPicture(id);
    })
    $('#thumbs_holder').append($(thumb));
}
function showThumbs(){
    visible_thumbs = 0;   
    visible_picture = 0;
    showThumb(visible_thumbs);
}
function showThumb(id){
    if(!html5_capable && id%2==0)
        $('#thumb'+id).css('margin-right','4px');
    if(!reseted){
        $('#thumb'+id).show(150 ,function(){
                //setThumbsControllersVisibility();
                visible_thumbs++;
                showThumb(visible_thumbs);
        });
    }
    //setThumbsControllersVisibility();
}

function galFormat(){
    var thumbs_container_height = $(window).height() - 40;
    var picture_container_top = ($(window).height() - 520)/2;
    $('#thumbs_container').css('height', thumbs_container_height+'px');
    $('#picture_container').css('top', picture_container_top+'px');
    var menu_top = $('#picture_container').css('top');
    menu_top = parseInt(menu_top.replace('px',''));
	var picture_container_height = $('#picture_container').css('height');
	picture_container_height = parseInt(picture_container_height.replace('px',''));
	menu_top += picture_container_height - 150;
    $('#menu_gal').css('margin-top', menu_top + 'px');
    $('#gal_bg').css('height', $(document).height());
    //setThumbsControllersVisibility();
}
function galInit(){
    if(openedOnce == true){
        openedOnce = false;
    
        current_album = 'outdoor';
        getDescriptions(); //it will call getPictures();

    }else{
        //setThumbsControllersVisibility();
    }
    
}
$(window).bind('resize', function(){
    galFormat();
}); 

function setThumbsControllersVisibility(){
    if($('#thumbs_holder').height() > $(window).height()-40){
        if($('#thumbs_controllers').css('display')=='none'){
            $('#thumbs_controllers').show(); 
            createGalleryEventListeners();
        }
    }else   {
        if($('#thumbs_controllers').css('display')=='block'){
            $('#thumbs_controllers').hide();
            removeThumbsControllersEventListeners(); 
        }
    }
}

function autoSlideUpThumbsHolder(){
    
    var window_height = $(window).height()-40;
    if(visible_picture>=thumbs_per_page*(thumbs_page-1) && visible_picture<thumbs_per_page*thumbs_page){
        ;
    }else{
        //alert(arguments.callee.caller.toString());
        inAnimation = false;
        thumbsPushUp();
        thumbs_page++;
    }
}
function autoSlideDownThumbsHolder(){   
    
    var window_height = $(window).height()-40;
    if(visible_picture>=thumbs_per_page*(thumbs_page-1) && visible_picture<thumbs_per_page*thumbs_page){
        ;
    }else{
        inAnimation = false;
        thumbsPushDown();
        thumbs_page--;
    }
}

function setThumbsPerPage(){
    var window_height = $(window).height()-40;
    thumbs_per_page = Math.floor(window_height/104)*2;
}

function thumbsPushUp(){
    if(!inAnimation){
        inAnimation = true;
        var thumbs_top = $('#thumbs_holder').css('margin-top');
        thumbs_top = thumbs_top.replace('px','');
        var offset = $('#thumbs_holder').height()-(($(window).height()-40)-thumbs_top);
        if(offset >= ($(window).height()-40)){
            var up = ($(window).height()-40);
            $('#thumbs_holder').animate({ marginTop: '-='+up }, 1000, function() {
                inAnimation = false;
                createThumbsControllersEventListeners();
            });
            
        }else{                  
            $('#thumbs_holder').animate({ marginTop: '-='+offset }, 1000, function() {
                inAnimation = false;
                createThumbsControllersEventListeners();
            });
            
        } 
    }    
}
function thumbsPushDown(){
    if(!inAnimation){
        inAnimation = true;
        var thumbs_top = $('#thumbs_holder').css('margin-top');
        thumbs_top = thumbs_top.replace('px','');

        if(thumbs_top <= -($(window).height()-40)){
            var down = ($(window).height()-40);
            $('#thumbs_holder').animate({ marginTop: '+='+down }, 1000, function() {
                inAnimation = false;
                createThumbsControllersEventListeners();
            });
        }else{
            $('#thumbs_holder').animate({ marginTop: '+='+(-thumbs_top) }, 1000, function() {
                inAnimation = false;
                createThumbsControllersEventListeners();
            });
        }
    }
}   

function resetGallery(){
    reseted = false;
    $('#thumbs_holder').css('margin-top','0px');
    $('#thumbs_holder').empty();
    $('#picture_holder').empty();
    //setThumbsControllersVisibility();
    inAnimation = false;
    visible_thumbs = 0;   
    visible_picture = 0;
    thumbs_page = 1;
}
function changeAlbum(album){
    if(!inAnimation){
        inAnimation = true;
        $('#bt_'+current_album).removeClass('menu_gal_bt_in_page');
        $('#bt_'+album).addClass('menu_gal_bt_in_page');
        current_album = album; 
        resetGallery();
        getDescriptions();
    }
}         

function createNavEventListeners(){
    $('#nav_container').css('display','block');
    document.getElementById('nav_right').onclick = function(){
        if(!inAnimation){ 
            if((parseInt(visible_picture)+1) > parseInt(pictures.length)-1)
                showPicture(0);
            else
                showPicture(parseInt(visible_picture)+1);
        }
    };
    
    document.getElementById('nav_left').onclick = function(){
        if(!inAnimation){
            if(parseInt(visible_picture)-1 < 0)
                showPicture(parseInt(pictures.length)-1);
            else
                showPicture(parseInt(visible_picture)-1);
        }
    };
                                        
    $(document).keydown(function(e){
        if (e.keyCode == 37) { 
           $('#nav_left').click();
        }
        if (e.keyCode == 39) { 
           $('#nav_right').click();
        }
    });
}
function removeNavEventListeners(){
    $('body').undelegate('#nav_right','click');
    $('body').undelegate('#nav_left','click');
    $(document).keydown(function(e){;});
}   
function createThumbsControllersEventListeners(){
    document.getElementById('thumbs_push_down').onclick = function(){ removeThumbsControllersEventListeners(); thumbsPushUp(); };
    document.getElementById('thumbs_push_up').onclick = function(){ removeThumbsControllersEventListeners(); thumbsPushDown(); };
    if(current_album != 'outdoor') $('body').delegate('#bt_outdoor', 'click', function(){ if(current_album != 'outdoor'){ reseted = true; setTimeout(changeAlbum('outdoor'),500); }});
    if(current_album != 'indoor') $('body').delegate('#bt_indoor', 'click', function(){ if(current_album != 'indoor'){ reseted = true; setTimeout(changeAlbum('indoor'),500); }});
}
function removeThumbsControllersEventListeners(){
    document.getElementById('thumbs_push_down').onclick = function(){ ; };
    document.getElementById('thumbs_push_up').onclick = function(){ ; };
}
function createGalleryEventListeners(){
    createThumbsControllersEventListeners();
    createNavEventListeners();
}   
function removeGalleryEventListeners(){
    removeThumbsControllersEventListeners();
    //removeNavEventListeners();    
    if(current_album != 'outdoor') $('body').undelegate('#bt_outdoor','click');
    if(current_album != 'indoor') $('body').undelegate('#bt_indoor','click');
}


