var $ = jQuery.noConflict();
var loc = window.history.location || window.location;

function Admin() {

	function _toggleCheckBox(name, action, value) {
		var elements = name.split('-');
		$.ajax({
			dataType: 'json',
			async: true,
			url: action + '/' + elements[1] + '/' + elements[2],
			data: {value: value},
			type: 'GET'
		}).done(function(data) {
			main.displayPage(data);
		});
	}
	
	function formatRow(d) {
		var line = '', i, j, key, value, output = '';
		var extra_data = d['data'];
/*		for(key in extra_data[0]) {
			line += '<th>' + key + '</th>';
		}
		output += '<tr class="detail-header">' + line + '</tr>'; */

		for(i = 0; i < extra_data.length; i++) {
			line = '';  j = 0;
			for(key in extra_data[i]) {
				j++;
				value = extra_data[i][key];
				if (value === null) {
					value = '&nbsp;';
				} else if (Array.isArray(value)) {		// first element is raw value, second is displayable version
					value = value[1];
				}
				line += '<td class="slidecol_' + j + '">' + value + '</td>';
			}
			output += '<tr>' + line + '</tr>';
		}
		
		return '<div class="slider">'+
			'<table cellpadding="5" cellspacing="0" border="0" style="padding-left:80px;width:calc(100% - 80px);">'+ output+
			'</table>'+
		'</div>';
	}
	
	function _locaterow(the_table, module) {
		var result = null;
		the_table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {
			var data = this.data();
			if (data.module == module) result = this;
		} );
		return result;
	}
	
	// update the extra_data structure in the database
	function _updateInternalStructure($text, module, field, value) {
		var $table = $text.closest('table.data-class');
		var phrase = 'data-field="' + field + '"';
		var the_table = $table.dataTable({'retrieve': true}).api();
		// get the row for this module
		var row = _locaterow(the_table, module);
		if (row !== null) {
			var data = row.data();
			for(var i = 0; i < data.data.length; i++) {			// rows
				if (data.data[i][1].indexOf(phrase) > -1) {		// col0 = label, col1 = data
					_updateInternalValue(data, i, value);
					row.data(data).draw();
					break;
				}
			}
		}
	}
	
	function escapeHtml(text) {
		var map = {
			'&': '&amp;',
			'<': '&lt;',
			'>': '&gt;',
			'"': '&quot;',
			"'": '&#039;'
		};

		return text.replace(/[&<>"']/g, function(m) { return map[m]; });
	}
	
	function _updateInternalValue(structure, rownum, new_value) {
		new_value = escapeHtml(new_value);
		var html = structure.data[rownum][1];
		html = html.replace(/">.*<\/b>$/, '">' + new_value + '</b>');
		structure.data[rownum][1] = html;
	}
	
	function _getTableData(value, settings) {
		var $text = $(this);
		var module = this.dataset.module;
		var field = this.dataset.field;
		if (typeof field != 'undefined') {
			_updateInternalStructure($text, module, field, value);
		}
		var action = $text.attr('href');
		$.ajax({
			dataType: 'json',
			async: true,
			url: action,
			data: {value: value},
			type: 'GET'
		}).done(function(data) {
			main.displayPage(data);
		});
		return value;
	}
	
	function _dropFile(event, $target) {
		event.stopPropagation();
		event.preventDefault();
		var evt = event.originalEvent;

		var files = evt.dataTransfer.files;
		var reader = new FileReader();  
		reader.onload = function(event) {            
			$target.val(event.target.result);
		}        
		reader.readAsText(files[0],'UTF-8');
	}

	
	$(document).on('loaded.datatables', function(event, $table) {
		$('.inline-edit', $table).each(function() {
			var $element = $(this);
			var type = this.dataset.type;
			switch(type) {
				case 'select':
					$element.editable(_getTableData,{ 
						data: jQuery.parseJSON(this.dataset.select),
						type: 'select',
						tooltip: "Click to edit...",
						cssclass: 'inline-editing',
						style: "inherit",
						callback: function (value, settings) { 
							$(this).html(settings.data[value]);
						}
					});
					break;
				default:
					$element.editable(_getTableData,{ 
						tooltip: "Click to edit...",
						cssclass: 'inline-editing',
						style: "inherit"
					});
				
			}
		});

		try {
			var the_table = $table.dataTable({'retrieve': true}).api();
			var json = the_table.ajax.json();
			if (typeof json.errors != 'undefined') main.displayErrors(json.errors);
		} catch (e) {
		}

/*	}).on('loaded.template', function(event, data) {
		if (typeof data.datatable != 'undefined') {
			_renderDataTables(data);
		} */

	// an addon is being enabled or disabled
	// or a setting within the addon is being checked
	}).on('click', 'table.monitor-checkbox input.checkbox-edit', function(event) {
		var $checkbox = $(this);
		var $table = $checkbox.closest('table');
		var href = $table.attr('href');
		var name = $checkbox.attr('name');
		_toggleCheckBox(name, href, this.checked ? $checkbox.val() : 0);
		
	}).on('click', 'table.monitor-checkbox input.checkbox-input', function(event) {
		var $checkbox = $(this);
		var href = $checkbox.attr('href');
		var value = $checkbox.prop('checked') ? 1 : 0;
		$.ajax({
			dataType: 'json',
			async: true,
			url: href,
			data: {value: value},
			type: 'GET'
		}).done(function(data) {
			main.displayPage(data);
		});
		
	}).on('click', 'td.details-control', function () {
		var $table = $(this).closest('table');
		var the_table = $table.dataTable({'retrieve': true}).api();
		var tr = $(this).closest('tr');
		var row = the_table.row( tr );
 
		if ( row.child.isShown() ) {
			// This row is already open - close it
			$('div.slider', row.child()).slideUp( function () {
				row.child.hide();
				tr.removeClass('shown');
			} );
		} else {
			// Open this row
			var x = row.child( formatRow(row.data()), 'no-padding' );
			var y = row.child();
			$(document).triggerHandler('loaded.datatables', y);		// add the inline editor
			x.show();
			tr.addClass('shown');
			$('div.slider', row.child()).slideDown();
		}
	}).on('dragover', '.filedrop', function(e) {
		e.stopPropagation();
		e.preventDefault();
		e.originalEvent.dataTransfer.dropEffect = 'copy';

	}).on('drop', '.filedrop', function(e) {
		_dropFile(e, $(this));
	});
}

admin = new Admin();
