/*
 *  preview.js
 *  Written by Brad McNaughton
 *  admin@bradism.com
 *  
 *  Vers  | Date       | Comments
 *  alpha | 19-02-2011 | In Progress...
 */

function getImageSize(img) {
    var oHeight = img.height();
    var oWidth = img.width();
    var fHeight;
    img.css('height', 'auto');
    img.css('width', 'auto');

    var rVal = new Object();
    rVal.height = img.height();
    rVal.width = img.width();

    fHeight = rVal.height;
    fWidth = rVal.width;

    return fHeight + "," + fWidth;
}

function doPreviewer(pr, prd){
    var prevo = new Object();
    // Create Loading Animation
    prevo.loader = $('<img src="./img/ajax-br-loader-spinner.gif" width=35 height=35 class="loader">');
    prevo.previewer = $("."+pr);
    prevo.pid = pr;
    prevo.debug_flag = false;
    prevo.debug_text = "";
    prevo.loadedImgs = new Array();
    prevo.currentId = 0;
	
    prevo.loadMainImage = function(imgObject, image_id){
        prevo.currentId = image_id;
		
        var CHANGE_HEIGHT = false; //Container will stretch/shrink to image size
        var MIN_HEIGHT = 0;
        var MIN_WIDTH = 470;
		
        var contHeight = parseInt(prevo.previewer.find(".preview_main").css("height"));
        var contWidth = parseInt(prevo.previewer.find(".preview_main").css("width"));
		
        if (prevo.debug_flag){
            prevo.debug_text = prevo.debug_text+ "\n"+"Load Triggered";
        }
		
		
        if (imgObject.data("displayWidth") && imgObject.data("displayHeight")){
            var curHeight = imgObject.data("displayHeight");
            var curWidth = imgObject.data("displayWidth");
            if (prevo.debug_flag){
                prevo.debug_text = prevo.debug_text+ "\n"+"Using existing size data";
            }
        } else {
            // Check the image size so we can increase the viewport if needed
            // Have to do this after loaded to be compatible with WebKit browsers
            // So we make a temporary copy of image to get its dimensions
            var tmp_this = new Image();
            tmp_this.src = imgObject.attr("src");
            var curHeight = tmp_this.height;
            imgObject.data("displayHeight", curHeight);
            var curWidth = tmp_this.width;
            imgObject.data("displayWidth", curWidth);
            if (prevo.debug_flag){
                prevo.debug_text = prevo.debug_text+ "\n"+"Generating Size Data via DOM copy";
            }
        }
		
        if (prevo.debug_flag){
            prevo.debug_text = prevo.debug_text+ "\nGot Width and Height "+curWidth+", "+curHeight;
        }

        // Expand the Container's height whenever an image height needs it
        if (curHeight != contHeight){
            if (prevo.debug_flag){
                prevo.debug_text = prevo.debug_text+ "\n"+"Heigh Stretch required";
            }
            prevo.previewer.find(".preview_main").animate({
                "height": curHeight
            }, 210);
        }
	    
        // The Width of the Container should be elastic to the image's width
        // But not narrower than MIN_WIDTH;
        if (contWidth != curWidth){
            if (curWidth < MIN_WIDTH) { 
                // Calculate Margins for Side when narrower than 470
                var margins_side = (MIN_WIDTH - curWidth)/2;
                curWidth = MIN_WIDTH;
            }
            prevo.previewer.find(".preview_main").css("width", curWidth);
            prevo.previewer.animate({
                "width": curWidth + 6
            }, 200, function(){
                // Load the Caption after changing width
                prevo.loadCaption(image_id, "fade");
                // Make sure the anchor link isn't affected by any resizing being done to the content
                // Only once
                if(!prevo.previewer.data("changedAnchor") && window.document.location.hash.substring(1).length > 0){
                    prevo.previewer.data("changedAnchor", 1);
                    window.document.location.hash = window.document.location.hash.substring(1);
                }
            });
        } else {
            prevo.loadCaption(image_id, "fade");
        }
	    
        // Height of Container is elastic, but greater than MIN_HEIGHT
        if (contHeight < MIN_HEIGHT){
            contHeight = MIN_HEIGHT;
        }
	    
        prevo.previewer.find(".preview_main img").css("width", curWidth).animate({
            "height": curHeight
        }, 180);
	    
        if (curHeight < contHeight){
            // Vertically Align Images
            var margins = parseInt((contHeight - curHeight)/2);
            if (prevo.debug_flag){
                prevo.debug_text = prevo.debug_text+ "\nGot Width and Height "+curWidth+", "+curHeight;
            }
        }
        var hover_icons_side;
        if (!margins_side){
            var margins_side = 0;
            hover_icons_side = 22;
        } else {
            hover_icons_side = 22+margins_side;
        }
        // Remove if not variable height div
        if (!CHANGE_HEIGHT){
            margins = 0;
        }
        // Apply Whatever Centering
        $(this).css("margin", margins+"px "+margins_side+"px");
        // Also move hover icons if necessary
        prevo.previewer.find(".hover_icons").css("left", hover_icons_side+"px");
	       
        // This section executes various functions based on if this is the first time the previewer
        // has loaded on this page generation.
        // If Previewer has already been used
        if (prevo.previewer.data("usedPreviewer") == "1"){
            // Scroll the page to make the image top visible each time we load a thumb
            $(window).scrollTop((prevo.previewer.offset().top - 15));
        } else {
            // Set the used flag
            prevo.previewer.data("usedPreviewer", "1")
            // If this is a direct image request then show the comments, otherwise hide them
            if (!prd){
                prevo.toggleComments("hide");
            }
        }
		
        // Remove Spinner
        prevo.loader.remove();
        // Remove Images Again in case anyone's been double clicking like a mofo
        prevo.previewer.find(".preview_main img").hide();
        // Now Add the image to previewer
        prevo.main_image.fadeIn(500);
	    
        // Load the comments
        prevo.populateCommentCount();
        prevo.loadComments();
    }
	
    prevo.loadThumb = function(clicked_thumb){
        if (typeof clicked_thumb == "string"){
            clicked_thumb = prevo.previewer.find(".thumb[id="+clicked_thumb+"]");
        }
		
        // Cache Option Flag
        var CACHE_NEXT = true;
		
        // Remove the Caption and show the Loading Icon
        prevo.loadCaption(0);
        prevo.previewer.find(".preview_caption").prepend(prevo.loader);
        prevo.toggleCommentForm("hide");
		
        // Work Out Image Details
        var path = $(clicked_thumb).attr("src").replace("&t", "");
        var image_id = $(clicked_thumb).attr("id").replace(prevo.pid+"_img_", "");
        //image_id = image_id.replace(prevo.pid+"_img_", "");
		
        if (prevo.previewer.find("img[id=sho_"+image_id+"]").length == 1){
            prevo.main_image = prevo.previewer.find("img[id=sho_"+image_id+"]");
            prevo.loadMainImage(prevo.main_image, image_id);
        } else {
            // New Image to load
            prevo.main_image = $('<img>')
            .hide()	
            .attr({
                src : path,
                id : "sho_"+image_id
            })
            .appendTo(prevo.previewer.find(".preview_main"));
			
			
            if (prevo.main_image.get(0).complete){
                prevo.loadMainImage(prevo.main_image, image_id);
            // Otherwise we bind the displayMain to the load event so the browser has time to load image
            // before it starts resizing/displaying it.
            } else {
                prevo.main_image.load(function(){
                    prevo.loadMainImage(prevo.main_image, image_id);
                });
            }
        }
		
        // Add opacity to indicate it's selected (unset opacity of all thumbs beforehand)
        prevo.previewer.find(".thumb").css("opacity", "1").css("cursor", "pointer");
        $(clicked_thumb).css("opacity", ".33").css("cursor", "auto");
		
        // Scroll Right or Left in Filmstrip if we click first/last image
        // Unless at ends
        if (($(clicked_thumb).attr("id") == prevo.previewer.find(".thumb:visible:first").attr("id")) && ($(this).attr("id") != prevo.previewer.find(".thumb:first").attr("id"))){
            // Scroll Left
            if (prevo.leftArrow.length == 1){ 
                prevo.leftArrow.trigger("click");
            }
        } else if (($(clicked_thumb).attr("id") == prevo.previewer.find(".thumb:visible:last").attr("id")) && ($(this).attr("id") != prevo.previewer.find(".thumb:last").attr("id"))){
            // Scroll Right
            if (prevo.rightArrow.length == 1){ 
                prevo.rightArrow.trigger("click");
            }
        }
		
        // Load Next Image in Filmstrip for effeciency
        if (CACHE_NEXT){
            console.log("Trying to cache next image");
            if (prevo.previewer.find(".thumb").eq($(clicked_thumb).index()).length == 1){
                console.log("Looking for new image");
                var next_thumb = prevo.previewer.find(".thumb").eq($(clicked_thumb).index());
                //var next_image_path = prevo.previewer.find(".thumb").eq($(clicked_thumb).index()).attr("src").replace("&t", "");
                var next_image_id = next_thumb.attr("id").replace(prevo.pid+"_img_", "");
                console.log("Next Image is "+next_image_id);
                // Only continue if is not already loaded
                if (prevo.previewer.find("img[id=sho_"+next_image_id+"]").length == 0){
                    var next_image_path = next_thumb.attr("src").replace("&t", "");
                    console.log("Got this next image: "+next_image_path);
                    if (typeof next_image_path == "string"){ 
                        // Load Next Image
                        var next_image = $('<img>')
                        .hide()	
                        .attr({
                            src : next_image_path,
                            id : "sho_"+next_image_id
                        })
                        .appendTo(prevo.previewer.find(".preview_main"));
                            
                    }
                }
            }
        }
    }
	
    prevo.loadCaption =  function(image_id, effect){
        var caption_text;
        // Optional Effect
        if (!effect) {
            effect = "none";
        }
        // Set blank if called with 0
        if (image_id == 0) {
            prevo.previewer.find(".preview_caption p span.caption").html("");
            return;
        }
        // Only try if ID is valid image id
        if (!isNaN(parseInt(image_id))){
            // Initialise Caption Text
            // See if we have already loaded this caption
            if (typeof prevo.previewer.find(".thumb[id$="+image_id+"]").data("caption") == "string"){
                caption_text = prevo.previewer.find(".thumb[id$="+image_id+"]").data("caption");
                // Add text to Document
                prevo.previewer.find('.preview_caption p span.caption').html(caption_text);
                // Apply Styling if Specified
                if (effect == "emphasize"){
                    prevo.previewer.find('.preview_caption p span.caption').css("fontStyle", "italic");
                } else if (effect == "fade"){
                    prevo.previewer.find('.preview_caption p span.caption').css("fontStyle", "normal").fadeIn(250);
                } else {
                    prevo.previewer.find('.preview_caption p span.caption').css("fontStyle", "normal");
                }
	    		
                // Stretch Out Caption Box if required
                var paragraph_height = prevo.previewer.find('.preview_caption p span.caption').height();
                if (paragraph_height > 68){
                    prevo.previewer.find('.preview_caption').css("height", paragraph_height+12);
                } else {
                    prevo.previewer.find('.preview_caption').css("height", 80);
                }
            } else {
                // Load the caption via AJAX service
                var caption_svc = './previewer_getcaption.php?iid='+image_id;
                $.ajax({
                    url: caption_svc,
                    success: function(data) {
                        //$('.result').html(data);
                        caption_text = data;
                        // Cache Caption for re-use
                        if (caption_text.length == 0){
                            caption_text = ' ';
                        }
                        prevo.previewer.find(".thumb[id$="+image_id+"]").data("caption", caption_text);
                        // Now Set once the data is loaded
                        prevo.loadCaption(image_id, effect);
                    },
                    error: function(data) {
                    //alert('Error Loading Caption');
                    }
                });
            }
        }
    }
	
    prevo.navigateFilmstrip = function (direction){
        var thumb_count = prevo.previewer.find(".thumb").length;
        var left_thumb = prevo.previewer.find(".thumb:visible:first");
        var right_thumb = prevo.previewer.find(".thumb:visible:last");
        if (direction == "right"){
            // left_thumb is hidden, right_thumb.next() is shown
            left_thumb.hide();
            // new right thumb to be shown
            var new_right_thumb;
            // Loop throw thumbs to find the one after the last current visible
            prevo.previewer.find(".thumb").each(function(index){
                if ($(this).attr("id") == right_thumb.attr("id")){
                    new_right_thumb = $(this).next();
                    new_right_thumb.css({
                        "visibility": "visible", 
                        "display": "inline"
                    });
                    prevo.toggleArrow(prevo.leftArrow, "enable");
                    if ((index+2) == thumb_count){
                        prevo.toggleArrow(prevo.rightArrow, "disable");
                    }
                    // break the .each() loop
                    return false;
                }
            });
        } else if (direction == "left"){
            // right_thumb is hidden, left_thumb.prev() is shown
            right_thumb.hide();
            // new right thumb to be shown
            var new_left_thumb;
            // Loop throw thumbs to find the one after the last current visible
            prevo.previewer.find(".thumb").each(function(index){
                if ($(this).attr("id") == left_thumb.attr("id")){
                    new_left_thumb = $(this).prev();
                    new_left_thumb.css("visibility", "visible").css("display", "inline");
                    prevo.toggleArrow(prevo.rightArrow, "enable");
                    if ((index-1) == 0){
                        prevo.toggleArrow(prevo.leftArrow, "disable");
                    }
                    // break the .each() loop
                    return false;
                }
            });
        }
    }
	
    // Returns the ID of the current image being shown
    prevo.getCurrentId = function(){
        return prevo.currentId;
    }
	
    // Returns the ID of the entry this previewer is in, or 0 if not in an entry
    prevo.getEntryId = function(){
        var jid = 0;
        if (prevo.previewer.closest(".entry").length == 1){
            var entryDiv = prevo.previewer.closest(".entry");
            var jLink = entryDiv.find(".entry-header-left a").attr("href");
            // Extract the jid from the Header Link at the top of the entry the previewer is in
            if (/jid=/.test(jLink)){
                var exec = /jid=([0-9]{1,4})/.exec(jLink);
                if (parseInt(RegExp.$1) > 0){
                    jid = parseInt(RegExp.$1);
                }
            }
        }
        return jid;
    }
	
	
    prevo.toggleArrow = function(arrow, action){
        if (action == "enable"){
            arrow.css("opacity", "1").css("cursor", "pointer");
        } else if (action == "disable"){
            arrow.css("opacity", "0.5").css("cursor", "auto");
        }
    }
	
    prevo.doFacebook = function(){
        // get the image to share
        var jid = 0; 
        // Default Values if can't find an entry container
        var fbLink = document.location;
        var fbTitle = "Bradism.com Previewer";
        var share_id = prevo.getCurrentId();
        if (prevo.previewer.closest(".entry").length == 1){
            var entryDiv = prevo.previewer.closest(".entry");
            fbTitle = entryDiv.find("h2").html();
            var jLink = entryDiv.find(".entry-header-left a").attr("href");
            // Extract the jid from the Header Link at the top of the entry the previewer is in
            if (/jid=/.test(jLink)){
                var exec = /jid=([0-9]{1,4})/.exec(jLink);
                if (parseInt(RegExp.$1) > 0){
                    jid = parseInt(RegExp.$1);
                    fbLink = "www.bradism.com/journal.php?jid="+jid;
                }
            }
        }
        // Check if pri is set in QS (in case of default)
        if (/pri=/.test(fbLink)){
            // If one already exists, overwrite it
            var p = /pri=([0-9]{1,4})/.exec(fbLink);
            fbLink = fbLink.replace(RegExp.$1, "&pri="+share_id);
        } else {
            // Append it to the end of the QS
            fbLink = fbLink+"&pri="+share_id;
        }
        // Get a Name
        // Check if blank
        if (!fbTitle){
            fbTitle = "bradism.com";
        }
		
        // Get Description & thumb
        var fbDesc = prevo.previewer.find(".preview_caption p span.caption").html()
        var fbThumb = "www.bradism.com/getimage.php?iid="+share_id;
		
        FB.init({
            appId  : '145302738866568',
            status : true, // check login status
            cookie : true, // enable cookies to allow the server to access the session
            xfbml  : true  // parse XFBML
        });
        var publish = {
            app_id: '145302738866568',
            method: 'feed',
            name: fbTitle,
            description: fbDesc,
            link: fbLink,
            picture: fbThumb,
            redirect_uri: 'http://www.bradism.com/',
            next: null
        };
        //prompt("","name = "+fbTitle);
        //prompt("","desc = "+fbDesc);
        //prompt("","link = "+fbLink);
        //prompt("","picture = "+fbThumb);
        FB.ui(publish);
    }
	
    // Set Up Nav arrows and disabled left one to start, if they exist
    if (prevo.previewer.find(".arrow_left").length == 1){
        // Set Up Object Containing Previewer Stuff like arrows
        prevo.leftArrow = $(prevo.previewer).find(".arrow_left");
        prevo.rightArrow = $(prevo.previewer).find(".arrow_right");
        prevo.previewer.find(".nav_arrow").css({
            "opacity": "0.5", 
            "cursor": "auto"
        }).bind("click", function(){
            if ($(this).css("opacity") == 1){
                var direction = $(this).attr("class").replace("nav_arrow arrow_", "");
                prevo.navigateFilmstrip(direction);
            }
        });
        // Enable Arrow only if > 4 images
        if (prevo.previewer.find(".thumb").length > 4){
            prevo.rightArrow.css("opacity", "1").css("cursor", "pointer");
        }
    } else {
        prevo.leftArrow = {
            "length": 0
        };
        prevo.rightArrow = {
            "length": 0
        };
    }
	
    // Enable Slideshow
    if ($("#"+prevo.pid+"_button_slides").length == 1){
        $("#"+prevo.pid+"_button_slides").bind("click", function(){
            if ($("#"+prevo.pid+"_button_slides").data("showing") != true){
                prevo.doSlideshow();
            } else {
                prevo.stopSlideshow();
            }
        });
    }
	
    // Enable FB Button
    if ($("#"+prevo.pid+"_button_facebook").length == 1){
        $("#"+prevo.pid+"_button_facebook").bind("click", function(){
            prevo.doFacebook();
        });
    }
	
    // Enable Comment Shortcut Button
    if ($("#"+prevo.pid+"_button_comment").length == 1){
        $("#"+prevo.pid+"_button_comment").bind("click", function(){
            prevo.doComment();
        });
    }
	
    // Converts json string into a comment and displays it
    prevo.populateComment = function(json_comment, params){
        // Clone the Template
        new_comment = prevo.previewer.find(".preview_discussion .toclone").clone();
        new_comment.find(".comment_name").text(json_comment.author);
        new_comment.find(".comment_body").html(json_comment.comment.replace(/\\\\/gi, "\\"));
        new_comment.find(".comment_time").text(json_comment.date);
        new_comment.attr("id", prevo.pid+"_com_"+json_comment.id);
        prevo.previewer.find(".preview_comment:first").after(new_comment);
        // Add CMS functions for admin
        if(typeof doCommentAdmin == 'function') { 
            new_comment.bind("updateCommentCount", function(){
                prevo.populateCommentCount();
            });
            doCommentAdmin(new_comment, json_comment.id); 
        }
        new_comment.removeClass("toclone");
        // Move Screen to focus on this comment
        if (params && params.focus){
            var center = $(window).height()/2;
            var top = new_comment.offset().top ;
            if (top > center){
                $(window).scrollTop(top-center);
            }
        }
        // Specialise the animation
        if (params && params.animate){
            new_comment
            .css({
                "opacity": 0, 
                "backgroundColor": "#FF8B00"
            })
            .animate({
                "opacity": 100, 
                "backgroundColor": "#FFC673"
            }, 4000);
        }
    }
	
    prevo.populateCommentCount = function(count){
        // Can use this function to update the count
        var comment_text;
        // Recursive Call to get starting count
        if (!count){
            // Get the Count if Necessary
            var comment_svc = './previewer_getcomments.php?iid='+prevo.getCurrentId()+"&gc";
            $.ajax({
                url: comment_svc,
                cache: false,
                success: function(data) {
                    prevo.populateCommentCount(data);
                },
                error: function() {
                    prevo.previewer.find(".comment_count").text("Error Loading Comment Count");
                }
            });
        } else {
            var show_comments_link = prevo.previewer.find(".discussion_header_link_show");
            count = parseInt(count);
            // Starts of clickable
            show_comments_link.addClass("discussion_header_link");
            // Enable show the comments link
            show_comments_link.unbind("click");
            show_comments_link.bind("click", function(){
                prevo.toggleComments();
            });
            switch (count){
                case 0:
                    comment_text = "No Comments"; 
                    // Loses clickability when no comments
                    show_comments_link.removeClass("discussion_header_link").unbind("click");
                    prevo.toggleComments("hide");
                    break;
                case 1:
                    comment_text = "1 Comment";
                    break;
                default:
                    comment_text = count+" Comments";
                    break;
            }
            prevo.previewer.find(".comment_count").text(comment_text);
            return count;
        }
    }
	
    // Load the comments for this image via ajax
    prevo.loadComments = function(){
        // Clear all current comments
        prevo.previewer.find(".preview_comment_list li").not(".toclone").remove();
        var image_id = prevo.getCurrentId();
        if (image_id){
            var comment_svc = './previewer_getcomments.php?iid='+prevo.getCurrentId();
            $.ajax({
                url: comment_svc,
                cache: false,
                dataType: "json",
                success: function(comments) {
                    var comment_count = comments.length;
                    var comment_text = "";
                    for (i = 0; i < comment_count; i++){
                        // Publish each retrieved comment onto the page
                        prevo.populateComment(comments[i]);
                    }
                },
                error: function(data) {
                //alert('Error Loading Comments');
                }
            });
        } else {
            if (prevo.debug_flag){
                alert("Error Loading Comments: Invalid Image ID");
            }
        }
    }
	
    // Show/Hide the current comments
    prevo.toggleComments = function(force){
        var comment_list_div = prevo.previewer.find(".preview_comment_list:visible");
        var toggleLabel = prevo.previewer.find(".discussion_header_link_show");
        if (comment_list_div.length == 1){
            if (force == "show"){
                return;
            }
            // hide it
            comment_list_div.slideUp(200);
            toggleLabel.text("show");
        } else {
            if (force == "hide"){
                return;
            }
            // not visible, so show it
            var comment_list_div = prevo.previewer.find(".preview_comment_list");
            comment_list_div.slideDown(200);
            toggleLabel.text("hide");
        }
    }
	
    // Show/Hide the comments form
    prevo.toggleCommentForm = function(force){
        var comment_form_div = prevo.previewer.find(".preview_add_comment:visible");
        var comment_form = prevo.previewer.find(".preview_add_comment form");
        var toggleLabel = prevo.previewer.find(".discussion_header_link_add");
        if (comment_form_div.length == 1){
            if (force == "show"){
                // set focus on first input (class, either traditional input or textarea)
                comment_form.find(".previewer_input:first").focus();
                // Scroll to form's position
                var center = $(window).height()/2;
                var top = comment_form.find(".previewer_input:first").offset().top ;
                if (top > center){
                    $(window).scrollTop(top-center);
                }
                return;
            }
            // hide it
            comment_form.fadeOut(100, function(){
                comment_form_div.slideUp(200);
            });
            toggleLabel.text("add comment");
        } else {
            if (force == "hide"){
                return;
            }
            comment_form_div = prevo.previewer.find(".preview_add_comment");
            // not visible, so show it
            comment_form_div.slideDown(200, function(){
                comment_form.fadeIn(100, function(){
                    // Stretch out the Comment TextArea
                    comment_form.find("textarea[name=comment]").attr("cols", parseInt(prevo.previewer.find(".preview_main").css("width")) /  10);
                    // set focus on first input (class, either traditional input or textarea)
                    comment_form.find(".previewer_input:first").focus();
                    // Scroll to form's position
                    var center = $(window).height()/2;
                    var top = comment_form.find(".previewer_input:first").offset().top ;
                    if (top > center){
                        $(window).scrollTop(top-center);
                    }
                });
            });
            toggleLabel.text("hide form");
        }
    }
	
	
    // Enable Comment Functions
    // Show the Comment Form
    if (prevo.previewer.find(".discussion_header_link_add").length == 1){
        var add_comments = prevo.previewer.find(".discussion_header_link_add");
        add_comments.bind("click", function(){
            prevo.toggleCommentForm();
        });
    }
	
    // Use jQuery to set Opacity of hover_icons for best compatibility
    prevo.previewer.find(".hover_icons").css("opacity", ".85");
	
    // Set Up Thumbnail Functionality
    prevo.previewer.find(".thumb").bind("click", function(){
        // Return if clicked on already selected thumbnail
        if ($(this).css("opacity") != 1){
            return;
        } else {
            prevo.loadThumb(this);
        }
		
    });
	
    // Caption Previewing On
    /*prevo.previewer.find(".thumb").bind("mouseover", function(){
        var image_id = this.id;
        image_id = image_id.replace(prevo.pid+"_img_", "");
        if (typeof image_id != "string") {
            return false;
        }
        if (prevo.getCurrentId() > 0){
            // Don't Bother if this is current image
            if (image_id && image_id != prevo.getCurrentId()){
                // Unset Caption Before DB call
                prevo.loadCaption(0);
                prevo.loadCaption(image_id, 'emphasize');
            }
        }
    });
	
    // Caption Previewing Off
    prevo.previewer.find(".thumb").bind("mouseout", function(){
        var image_id = prevo.currentId;
        // Don't Bother if this is current image
        if (image_id > 0 && image_id != this.id.replace(prevo.pid+"_img_", 'sho_')){
            // Unset Caption Before DB call
            prevo.loadCaption(0);
            if (image_id){ // Will be null if main image isn't loaded yet
                image_id = image_id.replace('sho_', '');
                prevo.loadCaption(image_id.toString());
            }
        }
    });*/
	
    // Image Hover Icons
    prevo.previewer.find(".preview_main img").live("mouseover", function(){
        prevo.previewer.find(".hover_icons").fadeIn(500);
    });
	
    prevo.previewer.find(".preview_main img").live("mouseout", function(e){
        // Prevents MouseOver Bubbling
        if (!e) {
            var e = window.event;
        }
        var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
        if (typeof reltg != 'undefined'){
            // Ignore MouseOut when mouse has simply moved onto icons
            if (reltg && (reltg.className == "hover_icons" || reltg.className == "hover_icon")){
                return;
            }
            prevo.previewer.find(".hover_icons").fadeOut(300);
        }
    });
	
    // Initial Comment Form Setup
    var comment_form = prevo.previewer.find(".preview_add_comment form");
    if (comment_form.length == 1){
        comment_form.find("input[type=submit]").bind("click", function(e){
            e.preventDefault();
            // Some Validation
            user_name = comment_form.find("input[name=commentator]");
            if (user_name.length == 1 && user_name.val().length == 0){
                alert("Please provide a name");
                user_name.focus();
                return;
            }
            user_email = comment_form.find("input[name=email]");
            if (user_email.length == 1 && user_email.val().length == 0){
                alert("Please provide an email address");
                user_email.focus();
                return;
            }
            // Show Loading Icon and disable form
            comment_form.parent().append(prevo.loader);
            var comment_data = comment_form.serialize()
            comment_form.find("input[type=submit]").attr("disabled", true);
            comment_form.find(".previewer_input").attr("disabled", true);
            // Build up the query string
            var comment_qs = comment_form.attr("action")+"&eid="+prevo.getCurrentId();
            var journal_id = prevo.getEntryId();
            if (journal_id > 0){
                comment_qs = comment_qs+'&jid='+journal_id;
            }
            // Send the data to DB
            $.ajax({
                url: comment_qs,
                type: comment_form.attr("method"),
                data: comment_data,
                dataType: "json",
                async:true,
                success: function(json_data, status){
                    // Clear the Form and Remove Loader
                    comment_form.parent().find(".loader").remove();
                    comment_form.find("input[type=submit]").attr("disabled", false);
                    comment_form.find(".previewer_input").attr("disabled", false);
                    if (!json_data.error){
                        comment_form.hide();
                        // Force show the comments
                        prevo.toggleComments("show");
                        // Load the New Comment and update the comment count
                        prevo.populateComment(json_data, {
                            "focus": true, 
                            "animate": true
                        });
                        prevo.populateCommentCount();
                        comment_form.get(0).reset();
                        // And hide the form
                        prevo.toggleCommentForm("hide");
                    } else {
                        //alert(json_data.error);
                        if (json_data.error_code){
                            switch (json_data.error_code) {
                                // 101: Tried to post without logging in
                                case "101":
                                    // Provide Password prompt
                                    var pword_label = 
                                    $("<label>")
                                    .attr({
                                        "for": "pword"
                                    })
                                    .addClass("previewer_label")
                                    .text("Password: ");
                                    var pword_field = 
                                    $("<input>")
                                    .attr({
                                        "name": "pword", 
                                        "type": "password"
                                    })
                                    .addClass("previewer_input");
                                    comment_form.find(".previewer_input[name=email]").after(pword_field).after(pword_label);
                                    pword_field.val("").focus();
                                    break;
                                case "102":
                                    // Focus on password
                                    comment_form.find(".previewer_input[name=pword]").val("").focus();
                            }
                        }
                    }
                },
                error: function(data, error){
                    alert("Error: "+error+". "+data);
                    comment_form.hide().parent().remove(prevo.loader);
                    comment_form.find("input[type=submit]").attr("disabled", false);
                    comment_form.find(".previewer_input").attr("disabled", false);
                }
            });
        });
    }
	
	
    prevo.doSlideshow = function(){
        var started = false;
        var images = [];
        var image_i = 0;
        // Slideshow starts from current image
        prevo.previewer.find(".thumb").each(function(){
            if ($(this).css("opacity") != 1 || started){
                images[image_i] = $(this).attr("id");
                image_i++;
                started = true;
            }
        });
        if (image_i > 1){
            // Get a (valid) delay between slides
            while (!prevo.slideDelay || typeof prevo.slideDelay == "undefined" || parseInt(prevo.slideDelay) <= 0 || isNaN(prevo.slideDelay)){ 
                var delay = prompt("Enter the number of seconds between images", "5");
                delay = parseInt(delay) * 1000;
                prevo.slideDelay = delay
            }
            // Glow the Slideshow icon
            prevo.previewer.find("#"+prevo.pid+"_button_slides").attr("src", "./img/slide_show_off.png");
            // Reset index to 1
            var image_i2 = 1;
            // Set SlideShow On
            $("#"+prevo.pid+"_button_slides").data("showing", true);
            // Do the Loop
            prevo.slideshowHandler = self.setInterval(function(){
                // Stop once we have an invalid image id
                if (typeof images[image_i2] != "string") { 
                    prevo.stopSlideshow(prevo.slideshowHandler); 
                } else {
                    prevo.loadThumb(images[image_i2]);
                    image_i2++;
                }
                if (image_i2 == image_i){
                    prevo.stopSlideshow(prevo.slideshowHandler);
                }
            }, prevo.slideDelay);
        } else {
            $("#"+prevo.pid+"_button_slides").data("showing", false);
            prevo.previewer.find("#"+prevo.pid+"_button_slides").attr("src", "./img/slide_show_off.png").delay(750).attr("src", "./img/slide_show.png");
        }
    }

    prevo.stopSlideshow = function(intervalHandler){
        if (!intervalHandler){
            intervalHandler = prevo.slideshowHandler;
        }
        prevo.previewer.find("#"+prevo.pid+"_button_slides").attr("src", "./img/slide_show.png");
        window.clearInterval(intervalHandler);
        $("#"+prevo.pid+"_button_slides").data("showing", false);
        prevo.slideDelay =  null;
    }
	
    prevo.doComment = function(){
        prevo.toggleComments('show');
        prevo.toggleCommentForm('show');
    }
	
    // Load a default image
    if (prd && parseInt(prd) > 0 && prevo.previewer.find("#"+prevo.pid+"_img_"+prd).length == 1){
        prevo.previewer.find("#"+prevo.pid+"_img_"+prd).trigger("click");
    } else {
        // Load first image automatically
        prevo.previewer.find(".thumb:first").trigger("click");
    }
	
    if ($("#"+prevo.pid+"_editCaption").length == 1){
        $("#"+prevo.pid+"_editCaption").bind("click", function(){
            doSecureEdit(prevo.previewer);
        });
    }
}
