/***************************************
 * Content Admin - Javascript
 ***************************************/

/**
 * Constants
 **/

//Constants for use with getContent()
var TEXT = 'text';
var IMAGE = 'img';
var CA_ROOT = '/ca_lib';

/**
 * Display functions
 **/

/*Use AJAX to load content
 * Arguments: 
 *           id - ID of element to change
 *           tag - Tag to load content from
 *           type - 'html' or 'img'
 * return: FALSE always
 * Output: <div> or <img>
 */
function getContent(id, tag) {
    var item = $(id);
    if (! item) {
        alert('No tag with id "' + id + '" found.');
    }
    if (item.tagName == 'img') {
        type = IMAGE;
    } else {
        type = TEXT;
    }
    if (type != TEXT && type != IMAGE) {
        alert('Uknown type: ' + type);
    }
    
    var handlerFunc = function(t) {
        //TODO: Fix this
        if (type == IMAGE) {
            item.src = t.responseText;
        } else {
            item.innerHTML = t.responseText;
        }
    }
    
    new Ajax.Request(CA_ROOT + '/ajax.php?action=getContent&fmt=raw&type=' + escape(type)
                                + '&tag=' + escape(tag), {
                        asynchronous:true,
                        onSuccess:handlerFunc
                    });
    
    return false;
}

/*Use AJAX to get content update date
 * Arguments: 
 *           id - ID of element to change
 *           tag - Tag to load content from
 *           fmt - OPTIONAL PHP date format to use
 * return: FALSE always
 * Output: <div> or <img>
 */
function getContentDate(id, tag) {
    var item = $(id);
    if (! item) {
        alert('No tag with id "' + id + '" found.');
    }
    
    //Check for optional format
    var fmt = '';
    if ( arguments.length > 2 ) {
        fmt = arguments[2];
    }
    
    data = '&fmt=' + escape(fmt) + '&tag=' + escape(tag)
    new Ajax.Updater(item, CA_ROOT + '/ajax.php?action=getContentDate', {
                        method: 'post',
                        postBody: data,
                        asynchronous:false //Must be false so it doesn't run before getContent() finishes
                    });
    
    return false;
}
 
/**
 * Tag List functions
 **/
function newTag(tagName) {
    //Data validation
    if (tagName.length > 50) {
        alert('Tag names must be less than 50 charactes long.');
        return false;
    }
    
    new Ajax.Request(CA_ROOT + '/ajax.php?action=addTag&name=' + escape(tagName), { 
                        asynchronous:true, 
                        onSuccess: function(result) { logMsg(result, updateTagList) }
                    });
}
//TODO: Rewrite old functions to use logging correctly

function delTag(tagId, tagName) {
    if (! confirm("Are you sure you want to delete the tag '" + tagName + "'?") ) {
        return false;
    }
    
    new Ajax.Request(CA_ROOT + '/ajax.php?action=removeTag&id=' + escape(tagId), 
                {asynchronous:true, onSuccess:updateTagList});
}

function updateTagList() {
    var lst = $('caTags');
    
    new Ajax.Updater(lst, CA_ROOT + '/ajax.php?action=getTagList', {asynchronous:true});
    
    return false;
}

/**
 * Edit Item Functions
 **/

/* makeContentEditable - Make the text content of an item editable 
 * Args: id - Content ID of item
 * Return: False
 */
function makeContentEditable(id) {
    var itm = $('caCont_' + id);   //Get the DIV with the text
    var txtId = 'caContGUI_' + id; //ID to use for TinyMCE Editor
    
    var editor = new Ajax.InPlaceEditor(itm, CA_ROOT + '/ajax.php?action=editContent&id=' + id, {
                                rows:10, cols:60,
                                okText: 'Save',
                                paramName: txtId, //Set the TextArea ID
                                callback: function (form, value) { 
                                    //the onLoading even stores the TinyMCE content back into the textarea
                                    //Use the textarea value to pass to the AJAX call
                                    return 'value=' + escape(editor.editField.value);
                                }
                           });
    
    Object.extend(editor, {
        //This will be attached to the onClick event after teh enterEditMode funciton is
        //This will create the TinyMCE Editor, from the textare
        newEnterEditMode: function(evt) {
            
            //Call old enterEdieMode event first
            this.enterEditMode(evt);
            
            //Set the textarea's ID
            this.editField.id = this.options.paramName;
            
            //Attach TinyMCE after textarea is created
            tinyMCE.execCommand('mceAddControl', false, this.options.paramName);
            //tinyMCE must be added an removed at the right times, for more details
            //see: http://tinymce.moxiecode.com/punbb/viewtopic.php?pid=22977
        },
        onLoading: function() {
            //Fetch TinyMCE Content and store it back in textarea
            var mce = tinyMCE.getInstanceById(txtId);
            this.editField.value = mce.getHTML();
            
            //Detach TinyMCE before textarea is removed
            tinyMCE.execCommand('mceRemoveControl', false, this.options.paramName);

            //This is the original onLoading code
            this.saving = true;
            this.removeForm();
            this.leaveHover();
            this.showSaving();
        },
        convertHTMLLineBreaks: function(string) {
            //Don't remove and HTML
            return string;
        }
    });
    
    //TODO: Make sure this works in IE and that both events are attached
    //Append newEnterEditMode as a second event of the onClick method
    Event.stopObserving(editor.element, 'click', editor.onclickListener);
    Event.observe(editor.element, 'click', editor.newEnterEditMode.bindAsEventListener(editor));
    //editor.onclickListener = editor.newEnterEditMode.bindAsEventListener(editor);
    //Event.observe(editor.element, 'click', editor.onclickListener);
    
    return false;
}

function addItem(tagId) {
    var handlerFunc = function(t) {
        var lst = new Insertion.Bottom( $('caItems'), t.responseText );
        var results = t.responseText.match( "id=.caCont_([0-9]+)" );
        if (! results) { alert('Error finding Content id.'); }
        makeContentEditable(results[1]);
    }
    
    new Ajax.Request(CA_ROOT + '/ajax.php?action=getNewItem&tag_id=' + tagId, {
                        asynchronous:true,
                        onSuccess:handlerFunc
                    });
    
    return false;
}

function delItem(itemId) {
    if (! confirm("Are you sure you want to delete the item?") ) {
        return false;
    }

    var cleanupFunc = function() {
        var item = $('caItem_' + itemId);
        new Effect.Fade( item ); //Does not really delete it, but at least hides it
    }
    new Ajax.Request(CA_ROOT + '/ajax.php?action=delItem&item_id=' + itemId, {
                        asynchronous:true,
                        onSuccess: function(result) { logMsg(result, cleanupFunc) }
                    });
    
    return false;
}

var States = ["Activate", "Deactivate"]; //Inactive, Active
var StatesClass = ["itemInactive", "itemActive"];
function toggleActive(itemId) {
    var item = $('caItem_' + itemId);
    var cmd = $('state_' + itemId);
    
    //Find Current state
    var state = 0; //Assume inactive
    if (cmd.innerHTML.indexOf(States[1]) >= 0 ) { state = 1; }
    
    //Change the DB
    var finishupFunc = function() {
        state = (state+1)%2; //JS does not use 0 & 1 for booleans, so this is a numeric not
        
        //Change the class
        item.addClassName( StatesClass[state] );
        item.removeClassName( StatesClass[(state+1)%2] );
        
        //Toggle the button
        cmd.innerHTML = States[state];
    }
    new Ajax.Request(CA_ROOT + '/ajax.php?action=toggleState&item_id=' + itemId, {
                        asynchronous:true,
                        onSuccess: function(result) { logMsg(result, finishupFunc) }
                    });
    
    //Don't let event bubble up
    return false;
}


/**
 * User Admin
 */
/* makeContentEditable - Make the text content of an item editable 
 * Args: id - Content ID of item
 * Return: False
 */

function reloadUserList() {
    var lst = $('caUsers');
    
    //Get a new list and then make all fields editable
    new Ajax.Updater(lst, CA_ROOT + '/ajax.php?action=getUserList', {
                        asynchronous:true,
                        onComplete: makeAllUsersEditable 
                    });
    
    return false;
}

//Find all fields that need the InPlaceEditor and add them
function makeAllUsersEditable() {
    var lst = $('caUsers');
    
    for(var i=0; i < lst.childNodes.length; i++) {
        var node = lst.childNodes[i];
        if (node.id) {
            var results = node.id.match( "user_([0-9]+)" );
            if (! results) { alert('Error finding user id.'); }
            makeUserEditable(results[1]);
        }
    }
    return false;
}

function makeUserEditable(id) {
    //Login Name
    var itm = $('ln_' + id);    

    new Ajax.InPlaceEditor(itm, CA_ROOT + '/ajax.php?action=editName&type=login&id=' + id, {
                                okText: 'Save',
                                evalScripts: true,
                                onComplete: function(rtn, element) {
                                    if ( rtn.responseText.indexOf('ERROR:') >= 0) {
                                        newMsg(rtn.responseText);
                                        element.innerHTML = oldTxt;
                                    } else {
                                        element.innerHTML = rtn.responseText;
                                    }
                                }
                           });
    
    //Full Name
    var itm = $('fn_' + id);

    new Ajax.InPlaceEditor(itm, CA_ROOT + '/ajax.php?action=editName&type=full&id=' + id, {
                                okText: 'Save',
                                evalScripts: true,
                                onComplete: function(rtn, element) {
                                    if ( rtn.responseText.indexOf('ERROR:') >= 0) {
                                        newMsg(rtn.responseText);
                                        element.innerHTML = oldTxt;
                                    } else {
                                        element.innerHTML = rtn.responseText;
                                    }
                                }
                           });
    
    return false;
}

function setAdmin(obj) {
    var results = obj.name.match( "isAdmin_([0-9]+)" );
    if (! results) { alert('Error finding User id.'); }
    var id = results[1];
    var isAdmin = (obj.checked)? 1:0;//Easier to transmit boolean as a number
    
    new Ajax.Request(CA_ROOT + '/ajax.php?action=setAdmin&id=' + id + '&admin=' + isAdmin, {
                        asynchronous:true,
                        onSuccess: function(result) { logMsg(result) }
                    });
}

function addUser(data) {
    new Ajax.Request(CA_ROOT + '/ajax.php?action=newUser', {
                        asynchronous:true,
                        method: 'post',
                        postBody: data,
                        onSuccess: function(result) { logMsg(result, reloadUserList) }
                    });
    return false;
}

function delUser(id) {
    var lName = $('ln_' + id).innerHTML;
    if (! confirm("Are you sure you want to delete the user '" + lName + "'?") ) {
        return false;
    }

    new Ajax.Request(CA_ROOT + '/ajax.php?action=delUser&id=' + id, {
                        asynchronous:true,
                        onSuccess: function(result) { logMsg(result, reloadUserList) }
                    });
    return false;
}

function togglePwdForm(id) {
    var ctrl = $('contorls_' + id);
    var pwdForm = $('pwdBox_' + id);

    Effect.toggle(ctrl, 'blind');
    Effect.toggle(pwdForm, 'blind');
    
    return false;
}

function setPwd(id) {
    var pwd = $('pwd_' + id).value;
    var pwd2 = $('pwd2_' + id).value;
    var finishupFunc = function(result) {
        logMsg(result, //togglePwdForm requires an argument
                function() { togglePwdForm(id) } //so it must go inside an anonymous func
                );
    }
    
    //This data must go in the POST so that it doesn't show in the server logs
    data = 'id=' + id + '&pwd=' + escape(pwd) + '&pwd2=' + escape(pwd2);
    new Ajax.Request(CA_ROOT + '/ajax.php?action=setPwd', {
                        asynchronous:true,
                        method: 'post',
                        postBody: data,
                        onSuccess: finishupFunc
                    });
    return false;

}

function toggleInstruct() {
    var control = $('instructCtrl');
    var txt = $('instructTxt');
    new Effect.toggle(txt, 'blind');
    control.innerHTML = ( (Element.getStyle(txt, 'display') != 'none') ? 'Show':'Hide' ) + ' include code:';
    
    return false;
}

/**
 * Message Loging
 **/

//Meant to be called from the onSuccess of Ajax.Request
//Takes the returned text from the AJAX call and outputs it as a message
//If the return text is not an error, it can optionally call a function (and pass in the return text)
function logMsg(rtn) {
    newMsg(rtn.responseText);
    
    //If this was an error message, return false
    if ( rtn.responseText.indexOf('ERROR:') >= 0) {
        return false;
    }
    
    //If there was a function passed in, and there was no error
    //then call the function
    if ( arguments.length > 1 ) {
        arguments[1](rtn.responseText);
    }
    
    return true;
}

 
//Create a new empty message and return the message object
function newMsg() {
    var txt = '';
    if (arguments.length > 0) { txt = arguments[0]; }
    var html = '<li>' + txt + '<\/li>';
    
    var lst = new Insertion.Bottom( $('caMsgLst'), html );
    var item = lst.element.lastChild;
    
    //Set a timeout to clear the message after a while
    setTimeout(function(){ 
                            new Effect.BlindUp( item );
                            Element.remove( item );
                         }, 30000 );
    
    return item;
}

