/**
 * 
 * 
 * ---------------------------------------------------------------------------
 * 
 * Copyright (C) 2007 Omnium Research Group
 * 
 * ---------------------------------------------------------------------------
 * 
 * LICENSE:
 * 
 * This file is part of Omnium(R) Software.
 * 
 * Omnium(R) Software is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * Omnium(R) Software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Omnium(R) Software; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * ---------------------------------------------------------------------------
 * 
 * @author    Sam Bauers <sam@omnium.net.au>
 * @copyright 2007 Omnium Research Group
 * @license   http://www.gnu.org/licenses/gpl.txt GNU GPL v2
 * @link      http://open.omnium.net.au Omnium Open
 **/


// omVars is a key->value hash object that allows for variable passing across the application,
// and is also a handy way of passing PHP variables to Javascript
var omVars = new Object;

function omVarsRegister(pairs)
{
	omVars = $H(omVars).update(pairs);
}

// Checks or unchecks all checkboxes in a group
function checkAll(checkContainer, checkAction, checkClass)
{
	$(checkContainer).select('input.' + checkClass).each(
		function (checkObj) { checkObj.checked = checkAction; }
	);
}

// A nice omAlert which confirms the deleting of an item
function confirmDelete(deleteLink)
{
	Alert.fire(
		omVars.get('alertDeleteConfirm'),
		'alert_logo.png',
		omVars.get('alertOK'),
		false,
		deleteLink,
		omVars.get('alertCancel')
	);
	return false;
}

// Open contextual help
function openHelp(topic, moduleId)
{
	window.open(omVars.get('url') + 'base/help.php?topic=' + topic + '&id_modules=' + moduleId, 'helpWindow', 'width=640,height=500,resizable=yes,toolbar=no,scrollbars=yes');
}


// Open admin window
function openAdministration()
{
	window.open(omVars.get('url') + 'administration/adminUpdate.php?redirect=1', 'adminWindow', 'width=680,height=500,resizable=yes,toolbar=no,scrollbars=yes');
}


// Open file viewer
function openView(url, unique)
{
	window.open(url, 'viewWindow_' + unique, 'width=160,height=160,dependent=yes,resizable=yes,toolbar=no,scrollbars=no,status=no');
}


// Control file viewer navigation
function navigateView(current)
{
	['File','Info'].each(
		function(view)
		{
			if ($('omViewNavigation' + view)) {
				$('omView' + view).hide();
				$('omViewNavigation' + view).removeClassName('on');
			}
		}
	);
	
	$('omView' + current).show();
	$('omViewNavigation' + current).addClassName('on');
}


function subscriptionProcess(action, module, id, team, feature, user)
{
	var args = 'action=' + encodeURIComponent(action);
	args += '&module_id=' + encodeURIComponent(module);
	args += '&entry_id=' + encodeURIComponent(id);
	args += '&id_teams=' + encodeURIComponent(team);
	args += '&feature=' + encodeURIComponent(feature);
	args += '&id_users=' + encodeURIComponent(user);
	var opt = {
		method:'post',
		postBody:args,
		onSuccess:subscriptionHandler,
		onFailure:function (t) {
			Alert.fire(alertError, 'subscription_logo.png');
		}
	}
	new Ajax.Request(omVars.get('url') + 'base/subscribe.ajax.php', opt);
}


function subscriptionHandler(response, json)
{
	switch (json.result) {
		case ('subscribe'):
			$('subscriptionLink').update(omVars.get('subsLinkUnsubscribe'));
			$('subscriptionLink').onclick = function () {
				subscriptionProcess(
					'unsubscribe',
					omVars.get('subsActiveModuleId'),
					omVars.get('subsEntryId'),
					omVars.get('subsTeamId'),
					omVars.get('subsFeature'),
					omVars.get('subsUserId')
				);
			}
			Alert.fire(omVars.get('subsAlertSubscribe'), 'subscription_logo.png');
			break;
		case ('unsubscribe'):
			$('subscriptionLink').update(omVars.get('subsLinkSubscribe'));
			$('subscriptionLink').onclick = function () {
				subscriptionProcess(
					'subscribe',
					omVars.get('subsActiveModuleId'),
					omVars.get('subsEntryId'),
					omVars.get('subsTeamId'),
					omVars.get('subsFeature'),
					omVars.get('subsUserId')
				);
			}
			Alert.fire(omVars.get('subsAlertUnsubscribe'), 'subscription_logo.png');
			break;
		case ('error'):
			Alert.fire(omVars.get('subsAlertError'), 'subscription_logo.png');
			break;
	}
}

// Deprecation Layer
function toggleFolderEditor(folderNameId, folderEditorId) {
	inplaceEditor = $(folderEditorId + '-inplaceeditor');
	if (!inplaceEditor) {
		$(folderNameId, folderEditorId).invoke('toggle');
	}
}

// Deprecation Layer
function deleteFolder(folderId) {
	omVars.set('chatInvite', false);
	Alert.fire(
		omVars.get('deleteAlertText'),
		false,
		false,
		false,
		'deleteHandler(' + folderId + ');',
		omVars.get('alertCancel'),
		false,
		'omVars.set(\'chatInvite\', true);'
	);
	$('folderOption' + folderId).remove();
}

// Deprecation Layer
function deleteHandler(folderId) {
	selectObj = $('folderSelect');
	chosenAction = selectObj.options[selectObj.options.selectedIndex].value;
	var params = 'id_folder=' + folderId;
	params += '&action=' + chosenAction;
	var opt = {
		parameters: params,
		onSuccess: function(t) {
			if (t.responseText == 'false') {
				window.location = 'index.php';
			} else {
				Alert.fire(t.responseText);
			}
		}
	}
	new Ajax.Request('index.deleteFolder.ajax.php', opt);
}

// Inserts a string into a specified textarea
// This is based on phpMyAdmin insertValueQuery() function
function insertText(textStr, textareaID) {
	
	// Initialise the textarea and form objects to be used
	textareaObj = $(textareaID);
	
	if (document.selection) {
		
		// IE Support
		
		textareaObj.focus();
		sel = document.selection.createRange();
		sel.text = textStr;
		
	} else if (textareaObj.selectionStart || textareaObj.selectionStart == "0") {
		
		// MOZILLA, NETSCAPE, SAFARI SUPPORT
		
		// Get the start and end positions of the selection
		var startPos = textareaObj.selectionStart;
		var endPos = textareaObj.selectionEnd;
		// Get the complete value of the textarea
		var textareaValue = textareaObj.value;
		
		// Test for leading space
		regex = new RegExp("\\S");
		match = regex.exec(textareaValue.substring(startPos - 1, startPos));
		if (match) {
			textStr = " " + textStr;
		}
		match = regex.exec(textareaValue.substring(startPos, startPos + 1));
		if (match) {
			textStr = textStr + " ";
		}
		
		// Replace the selection with the new text
		textareaObj.value = textareaValue.substring(0, startPos) + textStr + textareaValue.substring(endPos, textareaValue.length);
		
	} else {
		textareaObj.value += textStr;
	}
	
	// Get the caret position
	startPos = textareaObj.selectionStart;
	var newPos = startPos + textStr.length;
	
	// Set the position of the caret to after the inserted string
	if (textareaObj.setSelectionRange) {
		
		// Focus the textarea object
		textareaObj.focus();
		textareaObj.setSelectionRange(newPos, newPos);
		
	}
	
	return false;
}


// Loads thumbnail images in the specifed container object
// Requires a pre-defined array of image URIs called omThumbMap to replace the blanks
function loadThumbs(containerID, rowSelector, clipped, multiDimensional)
{
	// Get the DOM object from the ID
	var containerObj = $(containerID);
	
	// Get the rows specified by the selector, this should be any row that contributes
	// to the cumulative height of all rows or contains a thumbnail
	var containerRows = containerObj.select(rowSelector);
	
	// If we only want to load the thumbs that are within the height of the container
	if (clipped) {
		// Get the container's height
		var containerHeight = containerObj.getHeight();
	}
	
	// Check if we are dealing with a multi dimensional thumb map
	if (multiDimensional) {
		// Get the id number of the toggle to retrieve from the array
		var idNum = containerID.split('_')[1];
	}

	if (clipped) {
		// Initialise the cumulative height
		var cumulativeHeight = 0;
	}
	// Start the image counter at zero
	var imageCounter = 0;
	
	// Loop through the rows
	containerRows.each(
		function (row)
		{
			// Increment the cumlative height by the height of the row
			if (clipped) {
				cumulativeHeight += row.getHeight();
			}
			// Loop through all omThumbs contained within the row container
			row.select('.omThumb').each(
				function (thumbDiv)
				{
					// Get the image contained within the omThumb and set its source to the relevant entry in omThumbMap
					if (idNum) {
						$(thumbDiv).down('img').src = omThumbMap[idNum][imageCounter];
					} else {
						$(thumbDiv).down('img').src = omThumbMap[imageCounter];
					}
					// Increment the image counter to keep up with omThumbMap
					imageCounter++;
				}
			);
			
			if (clipped) {
				// If the combined height of the rows is more than the containers height
				if (cumulativeHeight > containerHeight) {
					// Stop processing
					throw $break;
				}
			}
		}
	);
}
