
// Determines which browser and browser version is in use and store those details. The type of browser and version
// affect various space aspects.

function setBrowser()
{
	var ie = 0;
	var version = 0;
	
	if( navigator.userAgent.indexOf( 'MSIE' ) != -1 )
	{	
		ie = 1;
		
		if( navigator.userAgent.indexOf( 'MSIE 8.0' ) != -1 )
			version = 8;
		else if( navigator.userAgent.indexOf( 'MSIE 7.0' ) != -1 )
			version = 7;
		else
			version = 6;
	}
	
	url = webRoot + '/libs/php/SetBrowser.php?IE=' + ie + '&version=' + version + '&webRoot=' + webRoot + '&' + 
		'absolutePath=' + absolutePath;
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, null, null);
}

/* Is used by the CMS to change the order of new, events, pictures etc in the database.
   It is used by the draganddrop Javascript functions. */

function updateDisplayOrder( ulListId )
{
	// Get the list items whose order can be changed.
	var list = document.getElementById( ulListId );
	var items = list.getElementsByTagName( "li" );
	var len = items.length;
	
	// Stores the new order of the items.
	var order = new Array();
		
	for( i = 0; i < len; i++ )
	{
		var html = items[i].innerHTML.toLowerCase();
		
		// Determine how to retrieve the primary key id value.
		var idxId = html.indexOf( '.php?' );
		
		if( idxId != -1 )
		{
			var idxEqual = html.indexOf( 'id=', idxId );
			
			if( idxEqual != -1 )
				idxId = idxEqual;
				
			var idxEqual = html.indexOf( '=', idxId );
			idxEqual++;
			var idxQuote = html.indexOf( '"', idxEqual );
			order.push( html.substring( idxEqual, idxQuote ) );
		}
		else
		{
			if( items[i].id.indexOf( '_' ) == -1 )
				order.push( items[i].id );
			else
			{
				var temp = items[i].id.split( '_' );
				temp[0] = temp[0].substring( 14, temp[0].length );
				
				var found = 0;
				
				for( j = 0; j < order.length; j++ )
				{
					if( order[j] == temp[0] )
						found = 1;
				}
				
				if( found == 0 )
					order.push( temp[0] );
			}
		}
	}
	
	url = webRoot + '/libs/php/UpdateDisplayOrder.php?order=' + order.join( "," ) + '&' + 'webRoot=' + 
		webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 'ulListId=' + ulListId;
  	
	callback = 
	{
     	success: function(o) 
		{
			//alert( o.responseText );
        }
  	} 
		
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

// Display the content specified of the type specified in a Shadowbox at the dimensions specified.

function openShadowbox( type, content, height, width )
{
	var options = 
	{ 
		onClose: function() { executeFunctionsOnShadowboxClose() },
		listenOverlay:	false
	};
		
	Shadowbox.init(options);
	
	Shadowbox.open({
		type:	type,
        content:	content,
		height:	height,
		width: width
    });
}

/* This function is used to delete items from the database where the items are displayed in an ordered
   list in the CMS. */

function deleteFromOrderedList( ulListId, checkboxIdName, liIdName )
{
	// Determine which item the user has chosen to delete.
	var checkBoxGrp = document.getElementsByName( checkboxIdName );
	var len = checkBoxGrp.length;
	
	var idxOfCheck = 0;
	
	for( i = 0; i < len; i++ )
	{
		if( checkBoxGrp[i].checked )
			idxOfCheck = i;
	}

	// Get a list of the items that may be removed.
	var list = document.getElementById( ulListId );
	var items = list.getElementsByTagName( "li" );
	
	// Get the details of the item to be removed, handling IE and Firefox differences.
	var html = items[idxOfCheck].innerHTML;
	
	var idxDelete = html.indexOf( checkboxIdName );
	var idxValue = html.indexOf( 'value=', idxDelete );
	var idxStartQuote = html.indexOf( '"', idxValue );
	
	// IE strips out the quote around attributes.
	if( idxStartQuote != -1 )
		idxStartQuote++;
	else
		idxStartQuote = idxValue + 6;
	
	var idxEndQuote = html.indexOf( '"', idxStartQuote );
	
	if( idxEndQuote == -1 )
		idxEndQuote = html.indexOf( '>', idxStartQuote );
		
	var temp = html.substring( idxStartQuote, idxEndQuote );
	
	var array = temp.split( ',' );
	
	// Get the different pieces of data required to delete an item.
	var id = array[0];
	var absolutePath = array[1];
	var webRoot = array[2];
	var checkBoxName = array[3];
	var tableNameToColumnName = array[4];
	var thingBeingRemoved = array[5];
	var noDataRows = array[6];
	
	// Delete the item from the database.
	var success = deleteFromDatabase( absolutePath, webRoot, checkBoxName, tableNameToColumnName,
		thingBeingRemoved, noDataRows );
	
	// Update the HTML.
	if( success == 1 || typeof( success ) == "undefined" )
	{
		liIdName += "_" + id;
		
		var child = document.getElementById( liIdName );
		var parent = child.parentNode;
		
		parent.removeChild( child );
	
		if( getNumRows( ulListId ) == 0 )
		{	
			// If no rows are left retrieve the name of the row to update and an integer value to 
			// determine whether the row should be made visible or invisible.
			var rows = noDataRows.split( '|' );
			
			for( i = 0; i < rows.length; i++ )
			{
				var rowNameToStatus = rows[i].split( '~' );
				
				if( document.getElementById( rowNameToStatus[0] ) != null )
				{
					if( rowNameToStatus[1] == "0" )
						document.getElementById( rowNameToStatus[0] ).style.display = "none";
					else
						document.getElementById( rowNameToStatus[0] ).style.display = "";
				}
			}
		}
	}
}

/*
 * Is used to update a field in the database to a specific value.
 */
 
function updateDatabase( absolutePath, webRoot, checkBoxName, tableNameToColumnName, value )
{
	var checkBoxGrp = document.getElementsByName( checkBoxName );
	
	var status = 0;
	
	if( checkBoxGrp[0].type == "checkbox" )
	{
		for( var i = 0; i < checkBoxGrp.length; i++ )
		{
			if( checkBoxGrp[i].checked && checkBoxGrp[i].value == value )
				status = 1;
		}
	}
	else if( checkBoxGrp[0].type == "radio" )
	{
		for( var i = 0; i < checkBoxGrp.length; i++ )
		{
			if( checkBoxGrp[i].checked )
				status = checkBoxGrp[i].value;
		}
	}
	
	// Again use Yahoo's Ajax Request function instead of prototype because of conflicts with the drag and
	// drop functionality.
	url = webRoot + '/libs/php/UpdateDatabase.php?tableNameToColumnName=' + tableNameToColumnName + '&' + 
		'webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath + '&' + 'status=' + status;
	
	callback = 
	{
     	failure: function(o) 
		{
			alert( 'Database Updated' );
  		}
	}
	
	transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
}

/*
 * Use Ajax to remove a database entry after double checking with the user. checkBoxName is used to identify 
 * the checkbox (along with rowReference) if the user cancels the delete and in which case the checkbox should 
 * be unchecked. tableNameToColumn is used to identify the table and the table row, thingBeingRemoved is used 
 * to customise the confirm message and noDataRows is used to make certain rows visible or invisible when 
 * there are no rows left in tableName to delete.
 */

function deleteFromDatabase( absolutePath, webRoot, checkBoxName, tableNameToColumnName, thingBeingRemoved, 
	noDataRows, headingRow )
{	
	// If the row should be deleted.
	if( confirm( "Are you sure you want to delete this " + thingBeingRemoved + "?" ))
	{
		url = webRoot + '/libs/php/DeleteFromDatabase.php?tableNameToColumnName=' + tableNameToColumnName + 
			'&' + 'webRoot=' + webRoot + '&' + 'absolutePath=' + absolutePath;
  	
		callback = 
		{
     		success: function(o) 
			{
				var table;
				var rows;
				
				// After deleting from the database remove the list item from the HTML and work out whether
				// to display the no rows message and hide the delete aspects.
				if( typeof( headingRow ) !== "undefined" )
				{
					var row = document.getElementById( headingRow );
					var start = row.rowIndex;
					var numRowsKey = headingRow.substring( 0, headingRow.indexOf( 'Row' ) + 3 );
					var numRows = getNumRows( numRowsKey );
					
					table = row.parentNode.parentNode;
					rows = table.rows;
					var len = rows.length;
					var end = -1;
	
					for( i = start; i < len; i++ )
					{
						if( rows[i].innerHTML.indexOf( '<td>&nbsp;</td>' ) != -1 && end == -1 )
							end = i;
					}
				
					if( end == -1 )
						end = len;
				
					for( i = start; i < end; i++ )
					{
						// Delete the table row from the HTML document.
						table.deleteRow( start );
					
						// Decrement the value of the variable that indicates how many rows are left in 
						// the table.
						numRows--;
					}
					
					if( numRows != 0 )
					{
						if( start != 0 )
						{
							start--;
						
							if( rows[start].innerHTML.indexOf( '<td>&nbsp;</td>' ) != -1 )
							{
								document.getElementById( 'contentRows' ).deleteRow( start );
								numRows--;
							}
						}
						else if( rows[start].innerHTML.indexOf( '<td>&nbsp;</td>' ) != -1 )
						{
							document.getElementById( 'contentRows' ).deleteRow( start );
							numRows--;
						}
						else if( start + 1 != rows.length )
						{
							start++;
						
							if( rows[start].innerHTML.indexOf( '<td>&nbsp;</td>' ) != -1 )
							{
								document.getElementById( 'contentRows' ).deleteRow( start );
								numRows--;
							}
						}
					}
				
					for( var i = 1; i < rows.length; i++ )
					{
						if( rows[i].innerHTML.indexOf( '<td>&nbsp;</td>' ) != -1 )
						{
							table.deleteRow( i );
							numRows--;
						}
					}
				
					if( numRows <= 0 )
					{
						// If no rows are left retrieve the name of the row to update and an integer value to 
						// determine whether the row should be made visible or invisible.
						var rows = noDataRows.split( '|' );
					
						for( i = 0; i < rows.length; i++ )
						{
							var rowNameToStatus = rows[i].split( '~' );
						
							if( rowNameToStatus[1] == "0" )
								document.getElementById( rowNameToStatus[0] ).style.display = "none";
							else
								document.getElementById( rowNameToStatus[0] ).style.display = "";
						}
					}
				}
				
				return( 1 );
        	}
  		} 
		
		transaction = YAHOO.util.Connect.asyncRequest('GET', url, callback, null);
	}
	else
	{
		var checkBoxGrp = document.getElementsByName( checkBoxName );
		var len = checkBoxGrp.length;
		
		for( i = 0; i < len; i++ )
		{
			if( checkBoxGrp[i].checked )
				checkBoxGrp[i].checked = false;
		}
		
		return( 0 );
	}
}

/*
 * Gets the number of rows in the database for use in the CMS index pages.
 */
 
function getNumRows( key )
{
	key = key.toLowerCase();
	
	contents = document.getElementById( key ).innerHTML.toLowerCase();
	
	var currentIdx = 0;
	var numRows = 0;
	
	var idxDelete = contents.indexOf( 'deletefromorderedlist', currentIdx );
	
	while( idxDelete != -1 )
	{
		numRows++;
		currentIdx = idxDelete;
		currentIdx++;
		idxDelete = contents.indexOf( 'deletefromorderedlist', currentIdx );
	}
	
	return( numRows );
}

/*
 * When deleting a row from a table it is sufficient just to have the id or name of the table row since
 * the table it belongs to can be found using parentNode. The removeChild function can then be used to
 * remove the table row from the table element. However, when adding rows it is necessary to identify
 * where in the table the rows should be inserted. headingRow does just this. It also explains what
 * data follows and therefore should be displayed if data exists and not if it doesn't. Once a row is
 * removed a count of the number of rows is computed and if this is zero the appendTo/header row is no
 * longer displayed. It can easily be displayed again if new data is added. The third argument to this
 * function is used to determine how many rows and left and when the header row should no longer be displayed.
 */
 
function deleteTableRow( headingRow, rowToDelete, deleteImage )
{
	var table = document.getElementById( rowToDelete ).parentNode;
	
	// Remove the row chosen by the user by navigating to the parent of the table row, the table, and then
	// using the removeChild function.
	table.removeChild( document.getElementById( rowToDelete ) );
	
	// Calculate how many rows are left following the headingRow. Each row has a delete button which
	// is a unique id but whose id has a common part for all rows belonging to the append to row.
	
	// Initially find all images on the page.
	var images = table.getElementsByTagName( 'img' );
	var len = images.length;
	
	var count = 0;
	
	for( i = 0; i < len; i++ )
	{
		// We are only interested in delete images that belong to rows related to headingRow
		if( images[i].id.indexOf( deleteImage ) != -1 )
			count++;
	}

	// If there aren't any rows hide the headingRow row so that we are not describing data that doesn't
	// exist.
	if( count == 0 )
	{
		var row = document.getElementById( headingRow );
		row.style.display = "none";
	}
}

/*
 * Delete a picture, download or link given the parent div to which each div is appended.
 */
 
function deleteDiv( divIdToRemove, headingRow )
{
	var ul = document.getElementById( divIdToRemove ).parentNode.parentNode;
	var li = document.getElementById( divIdToRemove ).parentNode;
	
	ul.removeChild( li );
	
	var listItems = ul.getElementsByTagName( 'li' );
	
	if( listItems.length == 0 )
	{
		var row = document.getElementById( headingRow );
		var table = row.parentNode;
		
		var rowIndex = row.rowIndex;
		table.deleteRow( rowIndex );
		table.deleteRow( rowIndex );
	}
}

/*
 * Completes the Javascript process of adding an image that has been cropped through the CMS.
 */
 
function addImage()
{
	// Get the details of the image just cropped.
	var innerHTML = document.getElementById( 'downloadLink' ).innerHTML;
	
	// The image details are stored in the HREF attribute
	var idxHREF = innerHTML.indexOf( 'href' );
	var start = innerHTML.indexOf( '"', idxHREF );
	start++;                  
	var end = innerHTML.indexOf( '"', start );
	
	// Add the details of this image crop to existing image crops. A user may crop many images at any one
	// time and there may be many sizes to create for a single image.
	if( document.getElementById( 'cropDetails' ).value != "" )
		document.getElementById( 'cropDetails' ).value += "|";

	document.getElementById( 'cropDetails' ).value += innerHTML.substring( start, end );
	
	// Create a new file input element.
	var newElem = document.createElement( 'input' );
	newElem.setAttribute( 'type', 'file' );
	newElem.setAttribute( 'id', currentFileIdx );
	newElem.setAttribute( 'name', currentFileIdx );
	
	// Replace the previous image element (this is needed for the file to be uploaded in PHP) with the new
	// file input element. Make sure to set the click event for the new file input element so that when the user
	// clicks the upload button it starts the crop process.
	var remElem = document.getElementById( currentFileIdx );
	remElem.parentNode.replaceChild( newElem, remElem );
	YAHOO.util.Event.on('uploadButton', 'click', uploader.carry);
	
	// Have all the image sizes be created for a single image.
	if( count != additionalCrops.length )
	{
		// No. Get the dimension details of the next image size and display the next image size image so it
		// can be cropped.
		temp = additionalCrops[count].split( '~' );
		currentFileId = temp[0];
		cropDimensions[currentFileIdx] = temp[1] + "," + temp[2];
		
		YAHOO.util.Dom.get('imageContainer').innerHTML = '<img id="yuiImg1' + '"' + ' src="' + imageDir +
			"/" + temp[3] + '" width="' + temp[4] + '" height="' + temp[5] + '" alt="" />';
	
		if( currentFileId == "thumbnail" )
			thumbnailImage = imageDir + "/" + temp[3];
			
		// Create the dotted box for the image (of the appropriate dimensions) so image cropping can take
		// place.
		photoshop.init(temp[3]); 
		photoshop.getCroppedImage();
	
		count++;
	}
	else
	{
		// Last image size for the current image has been set by the user.
		if( document.getElementById( 'imageContainerRow' ) != null )
			document.getElementById( 'imageContainerRow' ).style.display = "none";
		
		// Clear the area where cropping takes place (in preparation of another image)
		document.getElementById( 'imageContainer' ).innerHTML = "";
		
		// Reset the download link which stores the details of the last image crop.
		document.getElementById( 'downloadLink' ).innerHTML = "";
		
		// Hide the message that explains what to do to crop an image.
		if( document.getElementById( 'selectCropRow') != null )
			document.getElementById( 'selectCropRow' ).style.display = "none";
		
		// Hide the add image button until another image is uploaded.
		document.getElementById( 'addCroppedImageRow' ).style.visibility = "hidden";
		
		// Restore the crop dimensions (that have been changed as different image sizes have been created)
		// to their original values in preparation for the next image.
		cropDimensions = new Array();
		
		for( var fileIdx in originalCropDimensions )
			cropDimensions[fileIdx] = originalCropDimensions[fileIdx];
		
		// Increment the image counter.
		imageCount++;
		
		// Reset other variables ready for the next image.
		count = 0;
		additionalCrops = new Array();
		currentFileId = "picture";
		
		// Clear the single line input where the title/description of the image is input.
		if( document.getElementById( 'alt_tag' ) != null )
			document.getElementById( 'alt_tag' ).value = "";
		
		inputs = document.getElementsByTagName( 'input' );
		
		for( a = 0; a < inputs.length; a++ )
		{
			if( inputs[a].id.indexOf( 'alt_tag' ) != -1 )
				inputs[a].value = "";
		}
			
		if( document.getElementById( 'picturesToBeAdded' ) != null )
		{
			var headerRow = document.getElementById( 'picturesToBeAdded' );
			var rowIndex = headerRow.rowIndex;
			rowIndex++;
			var table = headerRow.parentNode.parentNode;
	
			// Create a new row.
			var new_row = table.insertRow( rowIndex );
		
			var column = document.createElement( 'td' );
			column.setAttribute( 'colspan', '2' );
		
			var image = document.createElement( 'img' );
		
			if( thumbnailImage == "" )
			{
				thumbnailImage = innerHTML.substring( start, end );
				start = thumbnailImage.indexOf( 'image=' ) + 6;
				end = thumbnailImage.indexOf( '&amp;', start );
				thumbnailImage = "/downloads/" + thumbnailImage.substring( start, end );
			}
		
			image.setAttribute( 'src', thumbnailImage );
		
			column.appendChild( image );
			new_row.appendChild( column );
		
			headerRow.style.display = "";
		}
		
		if( document.getElementById( 'continueButtonRow' ) != null )
			document.getElementById( 'continueButtonRow' ).style.display = "";
	}
}

// Empty a drop-down list, the id/name of which is password to this function.
function removeAllOptions( idName )
{
	selectElement = document.getElementById( idName );
	selectElement.innerHTML = "";
}

// Adds an option to the drop-down identified by the idName passed.
function addOption( idName, value, id, selected )
{
	var optn = document.createElement( "option" );
	optn.text = id;
	optn.value = value;
	
	if( selected !== undefined )
		optn.selected = true;

	if( document.getElementById( idName ) != null )
		document.getElementById( idName ).options.add(optn);
}

// Removes leading and trailing whitespace.
function trim(str, chars) 
{
	return ltrim(rtrim(str, chars), chars);
}

// Removes leading whitespace.
function ltrim(str, chars) 
{
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

// Removes trailing whitespace.
function rtrim(str, chars) 
{
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}