var WIDGETPROXY = (function() {		
	function sidebarChangeHandler(sidebar_id, widget_field_id, widget_id) {							
		jQuery.post(			
			WidgetProxyAjax.ajaxurl,
			{
				// here we declare the parameters to send along with the request
				// this means the following action hooks will be fired:
				// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
				action : 'widget_proxy_ajax_get_widgets',			
				sidebar_id : sidebar_id,
				widget_id : widget_id
			},
			function(response) {				
				if (response.success) {
					var widgets = response.widgets;
					var widget_select = document.getElementById(widget_field_id);
					clearSelect(widget_select);
					addOptionsToSelect(widget_select, widgets, "id", "text");
				}
			}
		);	
	}
	
	function refreshWidgetsHandler(sidebar_field_id, widget_field_id, widget_id) {
		var sidebar_select = document.getElementById(sidebar_field_id);
		sidebarChangeHandler(sidebar_select.value, widget_field_id, widget_id);
	}

	function refreshSidebarsHandler(sidebar_field_id, widget_field_id, widget_id) {		
		jQuery.post(
			WidgetProxyAjax.ajaxurl,
			{
				// here we declare the parameters to send along with the request
				// this means the following action hooks will be fired:
				// wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
				action : 'widget_proxy_ajax_get_sidebars'				
			},
			function(response) {			
				if (response.success) {
					var sidebars = response.sidebars;					
					var sidebar_select = document.getElementById(sidebar_field_id);					
					clearSelect(sidebar_select);
					addOptionsToSelect(sidebar_select, sidebars, "id", "text");					
					refreshWidgetsHandler(sidebar_field_id, widget_field_id, widget_id);
				}
			}
		);			
	}		
	
	// Select operations
	function clearSelect(select) {				
		while (select.options.length > 0) {					
			select.remove(0);
		}
	}
	function addOptionToSelect(select, value, text, title) {				
		var option = document.createElement("option");
		option.text = text
		option.value = value
		if (title) {
			option.title = title;
		}

		if (document.all && !window.opera) {
			select.add(option);
		} else {
			select.add(option, null);
		}
	}
	function addOptionsToSelect(select, options, valueProperty, textProperty) {				
		var i = options.length, option;				
		while (i--) {
			option = options[i];
			addOptionToSelect(select, option[valueProperty], option[textProperty], option.title);
		}
	}
	
	return {
		sidebarChangeHandler:sidebarChangeHandler,
		refreshWidgetsHandler:refreshWidgetsHandler,
		refreshSidebarsHandler:refreshSidebarsHandler
	};
})();