//Iditable Inline Content Management System
//Javascript Editor Creator
//
//parameter json is a JSON object (created from a perl array ref of hashes) created by parsing an HTML document with WebApp::Utils parse_iditable
//
//Last Updated: 2008-02-21 by Vijay Krishna Ramesh <vijay@ace4it.com>
//
//Copyleft 2008 (under the "do whatever the hell you want with this just take my name off of it if you screw it up" license agreement)
				
function returnIditable(){
	
	var error = arguments[0];
	
	if (error){ alert(error); }
}

function returnInsertIditable(){
	
	var insertPopulatedTemplateID = arguments[0];
	insertPopulatedTemplateID = insertPopulatedTemplateID.replace(/\s/,'');
	var populatedTemplateHTML = arguments[1];
	var appendBlock = document.getElementById(insertPopulatedTemplateID);
	var holdingDiv = document.createElement('div');
	holdingDiv.innerHTML = populatedTemplateHTML;
	appendBlock.appendChild(holdingDiv);
	
}

function refreshIditable(){
		var toId = arguments[0];
		var newContent = arguments[1];
		// remove whitespace from toId
		toId = toId.replace(new RegExp(/^\s+/),"");
		toId = toId.replace(new RegExp(/\s+$/),""); 
		
		//needs to handle multiple editor types (either return editor type or test for?)
		if (newContent && newContent != dijit.byId(toId).getValue(false)){
		//	alert('setting new');
			
			dijit.byId(toId).setValue(newContent);
		}
	
	//window.focus();
}


function loadIditable(json) {
	//get json object from perl
	var myJSONObject = eval('(' + json + ')');    
	
	for (var cnt=0;cnt<myJSONObject.length;cnt++){
		
		//if page does not contain to_id container, reset from_id.id = to_id
		if (document.getElementById(myJSONObject[cnt].iditabledestination) != ''){
			document.getElementById(myJSONObject[cnt].id).id = myJSONObject[cnt].iditabledestination;
		}
		
		//check if editor is database or static type
		if (myJSONObject[cnt].iditableeditor.match('DB')){
			
			if (myJSONObject[cnt].iditableeditor == 'dojoDBRowUpdate'){
				
				//if (cnt<5){
				for (var iecnt=0;iecnt<myJSONObject[cnt].iditableenabledblocks.length;iecnt++){
					
					//Kill inline edit box if already exists
					if (dijit.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id)){ dijit.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id).destroy(); }
					
					//create inline edit box for db column
					//if (cnt < 5){ alert(myJSONObject[cnt].iditableenabledblocks[iecnt].id);}
					var inlineEdit = new dijit.InlineEditBox({
                                                                        autoSave:true,
                                                                        renderAsHtml:false,
									onChange: function (value){
										updateDBIditable(['args__' + this.table_name,'args__'+this.iditable_enabled_column,'args__' + value, 'args__' + this.primary_key_name, 'args__' + this.primary_key_value],[returnIditable],'POST');
									},
									iditable_enabled_id: myJSONObject[cnt].iditableenabledblocks[iecnt].id,
									iditable_enabled_column: myJSONObject[cnt].iditableenabledblocks[iecnt].iditablecolumnname,
									table_name: myJSONObject[cnt].iditabletablename,
									primary_key_name: myJSONObject[cnt].iditableprimarykeyname,
									primary_key_value:  myJSONObject[cnt].iditableprimarykeyvalue
								}, dojo.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id));
							
					
				}
				
				//}
				
			}
			
			if (myJSONObject[cnt].iditableeditor == 'dojoDBRowInsert'){
				for (var iecnt=0;iecnt<myJSONObject[cnt].iditableenabledblocks.length;iecnt++){
					
					//Kill inline edit box if already exists
					if (dijit.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id)){ dijit.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id).destroy(); }
					
					//create inline edit box for db column
					var inlineEdit = new dijit.InlineEditBox({
						autoSave:true,
						renderAsHtml:false,
						onChange: function (value){
							if (this.order_column_name == ''){ this.order_column_name = 'none'; }
							//alert('args__' + this.table_name+'\n'+'args__'+this.iditable_enabled_column+'\n'+'args__' + value+'\n'+ 'args__' + this.primary_key_name+'\n'+ 'args__' + this.order_column_name+'\n'+ 'args__' + this.active_column_name+'\n'+ 'args__' + this.active_column_value+'\n'+'args__' + this.populate_template_script+'\n'+this.blank_template_id+'\n'+ 'args__' + this.insert_populated_template);
							//insertDBIditable(['args__' + this.table_name,'args__'+this.iditable_enabled_column,'args__' + value, 'args__' + this.primary_key_name, 'args__' + this.order_column_name, 'args__' + this.active_column_name, 'args__' + this.active_column_value,'args__' + this.populate_template_script,this.blank_template_id, 'args__' + this.insert_populated_template],[returnInsertIditable],'POST');
							//alert(this.default_value);
							//alert(this.editWidget.value);
							this._setDisplayValue(this.default_value);
							this.value=this.default_value;
							//var templateHTML = dojo.byId(this.blank_template_id).innerHTML;
						},
						iditable_enabled_id: myJSONObject[cnt].iditableenabledblocks[iecnt].id,
						iditable_enabled_column: myJSONObject[cnt].iditableenabledblocks[iecnt].iditablecolumnname,
						table_name: myJSONObject[cnt].iditabletablename,
						blank_template_id: myJSONObject[cnt].iditableblanktemplate,
						populate_template_script: myJSONObject[cnt].iditablepopulatetemplatescript,
						insert_populated_template: myJSONObject[cnt].iditableinsertpopulatedtemplate,
						primary_key_name: myJSONObject[cnt].iditableprimarykeyname,
						order_column_name: myJSONObject[cnt].iditableordercolumnname,
						active_column_name: myJSONObject[cnt].iditableactivecolumnname,
						active_column_value: myJSONObject[cnt].iditableactivecolumnvalue,
						default_value:dojo.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id).innerHTML,
						editor_id:myJSONObject[cnt].iditableenabledblocks[iecnt].id
					}, dojo.byId(myJSONObject[cnt].iditableenabledblocks[iecnt].id));
							
					
				}
					
			}
			
			
			
		}else{
			//if editor already exists, destroy
			//needs to handle multiple editor types (based on editor_type)
			if (dijit.byId(myJSONObject[cnt].iditabledestination)){
				dijit.byId(myJSONObject[cnt].iditabledestination).destroy();
			}
				
			//alert(myJSONObject[cnt].iditableeditor);
			//(need "fuller" switch based on editor_type; ie not just dojo toolbar settings, but dojoEditor vs lightboxEditor vs newpageEditor etc)
			
			//set toolbar based on editor_type
			switch (myJSONObject[cnt].iditableeditor){
				case 'dojoInlineSmall': 
					pluginsArray = ['createLink','insertImage'];
					break;
				case 'dojoInlineMedium':
					pluginsArray = ['bold','italic','underline','strikethrough','|','justifyLeft','justifyRight','justifyCenter','justifyFull','createLink',{name:'dijit._editor.plugins.ImageDialog'}];
					break;
				default:
					pluginsArray = ['undo','redo','|','bold','italic','underline','strikethrough','|','insertOrderedList','insertUnorderedList','insertParagraph','indent','outdent','|','justifyLeft','justifyRight','justifyCenter','justifyFull','createLink',{name:'dijit._editor.plugins.FileDialog'},{name:'dijit._editor.plugins.ImageDialog'}];
					break;
			}
			
			//create editor
			var descEditor = new dijit.Editor({
					plugins: pluginsArray,
					extraPlugins: ['dijit._editor.plugins.AlwaysShowToolbar'],
					styleSheets: 'mxvilla.css',
					style:'margin-top:-21px;',
					class: 'tundra'				
				}, dojo.byId(myJSONObject[cnt].iditabledestination));
			
				
			//save method based on save_type
			switch (myJSONObject[cnt].iditablesave){
				case 'button':
					var saveButton = document.createElement('div');
					saveButton.style.width="140px";
					saveButton.style.marginLeft="auto";
					saveButton.style.marginRight="auto";
					var onclicker = "document.getElementById('alteredHTML').innerHTML = dijit.byId('" + myJSONObject[cnt].iditabledestination + "').getValue(false);saveIditable(['alteredHTML','args__" + myJSONObject[cnt].id + "'"+ ",'args__" + myJSONObject[cnt].iditabledestination + "','template'],[refreshIditable],'POST');return false;"
					saveButton.innerHTML = '<a href="javascript:;" name="save" onclick="' + onclicker  + '">SAVE</a>';
					dojo.byId(myJSONObject[cnt].iditabledestination).appendChild(saveButton);
					break;
				case 'auto':
					// should work? question asked at http://www.dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/dojo-connect-dijit-editor
					// "hack" of sorts - using DOM access to the iframe inside the editor - should not have to do this!!!
					
					//var iframe = window.frames[cnt];
					//dojo.connect(iframe,'onblur',foo);
					if(document.all){
						var iframe = window.frames[cnt].document;
						iframe.from_id=myJSONObject[cnt].id;
						iframe.to_id=myJSONObject[cnt].iditabledestination;
						iframe.old_html=myJSONObject[cnt].html;
						iframe.attachEvent("onblur",autoSaveEditor);
					}else{
						
						var iframe = window.frames[cnt].document;
						iframe.from_id=myJSONObject[cnt].id;
						iframe.to_id=myJSONObject[cnt].iditabledestination;
						iframe.old_html=myJSONObject[cnt].html;
						iframe.addEventListener("blur",autoSaveEditor,false);
					}
					//dojo.connect(iframe,'onblur',bar = function() { foo(cnt);});
					break;
			}
		}
	}
}


function autoSaveEditor(e){
	
	var changedHTML = e.target.body.innerHTML;
	var from_id = e.target.from_id;
	var to_id = e.target.to_id;
	var oldHTML = e.target.old_html;
	
	document.getElementById('initialHTML').innerHTML = oldHTML;
	document.getElementById('alteredHTML').innerHTML = changedHTML;
	e.target.old_html = changedHTML;
	saveIditable(['alteredHTML','args__' + from_id  ,'args__' + to_id  , 'template','initialHTML'],[refreshIditable],'POST');
	
	
}

