// Functions.js
// Various javascript functions uses throughout the site

jQuery.noConflict();
var $j = jQuery;

$j(document).ready(function() {

    var origTitleObject;

    // Trigger the retrieval of unread comments
    getUnreadComments();

    // Initialize any colorboxes that may be required for this page
    $j('.cboxLink').colorbox({ 
        height: '85%',
        onComplete: function() {
            // Dynamically set the max-width for the photoname div
            var maxWidth = $j('#cboxTitle').width() - 150;
            $j('.photoname').css('max-width', maxWidth + 'px');
        },
        title: function() {
            var fullhref = $j(this).attr('href');
            var photoname = $j(this).attr('title');

            return "<div class='photoname'>" + photoname + "</div> <div class='fullsizelink'>[<a href='" + fullhref + "' target='_blank'>View Full Size</a>]</div>";
        }
    });

    // Set up the grey background on hover for editable titles
    $j('.editable', '#title').live({
        mouseenter: function() {
            $j(this).css('background-color', '#DCDCDC');
        },

        mouseleave: function() {
            $j(this).css('background-color', '');
        }
    });

    $j('.editable').live('click', function() {

        // Store the original title div, and remove the "untitlednotice" span if necessary
        origTitleObject = $j(this).clone();
        $j('.untitlednotice').remove();

        var editFormHTML = 
            '<div class="editTitleForm"><form method="post">\
            <textarea name="newtitle">'+ $j(this).html() + '</textarea>\
            <br /><input type="Submit" value="Submit" /><input type="button" class="nevermind" value="Nevermind" />\
            </form></div>';

        $j(this).replaceWith($j(editFormHTML));
    });

    $j('.nevermind', '#title').live('click', function() {
        $j('.editTitleForm').replaceWith(origTitleObject);
        $j('.editable').css('background-color', '');
    });


    // Mobile preference form
    $j('input[type=checkbox]', '#mobileprefform').click(function() {
        var _thisform = $j('#mobileprefform');
        var _thischeckbox = $j(this);
        
        // Figure out whether or not the checkbox is checked
        var checked = (($j('input:checked', '#mobileprefform').val()) ? 'true' : 'false');

        // Display visual confirmation
        _thisform.find('#conf').html('').append('<br /><img src="/img/loadingbar.gif" />');
        _thischeckbox.attr('disabled', 'disabled');
        
        // Set the preference
        $j.post('/cp/changemobilepref', { 'mobilepref': checked },
            function(data) {
                _thisform.find('img').remove();
                _thisform.find('#conf').append('&raquo ' + data);
                _thischeckbox.removeAttr('disabled');
            },
        'html');
    });
});

// displayLogin(user) : Displays the user login form
function displayLogin() {

    if ($j("#logindiv").is(":hidden")) {
        
        $j("#logindiv").animate({width: 'show'}, function() { $j("#loginusername").focus(); });
    }
    else {
        $j("#logindiv").animate({width: 'hide'});
    }
}

// getComments(photoid) : Gets the comments associated with a particular file
function getComments(photoid) {

    // This puts the "Comments" graphic in the div, among other things
    $j("#comments").addClass("commentsover");
    
    // Loading message
    $j("#comments").html("Getting Comments...");

    // Get the comments
    url = '/hello/comments/' + photoid;

    $j.get(url, '', 
        function(data, textStatus) {
            // Display retrieved comments
            $j("#comments").html(data);

            // Refresh new comments list
            getUnreadComments();
        }
    );
}


// Change_over(div) : Used to change the element "div"'s style when mouse-overed
function change_over(div) {
    div.className = "over";
}

// Change_out(div) : Used to change the element "div"'s style when mouse-outed
function change_out(div) {
    div.className = "out";
}

// Deletemedia() : Used to confirm that the user would really like to delete a file
function deletemedia() {
    sure = confirm('Are you sure you want to delete this item?');

    if (sure) {
        document.getElementById("deleteitem").submit();
    }
}

function deletecomment(id) {

    sure = confirm("Are you sure you'd like to delete this comment?");

    if (sure) {
            document.getElementById("deletecomment").delcomment_id.value = id;
            document.getElementById("deletecomment").submit();
    }
}

function editcomment(id) {
    commentdiv = eval("document.getElementById('comment-" + id + "')");
    orig_comment = eval("document.getElementById('comment-" + id + "-actualcomment').innerHTML");
    orig_entirediv = commentdiv.innerHTML;

    //orig_comment = orig_comment.replace(/<br>/g, "\n");
    var re = /<\S[^><]*>/g
    orig_comment = orig_comment.replace(re, "");

    formhtml = '<form id="editcomment" method="post" style="margin: 0px;">\
        <textarea id="commenteditbox" name="commenteditbox" style="height: 75px; width: 100%; border: 1px solid silver; font: normal 11px arial, sans-serif;">' + orig_comment + '</textarea>\
        <br / >\
        <input type="hidden" name="editcomment_id" value="' + id + '">\
        <input type="hidden" name="action" value="edit">\
        <input type="button" name="submitbutton" value="Submit" onClick="javascript: sendcomment(\'' + id + '\', document.getElementById(\'commenteditbox\'), orig_entirediv);">\
        <input type="button" name="cancel" value="Cancel" onClick="javascript: commentdiv.innerHTML = orig_entirediv;"></form>';

    commentdiv.innerHTML = formhtml;
}


// sendcomment(): This actually processes the edited comment
function sendcomment(editid, commentfield, orig_entirediv) {
        // Display "updating" message
        $j("#comment-" + editid).html('<img src="/img/loadingbar.gif" /> Updating...');

        $j.post("/hello/sendcomment/" + editid, { "data[comment]": commentfield.value },
            function(data) {
                commentdiv.innerHTML = orig_entirediv;
            
                datasplit = data.split('|');

                $j("#comment-" + editid + "-actualcomment").html(datasplit[0]);
                $j("#comment-" + editid + "-editedline").html('(<i>Edited: ' + datasplit[1] + '</i>)');
        }
    );
}


// randomPhoto(): Gets a random photo from the db
function randomPhoto() {

    // Display loading graphic 
    $j("#randomphotobox").html('<img src="/img/loading.gif">');

    // Load the box with the random photo
    $j.post('/hello/randomphoto', 
            function(data) {
                $j("#getbutton").attr("value", "Get another random photo");
                $j("#randomphotobox").css("border-width", "1px");
                $j("#randomphotobox").html(data);
            }
    );
}


// Used to display the site statistics stuff
function showstats() {
    if ($j("#morestats:hidden").length == 1) {
        $j("#morestats:hidden").show("blind");
    }
    else {
        $j("#morestats:visible").hide("blind");
    }
}

// Get unread comments
function getUnreadComments() {

    // Get unread comment list
    $j.get('/hello/unreadcomments/', function(data) {
        $j("#newcomments").html(data);
    });
}


// Copyright 2006,2007 Bontrager Connection, LLC
// http://bontragerconnection.com/ and http://www.willmaster.com/
// // Version: July 28, 2007
var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }
function AssignPosition(d) {
if(self.pageYOffset) {
rX = self.pageXOffset;
rY = self.pageYOffset;
}
else if(document.documentElement && document.documentElement.scrollTop) {
rX = document.documentElement.scrollLeft;
rY = document.documentElement.scrollTop;
}
else if(document.body) {
rX = document.body.scrollLeft;
rY = document.body.scrollTop;
}
if(document.all) {
cX += rX; 
cY += rY;
}
d.style.left = (cX+10) + "px";
d.style.top = (cY+10) + "px";
}
function HideContent(d) {
if(d.length < 1) { return; }
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
dd.style.display = "block";
}
function ReverseContentDisplay(d) {
if(d.length < 1) { return; }
var dd = document.getElementById(d);
AssignPosition(dd);
if(dd.style.display == "none") { dd.style.display = "block"; }
else { dd.style.display = "none"; }
}

// Used for creating Google charts
var simpleEncoding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

function simpleEncode(valueArray,maxValue) {

var chartData = ['s:'];
for (var i = 0; i < valueArray.length; i++) {
 var currentValue = valueArray[i];
     if (!isNaN(currentValue) && currentValue >= 0) {
         chartData.push(simpleEncoding.charAt(Math.round((simpleEncoding.length-1) * currentValue / maxValue)));
     }
     else {
         chartData.push('_');
     }
 }

 return chartData.join('');
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

