function sortOrder(items) {
	for(var i= items.length - 1; i >= 0;i--){
		for (var j = 0; j <= i;j++) {
			if (items[i].order < items[j].order) {
				var tmp = items[i];
				items[i] = items[j];
				items[j] = tmp;
			}
		}
	}
}

(function($){
$.fn.simulateSMSForm = function(options){
	if (typeof(options)=="string") {
		return;
	} else { //if type == object 
		$(this).data("item", options);
	}
	
	var formdiv = $(this),
	item = formdiv.data("item"),
	labels = item.labels.split(','),
	smsPart = isplit(item.format, "[^A-Za-z$]"),
	splitter = item.format.replace(new RegExp('[A-Za-z$]','g'), '').split("");
	splitter.push(" ");
	
	//test unique
	for (var i =0; i < labels.length-1; i++)
		for (var j = i+1; j < labels.length; j++)
			if (labels[i] == labels[j]) {
				alert('label tidak boleh kembar: ' + labels[i]);
				return;
			}
	
	if (smsPart.length != labels.length) {
		alert("jumlah label tidak sesuai dengan format SMS. Pastikan label dipisah dengan koma!");
		return;
	}
	formdiv.find('#formtitle').html(item.title);

	var	container = $('<form></form>')
		.appendTo(formdiv.find('.formcontent').html(''))
		.submit(function() {return false;})
		.after('<div id="smsoutput"><em>hasil simulasi text sms</em></div>').after("<br />");
	
	$.each(labels, function(i, label) {
		var elem;
		if (label == 'x' || smsPart[i].charAt(0) != '$') {
			elem = $('<div class="formfield">' +
			'<input type="text" class="formvalue" readonly="readonly" value="'+smsPart[i]+'"/></div>');		
		} else {
			var sampleValue ='',
			elemType = smsPart[i] == '$pin' ? 'password' : 'text';
			elem = $('<div class="formfield"><label class="formlabel">'+label+' <small>'+ smsPart[i] + '</small></label><br />' +
			'<input type="'+elemType+'" class="formvalue" value="'+sampleValue+'" /></div>');
		}
		
		container.append(elem);
	});

	var transform = function () {
		var smsText = '';
		container.find(":input").each(function (i) {
			if ($(this).attr('type') == 'text' || $(this).attr('type') == 'password')
				smsText += $(this).val()+splitter[i];
		});
		formdiv.find('#smsoutput').html(smsText);
		return false;
	}
	container.find(':input').change(transform);
	$('<button>Submit</buton>').appendTo(container).click(transform);
}

/*
 * MyItem 0.7.5
 *
 * Copyright (c) 2010 mubaidillah@gmail.com
 *
 * Date: Feb 06 2010
 */
 
$.fn.menuItem = function(options){
	var defaults = {
		itemDelete: true,
		itemEdit: true,
		data: [],
		sortable: true,
		option: {display:[]},
		useDialog: false,
		edit: null,
		menuLimit: 10,
		dialog: {addTitle:"Add Item"},
		onDeleteItem: null
	}
	
	var root = $(this),
	menuItemID = root.attr('id') + "_list",
	init = true;

	if (options == 'serialize') {
		return $('#'+menuItemID).sortable('serialize');
	}
	if (options == 'refresh') {
		options = root.data("options");
		init=false
	}
	
	if (init) {
		root.data("items", options.data)
		options.data = {}
		var options = $.extend(defaults, options)
		root.data("options", options)
		root.data("menuItemID", menuItemID)
		
		var sms_title = $("#sms_title"),
			sms_format = $("#sms_format"),
			sms_label = $("#sms_label"),
			allFields = $([]).add(sms_title).add(sms_format).add(sms_label);
			//tips = $("#validateTips");
		var x = options.dialog.addTitle;
		$("#add-menu-dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 300,
			width: 600,
			modal: true,
			buttons: {
				'Add Menu' : function() {
					if (root.data("items").length >= options.menuLimit) {
						alert("Batasan menu maksimum " + options.menuLimit + " menu");
					} else {
						var item = new Object;
						item.title = sms_title.val();
						item.format = sms_format.val(); 
						item.labels = sms_label.val();
						var message = "OK";//validate_sms_format(item);
						if ("OK" == message) {
							root.data("items").push(item);
							refresh();
						} else {
							alert(message);
							return false;
						}
					}
					$(this).dialog('close');
				},
					'Test Form': function() {
						var testitem = new Object;
						testitem.title = sms_title.val();
						testitem.format = sms_format.val(); 
						testitem.labels = sms_label.val();
						$('#formpreview').simulateSMSForm(testitem);
					},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			},
			open: function() {
				$('#menuform :input').tooltip({
					position: "center right",
					relative:true,
					effect: "fade",
					opacity: 0.7,
					tip: '.tooltip2'});
			}

		});
			
	}
	
	var updateItemValue = function(content) {
		if (content.current != content.previous) {
			var key = $(this).parent().attr('id'),
			name = $(this).attr('class'),
			ids = key.replace(menuItemID + "_", "").split("_"),
			data = root.data("items");
			//alert(content.current + ":" + ids[0] + ":"+ids[1] + data[ids[0]]['items'][ids[1]][name]);
			data[ids[0]]['items'][ids[1]][name] = content.current;
		}/**/
	}
	
	var refresh = function() {
		var deleteIcon = '<a href="#" rel="delete" title="delete"><span class="ui-icon ui-icon-circle-close righticon"></span></a>',
		editIcon = '<a href="#edit" title="edit" rel="edit"><span class="ui-icon ui-icon-pencil righticon"></span></a>',
		toggleIcon = '<a href="#toggle" title="toggle" rel="toggle"><span class="ui-icon ui-icon-circle-triangle-s righticon"></span></a>',
		sortIcon = '<span class="ui-icon ui-icon-arrowthick-2-n-s"></span>',
		
		container = $("<ul id='" + menuItemID + "' class='mblist'></ul>"),
		data = root.data("items"),
		order = 0,
		lastItem = null;
		
		sortOrder(data);
		
		for (var item in data) {
			data[item].order = order++;
			var thisID = menuItemID + "_" + item,
			formatShown = data[item][options.option.display] != null ? "<code>" + data[item][options.option.display] + "</code>" : "<span>&nbsp;</span>",
			// onclick="$(this).next().toggle()"
			listItem = $('<li id="'+thisID+'" class="ui-corner-top"><label>' +data[item].title + "</label>"+formatShown+"</li>").appendTo(container);
		
			if (options.option.iconField != null) {
				listItem.find('label').prepend('<img width="16" height="16" src="images/' + options.option.icons[data[item][options.option.iconField]].icon + '" />&nbsp;');
			}
			if (options.itemEdit)
				listItem.prepend(editIcon)
			if (options.itemDelete)
				listItem.prepend(deleteIcon)
			if (options.sortable)
				listItem.prepend('<span class="ui-icon ui-icon-arrow-4" title="re-order"></span>');
			//header.editableJSON({data:options.data[item], display:true});
			if (data[item].items != null) {
				listItem.prepend(toggleIcon);
				listItem = listItem
					.wrapInner('<div class="ui-widget-header" style="margin:-5px;padding:5px;border:none;"></div>');
				
				var itemsContainer = $("<ul class='itemList'></ul>"),
				items = data[item].items,
				deleteSubIcon = '<a href="#" rel="deletesub" title="delete"><span class="ui-icon ui-icon-circle-close righticon"></span></a>';
				sortOrder(items);
				
				for (var subItem in items) {
					var subItemId = thisID + "_" + subItem
					itemsContainer.append("<li id='"+subItemId+"'>"+deleteSubIcon+"<span class='prefix'>" + items[subItem].prefix + "</span><span class='title'>" + items[subItem].title + "</span></li>");
				}
				
				itemsContainer.find("a[rel*=deletesub]").one('click', function() {
					if (confirm('Yakin mau menghapus? ')) {
						var parent = $(this).parent();							
						var id = parent.attr('id'),
						parts = id.split("_");
						data[parts[2]].items.splice(parts[3],1);

						$('#'+id).fadeOut('fast', function () {
							$(this).remove();
						});
						refresh();
					}
					return false;
				})
				//editable
				itemsContainer.find('.prefix').editable({editClass: 'editPrefix', onSubmit: updateItemValue}).attr('title', 'click to edit');
				itemsContainer.find('.title').editable({onSubmit: updateItemValue}).attr('title', 'click to edit');
				
				var widgetContent = $('<div class="ui-widget-content" style="margin:5px -5px -5px;"></div>');
				lastItem = widgetContent.append(itemsContainer).hide().appendTo(listItem);
				
				listItem.find('.ui-widget-header')
					.find('label').click(function() {
						$(this).parent().next().toggle();
					})
					.css('cursor','pointer');
			}
			
		}
		
		if (lastItem != null) lastItem.show();
		
		root.html(container);
		
		container.find('a[rel*=toggle]').click(function() {
			$(this).parent().next().toggle();
		})
		
		if (options.sortable) {
			container.sortable({ cursor: 'move',placeholder: 'ui-state-highlight',handle:'.ui-icon-arrow-4',
				update: function(event, ui) { 
					var arr = $('#'+menuItemID).sortable('toArray') ;
					for (var idx in arr)
						data [ arr[idx].replace(menuItemID+"_", "") ].order=idx ;
				}
			});//.disableSelection();
		}
		if (options.itemDelete) {
			container.find("a[rel*=delete]").one('click', function() {
				if (confirm('Yakin mau menghapus?')) {
					var parent = $(this).parent();
					if (parent.hasClass('ui-widget-header'))
						parent = parent.parent();
						
					var id = parent.attr('id'),
					num = id.replace(menuItemID+"_", "");
					root.data("items").splice(num,1);
					$('#'+id).fadeOut('fast', function () {
						$(this).remove();
					});
					if (root.onDeleteItem != null)
						root.onDeleteItem(root.data("items"));
					$(document).trigger('mbro.itemDelete', root.data("items"))
					refresh();
				}
				return false;
			})
		}
		
		if (options.itemEdit) {
			if (options.edit != null)
				container.find("a[rel*=edit]").bind('click', {name:menuItemID}, options.edit);
			else
				container.find("a[rel*=edit]").bind('click', function() {
				var id = $(this).parent().attr('id'),
				num = id.replace(menuItemID+"_", ""),
				item = root.data("items")[num];
				sms_title.val(item.title);
				sms_format.val(item.format);
				sms_label.val(item.labels);
				$('#formpreview .formtitle').html('Simulasi Form SMS');
				$('#formpreview .formcontent').html('');
				$('#add-menu-dialog').dialog('option', 'buttons', {
					'Update Menu': function() {
						item.title = sms_title.val();
						item.format = sms_format.val(); 
						item.labels = sms_label.val();
						var message = "OK";//validate_sms_format(item);
						if ("OK" == message) {
							refresh();
						} else {
							alert(message);
							return false;
						}
						$(this).dialog('close');
					},
					'Test Form': function() {
						var testitem = new Object;
						testitem.title = sms_title.val();
						testitem.format = sms_format.val(); 
						testitem.labels = sms_label.val();
						$('#formpreview').simulateSMSForm(testitem);
					},
					Cancel: function() {
						$(this).dialog('close');
					}
				});
				$('#add-menu-dialog').dialog('open');
				return false;
			})
		}
	}
	refresh();
	return this;
}

$.fn.editableJSON = function(options){
	var defaults = {
		name:'setting',
		data:{},
		option:{disableItems:{}},
		header:false,
		display:true,
		container: null
	}
	var options = $.extend(defaults, options),
	root = $(this);

	options.disableItems = options.option.disableItems
	var container = options.container
	
	var updateValue = function(content) {
		if (content.current != content.previous) {
			var key = $(this).parent().attr('id')
			options.data[key.replace(options.name + "_", "")] = content.current == 'Numeric Only' ? 'num' : (content.current == 'Alphanumeric' ? 'str' : content.current) ;
		}
	}
	
	if (container == null) {
		container = $("<div id='"+options.option.id+"'></div>");
		if (options.header)
			container.append("<h2>"+options.option.label+"</h2>");

		root.html(container)
	}
	
	var display = '';
	if (!options.display) display = "style='display:none'";
	for(var item in options.data)  {
		var html = $("<div id='"+options.name+"_"+item+"' class='field' "+display+"><label>" +item+ "</label></div>"),
		elem = null,
		fieldTitle = options.option.titles[item] == null ? item : options.option.titles[item];
		
		if (options.option.choices != null && options.option.choices[item] != null ) {
			elem = $("<span class='value info'>" +options.option.choices[item][options.data[item]]+ "</span>");
			elem.css('cursor','pointer').attr('title', fieldTitle+"<br /> <small>click to edit</small>");
			
			elem.editable({type: 'select', options: options.option.choices[item], onSubmit: updateValue})
			
		} else  {
			elem = $("<span class='value info"+(options.disableItems[item] ? "":" editable")+"'>" +options.data[item]+ "</span>");
			elem.attr('title', fieldTitle+ (options.disableItems[item]?"":"<br /> <small>click to edit</small>") );
		}
		
		
		html.append(elem).appendTo(container);
	}
	
	container.find('.info')
		.tooltip({
			position: "center right",
			offset: [-2, 10],
			effect: "fade",
			opacity: 0.7,
			tip: '.tooltip'});
	container.find('.editable')
		.editable({onSubmit: updateValue});
	
	return root;
}

})(jQuery);

function isplit(string, regexp, flags){
	var splitter="#@#";
	while(string.indexOf(splitter)!=-1){ splitter+="#"; };
	flags=(flags && typeof(flags)=="string")?flags:
	(!isNaN(parseFloat(flags)))?"":"g";
	string=string.replace(
		((typeof(regexp)=="string")?new RegExp(regexp, flags):regexp),
		splitter
	);

	return string.split(splitter);
/*keep this comment to use freely
http://www.fullposter.com/?1 */}

