function getTab()
{
	var sel = config.selectedTab?config.selectedTab:config.metadata.table;
	return config.metatab[sel];
}

function selectTab(tab)
{
	config.selectedTab = tab;
	render();
}

function load(data)
{
	config.metadata = data;
	config.metatab = new Array();
	var table = new Array();
	config.metatab[data.table] = table;
	for(dnam in data.columns)
	{
		var dval = data.columns[dnam];
		dspl = dnam.split(".");
		if(dspl.length > 1)
		{
			var ctab = dspl[0];
			var pname = dspl[1];
			if(config.metatab[ctab])
				config.metatab[ctab][pname] = dnam;
			else
			{
				var ctable = new Array();
				ctable[pname] = dnam;
				config.metatab[ctab] = ctable;
			}
		}
		else
			table[dnam] = dnam;
	}

	render();
}

function render()
{
	var html = template.process(config);
	$(".preference").html(html);


	$(".gbi").draggable();
	$(".mei").draggable();
	$(".fi").draggable();

	$(".row-fields").droppable({drop: function(ev, ui){addField(config.groupby, ui);}});
	$(".data-fields").droppable({drop: function(ev, ui){addField(config.measures, ui);}});
	$(".fields").droppable({drop: delField});

	$('.gbi').dblclick(function(){showProperties(this, tGroupby)});
	$('.mei').dblclick(function(){showProperties(this, tMeasure)});
	$('.filter').dblclick(function(){showProperties(this, tFilter)});

}

function showProperties(div, tmpl)
{
	if(tmpl.name == 'reportFilter')
		config.selected = div.id;
	else
		config.selected = $(div).html().trim();
	var html = tmpl.process(config);
	var propWindow = window.open("", "DataField"+config.selected, "toolbar=no,menubar=no,location=no,status=no,width=480,height=300");
	propWindow.document.open();
	propWindow.document.write(html);
	propWindow.document.close();
}

function addField(ns, ui)
{
	var pname = ui.draggable.html().trim();
	if(ns == config.measures)
		ns[pname] = {op:"count"};
	else
		ns[pname] = {};
	setTimeout(render, 100);
}

function delField(event, ui)
{
	var pname = ui.draggable.html().trim();
	if(config.groupby[pname])
		delete config.groupby[pname];
	else if(config.measures[pname])
		delete config.measures[pname];
	setTimeout(render, 100);
}

function setProperty(frm, win, configType)
{
	var elems = $(frm.elements).serializeArray();
	var dict = {};
	var name;
	for(var i = 0; i < elems.length; i++)
	{
		var elem = elems[i];
		if(elem.value == null || elem.value == ""){
		}
		else if(elem.name == "name"){
			name = elem.value;
		}
		else if(elem.name == "hide" && elem.value=="on"){
			dict[elem.name] = 1;
		}
		else
			dict[elem.name] = elem.value;
	}
	config[configType][name] = dict
	win.close();
}

function saveConfig()
{
	if (config.reportPrefMetadataId)
	{
		if(config.preferenceId){
			sendConfig(config.preferenceId);
		}
		else
		{
			$.ajax({
			  url: "/"+config.applicationId+"/1/"+config.reportPrefMetadataId+"/"+config.reprotPrefStartActivityId+"/"+config.reportPrefMetadataId+"?mimetype=application/json&SheetId="+config.reportId+"&PreferenceId="+config.reportId,
			  type: "POST",
			  dataType: "json",
			  data: {},
			  success: function(data){
				sendConfig(config.reportId);
			  },
			  error: function(){
				alert("Save failed!");
			  }
			});
		}
	}
	else{
		alert("Model ReportPreference is not present in this application")
	}

}

function removeConfig()
{
	if (config.reportPrefMetadataId)
	{
			$.ajax({
			  url: "/"+config.applicationId+"/1/"+config.reportPrefMetadataId+"/"+config.reprotPrefStartActivityId+"/"+config.reportPrefMetadataId+"/"+config.reportId,
			  type: "DELETE",
			  dataType: "json",
			  data: {},
			  success: function(data){
				window.opener.location.reload();
	  			self.close();
			  },
			  error: function(){
				alert("Error Deleting Configuration!");
			  }
			});
	}
	else{
		alert("Model ReportPreference is not present in this application")
	}
}

function sendConfig(id)
{
	var inputGraph = {}
	inputGraph["GroupBy"] = JSON.stringify(config.groupby);
	//if(!config.measures["SheetId"]) config.measures["SheetId"] = {type:"Text", op:"count", hide:true};
	inputGraph["Measures"] = JSON.stringify(config.measures);
	inputGraph["Chart"] = JSON.stringify(config.chart);
	inputGraph["Theme"] = config.theme?config.theme:"light";
	inputGraph["Filter"] = JSON.stringify(config.filter);
	var dimensions = [];
	for(var gb in config.groupby)
		dimensions.push(gb);
	var measures = [];
	var operations = [];
	for(var mea in config.measures)
	{
		measures.push(mea);
		operations.push(config.measures[mea].op);
	}
	inputGraph["Url"] = "./"+config.reportId+"/aggregate?dimensions="+JSON.stringify(dimensions)
				+"&measures="+JSON.stringify(measures)+"&operations="+JSON.stringify(operations);
	inputGraph["SheetMetadataId"] = config.reportPrefMetadataId

	var updateGraph = {"update": {}}
	updateGraph["update"][id] = inputGraph
	var updateJson = JSON.stringify(updateGraph);

	$.ajax({
	  url: "/"+config.applicationId+"/1/"+config.reportPrefMetadataId+"/"+config.reprotPrefStartActivityId+"/"+config.reportPrefMetadataId+"/"+id+"?action=invoke&invoke=orangescape.model.server.services.runtime.invoke&method=batchUpdate",
	  type: "POST",
	  dataType: "json",
	  data: {batchJson: updateJson},
	  success: function(){
	  	//alert("Save successful!");
	  	window.opener.location.reload();
	  	self.close();
	  },
	  error: function(){
	  	alert("Save failed!");
	  }
	});
}

function getFilterConfig()
{
	var filterPref = config.metadata.filter;
	for(var filter in config.filter)
	{
		filterPref[filter].DisplayValue = config.filter[filter].display;
	}
	return filterPref;
}

function getOperations()
{
	return {sum:"Sum",count:"Count",avg:"Average",max:"Max",min:"Min"}
}

function keys(obj)
{
    var keys = [];
    for(var key in obj)
    {
        keys.push(key);
    }
    return keys;
}

function getCharts()
{
	return {
"Column2D" : 1,
"Column3D" : 1,
"Bar2D" : 1,
"Line" : 1,
"Area2D" : 1,
"Pie2D" : 1,
"Pie3D" : 1,
"Doughnut2D" : 1,
"Doughnut3D" : 1,
"Pareto2D" : 1,
"Pareto3D" : 1,

"Marimekko" : 2,
"MSArea" : 2,
"MSBar2D" : 2,
"MSBar3D" : 2,
"MSColumn2D" : 2,
"MSColumn3D" : 2,
"MSColumn3DLineDY" : 2,
"MSColumnLine3D" : 2,
"MSCombi2D" : 2,
"MSCombi3D" : 2,
"MSCombiDY2D" : 2,
"MSLine" : 2,
"MSStackedColumn2D" : 2,
"MSStackedColumn2DLineDY" : 2,
"Scatter" : 2,
"ScrollArea2D" : 2,
"ScrollColumn2D" : 2,
"ScrollCombi2D" : 2,
"ScrollCombiDY2D" : 2,
"ScrollLine2D" : 2,
"ScrollStackedColumn2D" : 2,
"SSGrid" : 2,
"StackedArea2D" : 2,
"StackedBar2D" : 2,
"StackedBar3D" : 2,
"StackedColumn2D" : 2,
"StackedColumn2DLine" : 2,
"StackedColumn3D" : 2,
"StackedColumn3DLine" : 2,
"StackedColumn3DLineDY" : 2
	};
}