// State Globals
var medium = "none";
var imgCount = {"print":1,
                "info":1,
                "photo":1,
                "textile":1,
                "digital":1};
var imgPtr = {"print":0,
              "info":0,
              "photo":0,
              "textile":0,
              "digital":0};
var library = {};

function updateViewer(){
    // Turn off the next/prev arrows during the transition
    disableArrows();
    
    // Update the counter text
    theCounter = $("#work-"+medium+" > span > .counter-message");
    theCounter.text((imgPtr[medium]+1)+" of "+(imgCount[medium]));
    
    // fade out the current image and fade in the new one
    currUrl = library[medium][imgPtr[medium]].url;
    var img = new Image()
    img.onload = function(){


        //
        // Insta-snap approach to changing images
        // 
        //$("#viewer").css('width',img.width+"px");
        $("#viewer").attr('src',currUrl);
        // Make sure the descriptive text is visible
        if ($("#work-detail").css('display')=='none'){
            $("#work-detail").fadeIn("slow");
        }

        // Update the text
        docTitle = library[medium][imgPtr[medium]].title
        docUrl = "/work/"+medium+"/"+(imgPtr[medium]+1)
        permalink = '<a title="Permanent link to this page" href="'+docUrl+'">'+docTitle+"</a>"
        // $("#detail-title").html(library[medium][imgPtr[medium]].title)
        $("#detail-title").html(permalink)
        $("#detail-remarks").html(library[medium][imgPtr[medium]].detail)
        
        // Turn the next/prev arrows back on again
        enableArrows()
        
/*
        //
        // Fast fade approach to changing images
        //
        //$("#viewer").clearQueue();
        $("#viewer").fadeOut("fast", function(){
            $("#viewer").attr('src',currUrl);
            $("#viewer").attr('title',library[medium][imgPtr[medium]].title);
            $("#viewer").fadeIn("fast");        

            // Make sure the descriptive text is visible
            if ($("#work-detail").css('display')=='none'){
                $("#work-detail").fadeIn("slow");
            }

            // Update the text
            docTitle = library[medium][imgPtr[medium]].title
            docUrl = "/work/"+medium+"/"+(imgPtr[medium]+1)
            permalink = '<a title="Permanent link to this page" href="'+docUrl+'">'+docTitle+"</a>"
            // $("#detail-title").html(library[medium][imgPtr[medium]].title)
            $("#detail-title").html(permalink)
            $("#detail-remarks").html(library[medium][imgPtr[medium]].detail)

            // Turn the next/prev arrows back on again
            setTimeout("enableArrows()",600);
        });
*/

        //Mint.TT.behavior.record("view "+medium+"/"+imgPtr[medium]+1);
        //$("#content").css('width',img.width+"px");
        //alert('size is '+img.width+'/'+img.height);
        $("#viewer").css('width',img.width+"px");

        // Preload the next image
        if (imgPtr[medium]<imgCount[medium]-1){
            nextUrl = library[medium][imgPtr[medium]+1].url;
            new Image().src = nextUrl;            
        }
    }
    img.src = currUrl;
}

function enableArrows(){
    $(".counter-prev").click(function(){if(decrementImg()){updateViewer();}})
    $(".counter-next").click(function(){if(incrementImg()){updateViewer();}})    
}
function disableArrows(){
    $(".counter-prev").unbind("click")
    $(".counter-next").unbind("click")
}

function incrementImg(){
    needsRedraw = true;
    imgPtr[medium] += 1;
    if (imgPtr[medium] >= imgCount[medium]){
        imgPtr[medium] = imgCount[medium]-1;
        needsRedraw = false;
    }

    return needsRedraw;
}

function decrementImg(){
    needsRedraw = true;
    imgPtr[medium] -= 1;
    if (imgPtr[medium] < 0){
        imgPtr[medium] = 0;
        needsRedraw = false;
    }    

    return needsRedraw;
}

function resetSelection(){
    // deselect the portfolio/cv links in the footer
    links = $("#footer").find("a");
	links.each(function(){
	    $(this).removeClass("selected");
        $(this).addClass("deselected");
    });
}
function resetMedium(){
    // hide all the counters in the portfolio navbar
    $("#work-nav > li > span").each(function(){
        if ($(this).attr("id") == "counter-" + medium){
            // this is the currently selected category
            $(this).css("display","block")
        }else{
            // this is a non-selected category
            $(this).css("display","none")
        }
    })
    
    $("#work-nav > li > a").each(function(){
        if ($(this).parent().attr("id") == "work-"+medium){
            $(this).addClass("selected");
        }else{
            $(this).removeClass("selected");
        }
    })

    $("#work-nav > li").each(function(){
        if ($(this).attr("id") == "work-"+medium){
            $(this).addClass("selected");
        }else{            
    	    $(this).removeClass("selected");
        }
    })
}


function setContent(caller){
    // Switches the content div to either portfolio, cv, or hidden state
    // caller is the element that triggered this 
    resetMedium();

    // Reveal the new content
    switch(caller.attr("id")){
        case "footer-work":
          // preload the image to be displayed while transitioning
          if (medium =='none'){
              new Image().src=library['print'][imgPtr['print']].url;
          }else{
              new Image().src=library[medium][imgPtr[medium]].url;
              $("#work-detail").fadeIn("slow");
          }
          $("#work-nav").css("display","block")
          $("#cv").hide(0);  // Hide (BUG: ideally only if shown though)
          $("#content").animate({height:520}, "slow");
          $("#work").show("fast");
          //Mint.TT.behavior.record("view portfolio");
          break;
        case "footer-me":
          $("#work-nav").css("display","none")
          $("#work").hide(0); // Hide (BUG: ideally only if shown though)
          $("#work-detail").css("display","none")
          self.scrollTo(0, 0)
          $("#content").css('width',"auto");
          $("#content").animate({height:811}, "slow");
          $("#cv").show("slow", function (){
                var properHeight = 6 + $("#cv").offset().top + $("#cv").outerHeight();
                var actualHeight = $("#content").outerHeight();
                if (actualHeight<properHeight){
                        $("#content").css('height',(10 + $("#cv").offset().top + $("#cv").height()));
                }                
          });
          //Mint.TT.behavior.record("view cv");
          break;
        case undefined: // <- which is to say the main banner
        case "cv-closebox":
          $("#work-nav").css("display","none")
          $("#work-detail").css("display","none")
          $("#cv").hide(0);   // Hide (BUG: ideally only if shown though)
          $("#work").hide(0); // Hide (BUG: ideally only if shown though)
          $("#content").css('width',"auto");
          $("#content").animate({height:35}, "slow");
          //Mint.TT.behavior.record("hide viewer")
          break;
    }    
}

function jumpToImg(mediumName, imgIdx){
    var needsRedraw = true;
    if (mediumName == medium && imgPtr[medium] == imgIdx-1){
        needsRedraw = false;
    }else{
        medium = mediumName;
        imgPtr[medium] = imgIdx-1;
    }
    
    return needsRedraw;
}


function initPortfolio(){
	$.getJSON("/work/library", function(json){
        library = json;

        // create the doc counter for each medium
        var media = ['print','info','photo','textile','digital'];
        for (i in media){
            var thisMedium = media[i];
            imgCount[thisMedium] = library[thisMedium].length;
            theCounter = $("#counter-"+thisMedium);
            $('<div class="counter-prev"></div>').appendTo(theCounter)
            $('<ol  class="counter-popup"></ol>').appendTo(theCounter)
            $('<div class="counter-message">'+(imgPtr[thisMedium]+1)+' of '+(imgCount[thisMedium])+'</div>').appendTo(theCounter)
            $('<div class="counter-next"></div></span>').appendTo(theCounter)
        }

        // populate the counter-popup menus.
        for (i in media){
            var thisMedium = media[i];
            for (j in library[thisMedium]){
                workIdx = Number(j)+1;
                newLink = "<li alt='"+thisMedium+"'><a href='/work/"+thisMedium+"/"+workIdx+"' alt='"+workIdx+"'>"+library[thisMedium][j].title+"</a></li>";
                
                newElem = $(newLink)
                newElem.click(function (){
                    //alert("You clicked me! How dare you? Jumping to "+$(this).find("a").attr('alt'));
                    var newMedium = $(this).attr('alt')
                    var shouldRedraw = jumpToImg(newMedium,$(this).find("a").attr('alt'));
                    //alert("switching to "+medium+"/"+imgPtr[medium]+" redraw: "+shouldRedraw);
                    if (shouldRedraw){
                        updateViewer();
                    }
                    return false;
                })
                newElem.appendTo($("#counter-"+thisMedium+" > ol"));
                
            }
        }

        // weird errors occur if this happens before content is loaded, so we'll chain the call here
        initEventHandlers();
    });
}

function initEventHandlers(){
    // everything needs to start out deselected
    resetSelection();
    resetMedium();

    // Add click handlers to open the portfolio and cv pages
    $("#footer-about > li > a").click(function(){
        if($(this).attr("class") == "selected"){
            $(this).blur();
            return false;
        }
        resetSelection();
        $(this).removeClass("deselected");
        $(this).addClass("selected");
        setContent($(this).parent());
        $(this).blur();
        $(this).hideFocus=true
        return false;
    })
    
    
    // Click on a portfolio category to reveal the counter
    $("#work-nav > li > a").click(function(){
        // update the medium global variable
        newMedium = $(this).parent("li").attr("id")
        newMedium = newMedium.substr(newMedium.indexOf("-")+1)
        if (newMedium == medium){ return false; }
        medium = newMedium;
        resetMedium();
        updateViewer();
        return false;
    })
    
    
    // Click on the counter to advance the image
    $(".counter-prev").click(function(){
        if(decrementImg()){
            updateViewer();
        }
        
    })
    $(".counter-next").click(function(){
        if (incrementImg()){
            updateViewer();
        }
    })

    // Counter popup menu appears on click and disappears on mouse-out
    $(".counter-message").click(function(){
        $(this).siblings(".counter-popup").fadeIn("fast");
    });    
    $(".counter-popup").hover(function(){},function(){
        $(this).fadeOut("fast");
    })


    
    // Make the banner reset everything back to the inital, closed state
    $("#banner > a").click(function(){
        if($(this).attr("class") == "selected"){return;}
        resetSelection();
        setContent($(this));
        return false;
    })
    $("#cv-closebox").click(function(){
        if($(this).attr("class") == "selected"){return;}
        resetSelection();
        setContent($(this));
        return false;
    })
}


