﻿var historyObject = new Array();
var historyCounter = 0;
var trackHistory = false;
var javascript = '';

function displayInfo(info)
{
	javascript = '';
	var i = 0;
	while(info[i] != null)
	{
		//alert(info[i].layer_id);
		if(info[i].where == 'innerHTML')
			$(info[i].layer_id).innerHTML = info[i].value;
		else if(info[i].where == 'remove')
			$(info[i].layer_id).remove();
		else if(info[i].where == 'append')
			$(info[i].layer_id).insert(info[i].value);
		else if(info[i].where == 'value')
			$(info[i].layer_id).value = info[i].value;
		else if(info[i].where == 'javascript')
		{
			eval(info[i].value);
			if(trackHistory != null && trackHistory)
			{
				javascript += info[i].value+"\n";
			}
		}
		i = i + 1;
	}
	if($('ajaxLoader1') != null)
	{
		$('ajaxLoader1').setStyle('display: none;');
	}
}

function toLocEditor(action,info)
{
	if($('ajaxLoader1') != null)
	{
		$('ajaxLoader1').setStyle('display: inline;');
	}
	
	var data = new Object();
	data.action = action;
	data.info = info;
	var json = encodeURIComponent(Object.toJSON(data));
	
	new Ajax.Request(ajaxUrl,
	{
		method:'post',
		parameters: 'json='+json,
		onSuccess: 
		function(transport)
		{
			if(transport.responseText.isJSON()) {
				//alert(transport.responseText);
				displayInfo(transport.responseText.evalJSON(true));
				if(trackHistory != null && trackHistory)
				{
					setTimeout("storeHistory();",100);
				}
			}
			else {
				var respText = transport.responseText.replace(/<br \/>/g, '\n');
				alert('There was a problem with the response text\n\n' + respText.replace(/<br>/g, '\n'));	
			}
		},
		onFailure: function(){ alert('Something went wrong...') }
	});
}

function storeHistory()
{
	var index = historyObject.length;
	if((historyCounter + 1) < index)
	{
		index = historyCounter + 1;
	}
	historyObject[index] = new Object();
	historyObject[index].historyHtml = $('historyContainer').innerHTML;
	historyObject[index].javascript = javascript;
	
	
	// Unset all future history entries
	var minValue = index + 1;
	var maxValue = historyObject.length - 1;
	
	while(minValue <= maxValue)
	{
		if(delete historyObject[minValue])
		{
			historyObject.length--;
		}
		minValue++;
	}
	
	historyCounter = index;
	updateHistoryButtons();
}	

function backButtonPressed()
{
	historyCounter--;
	$('historyContainer').innerHTML = historyObject[historyCounter].historyHtml;
	eval(historyObject[historyCounter].javascript);
	updateHistoryButtons();
}

function forwardButtonPressed()
{
	historyCounter++;
	$('historyContainer').innerHTML = historyObject[historyCounter].historyHtml;
	eval(historyObject[historyCounter].javascript);
	updateHistoryButtons();
}

function updateHistoryButtons(disableForward)
{
	var backDisabled = '';
	var forwardDisabled = '';
	if(historyCounter == 0)
	{
		backDisabled = 'disabled="disabled"';
	}
	if((historyCounter + 1) >= historyObject.length)
	{
		forwardDisabled = 'disabled="disabled"';		
	}
	var navButtonHtml = '<button onclick="backButtonPressed();" ' + backDisabled + '>Back</button>&nbsp;<button onclick="forwardButtonPressed();" ' + forwardDisabled + '>Forward</button>';
	$('historyButtonsLayer').innerHTML = navButtonHtml;
}

function handleSearch()
{
	var info = $('searchString').value;	
	toLocEditor('handle_search',info);
}

function clearSearch()
{
	$('searchString').value = '';	
	toLocEditor('handle_search','');
}

function confirmDeleteRow(id)
{
	if(confirm('Confirmer la suppression ?'))
	{
		toLocEditor('delete_row',id);	
	}
}

function aide(id)
{
	
	alert(id);

}

function updateRow(id)
{
	var info = new Object();
	info['old_primary_key_value'] = id;
	var formElem = document.getElementById('editRowForm');
	for(i=0; i < formElem.elements.length; i++)
	{
		var inputId = formElem.elements[i].id;
		info[inputId] = $(inputId).value;
	}
	toLocEditor('update_row',info);
}

function addRow()
{
	var info = new Object();
	var formElem = document.getElementById('addRowForm');
	for(i=0; i < formElem.elements.length; i++)
	{
		var inputId = formElem.elements[i].id;
		info[inputId] = $(inputId).value;
	}
	toLocEditor('insert_row',info);
}

function enterPressed(e)
{
	var characterCode;
	if(e && e.which){           // NN4 specific code
		e = e
		characterCode = e.which
	}
	else {
		e = event
		characterCode = e.keyCode // IE specific code
	}
	if (characterCode == 13) 
		return true   // Enter key is 13
	else 
		return false
}

function handleAdvancedSearch(numSearches)
{
	var i;
	var info = new Object();
	for(i = 0; i < numSearches; i++)
	{
		info[i] = new Object();
		info[i]['cols'] = $('as_cols_' + i).value;
		info[i]['opts'] = $('as_opts_' + i).value;
		info[i]['strs'] = $('as_strs_' + i).value;
	}
	toLocEditor('advanced_search',info);
}

function selectCbs(checkVar,table)
{
	if(checkVar == 'all')
	{
		for(i=0; i < $(table + '_table_form').elements.length; i++)
		{
			var checkbox = document.forms[0].elements[i];
			checkbox.checked = true;
			changeRowStyle(checkbox);
		}
		$('select_cb_link').innerHTML = '<a href="javascript: selectCbs(\'none\',\''+table+'\');">None</a>';
	}
	else
	{
		for(i=0; i < $(table + '_table_form').elements.length; i++)
		{
			var checkbox = document.forms[0].elements[i];
			checkbox.checked = false;
			changeRowStyle(checkbox);
		}
		$('select_cb_link').innerHTML = '<a href="javascript: selectCbs(\'all\',\''+table+'\');">All</a>';
	}
}

function changeRowStyle(cb)
{
	var idParts = cb.id.split('_');
	var id = idParts[1];
	if(cb.checked)
	{
		var row = $('row_' + id);
		row.setStyle('background-color: #fcffd0;');
	}
	else
	{
		var row = $('row_' + id);
		var oldColor = row.getAttribute("bgcolor");
		row.setStyle('background-color: ' + oldColor + ';');
	}
}

function checkBoxClicked(cb)
{
	var idParts = cb.id.split('_');
	var id = idParts[1];
	if(cb.checked)
	{
		cb.checked = false;
	}
	else
	{
		cb.checked = true;
	}
}

function cellClicked(id)
{
	var cb = $('cb_' + id);
	if(cb.checked)
	{
		cb.checked = false;
	}
	else
	{
		cb.checked = true
	}
	changeRowStyle(cb);
}

function userButtonClicked(table,buttonKey,confirmMsg)
{
	var info = new Object();
	info['buttonKey'] = buttonKey;
	info['checkboxes'] = new Object();
	var numRows = 0;
	for(i=0; i < $(table + '_table_form').elements.length; i++)
	{
		var cb = document.forms[0].elements[i];
		if(cb.checked)
		{
			var idParts = cb.id.split('_');
			var id = idParts[1];
			info['checkboxes'][i] = id;
			numRows++;
		}
	}
	if(numRows == 0)
	{
		alert('Sélectionnez une rangée.');	
	}
	else if(confirmMsg.length > 0)
	{
		if(confirm(confirmMsg))
		{
			toLocEditor('user_button_clicked',info);
		}
	}
	else
	{
		toLocEditor('user_button_clicked',info);		
	}
}

function userIconClicked(action,info,confirmMsg)
{
	if(confirmMsg.length > 0)
	{
		if(confirm(confirmMsg))
		{
			toLocEditor(action,info);
		}
	}
	else
	{
		toLocEditor(action,info);		
	}
}

function editCopyViewDelete(table,action)
{
	var info = new Object();
	var numRows = 0;
	var selectedIndex;
	for(i=0; i < $(table + '_table_form').elements.length; i++)
	{
		var cb = document.forms[0].elements[i];
		if(cb.checked)
		{
			var idParts = cb.id.split('_');
			var id = idParts[1];
			info[i] = id;
			selectedIndex = i;
			numRows++;
		}
	}
	if(numRows == 0)
	{
		alert('Please select a row.');	
	}
	else
	{
		if(action == 'edit_row')
		{
			if(numRows == 1)
			{
				toLocEditor(action,info[selectedIndex]);
			}
			else
			{
				alert('You can only edit 1 row at a time.');	
			}
		}
		else if(action == 'view_row')
		{
			if(numRows == 1)
			{
				toLocEditor(action,info[selectedIndex]);
			}
			else
			{
				alert('You can only view 1 row at a time.');	
			}
		}
		else if(action == 'delete_mult_rows')
		{
			var confirmMsg;
			if(numRows == 1)
			{
				confirmMsg = 'Are you sure you would like to delete this row?';
			}
			else
			{
				confirmMsg = 'Are you sure you would like to delete these ' + numRows + ' rows?';
			}
			if(confirm(confirmMsg))
			{
				toLocEditor(action,info);
			}
		}
		else if(action == 'copy_mult_rows')
		{
			if(numRows == 1)
			{
				toLocEditor('copy_row',info[selectedIndex]);
			}
			else if(confirm('Are you sure you would like to copy these ' + numRows + ' rows?'))
			{
				toLocEditor(action,info);
			}
		}
	}
}

function formatDate(dateStr,dateFormat)
{
	var date = new Date(dateStr.substring(0,4),dateStr.substring(5,7) - 1,dateStr.substring(8,10),dateStr.substring(11,13),dateStr.substring(14,16),dateStr.substring(17,19));
	info = new Object();
	info["disp_date"] = date.print(dateFormat);
	info["php_date"] = dateStr;
	info["js_date"] = date;
	return info;
}

function prepareForCalendar(input,id,dateFormat,extraInfo)
{
	//alert(dateFormat);
	if(input)
	{
		if(extraInfo == null) { extraInfo = ''; }
		input.id = id;
		var phpDate = '';
		var dispDate = 'Pas de date';
		var jsDate = new Date();
		var result = input.value.search(/0000-00-00/);

		if(result == -1 && input.value.length > 0)
		{
			dateInfo = formatDate(input.value,dateFormat);
			dispDate = dateInfo["disp_date"];
			jsDate = dateInfo["js_date"];
			phpDate = dateInfo["php_date"];
		}
		var container = input.parentNode;
		container.innerHTML = '<span id="show_'+id+'">'+dispDate+'</span><img src="js/jscalendar/img.gif" id="trigger_'+id+'" style="cursor: pointer; border: 1px solid red; margin: 0 3px 0 3px;" title="Sélection date" onMouseOver="this.style.background=\'red\';" onmouseout="this.style.background=\'\'" />'+extraInfo+'<input type="hidden" name="'+id+'" id="'+id+'" value="'+phpDate+'" />';
		Calendar.setup({
			inputField     :    id,     // id of the input field
			ifFormat       :    "%Y-%m-%d %H:%M:%S",     // format of the input field (even if hidden, this format will be honored)
			displayArea    :    "show_"+id,       // ID of the span where the date is to be shown
			daFormat       :    dateFormat,     // format of the displayed date
			button         :    "trigger_"+id,  // trigger button (well, IMG in our case)
			align          :    "Tl",
			date           :    jsDate,
			singleClick    :    true,		
			weekNumbers    :    false
		});			
	}
}

function resetScrollTop()
{
	document.documentElement.scrollTop = 0;
	document.body.scrollTop = 0;
}