// define some vars
if(window.location.host == 'www.jenox.com') var siteURL = 'http://www.jenox.com/clients/wwff/';
else var siteURL = 'http://' + window.location.host + '/Clients/WeWorkForFree/site/';
var user = new Array();
var IE6 = false;

$(function() {
    // if IE6, fix background image flicker
    if($.browser.msie && ($.browser.version == 6)) {
        fixIE6flicker(true);
        IE6 = true;
    }

    // Search
    var searchTXT = "search for [[TYPE]]...";
    $('div.header div.search input[@name=q]').val(searchTXT.replace("[[TYPE]]","art"));
    $('div.header div.search a').click(function(){
        $(this).siblings().removeClass("current");
        $('div.header div.search input[@name=type]').val($(this).attr("class"));
        var searchQ = $('div.header div.search input[@name=q]');
        if(searchQ.val().match(/^search for \w+\.\.\./) || searchQ.val() == "") searchQ.val(searchTXT.replace("[[TYPE]]", $(this).attr("class")));
        $(this).addClass("current");
        return false;
    });
    $('div.header div.search input[@name=q]').click(function(){
        if($('div.header div.search input[@name=q]').val().match(/^search for \w+\.\.\./)) $(this).val("");
    });
    
    // Main Navigation
    var lastTab = "";
    $('ul.nav li a').click(function(){
        $('div.' + lastTab + '-subnav').hide();
        lastTab = $(this).attr("class");
        if(lastTab != "" && lastTab != null) {
            $('ul.nav li.current').removeClass("current");
            $(this).parent().addClass("current");
            $('div.' + lastTab + '-subnav').show();
            return false;
        }
    });
    $('ul.nav li.current a').click();
    
    // Gallery
    initGallery();
});

// Fix IE6 background image flicker
function fixIE6flicker(fix) {
    try {
        document.execCommand("BackgroundImageCache", false, fix);
    } catch(err) { }
}

// load image
function loadImage(image) {
    // if the image url is not set
    if(image.url == "") {
        return false;
    }
    
    var img = new Image();
    $(img).load(function () {
        image.object.removeClass('loading').append(this);
    }).error(function () {
        // notify the user that the image could not be loaded
    }).attr('alt', image.title).attr('src', image.url);
    
    return true;
}

// Messages
function initMessages(page) {
    switch(page) {
        case 'compose':
            $("#receiver").autocomplete(
                siteURL + "messages.php",
                {
                    delay:10,
                    minChars:2,
                    matchSubset:1,
                    matchContains:1,
                    cacheLength:10,
                    onItemSelect:selectItem,
                    //onFindValue:findValue,
                    //formatItem:formatItem,
                    autoFill:true,
                    extraParams:{action:'compose',form_action:'receiverNames'}
                }
            ).change(function(){
                if($(this).val() == "") $("#receiver_id").val(0);
            });
            break;
        default:
            $("button.delete-btn").click(function(){
                if(!confirm("Are you sure you wish to delete the selected messages?")) {
                    return false;
                } else return true; 
            });
            $("#mod_messages a.selectAll").toggle(function(){
                $("#mod_messages").checkCheckboxes();
            },function(){
                $("#mod_messages").unCheckCheckboxes();
            });
            break;
    }
}
function selectItem(li) {
    $("#receiver_id").val(li.extra[0]);
}

// Comments
function initComments() {
    var options = {
        beforeSubmit: function(formArray, jqForm) {
            if($("#comment").val() == "") {
                $("form.new_comment").before('<div class="error" id="comment-msg">You forgot to enter your comment!</div>');
                setTimeout(function () {
                    $("#comment-msg").fadeOut().remove();
                }, 2000);
                return false;
            }
        },
        success: function(data) {
            $("span.commentsCount").html(parseInt($("span.commentsCount").text()) + 1);
            $("div.comments").show().append(data);
            $("#comment").val("");
        }
    };
    $("form.new_comment").prepend('<input type="hidden" name="ajax" value="1"/>').ajaxForm(options);
    
    $("a.delete-comment").click(function(){
        if(!confirm("Are you sure you wish to delete this comment?")) {
            return false;
        } else return true;
    });
}

function formatFileSize(bytecount) {
    var str = bytecount+' B';
    if (Number(bytecount) > 1000) { str = (bytecount/1000).toFixed(2)+' kB'; }
    if (Number(bytecount) > 1000000) { str = (bytecount/1000000).toFixed(2)+' MB'; }
    if (Number(bytecount) > 1000000000) { str = (bytecount/1000000000).toFixed(2)+' GB'; }
    return str;
} 

function initGallery() {
    // Gallery Grid
    $('div.gallery-grid a.thumbnail').each(function(){
        // define vars
        var picID = $(this).parent().attr("id").match(/\d+/);
        
        // add rating
        var rating = $(this).parent().find('div.rating');
        rating.rating(siteURL+"gallery.php?pic_id="+picID, {maxvalue:5, curvalue:rating.attr("title"), increment: .5, required: true});
        
        /*
        // load image
        var image = new Array();
        image['title'] = $(this).find("span.info-wrapper span.info strong").text();
        image['url'] = 'http://jenox.gotdns.org:8888/Clients/WeWorkForFree/site/' + $(this).attr("title");
        image['object'] = $(this);
        loadImage(image);
        // clean up
        $(this).removeAttr("title");
        */
        
        // hover features
        $(this).hover(function(){
            if($.browser.mozilla) $(this).find("span.info-wrapper").fadeIn();
            else $(this).find("span.info-wrapper").show("fast");
        },function(){
            if($.browser.mozilla) $(this).find("span.info-wrapper").fadeOut();
            else $(this).find("span.info-wrapper").hide("fast");
        })
    });
    $('div.gallery-grid div.pic a.more').click(function(){
        if($(this).attr("class") == "more-on") {
            $(this).parent().find('div.views-comments-info').hide();
            $(this).parent().find('div.rate-vote-info').show();
            $(this).attr("class","more");
        } else {
            $(this).parent().find('div.rate-vote-info').hide();
            $(this).parent().find('div.views-comments-info').show();
            $(this).attr("class","more-on");
        }
        return false;
    });
    
    $("div.gallery a.delete").click(function(){
        if(!confirm("Are you sure you wish to delete this image?")) {
            return false;
        } else return true; 
    });
}

function initPicture() {
    $('div.picture div.tags').hide();
    $('div.picture div.tagsLink a').click(function(){
        $('div.picture div.tags').toggle();
        return false;
    });
    $('div.picture a.image').each(function(){
        // define vars
        var picID = $(this).parent().attr("id").match(/\d+/);
        
        // add rating
        var rating = $(this).parent().find('div.rating');
        rating.rating(siteURL+"gallery.php?pic_id="+picID, {maxvalue:5, curvalue:rating.attr("title"), increment: .5, required: true});
        
        // add favorites
        var favLayer = $(this).parent().find('a.add-to-fav');
        favLayer.click(function(){
            if(user['logged_in'] != 1) {
                alert('You need to log into your account first.');
                return false;
            }
            var parent = $(this).parent();
            $.post(siteURL+"gallery.php",
                { pic_id: picID, mode: "addFav" },
                function(data){
                    parent.after('<div class="msg" id="fav-msg">' + (data > 0 ? 'This image has successfully been <strong>added</strong> to your favorites' : 'This image has successfully been <strong>removed</strong> from your favorites') + '</div>');
                    setTimeout(function () {
                        $("#fav-msg").fadeOut().remove();
                    }, 2000);
                    favLayer.text(data > 0 ? 'Remove from Favorites' : 'Add to Favorites');
                }
            );
            return false;
        });
        
        /*
        // load image
        var image = new Array();
        image['title'] = $(this).find("span.info-wrapper span.info strong").text();
        image['url'] = 'http://jenox.gotdns.org:8888/Clients/WeWorkForFree/site/' + $(this).attr("title");
        image['object'] = $(this);
        loadImage(image);
        // clean up
        $(this).removeAttr("title");
        */
        
        // hover features
        $(this).hover(function(){
            if($.browser.mozilla) $(this).find("span.info-wrapper-top,span.info-wrapper-bottom").fadeIn();
            else $(this).find("span.info-wrapper-top,span.info-wrapper-bottom").show("fast");
        },function(){
            if($.browser.mozilla) $(this).find("span.info-wrapper-top,span.info-wrapper-bottom").fadeOut();
            else $(this).find("span.info-wrapper-top,span.info-wrapper-bottom").hide("fast");
        })
    });
    // init comments
    initComments();
}

// Image Upload
var swfu = null;
var imageStats = new Array();
function initImageUpload(hc) {
    //console.log(siteURL);
    // define variables
    imageStats['total'] = 0;
    imageStats['current'] = 0;
    var settings = {
        flash_url : siteURL+"images/swfupload/swfupload_f9.swf?r="+Math.random(),
        upload_url: siteURL+"gallery.php",
        post_params: { "action" : "upload" , "type" : "swfupload" , "hc" : hc },
        file_size_limit : "100 MB",
        file_types : "*.jpg;*.gif;*.png",
        file_types_description : "All Image Files",
        file_upload_limit : 100,
        file_queue_limit : 0,
        custom_settings : {
            progressTarget : "fsUploadProgress",
            cancelButtonId : "btnCancel"
        },
        debug: false,

        // The event handler functions are defined in handlers.js
        file_queued_handler : fileQueued,
        file_queue_error_handler : fileQueueError,
        file_dialog_complete_handler : fileDialogComplete,
        upload_start_handler : uploadStart,
        upload_progress_handler : uploadProgress,
        upload_error_handler : uploadError,
        upload_success_handler : uploadSuccess,
        upload_complete_handler : uploadComplete,
        queue_complete_handler : queueComplete    // Queue plugin event
    };

    swfu = new SWFUpload(settings);
    
    $('div.gallery-upload div.step1JS a.choose-images,div.gallery-upload div.step2 a.add-more-btn').show().click(function(){
        swfu.selectFiles();
        return false;
    });
    
    $('div.step1').hide();
    $('div.step1JS').show();
    $('div.step1JS p.simple-form a').click(function(){
        $('div.step1').show();
        $('div.step1JS').hide();
        return false;
    });
}

/* **********************
   Event Handlers
   These are my custom event handlers to make my
   web application behave the way I went when SWFUpload
   completes different tasks.  These aren't part of the SWFUpload
   package.  They are part of my application.  Without these none
   of the actions SWFUpload makes will show up in my application.
   ********************** */
function fileQueued(file) {
    //console.log('fileQueued');
    try {
        // update file stats
        imageStats['total'] += file.size;
        
        // create file box
        var fileBox = $('div.fileTemplate').clone();
        fileBox.removeClass("fileTemplate").addClass("file").attr("id",file.id).prependTo("div.uploadQueue");
        fileBox.find("span.name").text(file.name);
        fileBox.find("span.size").text(formatFileSize(file.size));
        fileBox.find("p.remove a").click(function(){
            swfu.cancelUpload(file.id);
            var filesCount = $('div.stats span.filesCount');
            filesCount.text(parseInt(filesCount.text()) - 1);
            fileBox.find("p.remove").hide();
            fileBox.find("p.remove-disabled").show();
            imageStats['total'] -= file.size;
            $('div.stats span.filesSize').text(formatFileSize(imageStats['total']));
            setTimeout(function () {
                fileBox.fadeOut();
            }, 2000);
            return false;
        });
    } catch (ex) {
        this.debug(ex);
    }

}

function fileQueueError(file, errorCode, message) {
    try {
        if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
            alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
            return;
        }

        var fileBox = $("#" + file.id);
        fileBox.find("p.remove").hide();
        fileBox.find("p.remove-disabled").show();

        switch (errorCode) {
        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
            fileBox.find("p.error").text("File is too big.").show();
            this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            fileBox.find("p.error").text("Cannot upload Zero Byte files.").show();
            this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
            fileBox.find("p.error").text("Invalid File Type.").show();
            this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        default:
            if (file !== null) {
                fileBox.find("p.error").text("Unhandled Error").show();
            }
            this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
    //console.log('fileDialogComplete');
    try {
        // set current step to 2
        $('div.gallery-step1').removeClass("gallery-step1").addClass("gallery-step2");
        $('div.step1,div.step1JS').hide();
        
        // update stats
        $('div.stats span.filesCount').text(parseInt($('div.stats span.filesCount').text()) + numFilesQueued);
        $('div.stats span.filesSize').text(formatFileSize(imageStats['total']));
        
        // activate upload button
        $('div.step2 a.upload-images').click(function(){
            if($("#upload-error").css("display") == "block") return false;
            // if there is at least 1 image to upload
            if(parseInt($('div.stats span.filesCount').text()) > 0) {
                $('div.gallery-upload div.step2 a.add-more-btn, div.gallery-upload div.step2 a.upload-images').hide();
                $('div.gallery-upload div.step2 p.status,div.gallery-upload div.step2 div.bar').show();
                swfu.startUpload();
            } else {
                $('div.step2 a.upload-images').before('<div class="error" id="upload-error">You need to select at least one (1) image to upload.</div>');
                setTimeout(function () {
                    $("#upload-error").fadeOut();
                }, 2000);
            }
            return false;
        });
    } catch (ex)  {
        this.debug(ex);
    }
}

function uploadStart(file) {
    //console.log('uploadStart');
    try {
        var fileBox = $("#" + file.id);
        fileBox.find("p.status-progress").show();
        fileBox.find("p.remove").hide();
        fileBox.find("p.remove-disabled").show();
    }
    catch (ex) {}
    
    return true;
}

function uploadProgress(file, bytesLoaded, bytesTotal) {
    //console.log('uploadProgress');
    try {
        var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
        var current= imageStats['current'] + bytesLoaded;
        var totalPercent = (current > imageStats['total']) ? 100 : Math.ceil((current / imageStats['total']) * 100);

        var fileBox = $("#" + file.id);
        fileBox.find("p.status-progress em").text(percent);
        fileBox.find("span.img em").css("width", percent + "%");
        
        $('div.gallery-upload div.step2 div.bar em').css("width", totalPercent + "%");
    } catch (ex) {
        this.debug(ex);
    }
}

function uploadSuccess(file, serverData) {
    //console.log('uploadSuccess');
    //console.log(serverData);
    try {
        var fileBox = $("#" + file.id);
        fileBox.find("p.status-progress").hide();
        fileBox.find("p.status-complete").show();
        
        var imgData = serverData.split("|");
        var picID = imgData[0];
        var picURL = imgData[1];
        var imgLayer = fileBox.find("span.img");
        var img = new Image();
        $(img).load(function () {
            imgLayer.html(this);
        }).attr('alt', file.name).attr('src', siteURL + picURL);
        
        $('div.gallery-upload div.step2 div.proceed a').attr("href", $('div.gallery-upload div.step2 div.proceed a').attr("href") + picID + ",");
        
        imageStats['current'] += file.size;
    } catch (ex) {
        this.debug(ex);
    }
}

function uploadError(file, errorCode, message) {
    try {
        var fileBox = $("#" + file.id);
        fileBox.find("p.remove").hide();
        fileBox.find("p.remove-disabled").show();

        switch (errorCode) {
        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
            fileBox.find("p.error").text("Upload Error: " + message).show();
            this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
            fileBox.find("p.error").text("Upload Failed.").show();
            this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.IO_ERROR:
            fileBox.find("p.error").text("Server (IO) Error").show();
            this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
            fileBox.find("p.error").text("Security Error").show();
            this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
            fileBox.find("p.error").text("Upload limit exceeded.").show();
            this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
            fileBox.find("p.error").text("Failed Validation.  Upload skipped.").show();
            this.debug("Error Code: File Validation Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
            fileBox.find("p.error").text("Cancelled").show();
            break;
        case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
            fileBox.find("p.error").text("Stopped").show();
            break;
        default:
            fileBox.find("p.error").text("Unhandled Error: " + errorCode).show();
            this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
            break;
        }
    } catch (ex) {
        this.debug(ex);
    }
}

function uploadComplete(file) {
    //console.log('uploadComplete');
    if (this.getStats().files_queued === 0) {
        $('div.gallery-upload div.step2 p.status strong').text("100% complete");
        $('div.gallery-upload div.step2 div.proceed').show();
    }
}

// This event comes from the Queue Plugin
function queueComplete(numFilesUploaded) {
    //console.log('queueComplete');
}

// profile
function initProfile() {
    // email, msn
    $('p.email a, p.msn a').each(function(){
        var email = $(this).find('span.account').text() + "@" + $(this).find('span.provider').text();
        $(this).attr('href',$(this).attr('href').replace("anti-spam-email", email));
    });
}

// table functions
function initTableForm(fID) {
    $("#" + fID + " input[@name=selectAll]").toggle(function(){
        $("#" + fID).checkCheckboxes();
    },function(){
        $("#" + fID).unCheckCheckboxes();
    });
}