/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var name = "#menu";  
var menuYloc = null;  
var maxOffset = 355;
var toShow = '';
var toRemove = '';
var link='';
var projectOffset=350;
var visibleVideo = null;
var jpinterface = '<div id="jp_container_1" class="jp-video " ><div class="jp-type-single"><div class="jp-jplayer"></div><div class="jp-gui"><div class="jp-video-play"><a href="javascript:;" class="jp-video-play-icon" tabindex="1">play</a></div><div class="jp-interface group"><div style="display:none"><div class="jp-stop"></div><div class="jp-volume-max"></div><div class="jp-repeat"></div><div class="jp-repeat-off"></div></div><a href="javascript:;" class="jp-play" tabindex="1">PLAY</a><div class="jp-progress"><div class="jp-seek-bar"><div class="jp-play-bar"></div></div></div><a href="javascript:;" class="jp-pause" tabindex="1">PAUSE</a><div class="time-audio-divider" tabindex="1"></div><a href="javascript:;" class="jp-mute" tabindex="1" title="mute">AUDIO</a><a href="javascript:;" class="jp-unmute" tabindex="1" title="unmute"><del>AUDIO</del></a><div class="audio-screen-divider" tabindex="1"></div><div class="jp-current-time"></div><div class="time-divider" tabindex="1">/</div><div class="jp-duration"></div><div class="jp-volume-bar"><div class="jp-volume-bar-value"></div></div><a href="javascript:;" class="jp-full-screen" tabindex="1" title="full screen">FULL SCREEN</a><a href="javascript:;" class="jp-restore-screen" tabindex="1" title="restore screen"><del>FULL SCREEN</del></a></div></div><div class="jp-no-solution"><span>Update Required</span>To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.</div></div></div>'
var iOs = false;
var animationTime = 700;

function manageCarousel(resource){
    // no risorse, no carousel
    if(resource > 1){
        //carosello risorse
        $('.resources').cycle({
            fx:    'none',                 
            timeout: 0, 
            next:   '#right_arrow', 
            prev:   '#left_arrow',
            after: manageVideos,
            before: manageVideos
        });
    }
}

function playVideo(){    
    $(visibleVideo).jPlayer('play');    
    $('.resource.video:visible .jpplay').first().hide();
    $('.resource.video:visible .jpinterface').first().hover(function(){ $('.resource.video:visible .jppause').first().show() }, function(){ $('.resource.video:visible .jppause').first().hide() });
}
function removeVideo(){
    //stoppo l'eventuale video che sta andando
    $(visibleVideo).jPlayer('destroy');        
    //rimuovo l'interfaccia da tutti i video'
    $('.resource.video').empty();
}
function pauseVideo(){    
    $(visibleVideo).jPlayer('pause'); 
    $('.resource.video:visible .jppause').first().hide();
    $('.resource.video:visible .jpinterface').first().unbind('mouseenter').unbind('mouseleave');
    $('.resource.video:visible .jpplay').first().show();
}

function manageVideos(){
    
    removeVideo();
    //aggiungo l'interfaccia al video da mostrare
    $('.resource.video:visible').append(jpinterface);
    
    visibleVideo = $('.resource.video:visible div.jp-jplayer').first();
    
    // do  per scontato che ci siano tutti i formati video e il poster
    $(visibleVideo).jPlayer( {
        ready: function () {
          $(this).jPlayer("setMedia", {
            webm: $('.resource.video:visible').first().attr('src')+".webm", // Defines the counterpart ogv url
            m4v: $('.resource.video:visible').first().attr('src')+'.m4v', // Defines the m4v url
            //ogv: $('.resource.video:visible').first().attr('src')+".ogg", // Defines the counterpart ogv url            
            poster: $('.resource.video:visible').first().attr('src')+".png" //Se nello stesso path c'e' il poster, esso viene usato'
          }); // Attempts to Auto-Play the media
        },
        solution: "html, flash", // Flash with an HTML5 fallback.
        supplied: "webm, m4v",//, ogv",
        swfPath: "scripts",
        preload:"auto",        
        //errorAlerts: true,
        size: {width: 450, height:300}
      });
    
}

function fixMenu(){
    var offset = menuYloc+$(document).scrollTop();
    //console.log(offset.replace('px',''));
    
    if (offset > maxOffset){        
        offset = maxOffset;        
    }
    $(name).animate(
    {
        top: offset
    },
    {
        queue: false,
        duration: 1500
    });
}

function manageArrows(resource){
    if(resource > 1){
        $('#right_arrow').fadeIn();
        $('#left_arrow').fadeIn();
    }
    else{
        $('#right_arrow').fadeOut();
        $('#left_arrow').fadeOut();
    }
}
function loadWork(){
    $.ajax({
      url: "lavoro.php?id="+toShow,      
      success: function(data){
            
            //pulisco il markup
            data=data.replace(/>([^>.^<^\w^\/])*</g,"><");
            //iserisco i lavori            
            $('#loading').before(data);
            //rimuovo il lavoro
            $('#loading').removeClass('visibile');
            //rimuovo il lavoro di prima
            $(toRemove).remove();
            //gestisco il carosello delle risorse (immagini e video)
            manageCarousel($(data).find('.resource').length);
            //gestisco la visibilità delle frecce del carousel
            manageArrows($(data).find('.resource').length);
            //gestisco i video con jPlayer
            manageVideos();
            
       },                                   
       dataType:"html"
    });
}
function showWork(){
    
    if($('#project.visibile').length == 0){ //prima volta
        //apro progetti
        $("#project").addClass("visibile");
        //carico lavoro alla fine della animazione CSS3
        setTimeout('loadWork()',500);
    }
    else{
        //rimuovo il video
        removeVideo();
        //progetto da rimuovere
        toRemove = $('.project:first');
        //carico subito il lavoro
        loadWork();
    }
}
function manageURL(){
    toShow = SWFAddress.getPath().replace("/", "");
    
    if(toShow!=""){
        moveAndShow();
    }
    else{
        //serve per quando viene caricata la pagina del lavoro .html    
        toShow = window.location.pathname;        
        toShow = toShow.substring(toShow.lastIndexOf('/') + 1);
        toShow = toShow.replace('.html','');    
    }   
}
function goToProjects(callback){
    
    projectOffset = $("#breadcrumb").offset().top-20;
    if(callback!=''){        
        $('html').animate({scrollTop: projectOffset}, animationTime, 'easeOutCirc');
        $('body').animate({scrollTop: projectOffset}, animationTime, 'easeOutCirc',callback);
    }
    else{
        $('html,body').animate({scrollTop: projectOffset}, animationTime, 'easeOutCirc');
    }
    fixMenu();
}
function moveAndShow(){
    $('#loading').addClass('visibile');
    //titolo progetto nelle briciole di pane
    $("#breadcrumb span.progetto").html('> '+toShow.toUpperCase());
    //se non sei posizionato prima vai ai progetti poi carichi il progetto
    if($('body').scrollTop()!=projectOffset){        
        goToProjects(showWork);
    }
    else{
        //altrimenti carica il progetto direttamente
        showWork();
    }
}

$(function() {
    $('#thumbs a').click(function(e){        
        toShow = $(this).attr('href');
        toShow = toShow.replace('.html','');
        SWFAddress.setValue(toShow);
        moveAndShow();
        return false;        
    });         

    setTimeout('manageURL()',300);    
 
    menuYloc = parseInt($(name).css("top").substring(0,$(name).css("top").indexOf("px")));
    $(window).scroll(function () {          
        fixMenu();  
    });
});  
