/* displays an inline browser for selecting elements */
(function($){
	
	var configs = {};
	var methods = {
			
		show: function(e) {				
			e.preventDefault();
					
			var s = [], myconfig, mykey, values = [];
			$(e.target).parents('.selectTabList').find('li').each(function(i, o) {
				var x = o.id.match(/-([0-9]+)$/);
				if (x) {
					values.push(x[1]);
				}
			});			
						
			// step through url until we grab the key
			$.each(e.target.href.split(/\//g), function(i, o) {
				if (o.match(/^wgib-/)) {
					if (configs[o]) {
						myconfig = configs[o];
						mykey = o;
						return false;
					}			
				}
			});		
						
			if (! myconfig) {
				$.error('Config not found within jQuery.inlineBrowser');
				return;
			}
			
			var pos = $(e.target).offset();
			myconfig.top = pos.top;
			myconfig.left = pos.left;
			
			myconfig.top = isNaN(myconfig.top) ? myconfig.top : myconfig.top + 'px'; 
			myconfig.left = isNaN(myconfig.left) ? myconfig.left : myconfig.left + 'px';
			myconfig.width = isNaN(myconfig.width) ? myconfig.width : myconfig.width + 'px';
			myconfig.height = isNaN(myconfig.height) ? myconfig.height : myconfig.height + 'px'; 

			$(document.body).append('<div style="top:' + myconfig.top + ';left:' + myconfig.left + '" id="' + mykey + 
									'" class="inline-browser"><iframe  id="' + mykey + '-frame" src="' + e.target.href + 
									'?values=' + values.join('-') + '" frameborder="0" style="width:' + myconfig.width + 
									';height:' + myconfig.height + '" /></div>');	
			
			$('#' + mykey).data('activator', $(e.target));
		}, 	
		
		addConfig: function(id, config) {
			configs[id] = config;
		}, 
		
		save: function(key, items) {	
			var ul = $('#' + key).data('activator').parents('.selectTabList').find('ul');
			$.each(items, function(i, o) {
				$(o).appendTo(ul);
			});		
			$.fn.inlineBrowser('cleanup', key);
			$.fn.inlineBrowser('close', key);
		}, 
		
		// remove items from form displayed in iframe
		setup: function(f, v) {			
			var vals = v.replace(/\?values=/, '').split('-');
			var x = $(f).find(':input[name=values]');
			switch (x.get(0).tagName.toLowerCase()) {
				case 'select' :
					$.each(x.get(0).getElementsByTagName('option'), function(i, o) {
						// see if we have found a match
						if (o && $.inArray(o.value, vals) != -1) {
							o.parentNode.removeChild(o);
						}
					});
				break;
			}
			
		},
		
		// removes duplicates and sets value of hidden input
		cleanup: function(key) {			
			if (typeof(key) == 'object') {
				var ul = $(key), 
				inp = $(ul).parents('.selectTabList').find('input');
			}
			else {
				var ul = $('#' + key).data('activator').parents('.selectTabList').find('ul'), 
				inp = $('#' + key).data('activator').parents('.selectTabList').find('input');
			}
			
			console.log(ul);
			
			var values = [];
			ul.find('li').each(function(i, o) {		
				var x = o.id.match(/-([0-9]+)$/);
				if (x) {				
					// previously found
					if (values.indexOf(x[1]) != -1) {					
						o.parentNode.removeChild(o);
					}
					else {
						values.push(x[1]);
					}	
				}
			});		
			
			inp.val(values.join(','));
		},
		
		close: function(f) {	
			// get key from iframed form or passed directly
			var key = (f.tagName) ? $(f).find('input[name=wg-configKey]').val() : f;		
			$('#' + key).remove();
		},
		
		remove: function(e) {
			e.preventDefault();
			var li = $(e.target).parents('li').first(), ul = li.parent();
			li.remove();
			$.fn.inlineBrowser('cleanup', ul[0]);
		},
		
		showError: function(key, m)	{
			alert(m);
			$.fn.inlineBrowser('close', key);
		}			
	}

	$.fn.inlineBrowser = function(method) {
		if (methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(
					arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' + method + ' does not exist within jQuery.inlineBrowser');
		}
	};
	
	$().ready(function(){				
		// add click to add
		$('.selectTabList a.add').bind('click', function(e) { $.fn.inlineBrowser('show', e); });
		// add remove to remove
		$('.selectTabList li a.remove').live('click', function(e) { $.fn.inlineBrowser('remove', e); });
	});	
})(jQuery);
