/**
 * main.js - This script gets loaded once into the main application page
 */


// Declare a few global objects
var leftWindow;
var rightWindow;
var view;
var campaign;
var disclaimer = '';

var mailboxes = new Array();
var currentMailbox = '';
var currentMailboxName = '';
var toggled = false;

var toggleOpen = preloadImage('/lib/skins/mac/images/toggle-box_open.png');
var toggleClosed = preloadImage('/lib/skins/mac/images/toggle-box_closed.png');


// Constants
var SORT_ASC = 1;
var SORT_DESC = -1;
var NO_SAVE_INFO = 0;


/**
 * An associative array to hold information to store in the application's browser cookie
 * This is used to keep track of the state of the application so that it can be restored
 * if someone reloads the window.
 */
var state = new Object();


// Set some state defaults and defint state properties
state.user = '';
state.viewName = 'dashboard';
state.searchType = '';
state.searchVal = '';
state.changePassword = 0;
state.sortColumn = new Object();
state.sortDirection = new Object();



// Pre-load some of the interface images from the server so that they'll be ready to display
fetchImage('/lib/skins/mac/images/menu-bg_normal.png');
fetchImage('/lib/skins/mac/images/menu-bg_rollover.png');
fetchImage('/lib/skins/mac/images/tab-bg_normal.png');
fetchImage('/lib/skins/mac/images/tab-bg_on.png');
fetchImage('/lib/skins/mac/images/tab-bg_rollover.png');
fetchImage('/lib/skins/mac/images/button_blue_left.png');
fetchImage('/lib/skins/mac/images/button_blue_right.png');
fetchImage('/lib/skins/mac/images/window-title-bar_left.png');
fetchImage('/lib/skins/mac/images/window-title-bar_right.png');
fetchImage('/lib/skins/mac/images/window-body_left.png');
fetchImage('/lib/skins/mac/images/window-body_right.png');
fetchImage('/lib/skins/mac/images/window-bottom_left.png');
fetchImage('/lib/skins/mac/images/window-bottom_right.png');
fetchImage('/lib/skins/mac/images/modal-dialog_right.png');
fetchImage('/lib/skins/mac/images/modal-dialog_top-left.png');
fetchImage('/lib/skins/mac/images/modal-dialog_top-right.png');
fetchImage('/lib/skins/mac/images/modal-dialog_left.png');
fetchImage('/lib/skins/mac/images/modal-dialog_bottom-left.png');
fetchImage('/lib/skins/mac/images/modal-dialog_bottom-right.png');
fetchImage('/lib/skins/mac/images/progress-wheel_sm.gif');
fetchImage('/lib/skins/mac/images/progress-wheel_md.gif');
fetchImage('/lib/skins/mac/images/progress-wheel_lg.gif');



function onMainLoad() {
    if (disclaimer) {
        openModalDialogWithUrl(disclaimer);
    }


    // Set up some standard objects
    leftWindow = new AppWindow('LeftWindow');
    rightWindow = new AppWindow('RightWindow');

    view = new View();

    // Check to see if the state had previously been saved
    var cookie = getCookie('Power_AssetBank_State');
    if (cookie) {
        // Load the previous state
        var values = cookie.evalJSON();
        if (values.viewName != undefined && values.viewName != '') {
            state = values;
        }
    }

    view.set(state.viewName);

    if (state.changePassword == true) {
        showPasswordChangeDialog();
    }
}


function onMainUnload() {
    setCookie('Power_AssetBank_State', Object.toJSON(state));
}



/**
 * Controls the page view
 */
var View = Class.create({
    initialize: function() {
    },

    set: function(name) {
        resetWindows();
        clearSiteNav();

        switch (name) {
            case 'dashboard':
                showAssetBrowser();
                showDashboard();
                $('Nav_Dashboard').addClassName('On');
                break;

            case 'help':
                showHelp();
                $('Nav_Help').addClassName('On');
                break;

            case 'category':
                showAssetBrowser();
                showCategory(state.categoryId);
                break;

            case 'categoryList':
                showAssetBrowser();
                showCategoryList(state.categoryListId);
                break;

            case 'cart':
                showAssetBrowser();
                showCart();
                $('Nav_ViewCart').addClassName('On');
                break;

        }

        state.viewName = name;

    }
});  // View class


function clearSiteNav() {
    navLinks = $('SiteNav').getElementsByTagName('a');
    for (var i = 0; i < navLinks.length; ++i) {
        // Have to extend these manually due to a bug in IE 7
        Element.extend(navLinks[i]).removeClassName('On');
    }
}


function showAssetBrowser() {
    $('LeftWindow').setStyle({ width: '26%', right: 'auto' });
    $('RightWindow').setStyle({ width: '71%' });
    if(leftWindow.getTitle() != 'Browse Assets') {
        setLeftWindow('Browse Assets', 'browse', '', assignBrowseEvents);
    }
}


function showHelp() {
    state.viewName = 'help';

    setLeftWindow('Help', 'help_left');
    leftWindow.hideHeader();

    setRightWindow('Helpful Information', 'help_right');
    rightWindow.hideHeader();

    resetWindows();
}


function showDashboard() {
    setRightWindow('Dashboard', 'dashboard');
    rightWindow.hideHeader();

    showAssetBrowser();
}


function simpleSearch(searchTerms) {
    new Ajax.Request( '/lib/services/simple-search.php', {
        method:  'get',
        parameters:  {'searchTerms': searchTerms },
        onSuccess: function(response, jsonHeader) {
            try {
                if (jsonHeader['status'] == 'Success') {
                    state.viewName = 'search';
                    state.searchTerms = searchTerms;

                    showAssetBrowser();
                    rightWindow.hideHeader();
                    setRightWindow(jsonHeader['title'], 'asset-list');

                } else {
                    state.viewname = 'intro';
                    alert('Warning:  ' + jsonHeader['message']);
                }
            } catch(e) {
                alert('An error occurred on the server:  ' + e.message);
            }
        },
        onFailure:  function() {
            alert('An error occurred on the server. Please try again.');
        }
    });    
}

function doSimpleSearch(searchTerms, whereClause, queryString) {
    searchTerms = searchTerms.toUpperCase();
    searchTerms = searchTerms.replace(/\s+/g, "%");

    // Build a querystring out of the search terms
    whereClause = "UPPER(assets.name) LIKE '%" + searchTerms + "%' ";
    whereClause += " OR UPPER(assets.keywords) LIKE '%" + searchTerms + "%' ";
    whereClause += " OR UPPER(assets.file_name) LIKE '%" + searchTerms + "%' ";

    searchAssets( 'whereClause', whereClause );

    return(false);
}


function doAdvancedSearch(assetTitle, filename, whereClause, queryString) {
    var categoryId = $('CategoryID').value;

    state.viewName = 'advancedSearch';

    assetTitle = assetTitle.toUpperCase();
    assetTitle = assetTitle.replace(/\s+/g, "%");

    if(filename) {
        filename = filename.toUpperCase();
        filename = filename.replace(/\s+/g, "%");
    }

    categoryId = categoryId.replace('ID','');

    // Build a querystring out of the search terms
    if (assetTitle != '' || filename != '') {
        whereClause = '1=1 ';
        if (assetTitle != '') { whereClause += " AND UPPER(assets.name) LIKE '%" + assetTitle + "%' "; }
        if (filename != '') { whereClause += " AND UPPER(assets.file_name) LIKE '%" + filename + "%' "; }

        queryString = 'whereClause=' + encodeQueryString(whereClause);

        if (categoryId != '') { queryString += '&searchCategory=' + categoryId; }
        if (categoryId != '') { whereClause += " AND assets.category_id = " + categoryId + " "; }

        searchAssets( 'whereClause', whereClause );
    }

    return(false);
}


function searchAssets(searchType, searchVal, callback) {
    state.searchType = searchType;
    state.searchVal = searchVal;

    new Ajax.Request( '/lib/services/search-assets.php', {
        method:  'get',
        parameters:  {'searchType': searchType, 'searchVal':  searchVal},
        onSuccess: function(response, jsonHeader) {
            try {
                state.viewName = 'dashboard';
                if (jsonHeader['status'] == 'Success') {
                    var page = jsonHeader['nextPage'];
                    var params;

                    showAssetBrowser();
                    rightWindow.hideHeader();
                    setRightWindow(jsonHeader['message'], page, {'searchType': jsonHeader['searchType'], 'searchVal': jsonHeader['searchVal']});  

                } else {
                    state.viewname = 'intro';
                    alert('Warning:  ' + jsonHeader['message']);
                }
            } catch(e) {
                alert('Error occurred in searchAssets:  ' + e.message);
            }
        },
        onFailure:  function() {
            alert('Error occurred in searchAssets');
        }
    });
}

function showCart() {
    new Ajax.Request('/content/shopping-cart.php', {
        method: 'get',
        onSuccess: function(response, jsonHeader) {
            rightWindow.setTitle('Shopping Cart');
            setWindowHeader(rightWindow, 'shopping-cart-buttons')
            rightWindow.setContent(response.responseText);
            setCartCount(jsonHeader['count']);
            assignCartEvents();
        },
        onFailure: function() {
            alert('Something went wrong.');
        }
    });
}


function showCategoryList(categoryId) {
    state.viewName = 'categoryList';
    state.categoryListId = categoryId;
    new Ajax.Request('/content/category-list.php', {
        method: 'get',
        parameters: { 'categoryId': categoryId },
        onSuccess: function(response, jsonHeader) {
            rightWindow.setTitle('Categories');
            rightWindow.hideHeader();
            rightWindow.setContent(response.responseText);
        },
        onFailure: function() {
            alert('Something went wrong.');
        }
    });
}


function setRequiredFieldStyle(id){
    $(id).setStyle('border:  2px outset #ff0000');
}



function playFlash(fileName, width, height) {
    if (fileName != '' && !isNaN(width) && !isNaN(height)) {
        openModalDialogWithUrl('/content/flash-player.php?fileName=' + fileName + '&width=' + width + '&height=' + height, (width + 40));
    }
}



/**
  *  This is a callback that's called when the setRightWindow call inside of fetchCampaignList() is finished.
  *  At this point, all of the campaign list table data is loaded and we can initialize table sort.
  */
function sortAssetList() {
    genericSortTableCallback('AssetListTable', 'AssetistTableName', assetListSortEvent);
}


/**
  *  This is a callback that is triggered by the SortableTable._sort function.
  *  It finds the currently sorted column and stores it and the sort direction in the state.
  */
function assetListSortEvent() {
    $$('table#AssetListTable th.sortasc').each (
        function(element) {
            state.sortColumn['AssetListTable'] = element.id;
            state.sortDirection['AssetListTable'] = SORT_ASC;
            return;
        });

    $$('table#AssetListTable th.sortdesc').each (
        function(element) {
            state.sortColumn['AssetListTable'] = element.id;
            state.sortDirection['AssetListTable'] = SORT_DESC;
            return;
        });
}




/**
  * This is a general function for initializing sorting on a table
  */
function genericSortTableCallback(tableid, defaultColId, sortEventCallback){
    if(!$(tableid)) return;
    if(!$(defaultColId)) return;

    //Attach our callback to the sort event.
    //This event is triggered when a sortable column in a table is clicked.
    SortableTable.options.sortEventCallbacks[tableid] = sortEventCallback;
    
    //Initialize the sortable table.  This attaches the appropriate events & styles to the table to make it sortable
    //SortableTable.load();
    SortableTable.init(tableid);

    if (!state.sortColumn[tableid]) {
        //Default is to sort the Name colum ascending
        $(defaultColId).addClassName('sortasc');
    }else{
        SortableTable.sort($(tableid), $(state.sortColumn[tableid]), state.sortDirection[tableid]);
    }
}



function enlargeThumbnail(templatePath) {
    var content =
        '<p><img src="' + templatePath + '/thumbnail_lg.jpg" alt="" /></p>' +
        '<table class="Buttons"><tr>' +
        '<td><a href="" onclick="closeModalDialog(); return false;"><span>Close</span></a></td>' +
        '</tr></table>' +
        '';

    openModalDialog(content, 350);
}



function changePassword()
{
    if( !$('newPassword').value || !$('verify_newPassword').value) {
        alert('Please enter a new password.');
        return;
    }
    if($('newPassword').value != $('verify_newPassword').value) {
        alert("The passwords entered don't match.  Please reenter your password.");
        return;
    }

    new Ajax.Request('/lib/services/change-password.php', {
        method: 'post',
        parameters: { 'password': $('newPassword').value, 
                        'verifyPassword' : $('verify_newPassword').value },
        onSuccess: function(response, jsonHeader) {
            if (jsonHeader['status'] != 'Success') {
                alert(jsonHeader['message']);
            }
        },
        onFailure: function() { alert('The password was not changed because an error ocurred.'); }
    });

    closeModalDialog();
}




/**
 * Returns an HTML paragraph containing the img tag for a progress wheel of a specified size (sm, md, lg)
 */
function outputProgressWheel(size) {
    var result = '<p class="ProgressWheel"><img src="/lib/skins/mac/images/progress-wheel_' + size + '.gif" alt="" />';
    return result;
}

function saveCookie(){
    setCookie('Power_mLab_State', Object.toJSON(state));
}

function showPasswordChangeDialog() {
    state.changePassword = false;
    openModalDialogWithUrl('/content/password-change-form.php', 300, saveCookie);
}




/**
 * Class for application windows
 */
var AppWindow = Class.create({
    initialize: function(elementId) {
        this.div = $(elementId);

        this.bodyDiv = $(elementId + 'Body');
        this.titleDiv = $(elementId + 'Title');
        this.headerDiv = $(elementId + 'Header');
        this.footerDiv = $(elementId + 'Footer');

        this.prevTitle = '';
        this.prevBody = '';
        this.contentFilename = '';
    },

    /**
      * Sets the filename that the window content is based off of
      */
    setContentFilename: function(filename){
        this.contentFilename = filename;
    },

    set: function(title, filename, parameters) {
        try{
            // If not specified, add the .php extension
            if (filename.indexOf('.php') == -1) {
                filename += '.php';
            }
        
            // If no path was set, assume it's in the /content/ directory
            if (filename.indexOf('/') == -1) {
                filename = '/content/' + filename;
            }

            this.setContentFilename(filename);
            this.setTitle(title);
            this.setContent(outputProgressWheel('lg'));    

            new Ajax.Request(filename, {
                method: 'get',
                'parameters': parameters,
                onSuccess: function(response, jsonHeader) {
                    if (jsonHeader['title'] != '') {
                        this.setTitle(jsonHeader['title']);
                    }
                    if (response.responseText != '') {
                        this.setContent(response.responseText);
                    }
                }
            }.bind(this)
            );
        }catch(e) {
            alert('Error in AppWindow.set:  ' + e.message);
        }
    },


    /**
     * Changes the title of the window
     */
    setTitle: function(title) {
        // Save the previous title in case we need to revert back to it
        this.prevTitle = this.titleDiv.innerHTML;
        this.titleDiv.innerHTML = title;
    },

    getTitle:  function() {
        return this.titleDiv.innerHTML;
   },


    /**
     * Changes the contents of the window (the #bodyDiv tag)
     */
    setContent: function(content) {
        // Save the previous content in case we need to revert back to it
        this.prevBody = this.bodyDiv.innerHTML;
        this.bodyDiv.innerHTML = content;
    },


    /**
     * Change the content of the window by fetching it from the server
     */
    fetchContent: function(url) {
        // If not specified, add the .php extension
        if (url.substr(-4) != '.php') {
            url += '.php';
        }
    
        // If no path was set, assume it's in the /content/ directory
        if (url.indexOf('/') == -1) {
            url = '/content/' + filename;
        }

        this.setContent(outputProgressWheel('lg'));
    
        new Ajax.Request(url, {
            onSuccess: function(response, jsonHeader) {
                if (response.responseText != '') {
                    this.setContent(response.responseText);
                }
            }.bind(this)
        });
    },


    /**
     * Reverts the title and content back to what they were before the last setTitle() and setContent()
     */
    revert: function() {
        this.setTitle(this.prevTitle);
        this.setContent(this.prevBody);
    },


    /**
     * Hides the window
     */
    hide: function() {
        this.div.hide();
    },


    /**
     * Shows the window
     */
    show: function() {
        this.div.show();
    },


    /**
     * Turns on the header of the window and fills it with specified content
     */
    showHeader: function(content) {
        if (content == undefined) {
            content = '';
        }
        this.bodyDiv.setStyle({ top: '31px' });
        this.headerDiv.innerHTML = content;
        this.headerDiv.show();
    },


    /**
     * Turns off the header of the window and clears its contents
     */
    hideHeader: function() {
        this.bodyDiv.setStyle({ top: '0px' });
        this.headerDiv.hide();
        this.headerDiv.innerHTML = '';
    },


    isHeaderOn: function() {
        if (this.headerDiv.innerHTML == '') {
            return false;
        } else {
            return true;
        }
    },


    /**
     * Turns on the footer of the window and fills it with specified content
     */
    showFooter: function(content) {
        if (content == undefined) {
            content = '';
        }
        this.bodyDiv.setStyle({ bottom: '36px' });
        this.footerDiv.innerHTML = content;
        this.footerDiv.show();
    },
    

    /**
     * Turns off the footer of the window and clears its contents
     */
    hideFooter: function() {
        this.bodyDiv.setStyle({ bottom: '3px' });
        this.footerDiv.hide();
        this.footerDiv.innerHTML = '';
    },


    isFooterOn: function() {
        if (this.footerDiv.innerHTML == '') {
            return false;
        } else {
            return true;
        }
    }
});


/* ALL OF THE FOLLOWING WINDOW-RELATED FUNCTIONS NEED TO BE
 * REFACTORED INTO THGE APPWINDOW CLASS
 */

/**
 * This is only for setting the right window to a FIXED width
 */
function setRightWindowWidth(width) {
    // Change the windows a bit
    $('LeftWindow').setStyle({ width: 'auto', right: (width + 25) + 'px' });
    $('RightWindow').setStyle({ width: width + 'px' });
}

/**
 * This is only for setting the left window to a FIXED width
 */
function setLeftWindowWidth(width) {
    // Change the windows a bit
    $('RightWindow').setStyle({ width: 'auto', right: (width + 25) + 'px' });
    $('LeftWindow').setStyle({ width: width + 'px' });
}


function resetWindows() {
    $('LeftWindow').setStyle({ width: '48%', right: 'auto' });
    $('RightWindow').setStyle({ width: '48%' });
    leftWindow.show();
    rightWindow.show();
}

function setWindowHeader(thewindow, filename, params, callback) {
    // If not specified, add the .php extension
    if (filename.indexOf('.php') == -1) {
        filename += '.php';
    }

    // If no path was set, assume it's in the /content/ directory
    if (filename.indexOf('/') == -1) {
        filename = '/content/' + filename;
    }

    thewindow.showHeader(outputProgressWheel('sm'));


    new Ajax.Request(filename, {
        method: 'get',
        parameters: params,
        timeoutDelay:  20,
        onSuccess: function(response, jsonHeader) {
            if (response.responseText != '') {
                thewindow.showHeader(response.responseText);
            }

            //Check to see if we have a callback function
            //This lets us add functions that can only happen
            //after this Ajax call has finished
            if(callback) {
                callback.call();
            }
        },
        onTimeout: function(){
           showTimeoutError(); 
        } 
    });
}

/**
 * Change the contents of the LEFT window
 * THIS NEEDS TO BE REFACTORED INTO THE WINDOW CLASS
 */
function setLeftWindow(title, filename, parameters, callback) {

    // If not specified, add the .php extension
    if (filename.indexOf('.php') == -1) {
        filename += '.php';
    }

    // If no path was set, assume it's in the /content/ directory
    if (filename.indexOf('/') == -1) {
        filename = '/content/' + filename;
    }

    leftWindow.setContentFilename(filename);
    leftWindow.setTitle(title);
    leftWindow.setContent(outputProgressWheel('lg'));


    new Ajax.Request(filename, {
        method: 'get',
        'parameters': parameters,
        timeoutDelay:  20,
        onSuccess: function(response, jsonHeader) {
            if (response.responseText != '') {
                leftWindow.setContent(response.responseText);
            }

            //Check to see if we have a callback function
            //This lets us add functions that can only happen
            //after this Ajax call has finished
            if(callback) {
                callback.call();
            }
        },
        onTimeout: function(){
           showTimeoutError(); 
           leftWindow.revert();
        } 
    });
}


/**
 * Change the contents of the RIGHT window
 * THIS NEEDS TO BE REFACTORED INTO THE WINDOW CLASS
 */
function setRightWindow(title, filename, parameters, callback) {
    // If not specified, add the .php extension
    if (filename.indexOf('.php') == -1) {
        filename += '.php';
    }

    // If no path was set, assume it's in the /content/ directory
    if (filename.indexOf('/') == -1) {
        filename = '/content/' + filename;
    }

    rightWindow.setContentFilename(filename);
    rightWindow.setTitle(title);
    rightWindow.setContent(outputProgressWheel('lg'));


    new Ajax.Request(filename, {
        method: 'get',
        'parameters': parameters,
        timeoutDelay:  20,
        onSuccess: function(response, jsonHeader) {
            if (response.responseText != '') {
                //rightWindow.setTitle(jsonHeader.title);
                rightWindow.setContent(response.responseText);

                //Check to see if we have a callback function
                //This lets us add functions that can only happen
                //after this Ajax call has finished
                if (callback) {
                    callback.call();
                }
            }
        },
        onTimeout: function() {
            showTimeoutError(); 
            rightWindow.revert();
        } 
    });
}





function showTimeoutError(customMsg) {

    var content = '';

    customMsg = (typeof customMsg == 'undefined') ? 'The operation timed out.  Please try again.' : customMsg;

    content ='<p>' + customMsg + '</p>' +
            '<table class="Buttons"><tr>' +
            '<td><a href="" onclick="closeModalDialog(); return false;"><span>Close</span></a></td>' +
            '</tr></table>' +
            '';

    closeModalDialog();
    openModalDialog(content, 350);
}



function validateQuestionForm(){
    try{
        var i = 0;
        var valid = true;
        var fields = $w('name_Input email_Input phone_Input subject_Input question_Input');

        //Verify that all fields have values
        fields.each( function (field){
            if($(field).value == undefined || $(field).value == ''){
                setRequiredFieldStyle(field);
                valid = false;
            }
        });

        //If all fields have values, verify the email address is valid
        if(valid){
            if($('email_Input').value.indexOf('@') <= 0){
                valid = false;
                setRequiredFieldStyle('email_Input');
                alert('Please enter a valid email address.');
            }
        }
    }catch(e){
        alert('An exception occurred in the script.  (' + e.message + ')');
    }

    return valid;
}

function submitQuestion() {
    if(validateQuestionForm()){
        new Ajax.Request('lib/services/submit-question.php', {
            method:  'post',
            postBody:  $('ContactForm').serialize(),
            onSuccess:  function(response, jsonHeader) {
                try{
                    if (jsonHeader['status'] == 'Success') {
                        var content = '<p>Thank you.  Your question has been submitted.</p>' +
                                        '<p>Someone will be in touch with you shortly.</p>' +
                                        '<table class="Buttons"><tr>' +
                                        '<td><a href="" onclick="closeModalDialog(); return false;"><span>Okay</span></a></td>' +
                                        '</tr></table>';

                        $('ContactForm').reset();
                        openModalDialog(content, 350);
                    }else{
                        alert(jsonHeader['message']);
                    }
                }catch(e){
                    alert('[submitQuestion]  An error occurred (' + e.message + ')');
                }
            },
            onFailure:  function(){ alert('Your question could not be submitted because an error occurred.');}
        });
    }
};










/**
 * Prepares a string to be used as a filename. Strips out any character that is not alphanumeric, a period, or a space.
 */
function prepFileName(name) {
    name = name.replace(/[^A-Za-z0-9_\-\.\ ]/g, '');
    return name;
}




function showAnswer(element) {
    Element.toggleClassName(element.parentNode.parentNode, 'On');
}




/**
 * Places a dimming layer over the entire page and disables the page
 */
function dimWindow() {
    // Only do this because of a bug in Firefox 2 for Mac
    if (navigator.userAgent.indexOf('Firefox/2') != -1 && navigator.userAgent.indexOf('Macintosh') != -1) {
        $('RightWindowContent').setStyle({ overflow : 'hidden' });
        $('LeftWindowContent').setStyle({ overflow : 'hidden' });
    }

    $('PageDimmer').show();
}


/**
 * Lifts the dimming layer and re-enables the page
 */
function undimWindow() {
    $('PageDimmer').hide();

    // Only do this because of a bug in Firefox 2 for Mac
    if (navigator.userAgent.indexOf('Firefox/2') != -1 && navigator.userAgent.indexOf('Macintosh') != -1) {
        $('RightWindowContent').setStyle({ overflow : 'auto' });
        $('LeftWindowContent').setStyle({ overflow : 'auto' });
    }
}






/*
 * MODAL DIALOG BOX
 */

// ALL THIS NEEDS TO BE REFACTORED INTO A CLASS!
// AND IT NEEDS TO IMPLEMENT A STACK SO THAT A MODAL
// DIALOG CAN OPEN ANOTHER MODAL DIALOG

function openModalDialog(content, boxWidth) {
    if (boxWidth == undefined) {
        boxWidth = 450;
    }
    $('ModalDialog').setStyle({ width : boxWidth + 'px' });
    $('ModalDialogContent').innerHTML = content;
    dimWindow();
    $('ModalDialogContainer').show();
}


function openModalDialogWithUrl(url, boxWidth, callback) {
    if (boxWidth == undefined) {
        boxWidth = 450;
    }
    $('ModalDialog').setStyle({ width : boxWidth + 'px' });


    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(response, jsonResponse) {
            $('ModalDialogContent').innerHTML = response.responseText;
            dimWindow();
            $('ModalDialogContainer').show();

            // Execute any javascript that was in the returned HTML
            var scripts = response.responseText.extractScripts();
            eval(scripts[0]);

            if(callback){
                callback.call();
            }
        },
        onFailure: function() {
            alert('The modal dialog could not be opened because an error occurred.');
        }
    })
}



function closeModalDialog() {
    $('ModalDialogContainer').hide();
    $('ModalDialogContent').innerHTML = '';
    undimWindow();
}



function toggleSearch() {
    if($('SimpleSearch').visible()) {
        $('SimpleSearch').hide();
        $('simpleTerms').hide();

        $('AdvancedSearch').show();
        $('advancedTerms').show();
    }else {
        $('SimpleSearch').show();
        $('simpleTerms').show();

        $('AdvancedSearch').hide();
        $('advancedTerms').hide();
    }
}



function switchNav(from, to) {
    from = document.getElementById(from);
    to = document.getElementById(to);
    from.style.display = 'none';
    to.style.display = 'table-cell';
}





/* Browse Tree Functions */
/*************************/

function expandNav() {
    try {
        var mailbox = $('ID' + state.searchVal);

        if(mailbox) {
            var parents = mailbox.ancestors();

            parents.each( function(element) {
                if(element.hasClassName('Mailbox')) {
                    toggleBox();
                } else {
                    var siblings = element.siblings();

                    siblings.each( function(element) {
                        if (element.hasClassName('Mailbox')) {
                            toggleBox();
                        }
                    });
                }
            });

            switchMailbox('ID' + state.searchVal);
        }else {
            alert('The resource browser could not be expanded because category ' + state.searchVal + ' was not found.');
        }
    }catch(e) {
        alert('Error occurred in expandNav (' + e.message + ')');
    }
}


function assignBrowseEvents() {
    try {
        $$('div.Mailbox').each(
            function(element) {
                var toggleImage = getChildByName(element, 'img');
                if (toggleImage.alt == '[+]' || toggleImage.alt == '[-]') {
                    element.onclick = function() { toggleBox(this); }
                } else {
                    element.onclick = function() { 
                        showCategory(this.id); 
                    }
                }

                Event.observe(element, 'mouseover',
                    function() {
                        element.addClassName('Hover');
                    });
                Event.observe(element, 'mouseout',
                    function() {
                        element.removeClassName('Hover');
                    });
            });
    } catch(e) {
        alert('Error in assignBrowseEvents:  ' + e.message);
    }
}


function toggleBox(mailbox)
{
    var toggleImage = getChildByName(mailbox, 'img');

    var list = getNextByName(mailbox, 'ul');

    if (list.style.display == 'block') {
        list.style.display = 'none';
        toggleImage.src = toggleClosed.src;
    } else {
        list.style.display = 'block';
        toggleImage.src = toggleOpen.src;
    }

    return false;
}


function showCategory(categoryId, categoryName) {

    var title = 'Assets';

    if (categoryName != undefined && categoryName != '') {
        title = categoryName;
    }

    if (categoryId.substr(0, 2) == 'ID') {
        categoryId = categoryId.substr(2);
    }

    if(categoryId != '') {
        state.viewName = 'category';
        clearSiteNav();

        if (currentMailbox != '') {
            changeClass('remove', currentMailbox, 'Current');
        }

        currentMailbox = 'ID' + categoryId;
        changeClass('add', currentMailbox, 'Current');

        showAssetBrowser();
        rightWindow.hideHeader();
        setRightWindow(title, 'asset-list', { 'category_id': categoryId });
    }
}


function switchMailbox(categoryId) {
    if(categoryId != '') {
        state.viewName = 'category';
        clearSiteNav();

        if (currentMailbox != '') {
            changeClass('remove', currentMailbox, 'Current');
        }
        currentMailbox = categoryId;
        changeClass('add', currentMailbox, 'Current');
        categoryId = categoryId.substr(2);

        searchAssets( 'category', categoryId );
        //parent.Service.location.replace('services/search-assets.php?category=' + categoryId);
    }
}



function setMessageCount(mailboxId, unread, total) {
    var mailbox = document.getElementById(mailboxId);

    // Is the count already displayed for this mailbox?...
    var messageCount = getChildByName(mailbox, 'span');
    if(messageCount) {
        var text = getChildTextNode(messageCount);

        text.data = ' (' + unread + '/' + total + ')';

    // ...if not, create a new SPAN tag and display it
    } else {
        messageCount = document.createElement('span');
        messageCount.appendChild(document.createTextNode( ' (' + unread + '/' + total + ')' ));
        mailbox.appendChild(messageCount);
    }

    if(unread > 0) {
        changeClass('add', mailboxId, 'Unread');
    } else {
        changeClass('remove', mailboxId, 'Unread');
    }
}



var oldFileType = "";        // Used by the File Type popup menu

function ChangeSection(offset) {
    window.location.replace(window.location.pathname + '?select_offset=' + offset);
}

function SwitchToAll() {
    window.location.replace(window.location.pathname + '?listSizeLimit=all');
}

function SwitchToPaged() {
    window.location.replace(window.location.pathname);
}










/* SHOPPING CART FUNCTIONS */
/* These should be rolled into a ShoppingCart class eventually */

/**
 * Add assets to the tagged list (or shopping cart)
 *
 * @param assetIds string   A comma-separated list of asset IDs to tag
 */
function tagAssets(assetIds, toShowCart) {
    if (toShowCart == undefined || toShowCart != true) {
        toShowCart = 'false';
    } else {
        toShowCart = 'true';
    }

    new Ajax.Request('/lib/services/tag-assets.php', {
        method:  'post',
        parameters:  { 'asset_ids': assetIds, 'showCart': toShowCart },
        onSuccess:  function(response, jsonHeader) {
            if (jsonHeader['status'] == 'Success') {
                if (jsonHeader['showCart'] == 'true') {
                    showCart();
                } else {
                    setCartCount(jsonHeader['count']);
                }
            } else {
                alert(jsonHeader['message']);
            }
        },
        onFailure:  function() {
            alert('Error occurred in tagAssets.');
        }
    });
}


/**
 * Removes assets to the tagged list (or shopping cart)
 *
 * @param assetIds string   A comma-separated list of asset IDs to tag
 */
function untagAssets(assetIds) {
    new Ajax.Request('/lib/services/untag-assets.php', {
        method:  'post',
        parameters:  { 'asset_ids': assetIds },
        onSuccess:  function(response, jsonHeader) {
            if (jsonHeader['status'] == 'Success') {
                if (jsonHeader['count'] == 0) {
                    showCart();
                } else {
                    setCartCount(jsonHeader['count']);
                }
            } else {
                alert(jsonHeader['message']);
            }
        },
        onFailure:  function() {
            alert('Error occurred in tagAssets.');
        }
    });
}


function removeCartItem(assetId) {
    cartItemRow = $('CartItem_' + assetId);
    if (cartItemRow) {
        cartItemRow.parentNode.removeChild(cartItemRow);
    }
    untagAssets(assetId);
}


function setCartCount(count) {
    if (!isNaN(count)) {
        $('CartCount').innerHTML = count;
    }
}


/**
 * Asks the server how many items are in the cart, and updates the display
 */
function checkCartCount() {
    new Ajax.Request('/lib/services/tag-assets.php', {
        method:  'post',
        onSuccess:  function(response, jsonHeader) {
            if (jsonHeader['status'] == 'Success') {
                setCartCount(jsonHeader['count']);
            }
        },
        onFailure:  function() {
            alert('Error occurred in tagAssets.');
        }
    });
}


function assignCartEvents() {
    assignCartEvent('select', 'new_file_type');
    assignCartEvent('select', 'new_dpi');
    assignCartEvent('input', 'new_width');
    assignCartEvent('select', 'width_units');
}


function assignCartEvent(elementType, className) {
    $$(elementType + '.' + className).each(
        function(element) {
            Event.observe(element, 'change',
                function(event) {
                    var re = /[^0-9]/ig;
                    var assetId = this.id.replace(re, '');
        
                    setConvertParameter(assetId, className, element);
        
                    Event.stop(event);
                });
        });
}


function setConvertParameter(assetId, className, element) {
    new Ajax.Request('/lib/services/set-convert-parameter', {
        method:  'post',
        parameters:  {'assetId': assetId, 'name': className, 'value': element.value},
        onSuccess:  function( response, jsonHeader) {
            try {
                if (jsonHeader['status'] == 'Success') {
                    // If the file type was changed, make a few modifications to the other fields
                    if (jsonHeader['name'] == 'new_file_type') {
                        // If this is an EPS, hide the conversion parameters, otherwise show them
                        if (jsonHeader['value'] == 'eps' || (jsonHeader['value'] == '' && $('orig_file_type_' + jsonHeader['assetId']).value == 'eps')) {
                            $('new_dpi_' + jsonHeader['assetId']).hide();
                            $('new_width_' + jsonHeader['assetId']).hide();
                            $('width_units_' + jsonHeader['assetId']).hide();
                        } else {
                            $('new_dpi_' + jsonHeader['assetId']).show();
                            $('new_width_' + jsonHeader['assetId']).show();
                            $('width_units_' + jsonHeader['assetId']).show();
                        }
                    } else if (jsonHeader['name'] == 'width_units') {
                        var widthFieldId = 'new_width_' + jsonHeader['assetId']; 
                        var dpiFieldId = 'new_dpi_' + jsonHeader['assetId'];
                        if (jsonHeader['value'] == 'px' && $(widthFieldId).value < 20) {
                            $(widthFieldId).value = 300;
                            $(dpiFieldId).selectedIndex = 2;
                        } else if (jsonHeader['value'] == 'in' && $(widthFieldId).value > 20) {
                            $(widthFieldId).value = 6;
                            $(dpiFieldId).selectedIndex = 0;
                        } 
                        setConvertParameter(jsonHeader['assetId'], 'new_width', $(widthFieldId));
                        setConvertParameter(jsonHeader['assetId'], 'new_dpi', $(dpiFieldId));
                    }
                } else {
                    alert(jsonHeader['message']);
                }
            } catch(e) {
                alert('Error occurred in setConvertParameter (' + e.message + ')');
            }
        },
        onFailure: function() {
            alert('Error occurred in setConvertParameter');
        }
    });
}


function prepareCartDownload() {

    // Check to make sure they have not left any width field blank or non-numeric
    var widthInputs = $$('input.new_width');
    for (var i = 0; i < widthInputs.length; ++i) {
        if (isNaN(parseFloat(widthInputs[i].value))) {
            alert('Please enter a numeric width value for any assets you are converting.');
            return false;
        }
    }

    openModalDialog('<p>Gathering assets into ZIP file. Please wait...</p>' + outputProgressWheel('lg'), 500);
    new Ajax.Request('/lib/services/prepare-cart-download.php', {
        method: 'get',
        onSuccess: function(response, jsonHeader) {
            try {
                if (jsonHeader['status'] == 'Success') {
                    //setRightWindow(jsonHeader['title'], 'download', {'file': jsonHeader['zipFileName']});
                    openModalDialogWithUrl('/content/download.php?file=' + jsonHeader['zipFileName'], '500');
                } else {
                    alert(jsonHeader['message']);
                }
            } catch (e) {
                alert('Error occurred in prepareCartDownload. (' + e.message + ')' );
                closeModalDialog();
            }
        },
        onFailure:  function() {
            alert('Error occurred in prepareCartDownload.');
            closeModalDialog();
        }
    });
}







/* THIS IS OLD AND REALLY SHOULD BE REFACTORED */
function Commands(command) {
    var assetNumbers = "";
    var inputFields = document.getElementsByTagName("input");

    switch(command) {
        case "showHideThumbnails":
            $$('a.thumbnailLink').each( function(element) {
                element.toggle();
            });
            break;
        case "checkall":
            for (var i = 0; i < inputFields.length ; i++) {
                if(inputFields[i].name.substring(0,6) == 'check_') {
                    inputFields[i].checked = true;
                }
            }
            break;
    
        case "uncheckall":
            for (var i = 0; i < inputFields.length ; i++) {
                if(inputFields[i].name.substring(0,6) == 'check_') {
                    inputFields[i].checked = false;
                }
            }
            break;
    
        case "tag":
            //Otherwise we're in list view and need to look at all of the checkboxes
            for (var i = 0; i < inputFields.length ; i++) {
                if(inputFields[i].className == 'Checkbox' && inputFields[i].checked == true) {
                    if(assetNumbers != "") { assetNumbers += ","; }
                    assetNumbers += inputFields[i].value;
                }
            }
    
            tagAssets(assetNumbers, true);
            break;
    
        case "untag":
            if($('asset_id')) {
                assetNumbers = $('asset_id').value;
            }else {
                for (var i = 0; i < inputFields.length ; i++) {
                    if(inputFields[i].className == 'Checkbox' && inputFields[i].checked == true) {
                        if(assetNumbers != "") { assetNumbers += ","; }
                        assetNumbers += inputFields[i].value;
                    }
                }
            }
    
            untagAssets(assetNumbers);
            break;

    }
}  // Commands()





function ChangeFileType(oldType, newType, assetId) {
    // alert(oldType + ", " + newType + ", " + assetId);
    var widthField = document.getElementById("width_" + assetId);
    var resolutionField = document.getElementById("resolution_" + assetId);
    if(oldType == "jpg") {
        widthField.value = widthField.value / resolutionField.value;
    }
    if(newType == "jpg") {
        widthField.value = widthField.value * resolutionField.value;
    }
}


function showAssetInfo(assetId, searchType, searchVal) {
    openModalDialogWithUrl('/content/asset-info.php?asset_id=' + assetId + '&searchType=' + searchType + '&searchVal=' + searchVal + '&width=700', 740);
}




/*
 * FROM OLD /res/includes/javascript.js file
 */
function ThumbnailPopup(file, height, database) {
    var popupWindow = window.open('/popup.php?file=/assets/' + database + '/lennox/thumbnails-large/' + file + '.jpg', 'thumbnailPpopup', 'width=210,height=300,scrollbars=no,resizable=no');
    popupWindow.focus();
}

function PreviewPopup(file, height, database) {
    var previewWindow = window.open('/popup.php?file=/assets/' + database + '/previews/' + file + '_preview.jpg', 'previewPopup', 'width=710,height=710,scrollbars=yes,resizable=yes');
    previewWindow.focus();
}


function encodeQueryString(queryString) {
    //queryString = queryString.replace(/[&\?#]/g, function(character) { return('%' + character.charCodeAt(0).toString(16)); } );
    queryString = queryString.replace(/%/g, "%25");
    queryString = queryString.replace(/&/g, "%26");
    queryString = queryString.replace(/\?/g, "%3F");
    queryString = queryString.replace(/#/g, "%23");
    queryString = queryString.replace(/\s/g, "%20");
    return(queryString);
}

function ChangeImage(imgTagName, image) {
    document[imgTagName].src = image.src;
}


// This function simply strips a string of everything that's not a digit, comma, or period
function ScrubNumber(value) {
    return(value.replace(/[^\d,\.]/g, ''));
}

// This one strips a string of everything that's not a digit, comma, period, or dollar sign.
function ScrubCurrency(value) {
    value = value.replace(/[^\d,\.\$]/g, '');
    return(value);
}

// This function is used to make sure that required form fields have values.
//    Field_Name: name of a form field in the form of document.form_name.form_field_name that will be validated.
//    Error_Message: this is the alert error message that will be displayed to the user.
function Has_Value(Field_Name, Error_Message) {
	var text;

	text = Field_Name.value;

	while(text.search(/\s/) > -1) {
        text = text.replace(/\s/, "");
    }
	
    if(text == 0) {
        alert(Error_Message);
        Field_Name.focus();
        return false;   
    }
    return true;
}

// IS_VALID_EMAIL( emailaddy )
// Returns TRUE if Email is valid and FALSE if NOT VALID
function Is_Valid_Email( emailaddy ) {
    var tempchar;       // temp holder
    var atPos;          // string position holder
    var periodPos;      // position of the period in string
    var invalchar = "/:,;"; // not valid email characters
    // if the email string is empty return false
    //if( Is_Empty( emailaddy ) ){ return false; }
    // Loop through each invalid character
    for( count = 0; count < invalchar.length; count++ ){
        // Pull one character out of the string
        tempchar = invalchar.charAt( count );
        // If an invalid character is found return false
        if( emailaddy.indexOf( tempchar, 0 ) > -1 ){
            return false;
        }
    }
    // find and store the position of the at sign
    atPos = emailaddy.indexOf( "@", 1 );
    // If no at sign is in the string return false
    if( atPos == -1 ){ return false; }
    // If at sign is the last character in the string return false
    if( emailaddy.indexOf( "@", atPos + 1 ) > -1 ){ return false; }
    // Find and store the position of the period in the email string
    periodPos = emailaddy.indexOf(".", atPos);
    // If there is no period in the string return false
    if( periodPos == -1 ){ return false; }
    // If the period is less than 3 characters from
    // the end of the string return false
    if( periodPos + 3 > emailaddy.length ){ return false; }
    // all is well this is a valid email address so return true
    return true;
}





// Make sure the "FM" namespace object exists
if (typeof FM != 'object') {
    FM = new Object();
}

/**
 * Checks a given class attribute for the presence of a given class
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     The name of the CSS class to check for
 */
FM.checkForClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (element.className == '') {
        return false;
    } else {
        return new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }
}


/**
 * Adds a class to an element's class attribute
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to add the class to
 * @param   nameOfClass     Class name to add
 * @see     checkForClass
 */
FM.addClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (!FM.checkForClass(element, nameOfClass)) {
        element.className += (element.className ? ' ' : '') + nameOfClass;
        return true;
    } else {
        return false;
    }
}


/**
 * Removes a class from an element's class attribute
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   nameOfClass     Class name to remove
 * @see     checkForClass
 */
FM.removeClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, nameOfClass)) {
        element.className = element.className.replace(
            (element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),
            '');
        return true;
    } else {
        return false;
    }
}


/**
 * Replaces a class with another if the class is present
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to remove the class from
 * @param   class1          Class name to replace
 * @param   class2          Class name to replace it with
 * @see     checkForClass
 * @see     addClass
 * @see     removeClass
 */
FM.replaceClass = function(element, class1, class2) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, class1)) {
        FM.removeClass(element, class1);
        FM.addClass(element, class2);
        return true;
    } else {
        return false;
    }
}


/**
 * Toggles the specified class on and off
 *
 * @author  Dan Delaney     http://fluidmind.org/
 * @param   element         DOM Element object (or element ID) to toggle the class of
 * @param   nameOfClass     Class name to toggle
 * @see     checkForclass
 * @see     addClass
 * @see     removeClass
 */
FM.toggleClass = function(element, nameOfClass) {
    if (typeof element == 'string') { element = document.getElementById(element); }

    if (FM.checkForClass(element, nameOfClass)) {
        FM.removeClass(element, nameOfClass);
    } else {
        FM.addClass(element, nameOfClass);
    }

    return true;
}

