// this is used for toggling a group of plugin outputs in a table
// this script is used in plugin-block.html
// key = (library):plugin:DOMelementID
function hideTable(key) {

    var tbody, img;

    tbody = key + ":tbody";
    tbody = document.getElementById(tbody);

	img = key + ":img";
	img = document.getElementById(img);

	if (tbody.style.display == 'none') { 

		tbody.style.display = '';
		img.src="img/collapse.png";		 

	} else { 

		tbody.style.display = 'none';
		img.src="img/expand.png";
	}
}

function jq(myid) { 
  return '#' + myid.replace(/(:|\.)/g,'\\$1');
}

/// Toggle table showing plugin outptus (using jQuery)
function hideTable_jq(key) {

	var tbody = $(jq(key + ":tbody"));

	var img = key + ":img";
	img = document.getElementById(img);

	if (tbody.is(':visible')) {

		tbody.hide();
		img.src="img/expand.png";		

	} else { 

		tbody.show();
		img.src="img/collapse.png";		 		
	}
}


//same as above, but do it in batch
function toggle_plugin_outputs() {

	var pbodies=document.getElementsByName("plugin_output_table");
	var triangles=document.getElementsByName("plugin_output_triangle");
 	for (var i = 0; i < pbodies.length; i++) {
		tbody = pbodies[i];
		img = triangles[i];

		if (tbody.style.display == 'none') { 
			tbody.style.display = '';
			img.src="img/collapse.png";

		} else { 

			tbody.style.display = 'none'; 
			img.src="img/expand.png";
		}
    }
	load_config_status();
}

// Show/Hide an element, e.g. a div block
function toggle_element_by_id(element_id) {
	element = document.getElementById(element_id);
	if (element.style.display == 'none') { 
		element.style.display = '';

	} else { 

		element.style.display = 'none';
	}
	return true;
}

// Open plugin table if an output is selected
function open_selected(output_key_hash) {
	
	chkbox = document.getElementById(output_key_hash+"-chk");
	var keys = chkbox.value.split(":");
	keys.shift(); // remove vamp:xxx (first element)
	keys.pop(); // remove output key (last element)
	var table_key = keys.join(":");
	// alert(table_key);
	var tbody, img;

    tbody = table_key + ":tbody";
    tbody = document.getElementById(tbody);
	img = table_key + ":img";
	img = document.getElementById(img);
	
	if (tbody.style.display == 'none') { 
	
		tbody.style.display = '';
		img.src="img/collapse.png";		 
	
	} else { 
		return ;
		// tbody.style.display = 'none';
		// img.src="img/expand.png";
	}    	
}


// Display a popup window
function config_popup(target, window_name) {

	if (! window.focus) return true;

	var href;
	if (typeof(target) == 'string')
   		href=target;
	else
   		href=target.href;

	w = window.open(href, window_name, 'screenX=100, screenY=40, screenLeft=100, screenTop=40, width=900, height=300, scrollbars=yes, toolbar=no, location=no, directories=no, status=no, menubar=no, resizable=yes, copyhistory=no');
	return false;
}

/// Select the checkbox if the vamp plugin configuration was used
function select_checkbox(id) {
	onSelectorChange(id);
	// var chkboxID = id + "-chk";
	// var chkbox = document.getElementById(chkboxID);
	// chkbox.checked = true;
}

var gDialog = null; //config_dialog();

function set_config_tab_url(output_key,selector_id) {	
	var id = "#"+selector_id+"-sel";
	var selected_transform_id = $(id).val();
	var href = 'configure_transform?outputkey='+output_key+'&transform='+selected_transform_id;
	$( "#tabs" ).tabs( "url" , 2 , href );
}


function show_popup(output_key,selector_id) {	

	// var window_name = "Configure Transform...";
	var id = "#"+selector_id+"-sel";
	var selected_transform_id = $(id).val();
	var href = 'configure_transform?outputkey='+output_key+'&transform='+selected_transform_id;
	// return config_popup(href, window_name);
	
	/* NEW JQUERY DIALOG */

	if (gDialog == null) gDialog = config_dialog();
	$.get(href, function(data){ 
		$('.config_dialog').html(data); 
		var custom_rules = {
			transform_name:{required:true, filename:true, reserved:true, maxlength:15, minlength:5}
			};
		$("#config_form").validate({rules:custom_rules, errorContainer: '#general_error', disableOnErrorContainer: '.doe' });
		$("#transform_name").click(function(){$("#transform_name").valid(); });
		$(".doe").mouseover(function(){$("#config_form").valid(); });
		
		$("#config_cancel").click(function(){$(".config_dialog").dialog("close");});
		var divh = document.getElementById('popup_content').offsetHeight;
		var plugin_output = "Configure Transform: " + $("#plugin_output").html();
		$(".config_dialog").dialog({ height:divh+60, title:plugin_output });		
		gDialog.dialog("enable");		
	});
	gDialog.dialog('open');
	gDialog.dialog("disable");
	return false;
}


function config_dialog() {
	var window_height = $(window).height()-20;
	var dialog = $('<div class="config_dialog" id="config_dialog"></div>')
		.dialog( {
			autoOpen:false,
			show: 'slide',
			hide: 'fold',
			title:'Configure Transform', 
			autoResize:true,
			width:950,
			height:450,
			maxWidth:950,
			minWidth:700,
			maxHeight: window_height,
			minHeight: 60,
			modal:true
			// overlay: {opacity:0.5, background:"black"}
			})
		.html('Please wait while loading content...')
		.width(950)
		.height(450);
	return dialog;
}


///  		CONFIG STATUS AND SELECTOR UPDATE   	///

var gConfigStatus = { "init" : false, "status" : "unknown" };
var gClientConfigStatus = { "updated" : false, "load_count" : 0, "refresh_all" : true, "request" : "none" };
var gTimeOutArray = new Array();

var gSelStart = "<select class='config' name='output:";
var gSelId = "' id='";
var gSelOnChange = '-sel\' onchange="onSelectorChange(\'';  
var gSelEnd = '\');" >';

var gDefaults = "<option value='default'>default transform</option>"
var gAllInc = "<option value='all-incl'>All (incl. default)</option>"
var gAllEx = "<option value='all-excl'>All (excl. default)</option>"
var gEndSelectTemplate = "</select>";


function update_selectors() {

	if (!gConfigStatus.init) return false;
	gConfigStatus.load_count = 0;
	// if (!gConfigStatus.init) { $('span#cf25af812a').html("invalid"); return false;}	
	var cf = gConfigStatus;
	var request_found = false;
	
	for (var i = 0; i < cf.length; i++) {
		var output_key_hash = cf[i].key;
		if (!gClientConfigStatus.refresh_all && (gClientConfigStatus.request != output_key_hash)) continue;		
		if (gClientConfigStatus.request == output_key_hash) request_found = true;
		// var selector = gSelectStart + output_key_hash + "-sel' " + gOnChange + output_key_hash + gOnChangeEnd + gDefaults;
		var selector = gSelStart + output_key_hash + gSelId + output_key_hash  + gSelOnChange + output_key_hash + gSelEnd + gDefaults;
		var transform_list = cf[i].transform_list;
		var enabled_transforms = 0;
		var user_options = "";
		for (var j=0; j < transform_list.length; j++) {
			var opt;
			var name = transform_list[j].name;
			var hash = transform_list[j].hash;
			if (transform_list[j].hash == cf[i].last && transform_list[j].enabled) {
				opt = '<option selected="selected" value="'+hash+'">' + name + '</option>';
				enabled_transforms++;
			} else if (!transform_list[j].enabled) {
				opt = '<option style="color:#999;" value="'+hash+'">&#9747; ' + name +'</option>';
			} else {
				opt = '<option value="'+hash+'">' + name +'</option>';
				enabled_transforms++;
			}
			user_options += opt;
		}
		if (enabled_transforms > 0) selector += gAllInc;
		if (enabled_transforms > 1) selector += gAllEx;
		selector += user_options;		
		selector += gEndSelectTemplate;
		$('span#'+output_key_hash).html(selector);
		$("span#"+output_key_hash+"-img").hide();
		onSelectorChange(output_key_hash);
		/// open the plugin table if any outputs/transforms are configured
		if (gClientConfigStatus.refresh_all) open_selected(output_key_hash);
	}
	if (!request_found && gClientConfigStatus.request != "none") reset_transform_selector();
	gClientConfigStatus.updated = true;	
}


function reset_transform_selector() {
	
	var output_key_hash = gClientConfigStatus.request;
	var selector = "<select name='config' class='config' id='" + output_key_hash 
	+ "'-sel disabled='disabled'><option value='default'>default transform</option></select>";
	$('span#'+output_key_hash).html(selector);
	$("span#"+output_key_hash+"-img").hide();
	var chkbox_sel = "#"+output_key_hash+"-chk";
	$(chkbox_sel).attr('disabled',false);
	$(chkbox_sel).removeAttr('disabled');
	$(chkbox_sel).attr('checked',false);
	$(chkbox_sel).removeAttr('checked');
}


/// High-level function called by config_popup event handlers (button clicks)
function update_transform_selector(output_key_hash) {
	
	gConfigStatus.init = false;
	gClientConfigStatus.load_count = 0;

	if (output_key_hash == 'all') {
		gClientConfigStatus.refresh_all = true; 
		gClientConfigStatus.request = "none";
	} else {
		gClientConfigStatus.refresh_all = false; 
		gClientConfigStatus.request = output_key_hash;
		$("span#"+output_key_hash+"-img").show();
	}
	
	setTimeout("load_config_status()",1500);
	$(".config_dialog").dialog("close");
	/// wait until the transform data is accepted and the status is updated on the server.
	
	///for TempEst; change the selected tab
	$( "#tabs" ).tabs({ selected: 3 });
}


function update_config_status(jsConfigStatus,textStatus) {
	gConfigStatus = jsConfigStatus.output_list;
	gConfigStatus.status = jsConfigStatus.config_status;
	gConfigStatus.init = true;
	if (gConfigStatus.status != 'updated') gClientConfigStatus.updated = false;
	if (!gClientConfigStatus.updated) update_selectors();
}

function load_config_status() {		

	/// Get the data from the server
	var i = gClientConfigStatus.load_count;
	gClientConfigStatus.load_count++;
	// alert(gConfigStatus.status);		
	$.getJSON("get_config_status",update_config_status);
	
	/// 1) setup polling
	if (!gConfigStatus.init || gConfigStatus.status != "updated")
	{
		gTimeOutArray[i] = setTimeout("load_config_status()", 2000); //2secs
	}
	
	/// 2) delete scheduled config loads if already updated...
	if (gConfigStatus.status == "updated")
	{
		while (gTimeOutArray.length > 0) clearTimeout(gTimeOutArray.pop());
	}
	
	/// 3) handle response timeouts
	if (!gConfigStatus.init && gClientConfigStatus.load_count > 5)
	{
		// this may happen if the server returns invalid json, or not responding at all
		window.location = "/sawa/?error_code=config_status_error";
	}		
}


function is_transform_enabled(transform_id) {

	var cf = gConfigStatus;
	// transforms such as default etc.. are always enabled
	var enabled = true;
	
	for (var i = 0; i < cf.length; i++) {
		var transform_list = cf[i].transform_list;
		for (var j=0; j < transform_list.length; j++) {			
			if (transform_id == transform_list[j].hash && !transform_list[j].enabled) enabled = false;
		}
	}
	return enabled;	
}


function onSelectorChange(selector_id) {

	var id = "#"+selector_id+"-sel option:selected";
	var chkbox_sel = "#"+selector_id+"-chk";
	var selected_transform_id = $(id).val();
	var status = is_transform_enabled(selected_transform_id);
	if (status == true) {
		$(chkbox_sel).attr('disabled',false);		
		$(chkbox_sel).removeAttr('disabled');
		$(chkbox_sel).attr('checked','checked');
	} else {
		$(chkbox_sel).attr('checked',false);
		$(chkbox_sel).removeAttr('checked');		
		$(chkbox_sel).attr('disabled','disabled');
		return;
	}
}

///			POPUP (CONFIG DIALOG) SCRIPTS 		///

function hide_rdf_content()
{
	document.getElementById("rdf_content").style.display = 'none';
	// document.getElementById("rdf_content").innerHTML = "";
	return true;
	var divh = document.getElementById('popup_content').offsetHeight;
	$(".config_dialog").dialog({ height:divh+60 });					
}

function show_rdf_content(resize)
{
    if (document.getElementById("rdf_content").style.display == 'none')
 	{
		document.getElementById("rdf_button").value = 'Update';
		document.getElementById("rdf_content").style.display = '';
		popup_div = document.getElementById("popup_content");
		var divh = document.getElementById('popup_content').offsetHeight+60;
		var winh = $(window).height();
		if (divh > winh-60) { 
			$(".config_dialog").dialog({ height:winh-20, position: 'top' });
		} else { 
			$(".config_dialog").dialog({ height:divh }); 
		}
	}
}

function show_save_as_field()
{
    if (document.getElementById("save_as_field").style.display == 'none')
 	{
		document.getElementById("save_as_field").style.display = '';
		// popup_div = document.getElementById("popup_content");
		var divh = document.getElementById('popup_content').offsetHeight;
		$(".config_dialog").dialog({ height:divh+60 });		
	}
}


///		SAWA FEATURE EXTRACTOR INITIALISER		///


function init_sawa_fe(action) {

	/// use at every page refresh
	if (action.gohash) window.location.hash='file_id';
	if (action.toggle) toggle_plugin_outputs();
	gClientConfigStatus.refresh_all = true; 
	gClientConfigStatus.request = "none";	
	load_config_status();
	// open_selected();

	$.validator.addMethod("filename",function(value,element){
			return this.optional(element) || !/[^A-Za-z0-9]/.test(value); }, 
		"Invalid character..." );

	$.validator.addMethod("reserved",function(value,element){
			return this.optional(element) || !/^default$/i.test(value); }, 
		"Invalid name..." );
		
	gDialog = config_dialog();
	
}

// $(document).ready(function(){});
