

/*
 * InPlaceEditor extension that adds a 'click to edit' text when the field is 
 * empty.
 */
Ajax.InPlaceEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
Ajax.InPlaceEditor.prototype.__getText = Ajax.InPlaceEditor.prototype.getText;
Ajax.InPlaceEditor.prototype.__onComplete = Ajax.InPlaceEditor.prototype.onComplete;
Ajax.InPlaceEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {

    initialize: function(element, url, options){
        this.__initialize(element,url,options)
        this.setOptions(options);
        this._checkEmpty();
    },

    setOptions: function(options){
        this.options = Object.extend(Object.extend(this.options,{
            emptyText: 'click to edit...',
            emptyClassName: 'inplaceeditor-empty'
        }),options||{});
    },

    _checkEmpty: function(){
        if( this.element.innerHTML.length == 0 ){
            this.element.appendChild(
                Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
            
        }
    },
    getText: function(){
        document.getElementsByClassName(this.options.emptyClassName,this.element).each(function(child){
            this.element.removeChild(child);
        }.bind(this));
        return this.__getText();
    },
    onComplete: function(transport){
        this._checkEmpty();

        this.__onComplete(transport);
        
    }
});


/*
 * InPlaceRadioEditor - Create InPlaceEditor for radio buttom
 *
 */
Ajax.InPlaceRadioEditor = Class.create();
Object.extend(Ajax.InPlaceRadioEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceRadioEditor.prototype, {
  createEditField: function() {
  
  	if (!this.radio_tag) {
  		var collection = this.options.collection || [];
  		this.radio_tag = document.createElement("span");
  		
  	 	collection.each(function(e,i) {  
  	 	
  	 	if(!document.all){//FF
			radioField = document.createElement("input");     	
      		radioField.type = "radio";
      		radioField.name = "radioValue"; 
      		radioField.id = "radioValue";      	      	
      		radioField.value = (e instanceof Array) ? e[0] : e;    	
    		if(this.options.value==radioField.value) radioField.checked = true;
    		this.radio_tag.appendChild(radioField);
    		this.radio_tag.appendChild(	document.createTextNode((e instanceof Array) ? e[1] : e));
		}
		else{//IE
			var curValue = (e instanceof Array) ? e[0] : e;  
			//TODO: find a way to make radio botton with default selected			
			//if(this.options.value==curValue){
			//	radioField = document.createElement("<INPUT type=radio name='radioValue' checked>");
			//}else{
				radioField = document.createElement("<INPUT type=radio name='radioValue'>");
			//}
			
			radioField.value = curValue;   
    		if(this.options.value==radioField.value) {
    			radioField.checked = true;
    		}
			this.radio_tag.appendChild(radioField);
    		this.radio_tag.appendChild(	document.createTextNode((e instanceof Array) ? e[1] : e));
		}
      	}.bind(this));
     }
      
     this.editField = this.radio_tag;
     this.form.appendChild(this.editField);
     this.form.radioValue.disabled = false;
       
    
  },
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    
    var form = this.form;
    var collection = this.options.collection || [];
    
 	var value = '';
 	
 	collection.each(function(e,i) {  
 		if(	form.radioValue[i].checked){
 			value = (e instanceof Array) ? e[0] : e;
 		}  	     
      }.bind(this));
 	 	 	    
    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();     
    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true, 
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null }, 
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  }
  
});

function ReplaceAll(strOrg,strFind,strReplace){
	var index = 0;
	while(strOrg.indexOf(strFind,index) != -1){
		strOrg = strOrg.replace(strFind,strReplace);
		index = strOrg.indexOf(strFind,index);
	}
	return strOrg
}

/*
 * InPlaceRadioEditor - Create InPlaceEditor for radio buttom
 *
 */
Ajax.InPlaceTableEditor = Class.create();
Object.extend(Ajax.InPlaceTableEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceTableEditor.prototype, {
  createEditField: function() {
    var text;
    if(this.options.loadTextURL) {
      text = this.options.loadingText;
    } else {
      text = this.getText();
    }

    var obj = this;
    
    if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
      this.options.textarea = false;
      var textField = document.createElement("input");
      textField.obj = this;
      textField.type = "text";
      textField.name = "value";
      textField.value = text;
      textField.style.backgroundColor = this.options.highlightcolor;
      textField.className = 'editor_field';
      var size = this.options.size || this.options.cols || 0;
      if (size != 0) textField.size = size;
      if (this.options.submitOnBlur)
        textField.onblur = this.onSubmit.bind(this);
      this.editField = textField;
    } else {
      this.options.textarea = true;
      var textArea = document.createElement("textarea");
      textArea.obj = this;
      textArea.name = "value";
      textArea.value = this.convertHTMLLineBreaks(text);
      textArea.rows = this.options.rows;
      textArea.cols = this.options.cols || 40;
      textArea.className = 'editor_field';      
      if (this.options.submitOnBlur)
        textArea.onblur = this.onSubmit.bind(this);
      this.editField = textArea;
    }
    
    if(this.options.loadTextURL) {
      this.loadExternalText();
    }
    this.form.appendChild(this.editField);
  },
  getText: function() {
  	document.getElementsByClassName(this.options.emptyClassName,this.element).each(function(child){
            this.element.removeChild(child);
        }.bind(this));
   	var input = this.element.innerHTML;
   
   //remove table tag for IE
  	var result = ReplaceAll(input,"<TABLE cellSpacing=1 cellPadding=0>",""); 
  	result = ReplaceAll(result,"<TABLE class=PONoBorder cellSpacing=1 cellPadding=0>",""); 
  	result = ReplaceAll(result,"\n",""); 
	result = ReplaceAll(result,"\r","");
	result = ReplaceAll(result,"</TR><TR>","<br>");
	result = ReplaceAll(result,"<TBODY>","");
	result = ReplaceAll(result,"<TR>","");
	result = ReplaceAll(result,"<TD colSpan=3>",""); 
	result = ReplaceAll(result,"<TD vAlign=top width=\"25%\">",""); 
	result = ReplaceAll(result,"<TD vAlign=top width=\"5%\">",""); 
	result = ReplaceAll(result,"<TD vAlign=top width=\"70%\">",""); 
	result = ReplaceAll(result,"<TD>","");
	result = ReplaceAll(result,"</TD>",""); 
	result = ReplaceAll(result,"</TR>",""); 
	result = ReplaceAll(result,"</TBODY>",""); 
	result = ReplaceAll(result,"</TABLE>",""); 
	result = ReplaceAll(result,"<SPAN class=inplaceeditor-empty>click to edit...</SPAN>",""); 
	
	 //remove table tag for FireFox
	result = ReplaceAll(result,"<table cellpadding=\"0\" cellspacing=\"1\">","");
	result = ReplaceAll(result,"<table class=\"PONoBorder\" cellpadding=\"0\" cellspacing=\"1\">",""); 
	result = ReplaceAll(result,"</tr><tr>","<br>");  
	result = ReplaceAll(result,"<tbody>","");
	result = ReplaceAll(result,"<tr>","");
	result = ReplaceAll(result,"<td colspan=\"3\">",""); 
	result = ReplaceAll(result,"<td valign=\"top\" width=\"25%\">",""); 
	result = ReplaceAll(result,"<td valign=\"top\" width=\"5%\">",""); 
	result = ReplaceAll(result,"<td valign=\"top\" width=\"70%\">",""); 
	result = ReplaceAll(result,"<td>",""); 
	result = ReplaceAll(result,"</td>",""); 
	result = ReplaceAll(result,"</tr>",""); 
	result = ReplaceAll(result,"</tbody>",""); 
	result = ReplaceAll(result,"</table>",""); 
	
	return this.convertHTMLSpecailChar(result);
  }
  
  
});

/*
 * InPlaceRadioEditor - Create InPlaceEditor for radio buttom
 *
 */
Ajax.InPlaceNumberEditor = Class.create();
Object.extend(Ajax.InPlaceNumberEditor.prototype, Ajax.InPlaceEditor.prototype);
Object.extend(Ajax.InPlaceNumberEditor.prototype, {
  getText: function() {  
   	var input = this.element.innerHTML;
   	result = input;
   	if(input.indexOf("(") == 0){   		
		result = ReplaceAll(input,"(",""); 
		result = ReplaceAll(result,")",""); 
		result = "-"+result;
	
   	}
	
	return result;
  }
  
});


/*
 * getInplaceEditor: get InPlaceEditor for text input
 * element: the id or class of the html tag
 * key: key of the object
 * keyField: name of the key field
 * table: name of the table that you want to editor
 * field: name of the field in the table that you want to editor
 * row: not required(default 1),number of rows for the input field
 * cols: not required(default null),number of columns for the input field
 */
function getInplaceEditor(element,key,keyField,table,field,rows,cols){
	if(!rows){
		rows = 1;
	}
	if(!cols){
		cols = null;
	}
	return new Ajax.InPlaceEditor(element, '/servlet/InPlaceEditor', 
					{ 
						rows: rows,
						cols: cols,
						highlightendcolor : '#DFE2FF',
						callback: function(form, value) { 	
							return 'key='+key+'&keyField='+keyField+'&table='+table+'&field='+field+'&value=' + encodeURIComponent(value) 
						},
						onFailure: function(transport) { 
							rawText = transport.responseText;
  							json = eval('('+rawText+')');
							alert(json.error);
						}			
					}
					); 
}

/*
 * getInPlaceCollectionEditor: get InPlaceEditor for select list
 * element: the id or class of the html tag
 * key: key of the object
 * keyField: name of the key field
 * table: name of the table that you want to edit
 * field: name of the field in the table that you want to edit
 * collection: list of options, type must be String[<num>][2]
 * defaultValue: default value
 */
function getInPlaceCollectionEditor(element,key,keyField,table,field,collection,defaultValue){

	var url = '/servlet/InPlaceEditor';
		return new Ajax.InPlaceCollectionEditor(
  				element, url, {
  				collection: collection,
  				value: defaultValue,
  				highlightendcolor : '#DFE2FF',
 				ajaxOptions: {method: 'post'},
 				callback: function(form, value) { 	
							return 'key='+key+'&keyField='+keyField+'&table='+table+'&field='+field+'&value=' + encodeURIComponent(value) 
						},
 				onFailure: function(transport) { 
					rawText = transport.responseText;					
  					json = eval('('+rawText+')');
					alert(json.error);
				}	 				 				
 				}
  			);
}



/*
 * getInPlaceRadioEditor: get InPlaceEditor for radio bottom
 * element: the id or class of the html tag
 * key: key of the object
 * keyField: name of the key field
 * table: name of the table that you want to edit
 * field: name of the field in the table that you want to edit
 * collection: list of options, type must be String[<num>][2]
 * defaultValue: default value
 */
function getInPlaceRadioEditor(element,key,keyField,table,field,collection,defaultValue){

	var url = '/servlet/InPlaceEditor';
		return new Ajax.InPlaceRadioEditor(
  				element, url, {
  				collection: collection,
  				value: defaultValue,
  				highlightendcolor : '#DFE2FF',
 				ajaxOptions: {method: 'post'},
 				callback: function(form, value) { 	
							return 'key='+key+'&keyField='+keyField+'&table='+table+'&field='+field+'&value=' + encodeURIComponent(value) 
						},
 				onFailure: function(transport) { 
					rawText = transport.responseText;					
  					json = eval('('+rawText+')');
					alert(json.error);
				}	 				 				
 				}
  			);
}

/*
 * getInplaceEditor: get InPlaceEditor for text input
 * element: the id or class of the html tag
 * key: key of the object
 * keyField: name of the key field
 * table: name of the table that you want to editor
 * field: name of the field in the table that you want to editor
 * row: not required(default 1),number of rows for the input field
 * cols: not required(default null),number of columns for the input field
 */
function getTestingInplaceEditor(element,url,rows,cols){
	if(!rows){
		rows = 1;
	}
	if(!cols){
		cols = null;
	}
	return new Ajax.InPlaceEditor(element, url, 
					{ 
						rows: rows,
						cols: cols,
						highlightendcolor : '#DFE2FF',
						callback: function(form, value) { 	
							return 'value=' + encodeURIComponent(value) 
						},
						onFailure: function(transport) { 
							rawText = transport.responseText;
  							json = eval('('+rawText+')');
							alert(json.error);
						}
									
					}
					); 
}

/*
 * getInPlaceCollectionEditor: get InPlaceEditor for select list
 * element: the id or class of the html tag
 * key: key of the object
 * keyField: name of the key field
 * table: name of the table that you want to edit
 * field: name of the field in the table that you want to edit
 * collection: list of options, type must be String[<num>][2]
 * defaultValue: default value
 */
function getTestingInPlaceCollectionEditor(element,myUrl,collection,defaultValue){

	var url = myUrl;
		return new Ajax.InPlaceCollectionEditor(
  				element, url, {
  				collection: collection,
  				value: defaultValue,
  				highlightendcolor : '#DFE2FF',
 				ajaxOptions: {method: 'post'},
 				callback: function(form, value) { 	
							return 'value=' + encodeURIComponent(value) 
						},
 				onFailure: function(transport) { 
					rawText = transport.responseText;					
  					json = eval('('+rawText+')');
					alert(json.error);
				}	 				 				
 				}
  			);
}


