/*!
 * 
 * Author: @DavidBobles
 * Further changes: @DavidBobles
 * Licensed private
 *USE jQuery UI Widget-factory plugin boilerplate (for 1.8/9+) - http://jqueryui.com/demos/widget/
 */

;(function ( $, window, document, undefined ) {

  

//########################################################## DataE_DataElementTable ##############################################################################################
/*  ! ... DataE_DataElementTable ........................................................................................ (Bookmark for Coda)  */
        
    
     $.widget( "CE.DataE_DataElementTable" ,$.CE.DataElement, {
        options: { 
                ObjName: 'DataE_DataElementTable',
                isTableElement: true, 
                
                ActiveItemID:'',
                ActiveDataID:'',
                lastActiveDataID:'',
                
                OrderAttributForItems:'',
                orderByIDList: false,
                IDList: [],
                IDLIST_linked_Data: [], //linkedDataTable, linkedDataAttribut, mappedItemAttribut linkedDataAttributeSelector, linkedDataMappedAttribute
                is_master: false,
                MasterTable:'',
                is_slave: false,
                SlaveTable:'',
                DataMapping_for_Listitem:'',
                is_sortable: false,
                is_enabled:true,
                is_copyRelation: false,  // 2 Variants Copie and Linked Relation 
        		linked_Data_only:false
        },
        _init: function(){

        	var w=this, e=w.element, o=w.options;
         	
         	w._initDataElement();
        	e.addClass('DataE_DataElementTable');	
        	
        	w.setVisibility(false);
        	
        	e.bind('saveReorder', function(event)
        	{
        		w._saveReorderInLinkedAttr();
        		event.stopPropagation();
        	});
       
        	e.bind('dragItem', function(event, param1)
        	{
        		w._dragItem(param1);
        		event.stopPropagation();
        	});	
        },
        _initSlaveMasterRelationAndDragging: function()
        {
        	var w=this, e=w.element, o=w.options;
        	
        	//debug(o.ObjName+" _initSlaveMasterRelationAndDragging", true, o.debug_it);

        	if(!e.hasClass('ui-sortable') && o.is_sortable) // nur einmal Initierieren
			{
				e.sortable({revert:true,  axis: 'y', containment: e, handle: '.CEButton_Dragbutton', update: function(event, ui)
        		{
        			w._dropListItem(ui.item);
        		}});
			}
        	
        	if(o.is_master && !e.hasClass('DataE_DataElementTable_Master')) // nur einmal Initierieren
        	{
        		//debug(o.ObjName+" _initSlaveMasterRelationAndDragging INIT AS MASTER", true, o.debug_it);
        		
        		e.addClass('DataE_DataElementTable_Master');	
        		
        		if(o.SlaveTable!='') // wenn sie bekannt ist, dem anderen Part Bescheid sagen
        		{
        			o.SlaveTable.DataE_DataElementTable('setOption', 'MasterTable', e);
        		}
        	}
        	
        	if(o.is_slave && !e.hasClass('DataE_DataElementTable_Slave')) // nur einmal Initierieren
        	{
        		//debug(o.ObjName+" _initSlaveMasterRelationAndDragging INIT AS SLAVE", true, o.debug_it);
        		
        		e.addClass('DataE_DataElementTable_Slave');	
        		
        		if(o.MasterTable!='') // wenn sie bekannt ist, dem anderen Part Bescheid sagen
        		{
        			o.MasterTable.DataE_DataElementTable('setOption', 'SlaveTable', e);
        		}
        	}
        	
        	if(o.MasterTable!='')
        		{
        			if(o.is_sortable)
        			{
        				//debug(o.ObjName+" _initSlaveMasterRelationAndDragging draggble"+e.attr('class'), true, o.debug_it);
        			
        				o.MasterTable.find('.DataE_Listitem').draggable(
        				{
        					connectToSortable:e,
        					helper: function(event, ui)
        					{
        						return $('<div class="DataE_Listitem_Dragged_Helper">'+$(this).find('.DataE_Listitem-Text').text()+'</div>');
        					},
        					opacitiy:0.7,
        					revert: "invalid",
        					appendTo: 'body'
        				});
        			}
        		}       	
        },        
        _dropListItem: function(item)
        {
        	var w=this, e=w.element, o=w.options, d=o.DataMapping;
        	
        	if(o.is_enabled)
        	{     	
        		//debug('<span class="debug_dragging">'+o.ObjName+' >>>>>>> Dropelement '+item.attr('dataid')+'-'+item.hasClass('ui-draggable')+'</span>',true, o.debug_it);        
        		
        		if(item.hasClass('ui-draggable'))
        		{
        			var listitem=e.find('.DataE_Listitem[dataid="'+item.attr('dataid')+'"]');
						
					//debug('<span class="debug_dragging">'+o.ObjName+' add new Listitem - >>>>>>'+listitem.length+'</span>', true, o.debug_it);	
					
        			if(listitem.length<2) //das gedropte Item zählt selber
        			{
        					//debug('<span class="debug_dragging">'+o.ObjName+' add new Listitem - dropListItem'+item.attr('dataid')+'</span>', true, o.debug_it);
        					var relatedDataAttribut=$('#db_datatables .data_table[DataTableName="'+d[0]['DataTableName']+'"] .data_row[data_DataID="'+item.attr('dataid')+'"]');

        					w._addNewListItem(relatedDataAttribut, true);
        			}else
        			{
        				item.css('background-color', 'red').fadeOut(1000, function(){$(this).remove();});
        			}	
        		}
        		if(!o.is_copyRelation || !item.hasClass('ui-draggable')) w._saveReorderInLinkedAttr();  
        	}	
        },        
        sortfunction: function(listitemA, listitemB, attribut_name, is_null_lastIndex, is_aufsteigend)
        {
        	var w=this, e=w.element, o=w.options;
        	
        	var keyA=Math.abs(listitemA.attr(attribut_name));
        	var keyB=Math.abs(listitemB.attr(attribut_name));
        	
        	var aufsteigend=is_aufsteigend;
        	if(aufsteigend!=true && aufsteigend!=false) aufsteigend=true;
        		
        	var wasChange=false;
        	
        	if(is_null_lastIndex)
        	{
        		if(keyA=='0' && keyB!='0') //  => keyA > keyB
        		{
        			if(aufsteigend) keyA=keyB+1;
        			if(!aufsteigend) keyA=keyB-1;
        			
        		}else if(keyA!='0' && keyB=='0')
        		{
        			if(aufsteigend) keyB=keyA+1; 
        			if(!aufsteigend) keyB=keyA-1;        		
        		}
        	}
        	
        	if (keyA > keyB && aufsteigend)
        	{
        		$(listitemA).next().after(listitemA); 
        		wasChange=true; 
        	} 
        	
        	if (keyA < keyB && !aufsteigend)
        	{
        		$(listitemA).next().after(listitemA); 
        		wasChange=true; 
        	} 
        	//debug(o.ObjName+ '> SORT ('+keyA+' VS '+keyB+') wasChanged='+wasChange, false, o.debug_it);

        	return wasChange;   
        },
        reorderItemsByAttribut: function()
        {
        	var w=this, e=w.element, o=w.options, l=o.IDLIST_linked_Data;
        	
        	if(o.OrderAttributForItems!=undefined && o.OrderAttributForItems!='' && l.length==0) // Order by Item Attribut
        	{
        		var ItemListLength=e.find('.DataE_Listitem').length;
        		var hashanged=true;
        		var index_m=0;
        		var INDEX_MAX=ItemListLength*ItemListLength;
        		
        		while(hashanged)
        		{
        				hashanged=false;
        					
        				e.find('.DataE_Listitem').each(function(index, value)
        				{
        					var tmp_change=false;
        					if($(this).next().attr(o.OrderAttributForItems)!=undefined)
        					{
        						tmp_change=w.sortfunction($(this),$(this).next(), o.OrderAttributForItems, false);
        					}
        					
        					if(tmp_change) hashanged=true;
        				
        				});
        				index_m++;
        				if(index_m>INDEX_MAX) hashanged=false;
        		}
        		//debug(o.ObjName+' Reorder > ItemList+('+ItemListLength+')-steps('+index_m+'/'+INDEX_MAX+')', false, o.debug_it);
        		
        		e.find('.DataE_Listitem').each(function(index, value)
        		{
        				$(this).DataE_Listitem('setOption','OrderNr', index);        			
        		});
        	}
        	
        	if(l.length>0 && o[l[4]]!='' && o[l[4]]!=undefined) //Ordering by linked Attribute
        	{
        		var Reorder_by_linked_Attribut=$('#db_datatables .data_table[DataTableName="'+l[0]+'"] .data_row['+l[3]+'="'+o[l[4]]+'"]').attr(l[1]);
        		
        		//debug(o.ObjName+' > ORDER ITEMS by linked Attribut('+l[0]+'-'+l[1]+'>'+l[2]+' WHERE'+l[3]+'='+o[l[4]]+') - ['+Reorder_by_linked_Attribut+']', true, o.debug_it);
        	
        		if(Reorder_by_linked_Attribut!=undefined)
        		{
        			Reorder_by_linked_Attribut=Reorder_by_linked_Attribut.split(',')
        			// 1. ELEMENTE ohne order_nr_passende Nr. zuweisen, wenn nicht vorhanden 0 (als letztes) ###############################
        			var listitem_without_linked_order_nr=e.find('.DataE_Listitem').filter(function(){return !$(this).attr('linked_order_nr');});
        			
        			var hasNewItems=false;
        			
        			//debug(o.ObjName+' > ORDER ITEMS by linked Attribut - order ('+listitem_without_linked_order_nr.length+') new items', false, o.debug_it);
        			listitem_without_linked_order_nr.each(function(index, value)
        			{
        				var tmp_order_id=$(this).attr(l[2]);
        				var linked_order_nr=Reorder_by_linked_Attribut.indexOf(tmp_order_id);
        				if(linked_order_nr>=0)
        				{
        					linked_order_nr++;
        				}else
        				{
        					linked_order_nr=0;
        					hasNewItems=true;
        				}
        				
        				$(this).attr('linked_order_nr',linked_order_nr);
        				//debug(o.ObjName+' > ORDER ITEM by linked Attribut - order ('+tmp_order_id+'-> '+linked_order_nr+')', false, o.debug_it);
        			});
        			
        			var listitem_with_linked_order_nr=e.find('.DataE_Listitem[linked_order_nr]');
        			//debug(o.ObjName+' > ORDER ITEMS by linked Attribut - order ('+listitem_with_linked_order_nr.length+') items', false, o.debug_it);
        			
        			//2. Reorder Elements ##########################################################################################
        			var ItemListLength2=e.find('.DataE_Listitem').length;
        			var hashanged2=true;
        			var index_m2=0;
        			var INDEX_MAX2=ItemListLength2*ItemListLength2;
        		
        			while(hashanged2)
        			{
        				hashanged2=false;
        					
        				e.find('.DataE_Listitem').each(function(index, value)
        				{
        					var tmp_change=false;
        					if($(this).next().attr('linked_order_nr')!=undefined)
        					{
        						tmp_change=w.sortfunction($(this),$(this).next(), 'linked_order_nr', true, true);
        					}
        					
        					if(tmp_change) hashanged2=true;
        				});
        				
        				index_m2++;
        				if(index_m2>INDEX_MAX2) hashanged2=false;
        			}	
        			//debug(o.ObjName+' Reorder > ItemList+('+ItemListLength2+')-steps('+index_m2+'/'+INDEX_MAX2+')', true, o.debug_it);
        			
        			if(hasNewItems) w._saveReorderInLinkedAttr();
        		}
        	}
        	//get();  get(0); get(1);
        	//$("#mylist li:eq(1)").insertAfter($("#mylist li:eq(2)"));
			// URL: http://stackoverflow.com/questions/304396/what-is-the-easiest-way-to-order-a-ul-ol-in-jquery
			//http://stackoverflow.com/questions/2951941/jquery-sortable-move-up-down-button
        },
        _saveReorderInLinkedAttr: function(without_saving)
        {
        	var w=this, e=w.element, o=w.options, l=o.IDLIST_linked_Data;
        	
        	if(l.length>0 && o[l[4]]!='' && o[l[4]]!=undefined) //Ordering by linked Attribute
        	{
        		var order_array_string='';
        		var ItemListLength2=e.find('.DataE_Listitem').length;
        		
        		e.find('.DataE_Listitem').each(function(index, value)
        				{
        					
        					$(this).attr('linked_order_nr', index+1);
        					
        					order_array_string=order_array_string+$(this).attr(l[2]);
        					
        					if(index<ItemListLength2-1)order_array_string=order_array_string+','
        				});
        		//debug('<span class="debug_dragging">'+o.ObjName+ '>> SaveReorder['+order_array_string+']</span>', true, o.debug_it);

        		if(without_saving!=true) w._sendDataToDatatables(l[0], o[l[4]], l[1], order_array_string, 1, 0, true, false, false);
        	}
        },       
        _getDataFromDatatables: function(without_looking_on_changenumbers)
        {	
         	var w=this, e=w.element, o=w.options, d=o.DataMapping;
        	
        	var last_change_number_global=$('#db_datatables').attr('last_change_number');        	
        	var my_last_changenumber=Math.abs(o.last_change_number);
        	
        	w._DeleteItemsIfNewActiveDataID();

        	if((my_last_changenumber<last_change_number_global || without_looking_on_changenumbers)&& d.length>0)
        	{
        		//debug('<span class="debug_loading">>do it 2 >> '+o.ObjName+' - getDataFromDatatables() '+o.last_change_number+' < '+last_change_number_global+'</span>',true, o.debug_it);

				if(!o.linked_Data_only)//(ConstrainString!=false)
				{	
        			w._AddItemsByConstrains(without_looking_on_changenumbers);	
       			}else
       			{
       				w._AddItemsByLinkedOrderAttr(without_looking_on_changenumbers);	
       			}
       			
       			w.setVisibility(true);		
        		
       			var global_updates_elements_nr=$('#db_datatables').parent().Datatable('option','global_updates_elements');        			        
       			$("#db_datatables").parent().Datatable('setOption','global_updates_elements', (global_updates_elements_nr+1));
       			
       			w.setOption('last_change_number',last_change_number_global, false, false); 
       			w.reorderItemsByAttribut(); 
       			w._initSlaveMasterRelationAndDragging();
       		}		  
        },
        _DeleteItemsIfNewActiveDataID: function()
        {
        	var w=this, e=w.element, o=w.options, d=o.DataMapping;
        	
        	if(o.ActiveDataID!='')// && !o.linked_Data_only)
        	{		
        		if(o.lastActiveDataID!=o.ActiveDataID)
        		{
        			//debug(o.ObjName+' _DeleteItemsIfNewActiveDataID >>>>>>> Start 1 - '+o.ActiveDataID+' VS '+o.lastActiveDataID, true, o.debug_it);
        			o.lastActiveDataID=o.ActiveDataID;
        		
        			var tmp_mappingData='';
        			var tmp_mappingDataNot='';
        			var MappingData=w._getMappingDataForAttribut('ActiveDataID');
        			if(MappingData!=undefined && MappingData.length>0)
        			{
        				var related_Attribut=MappingData[0][2];
        				tmp_mappingData='['+related_Attribut+'="'+o.ActiveDataID+'"]';
        				tmp_mappingDataNot='['+related_Attribut+'!="'+o.ActiveDataID+'"]';
        			} 
				
					//debug(o.ObjName+' _DeleteItemsIfNewActiveDataID >>>>>>> 2 DataMapping:'+tmp_mappingData, true, o.debug_it);
				
					var ActvieItems=e.find('.DataE_Listitem_Activ'+tmp_mappingData);
				
					if(ActvieItems.length>0 && o.is_copyRelation) //bei einer link relation ist das andere immer noch aktiv
					{
						w.setOption('ActiveItemID','-1'); 
					}

        			var Items=e.find('.DataE_Listitem'+tmp_mappingDataNot);
        			//debug(o.ObjName+' _DeleteItemsIfNewActiveDataID >>>>>>> End 3 - Deleted '+Items.length, true, o.debug_it);
        		    		
        			Items.remove();
				}
        	}  
        },
        _AddItemsByConstrains: function(without_looking_on_changenumbers)
        {
        	var w=this, e=w.element, o=w.options, d=o.DataMapping;
        	
        	var my_last_changenumber=Math.abs(o.last_change_number);
        	
        	var ConstrainString=w._getConstrainString();
     		//debug(o.ObjName+' >> Constrains('+ConstrainString+')', true, o.debug_it);
        
        	$('#db_datatables .data_table[DataTableName="'+d[0]['DataTableName']+'"] .data_row'+ConstrainString).each(function()
        	{	
				if($(this).attr('last_change_number')>my_last_changenumber || without_looking_on_changenumbers)     	    			
				{
    	    		var listitem=e.find('.DataE_Listitem[dataid="'+$(this).attr('data_DataID')+'"]');
						
					//debug(o.ObjName+' >> _AddItemsByConstrains('+listitem.attr('data_DataID')+')-'+$(this).attr('data_DataID'), true, o.debug_it);
        			if(listitem.size()===0) w._addNewListItem($(this), false);	
        		}
        	});
        },
        _AddItemsByLinkedOrderAttr:function(without_looking_on_changenumbers)
        {
        	var w=this, e=w.element, o=w.options, l=o.IDLIST_linked_Data, d=o.DataMapping;
        	
        	//debug(o.ObjName+'  >> linked_Data_only getDataFromDatatables', true, o.debug_it);
        	
        	if(l.length>0 && o[l[4]]!='' && o[l[4]]!=undefined) 
        	{	
        		var linked_data_attribut=$('#db_datatables .data_table[DataTableName="'+l[0]+'"] .data_row['+l[3]+'="'+o[l[4]]+'"]').attr(l[1]).split(',');
        		
        		for(var i=0; i<linked_data_attribut.length; i++)
        		{
        			var row_item=$('#db_datatables .data_table[DataTableName="'+d[0]['DataTableName']+'"] .data_row[data_DataID="'+linked_data_attribut[i]+'"]');
        			
        			if(row_item.attr(l[3])!=undefined)
        			{
        				var listitem=e.find('.DataE_Listitem[dataid="'+row_item.attr('data_DataID')+'"]');        				
        				if(listitem.size()===0) w._addNewListItem(row_item, false);
        			}
        		}
        	} 
        },
        _addNewListItem: function(item, isClone)
        {
        	var w=this, e=w.element, o=w.options, d=o.DataMapping;
        	
        	var tmp_mappingData='';
        	var MappingData=w._getMappingDataForAttribut('ActiveDataID');
        	if(MappingData!=undefined && MappingData.length>0)
        	{
        		var related_Attribut=MappingData[0][2];
        		tmp_mappingData=related_Attribut+'="'+o.ActiveDataID+'"';
        	} 
        	
        	var item_span_waiting=e.find('span[waiting_for_new_Element="true"]');
        	var item_span_dragged= e.find('.ui-draggable');
        	
        	if(item_span_waiting.length!=0)
        	{
        		item_span_waiting.replaceWith('<span DataTableName="'+d[0]['DataTableName']+'" DataID="'+item.attr('data_DataID')+'" '+tmp_mappingData+'></span>');
        		//debug(o.ObjName+' > REPLACE wait('+item_span_waiting.attr('dataid')+') with new('+item.attr('data_DataID')+')',true, o.debug_it);
        	}
        	else if(item_span_dragged.length!=0 && o.is_slave)
        	{
        		item_span_dragged.replaceWith('<span DataTableName="'+d[0]['DataTableName']+'" DataID="'+item.attr('data_DataID')+'" '+tmp_mappingData+'></span>');
        		//debug(o.ObjName+' > REPLACE dragged('+item_span_dragged.attr('dataid')+') with new('+item.attr('data_DataID')+')',true, o.debug_it);
        	}else
        	{	
        		if(e.find('span[DataID="'+item.attr('data_DataID')+'"]').length==0)
        		{
        			e.append('<span DataTableName="'+d[0]['DataTableName']+'" DataID="'+item.attr('data_DataID')+'" '+tmp_mappingData+'></span>');
        		}	
        	}	
        	var item_span= e.find('span[DataID="'+item.attr('data_DataID')+'"]');

        	item_span.DataE_Listitem(
        	{
        		DataMapping: clone(o.DataMapping_for_Listitem),
        		ObjName: o.ObjName+' Item', 
        		hasOrderButton: o.is_sortable,
        		hasEditButton:false,
        		hasCloneButton: !o.linked_Data_only,
        		clicked_clone: function()
        		{
        			if(!o.linked_Data_only)
        			{
        				$(this).DataE_Listitem('ActionClone');
        			}else
        			{
        				        			
        			}      		
        		},
        		clicked_item: function()
        		{
        			w._clickListItem($(this));
        		},
        		clicked_delete: function()
        		{
        			if(!o.linked_Data_only)
        			{
        				$(this).DataE_Listitem('ActionDelete');
        			}else
        			{
        				$(this).DataE_Listitem('DeleteInstance');
        				w._saveReorderInLinkedAttr();
        			}
        		},
        		init_afterAll: function()
        		{
        			$(this).DataE_Listitem('setDataID',item.attr('data_DataID'));
        			$(this).DataE_Listitem('updateElement');
        		}		
        	});
        	
        	if(item_span_waiting.length!=0 || item_span_dragged.length!=0)
        	{
        		w._saveReorderInLinkedAttr(true);
        	}
        	
        	if(o.is_copyRelation && isClone)
        	{
        		item_span.attr('waiting_for_new_Element','true');
        		w._createNewElement(false, true, true, '', item.attr('data_DataID'));
        	}
        	
        },
         _clickListItem: function(item)
         {
         	var w=this; var e=w.element; var o=w.options;
        		
        	e.find('.DataE_Listitem').removeClass('DataE_Listitem_Activ');
        	
        	if(o.MasterTable!='')
        	{
        		o.MasterTable.find('.DataE_Listitem').removeClass('DataE_Listitem_Activ');
        		if(!o.is_copyRelation) o.MasterTable.find('.DataE_Listitem[dataid="'+item.attr('DataID')+'"]').addClass('DataE_Listitem_Activ', 500);
        	}
        	if(o.SlaveTable!='')
        	{
        		o.SlaveTable.find('.DataE_Listitem').removeClass('DataE_Listitem_Activ');
        		if(!o.is_copyRelation) o.SlaveTable.find('.DataE_Listitem[dataid="'+item.attr('DataID')+'"]').addClass('DataE_Listitem_Activ', 500);
        	}        	
	
        	w.setOption('ActiveItemID',item.attr('DataID'));        	
        	
         },
        setVisibility: function(value)
        {
        	var w=this, e=w.element, o=w.options;
        	
        	var show_it=value;
        	
        	if(show_it=='' || show_it==undefined)
        	{
        		show_it=o.is_enabled;
        	}
        	
        	//debug(o.ObjName+' ############### set Visiblity '+show_it, false, o.debug_it);
        	
        	if(show_it!=true) 
           {	
           		o.is_enabled=false;	
           		 e.prepend('<div class="CE-Disabled_Container CE-Disabled_Container_visible"></div>');               								
           } else
           {
                e.find('.CE-Disabled_Container').remove(); 	
                o.is_enabled=true;
           } 
        } 
          
    });
  

    


  
//########################################################## DataE_Listitem ##############################################################################################    	
/*  ! ... CE.DataE_Listitem ........................................................................................ (Bookmark for Coda)  */

      $.widget( "CE.DataE_Listitem" ,$.CE.DataElement, {
        options: { 
                text: '',             
                content:'',
                id_text:'',
                ObjName:'DataE_Listitem',
             
                DataTableName:'',
                DataID:'',
                
                hasToggleButton: false,
                ToggleButton: 0,
                hasOrderButton: false,
                OrderButton: 0,
                hasDeleteButton: true,
                DeleteButton: 0,
                hasEditButton: true,
                EditButton:0,
                hasCloneButton: true,
                CloneButton:0,
                ParentWidgetElement:'',
                ParentWidget:'',
                
                ActionWasClicked: false,
                OrderNr:'0',
                debug_it: false
        },
        _init: function(){
			var w=this, e=w.element, o=w.options;

   			w._trigger('init_before_DataElements');
   			w._initDataElement(); 
   			w._trigger('init_after_DataElements');
   			
   			// ADD OPTIONS
   			if(o.ParentWidgetElement=='') o.ParentWidgetElement=e.parent();
   			
   			// ADD CLASSES   	
			e.addClass('DataE_Listitem');
			
			// HTML ELMENTS and ACTION
			e.append('<span class="CEButton_Dragbutton CE-Button"></span>');
			o.OrderButton=e.find('.CEButton_Dragbutton');
			
			o.OrderButton.click(function()
			{
				o.ActionWasClicked=true;
				w._trigger('clicked_drag');
				
			});
			
        	e.disableSelection();
			
			e.append('<span class="CEButton_Deletebutton CE-Button"></span>');
			o.DeleteButton=e.find('.CEButton_Deletebutton');
			o.DeleteButton.click(function()
			{
				o.ActionWasClicked=true;
				w._trigger('clicked_delete');
			});

			e.append('<span class="CEButton_Clonebutton CE-Button"></span>');
			o.CloneButton=e.find('.CEButton_Clonebutton');
			o.CloneButton.click(function()
			{
				o.ActionWasClicked=true;
				w._trigger('clicked_clone');
			});
			
			e.append('<span class="CEButton_Editbutton CE-Button"></span>');
			o.EditButton=e.find('.CEButton_Editbutton');
			o.EditButton.click(function()
			{
				o.ActionWasClicked=true;
				w._trigger('clicked_edit');
			});
			
			e.append('<span class="DataE_Listitem-ID"></span>');
        	e.append('<span class="DataE_Listitem-Text"></span>');
        	e.append('<span class="DataE_Listitem-Content"></span>');
			
			// INIT HTML ELEMENTS
        	w.setOption('hasToggleButton', o.hasToggleButton );
        	w.setOption('hasOrderButton', o.hasOrderButton );
        	w.setOption('hasDeleteButton', o.hasDeleteButton );
        	w.setOption('hasEditButton', o.hasEditButton );
        	w.setOption('hasCloneButton', o.hasCloneButton );
        	
        	// ADD ACTION
        	e.click(function()
        	{
        		w.ActionClick();
        	});	
        	w._trigger('init_afterAll');
        },
        ActionClick: function()
        {
        	var w=this, e=w.element, o=w.options;
        	
        	if(o.ActionWasClicked)
        		{
        			o.ActionWasClicked=false;
        		}else
        		{
        			w._trigger('clicked_item');
        			e.addClass('DataE_Listitem_Activ', 500);
        			//debug(o.ObjName+' Activated item', true, o.debug_it);
        		}
        },
        ActionClone: function()
        {
        	var w=this, e=w.element, o=w.options;
        	o.ActionWasClicked=true;     
        	var cloneItemDataID=w._cloneElement(); 
        	      	
        	w._sendDataToDatatables(o.DataTableName,cloneItemDataID,'data_DataID',cloneItemDataID,0,0, false, true, false);
        	//debug(o.ObjName+' clone item('+cloneItemDataID+')', true, o.debug_it);
        },
        ActionDelete: function()
        {
        	var w=this, e=w.element, o=w.options;
        	o.ActionWasClicked=true; 
        	
        	w._deleteElement();
        	e.fadeOut('slow', function()
        	{
        		e.remove();
        	});
        	
        	//debug(o.ObjName+' Delete item', true, o.debug_it);
        },
         DeleteInstance:function()
        {
        	var w=this, e=w.element, o=w.options;
        	
        	e.fadeOut();
        	e.remove();
        },   
        setOption: function ( key, value, animate, commitToDatabase ) 
        {
           	var w=this, e=w.element, o=w.options;
        	
        	//debug(o.ObjName+' setOptionLI('+key+','+o[key]+'->'+value+')', true, o.debug_it);
        	
        	if(key!=null && key!=undefined)
            {
            		
            		switch (key) 
            		{        	
            			case "hasOrderButton":
                			o.key = value;  
                			o[key] = value; 
                			if(value==true) 
                			{
                				o.OrderButton.fadeIn();   				
                			} else 
                			{
                				o.OrderButton.fadeOut('fast'); 
                			}                			              			
                  			break;
                  		case "hasDeleteButton":
                			o.key = value;  
                			o[key] = value; 
                			if(value==true) o.DeleteButton.fadeIn(); 
                			  else o.DeleteButton.fadeOut('fast');                			
                  			break;
                  		case "hasEditButton":
                			o.key = value;  
                			o[key] = value; 
                			if(value==true) o.EditButton.fadeIn(); 
                			  else o.EditButton.fadeOut('fast');                			
                  			break;
                  		case "hasCloneButton":
                			o.key = value;  
                			o[key] = value; 
                			if(value==true) o.CloneButton.fadeIn(); 
                			  else o.CloneButton.fadeOut('fast');                			
                  			break;
                  		case "text":
                			o.key = value;  
                			o[key] = value; 
                			e.find('.DataE_Listitem-Text').html(value);  
                  			break;
                  		case "content":
                			o.key = value;  
                			o[key] = value; 
                			e.find('.DataE_Listitem-Content').html(value);  
                  			break;
                  		case "id_text":
                			o.key = value;  
                			o[key] = value; 
                			e.find('.DataE_Listitem-ID').html(value);  
                  			break;
                  		case "OrderNr":
                  			o.key = value;  
                			o[key] = value; 
                  				e.attr(key, value);
                  			break;
            		default:
               	 		o.key = value;  
                		o[key] = value;   
                		break;
           			}
           			
           			if(commitToDatabase)  w._setOption(key, value);
            }
            $.Widget.prototype._setOption.apply( this, arguments );
        }
    });
//########################################################## DataE_Inputfield ##############################################################################################
/*  ! ... CE. DataE_Inputfield ........................................................................................ (Bookmark for Coda)  */     
	 $.widget( "CE.DataE_Inputfield" ,$.CE.DataElement, {
        options: { 
                
                ObjName:'Inputfield',
                
                text: '',
                label: '',
                content:'',
                
                input_value:'', // for Mapping
                 
                isTextfield:false,
                isSelectbox: false,
                SelectOptions:[],
                
                is_enabled: false,
                ActivDataID: '-1',
                
                hasChangedActivSessionID:false,
                hasNewActivSessionID: false,
                hasSubmitButton:false
        },
        _init: function(){
			var w=this, e=w.element, o=w.options;
			
			w._initDataElement();
			
			e.addClass('DataE_Inputfield');

			w._initHTMLElements();
			
			if(o.hasSubmitButton)
			{
				w._initSubmitButton();
			}

			
			w.setOption('is_enabled',o.is_enabled,false,false,true);

			e.find('.CE-Inputfield').keypress(function(event)
			{
				if(event.which==13)
				{
					w._submitValue();
					event.stopPropagation();
				}				
			});

			e.find('.CE-Inputfield').focusout(function(event)
			{
				w._updateInput();
				w._submitValue();
				event.stopPropagation();
			});
			
			e.find('.CE-Inputfield').focus(function(event)
			{
				w._updateInput(true);
				event.stopPropagation();
			});
			
			e.find('.CE-InputDefaultText').click(function(event)
			{
				e.find('.CE-Inputfield').trigger('focus');
			});
						
			e.find('.CE-Inputfield').change(function(event)
			{					
					w._updateInput();
					event.stopPropagation();
			});	
			
			e.bind('updateView', function(event)
        	{
        		w._updateInput();
        		event.stopPropagation();
        	});
        	

			w._trigger('has_init');
			
        },
        _initHTMLElements: function()
        {
        	var w=this, e=w.element, o=w.options;
        	
        	e.append('<span class="CE-InputLabel">'+o.label+'</span>');
			
			if(o.isTextfield)
			{
				e.append('<textarea class="CE-Inputfield" cols="2" rows="1" type="text"></textarea>');
			}
			else if(o.isSelectbox)
			{
				var INPUT_STRING='<select size="1" class="CE-Inputfield">';
				INPUT_STRING=INPUT_STRING+'<option value="">'+o.text+'</option>';
				
				for(var i=0; i<o.SelectOptions.length; i++)
				{
					INPUT_STRING=INPUT_STRING+'<option value="'+o.SelectOptions[i][1]+'">'+o.SelectOptions[i][0]+'</option>';
					//debug(o.ObjName+' > add Option '+o.SelectOptions[i][0],true, o.debug_it);
				}

				INPUT_STRING=INPUT_STRING+'</select>';
				e.append(INPUT_STRING);
	
			}else
			{
				e.append('<input class="CE-Inputfield" type="text"></input>');
			}
			
			if(!o.isSelectbox) e.append('<span class="CE-InputDefaultText">'+o.text+'</span>');
			e.append('<div class="CE-Disabled_Container"></div>');
        
        
        },
        _initSubmitButton: function()
        {
        	var w=this, e=w.element, o=w.options;
        	e.append('<span class="CE-Inputfield-SubmitButton">SPEICHERN</span>');
				e.find('.CE-Inputfield').css('padding-right', '100px');
				e.find('.CE-Inputfield-SubmitButton').click(function()
				{
					var tmp_string=e.find('.CE-Inputfield').val();
					tmp_string=tmp_string.replace (/^\s+/, '').replace (/\s+$/, '');										
					tmp_string=tmp_string.replace (/\r/, '');
					e.find('.CE-Inputfield').val(tmp_string);					
					w.setOption('input_value', e.find('.CE-Inputfield').val(), false, true); //und Mitteilen
					
					e.find('.CE-Inputfield-SubmitButton').fadeOut();
				});
				
				e.find('.CE-Inputfield-SubmitButton').fadeOut();
        
        
        },
        _submitValue: function()
        {
        	var w=this, e=w.element, o=w.options;
        	
        	var tmp_string=e.find('.CE-Inputfield').val();
			
			tmp_string=tmp_string.replace (/^\s+/, '').replace (/\s+$/, '');										
			tmp_string=tmp_string.replace (/\r/, '');

			e.find('.CE-Inputfield').val(tmp_string);					
			w.setOption('input_value', e.find('.CE-Inputfield').val(), false, true); //und Mitteilen
			
			w._trigger('has_submitValue');
        },
        _updateInput: function(gotFocus)
        {
        	var w=this, e=w.element, o=w.options;
        	
        	//debug(o.ObjName+'updateInput 1',true,o.debug_it);
        	////debug(o.ObjName+ '>>>>>>> updateInput 1('+o['hasChangedActivSessionID']+'!='+o['ActivDataID']+')', true, o.debug_it);
        	
        	if(gotFocus==true)
        	{
        		e.find('.CE-InputDefaultText').fadeOut();
        		e.find('.CE-Inputfield-SubmitButton').fadeIn();	
        		//debug(o.ObjName+'updateInput 1a',true,o.debug_it);
        	}else
        	{
        		if(o['input_value']=='')
        		{
        			e.find('.CE-InputDefaultText').fadeIn();
        			e.find('.CE-Inputfield-SubmitButton').fadeOut();
        		
        		}else
        		{
        			e.find('.CE-InputDefaultText').fadeOut();
					if(o['input_value']!=e.find('.CE-Inputfield').val())
					{
						e.find('.CE-Inputfield-SubmitButton').fadeIn();
					} 
        		}
        		
        		//debug(o.ObjName+'updateInput 1c',true,o.debug_it);
        		
        		//o.input_value=e.find('.CE-Inputfield').val();
        		if(o.isSelectbox)
				{
						if(!o.hasChangedActivSessionID)
						{
							w.setOption('input_value', e.find('.CE-Inputfield').val(), false, true);
						}else
						{
							o.hasChangedActivSessionID=false;
						}	 
				} 
				//debug(o.ObjName+'updateInput 1d',true,o.debug_it);
        	}
        	//debug(o.ObjName+'updateInput 2',true,o.debug_it);
        	
        	w._trigger('has_updateInput');
        },
        _showSavingFeedback:function()
        {
        	var w=this, e=w.element, o=w.options;
        	
        	e.find('.CE-Inputfield').effect("highlight", {'color': '#CCFF66'}, 5000);
        	e.find('.CE-Inputfield-SubmitButton').fadeOut();
        	
        	w._trigger('has_savedChange');
        
        },
        setOption: function ( key, value, animate, commitToDatabase, without_comparison ) 
        {
           	var w=this, e=w.element, o=w.options, d=o.DataMapping, a=o.ArrayMonitoredAttributes;         	

           	
           	//debug(o.ObjName+' setOptionIF('+key+','+o[key]+'->'+value+')', true, o.debug_it);
        	
        	if(key!=null && key!=undefined && (o[key]!=value || without_comparison==true || key=='ActivDataID' ))
            {	
            		switch (key) 
            		{        	
            			case "last_change_number":
            				o.key = value;  
                			o[key] = value; 
            				break;
            			case "is_enabled":
                			o.key = value;  
                			o[key] = value; 
                				if(value!=true) 
                				{
                					e.find('.CE-Disabled_Container').addClass('CE-Disabled_Container_visible');   
                					           								
                				} else
                				{
                					e.find('.CE-Disabled_Container').removeClass('CE-Disabled_Container_visible'); 	
                					  
                				}                			              			
                  			break;
                  		case "ActivDataID":
                			o.key = value;  
                			o[key] = value; 
          			
                			if(value!='' && value!=-1)
                			{ 
                				w._setDataID(value); //wichtig da sonst, nicht geladen oder gespeichert werden kann
                				
                			 	w.setOption('is_enabled', true);            
                			 	o.hasChangedActivSessionID=true;           			 	
                			 	w.setOption('hasNewActivSessionID', true); 
                			 	w._getDataFromDatatables(true);
                			 	e.find('.CE-Inputfield').trigger('change');
                			}else
                			{
                				//debug(o.ObjName+' RESET >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>', true, o.debug_it);
                				w.setOption('is_enabled', false);
                				e.find('.CE-Inputfield').val(''); 
                				o.input_value='';
                				e.find('.CE-Inputfield').trigger('change');	
                			}             			
                  			break;
                  		case "input_value":
                			o.key = value;  
                			o[key] = value; 
                			
                			
                			if(animate) 
                			{ 
                			 	e.find('.CE-Inputfield').val(value); 
                			 }             			
                  		break;
                  		default:
               	 		o.key = value;  
                		o[key] = value; 
                		break;
           			}
           			
           			if(commitToDatabase)
           			{
           				w._setOption(key, value);
           				w._showSavingFeedback();
           			}  
            }  
        }
    });
  
    


     
//########################################################## DataE_Inputfield_forNewElement ##############################################################################################
/*  ! ... CE.DataE_Inputfield_forNewElement ........................................................................................ (Bookmark for Coda)  */       
       
       $.widget( "CE.DataE_Inputfield_forNewElement" ,$.CE.DataElement, {
        options: { 
                text: '',
                input_value:'',
                ObjName:'DataE_Inputfield_forNewElement',
                ActiveDataID:'',
                is_enabled: true,
                IDLIST_linked_Data: ['RatingSession', 'data_array_of_IdeaIDs', 'DataID', 'data_DataID', 'ActiveDataID'],
                linked_Data_only:true     
        },
        _create: function () {},
        _init: function(){
			 var w=this; var e=w.element; var o=w.options;

        	e.addClass('DataE_Inputfield_forNewElement');
        		
			e.append('<input class="CE-InputAdd"></input>');
			e.append('<div class="CE-InputAddButton CE-Button"></div>');
			e.append('<span class="CE-InputDefaultText">'+o.text+'</span>');
			
			e.append('<div class="CE-Disabled_Container"></div>');
			w.setOption('is_enabled',o.is_enabled,false,false,true);

			e.find('.CE-InputAddButton').click(function()
			{
				 w._addNewDataTableItem();
			});
			
			e.find('.CE-InputAdd').change(function()
			{
				o.input_value=$(this).val();
				if(o.input_value=='')
				{
					e.find('.CE-InputDefaultText').fadeIn();
				}
			});
			
			e.find('.CE-InputAdd').keypress(function(event)
			{
				if(event.which==13)
				{
					o.input_value=$(this).val();
					w._addNewDataTableItem(true);
				}				
			});
			
			e.find('.CE-InputAdd').focusout(function()
			{
				if(o.input_value=='')
				{
					e.find('.CE-InputDefaultText').fadeIn();
				} 
			});
			
			e.find('.CE-InputAdd').focus(function()
			{
				e.find('.CE-InputDefaultText').fadeOut();
			});
			
			e.find('.CE-InputDefaultText').click(function()
			{
				e.find('.CE-InputAdd').trigger('focus');
			});
			
			w._initDataElement();
			
        },setOption: function ( key, value, animate, commitToDatabase,without_comparison ) 
        {
           	var w=this, e=w.element, o=w.options, d=o.DataMapping, a=o.ArrayMonitoredAttributes;         	
           	var tmp_value=o.key;
           	
        	
        	//debug(o.ObjName+' setOptionNewI('+key+','+o[key]+'->'+value+')', true, o.debug_it);
        	
        	if(key!=null && key!=undefined && (o[key]!=value || without_comparison==true))
            {	
            		switch (key) 
            		{        	
            			case "is_enabled":
                				o.key = value;  
                			o[key] = value; 
                				if(value!=true) 
                				{
                					e.find('.CE-Disabled_Container').addClass('CE-Disabled_Container_visible');                 								
                				} else
                				{
                					e.find('.CE-Disabled_Container').removeClass('CE-Disabled_Container_visible'); 	
                				}                			              			
                  			break;
                  		case "ActiveDataID":
                			o.key = value;  
                			o[key] = value; 
                			w._setDataID(value); //wichtig da sonst, nicht geladen oder gespeichert werden kann
                			
                			if(value!='')
                			{ 
                			 	w.setOption('is_enabled', true);
                			 	w.setOption('hasNewActivSessionID', true); 
                			 	w._getDataFromDatatables(true);
                			 	e.find('.CE-Inputfield').trigger('change');
                			}             			
                  			break;		
                  		default:
               	 		o.key = value;  
                		o[key] = value; 
                		break;
           			}
           			
           			w._setOption(key, value);
           			if(commitToDatabase)  w._setOption(key, value);
            }  
        },
        _addNewDataTableItem: function(waskeypress)
        {
        	var w=this, e=w.element,  o=w.options, d=o.DataMapping;
        	
        	o.input_value=e.find('.CE-InputAdd').val();
        	
        	//debug(o.ObjName+' ADD NEW DATATABLEITEM('+o.input_value+')', true, o.debug_it);
        	        	
        	if(o.input_value!='')
        	{
        		var newItemDataID=w._createNewElement(false, true, true, [d[0]['DataAttributes'][0],o[d[0]['DataAttributes'][1]]] );	
        	}
        	o.input_value='';
        	e.find('.CE-InputAdd').val('');
        	if(!waskeypress) e.find('.CE-InputDefaultText').fadeIn();
        }
    });

    
    
//########################################################## SLIDE ##############################################################################################    

 
 
 function clone(obj) {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0; i < obj.length; ++i) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}



    
/*  ! ... CE.Buttons ........................................................................................ (Bookmark for Coda)  */    

    $.widget( "CE.ToggleViewButton" , {
        options: { 
                isMinimized: false,
                savedHeight:0,
                minHeight:30,
                maxHeight:0
        },
        _create: function () {},
        _init: function(){
			 var w=this; var e=w.element; var o=w.options;
			 
			e.append('<div class="CE-ToogleViewButton CE-Button"></div>');
			e.find('.CE-ToogleViewButton').click(function()
			{
				 w.toogleView();
			});
        },   
        destroy: function () { $.Widget.prototype.destroy.call(this); },        
        setOption: function ( key, value, animate, commitToDatabase ) {$.Widget.prototype._setOption.apply( this, arguments ); },
        toogleView: function(maximize_it)
        {
        	
        	var w=this; var e=w.element; var o=w.options;
        	
        	if(maximize_it==true || (o.isMinimized && maximize_it!=false))
        	{
        		//debug('maximized it', true, o.debug_it);
        		e.find('.ToogleViewButton_Content').fadeIn('fast');
        		e.find('.ui-resizable-handle').fadeIn('fast');         		     		
        		//e.animate({height:o.savedHeight+'px'});
        		o.maxHeight=e.css('height');
        		
        		o.isMinimized=false;
        	}else 
        	{
        		//debug('minimize it', true, o.debug_it);
        		o.minHeight=e.css('height');
        		e.find('.ToogleViewButton_Content').fadeOut('fast');
        		e.find('.ui-resizable-handle').fadeOut('fast');  
        		//e.animate({Height:o.minHeight+'px'});
        		o.isMinimized=true;
        	}	
        }
    });  
    
    //########################################################## Session Template auswählen ##############################################################################################

    

})( jQuery, window, document );
