YAHOO.namespace("mazzle");	

/**
 * Annotate class
 *
 * @class Annotate
 * @constructor
 * @param elTags {HTMLElement} DOM element reference of an existing DIV.
 * @param elTags {String} String ID of an existing DIV.
 * @param elInput {HTMLElement} DOM element reference of an input field.
 * @param elInput {String} String ID of an input field.
 * @param elContainers {HTMLElement[]} Array of DOM element reference of existing DIVs.
 * @param elContainers {String[]} Array of String IDs of existing DIVs.
 * @param oServer {String} Server to get the data from.
 * @param oTagConfigs {object} Object literal with annotate configuration params.
 * @param oACConfigs {Object} (optional) Object literal with ac configuration params.
 * @param oYUIConfigs {Object} (optional) Object literal of YUI configuration params.
 */

YAHOO.mazzle.UpdateField = function(elContainer, sServer, sSubject, sProperty, oConfigs) {	
	
	// get element
	this._elContainer = YAHOO.util.Dom.get(elContainer);
	this._sContent = this._elContainer.innerHTML;
		
	// set server vars
	this.sServer = sServer;
	this.sSubject = sSubject;
	this.sProperty = sProperty;

	// Set any config params passed in to override defaults
	if(oConfigs && (oConfigs.constructor == Object)) {
		for(var sConfig in oConfigs) {
		    // update interface labels
		    if(sConfig == "labels" && (oConfigs[sConfig].constructor == Object)) {
		        var oLabels = oConfigs[sConfig];
		        for(var sLabel in oLabels) {
		            this.labels[sLabel] = oLabels[sLabel];
		        }
		    }
			else if(sConfig) {
				this[sConfig] = oConfigs[sConfig];
			}
		}
	}
	// create the field
    this._initField();
    this._initTooltip();
	
	// add handlers
	YAHOO.util.Event.addListener(this._elContent, "mouseover", this._toggleHighlight, this);
	YAHOO.util.Event.addListener(this._elContent, "mouseout", this._toggleHighlight, this);
    YAHOO.util.Event.addListener(this._elContent, "click", this._toggleEdit, this);
};


/////////////////////////////////////////////////////////////////////////////
//
// Public member variables
//
/////////////////////////////////////////////////////////////////////////////

/**
 * Server
 *
 * @property server
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.sServer = '/api/update';

/**
 * Subject being tagged
 *
 * @property subject
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.sSubject = null;

/**
 * Property to link oSubject with sTagURI
 *
 * @property propertyURI
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.sProperty = null;

/**
 * Language of the txt
 *
 * @property lang
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.lang = null;

/**
 * Type of resource
 *
 * @property type
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.type = "literal";

/**
 * Submission type "update or add"
 *
 * @property submit
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.submit = "update";

/**
 * Labels used in the interface
 *
 * @property labels
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.labels = {
    tooltipTxt: "Click to edit",
    update: "Update",
    cancel: "Cancel"
};

/**
 * The number of rows used for the input field.
 * If rows > 1 a <textarea> is used instead of <input>.
 *
 * @property field
 * @public
 */
YAHOO.mazzle.UpdateField.prototype.rows = 1;

/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////


YAHOO.mazzle.UpdateField.prototype._initField =  function() {
    // empty main container
    YAHOO.util.Dom.addClass(this._elContainer, "mz-update-field");
    this._elContainer.innerHTML = '';
    
    // create new elemement for container content
    var elContent = document.createElement('div');
    elContent.className = "mz-content";
    elContent.innerHTML = this._sContent;
    this._elContent = this._elContainer.appendChild(elContent);
    
    // create form
    var elFieldset = document.createElement('div');
    elFieldset.className = "mz-fieldset hidden";
    this._elFieldset = this._elContainer.appendChild(elFieldset);
    
    // create input field
    var elTextbox;
    if(this.rows>1) {
        elTextbox = document.createElement('textarea');
        elTextbox.setAttribute("rows", this.rows);
    }
    else {
    	elTextbox = document.createElement('input');
        elTextbox.setAttribute("type", "text");
	    YAHOO.util.Event.addListener(elTextbox, "keypress", this._keyPress, this);
    }
    elTextbox.className = "mz-input";
	this._elTextbox = this._elFieldset.appendChild(elTextbox);
	
	// create buttons
	var elButtons = document.createElement('div');
	elButtons.className = "mz-buttons";
	this._elFieldset.appendChild(elButtons);
	
	var oSubmitButton = new YAHOO.widget.Button({
        type: "button", 
        label: this.labels.update, 
        container: elButtons
    });
	oSubmitButton.addListener("click", this._submit, this);
	
	// cancel button
    var oCancelButton = new YAHOO.widget.Button({
        type: "button", 
        label: this.labels.cancel, 
        container: elButtons
    });
	oCancelButton.addListener("click", this._toggleEdit, this);
};

YAHOO.mazzle.UpdateField.prototype._initTooltip =  function() {
    if(this.labels.tooltip) {
        this._tooltip = new YAHOO.widget.Tooltip("tooltip", 
            {   context:this._elContent,
                text:this.labels.tooltip,
                showDelay:500 
            });
    }
};

YAHOO.mazzle.UpdateField.prototype._toggleHighlight =  function(v, oSelf) {
    if(YAHOO.util.Dom.hasClass(oSelf._elContent, "mz-content-highlight")) {
        YAHOO.util.Dom.removeClass(oSelf._elContent, "mz-content-highlight");
    }
    else {
        YAHOO.util.Dom.addClass(oSelf._elContent, "mz-content-highlight");
    }
};

YAHOO.mazzle.UpdateField.prototype._toggleEdit =  function(v, oSelf) {
    var elContent = oSelf._elContent;
    var elField = oSelf._elFieldset;
    var elTextbox = oSelf._elTextbox;
    
    if(YAHOO.util.Dom.hasClass(elField, "hidden")) {
        elTextbox.value = oSelf._sContent;
        YAHOO.util.Dom.replaceClass(elContent, "visible", "hidden");
        YAHOO.util.Dom.replaceClass(elField, "hidden", "visible");
        oSelf._elTextbox.select();
        oSelf._elTextbox.focus();   
    }
    else {
        YAHOO.util.Dom.removeClass(elContent, "mz-content-highlight");
        YAHOO.util.Dom.replaceClass(elField, "visible", "hidden");
        YAHOO.util.Dom.replaceClass(elContent, "hidden", "visible");
    }
};

YAHOO.mazzle.UpdateField.prototype._submit =  function(v, oSelf) {
    // the current value
    var sOldValue = oSelf._sContent;
    var sNewValue = oSelf._elTextbox.value;
    
    // the callbacks
    function updateProperty(o) {
        oSelf._sContent = sNewValue;
	    oSelf._elContent.innerHTML = sNewValue;
		oSelf._toggleEdit("update", oSelf);
	}
	function failureHandler(o){
		alert('unable to update value');
		oSelf._toggleEdit("noupdate", oSelf);
	}
	
    if(sOldValue != sNewValue) {
        if(oSelf.sServer) {
            var sLink = oSelf.sServer+"?";
            // update tag on server
            if(oSelf.submit == "update") {
        	
        	    var oOldValue = {type:oSelf.type};
        	    var oNewValue = {type:oSelf.type};
        	    if(oSelf.lang) {
        	        oOldValue.value = {literal:sOldValue, lang:oSelf.lang};
        	        oNewValue.value = {literal:sNewValue, lang:oSelf.lang};
        	    }
        	    else {
        		    oOldValue.value = sOldValue;
        		    oNewValue.value = sNewValue;
        	    }
        	    sLink += queryString("oldType", oSelf.sProperty);
        	 	sLink += "&"+queryString("oldTag", oOldValue);
        		sLink += "&"
        	}
        	else {
        	    oNewValue = sNewValue;
        	}
            sLink += queryString("type", oSelf.sProperty);
    		sLink += "&"+queryString("tag", oNewValue);
    	    sLink += "&"+queryString("url", oSelf.sSubject);
	    

    		var oCallback = {
    			success:updateProperty,
    			failure:failureHandler
    		};
    		var request = YAHOO.util.Connect.asyncRequest('GET', sLink, oCallback);
    	}
    	// just update the interface if no server is known
    	else {
    		updateProperty();
    	}
    }
    else {
        oSelf._toggleEdit("nothing", oSelf);
    }
};

YAHOO.mazzle.UpdateField.prototype._keyPress =  function(v, oSelf) {
    var nKeyCode = v.keyCode;
    if(nKeyCode==13) {
        oSelf._submit('enter', oSelf);
    }
};


YAHOO.mazzle.UpdateField.prototype._initSaveDialog =  function() {
    var oSelf = this;
    this._oSaveDialog = new YAHOO.widget.SimpleDialog("dlg", { 
	    width: "20em", 
	    effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25}, 
        fixedcenter:true,
        modal:true,
        visible:false,
        draggable:false
    });
    this._oSaveDialog.setHeader("Warning!");
    this._oSaveDialog.setBody("Do you want to save the changed value?");
    this._oSaveDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN);
    
    var handleYes = function() {
        oSelf._submit('confirm', oSelf);
        this.hide();
    };
    var handleNo = function() {
        this.hide();
    };
    var buttons = [ { text:"Yes", 
    					handler:handleYes},
    				  { text:"Cancel", 
    				  	handler:handleNo,
    					isDefault:true } ];
    this._oSaveDialog.cfg.queueProperty("buttons", buttons);
    this._oSaveDialog.render(document.body); 
};
