/*
    popover v0.1
    by Adrian Unger <hello{AT}staydecent.ca>
*/

function popover_create() {
    $('body').append('<div id="overlay"></div><div id="popover">'
        + '<div id="po_close" title="Close"></div></div>');
    popover_position();
}
/*
    state
     - object holds current index,set etc.
    el
     - pass this(obj) to the func
    evt
     - pass event
*/
popover_click = function(state, el, evt) {
    var ths   = el;
    var src   = ths.href;
    var title = ths.title;
    
    for (var i = 0; i < state.set.length; i++) { if (src == state.set[i]) state.setIndex = i; }
    popover_show(src, title, state.setIndex, state.set);
    $("#po_prev,#po_next").click(function(evt) { return popover_click(state, this, evt); });        
    return false;
}
/*
    src
     - the href of the clicked thumb
    index
     - 0 index of all thumbs on page
    set
     - flat array of all src's
 */
function popover_show(src, title, index, set) {
    $("#po_img,#po_prev,#po_next").remove();
    $("#popover").append('<img id="po_img" src="'+src+'" alt="'+title+'"/>');
    $("#po_img").hide();
    
    // more than 1 image, so add navigation
    if (set.length > 1) {
        // not first so add prev
        if (index > 0) { $("#popover").append('<a id="po_prev" href="'+set[index-1]+'"></a>'); }
        else { $("#popover").append('<a id="po_prev" href="'+set[set.length-1]+'"></a>'); }
        // not last so add next
        if (index < set.length-1) { $("#popover").append('<a id="po_next" href="'+set[index+1]+'"></a>'); }
        else { $("#popover").append('<a id="po_next" href="'+set[0]+'"></a>'); }
        $("#po_next,#po_prev").hide();
    }
    
    $("#overlay").show();
    $("#popover,#po_img").fadeIn(350, function() {
        $("#po_next,#po_prev").show();
        popover_position(); 
    });
    $("#overlay,#po_close").click(popover_hide);
}

function popover_hide() {
    $("#popover,#overlay").hide();
}

function popover_position() {
    var doc = $('body');
    var img = $("#po_img");
    
    $("#popover").css({
        width   : img.width(),
        height  : img.height(),
        left    : ((doc.width() - img.width())/2),
        top     : 190
    });
    $("#po_next, #po_prev").css({
        top     : (img.height()/2)
    });
}