﻿
(function($) {
    $.fn.reorderlist = function(options) {   
		 var target = $(this);	
		 				 
		var settings = {
            maxlength: 1000
        };
        
        if(options) {
            $.extend(settings, options);
        }
        options = settings;
		                            
        target.find('.add').click(function() {		
			if(typeof options.onAdd == 'function') {			
				var item = options.onAdd();
				if(item) {
					target.add(item);
				}				
			}	  
		});
				
		target.find('.textbox').keydown(function(event) {
			if (event.keyCode == 13) {
				target.find('.add:first').click();		
				event.preventDefault();
				return false; 
			}  
		});
						
		target.add = function(item) {
			var newEl = this.find("#template").clone().attr("style", "").attr("id", item.id);
			
			
			newEl.find('span').each(function() {			
				$(this).html(eval('item.'+$(this).attr('id')));
			});
					
			
			newEl.insertBefore("#template"); 	
			
			//TODO this may not work with every template	
			newEl.find('.delete').click(function() {
				if(typeof options.onDelete == 'function') {
					options.onDelete($(this).parent().parent().attr('id'));
				}	  
				$(this).parent().parent().remove();
			});
			
			newEl.find('.editable').editable(function(value, settings) {                
				return(value);
			 }, {     
				indicator : "<img src='../../images/common/indicator.gif'>",            
				tooltip   : "Click to edit...",    
				placeholder : "No current ALT text",            
				onblur     : 'submit',				
				type : "text",
				width: "auto",
				maxlength: options.maxlength
			 }); 
		};
				
		target.find('.reorder').click(function() {			
			target.tableDnD(
				{	enable: true,
					onDragClass: 'drag-row',
					altStyle: options.altStyle
				}
			);
			target.find('.sortable .delete').hide();
			target.find('.reorder').hide();
			target.find('.done-reorder').show();
			target.find('.drag').show();
		});
        
        target.find('.done-reorder').click(function() {        	
			target.tableDnD(
				{enable: false}
			);
        
			target.find('.sortable .delete').show();
			target.find('.reorder').show();
			target.find('.done-reorder').hide();
			target.find('.drag').hide();
			
			if(typeof options.onClientSave == 'function') {			
				var ids = "";
				target.find("tr").each(function(i,o){
					if(!$(o).hasClass("nodrag") && o.id != 'template') {
						if (ids.length) {
							ids += ","
						}		
						ids += o.id;
					}
				});  				
				options.onClientSave(ids);
			}	  
			
		});
		
		target.find('.drag').hide();
		target.find('.done-reorder').hide();		
		
		                   
        if(options.items) {
			for(var i = 0; i < options.items.length; i++) {
				target.add(options.items[i]);
			}
        }
        
                  
	}
})(jQuery);