var DIV_FILE_LISTING_CONTAINER = 'mwfFileListingContainer';
var DIV_FILE_ACTION_FORMS = 'mwfFileActionForms';

/*
* PUBLIC FILE ACTION FUNCTIONS
*/
function printFileActionOptions( isDir ){
	code = '';
	for( actionId = 1; actionId < fileActions.length; actionId++ ){
		onDir = fileActions[ actionId ][ 2 ];
		if( (! isDir) || onDir ){
			actionTitle = fileActions[ actionId ][ 0 ];
			code += '<OPTION VALUE="' + actionId + '">' + actionTitle + '</OPTION>';
			}
		}
	document.write( code );
	}

function fileActionCode( actionId ){
	actionId = arguments[ 0 ];
	if( arguments.length > 1 )
		selectedFileName = arguments[ 1 ];

	code = '';
	fileNamePlaceHolder = '_selectedFileName_';

	if( actionId > 0 ){
		code = fileActions[ actionId ][ 1 ];

		position = code.lastIndexOf(fileNamePlaceHolder);
		while( position > -1 ){
			code = code.slice( 0, position ) + selectedFileName + code.slice( position + fileNamePlaceHolder.length )
			position = code.lastIndexOf(fileNamePlaceHolder);
			}
		}
	return code;
	}

//showActionForm
function shaf( formId, fileListId, errorNoteId ){
	var ok = true;

	if( fileListId ){
		filesArray = _getSelectedFiles();
		if( filesArray.length > 0 ){
			fileList = new myDiv( fileListId );
			fileList.setContent( _buildSelectedFilesListHTML(filesArray) );
			}
		else {
			ok = false;
			}
		}

	// HIDE FILE LISTING CONTAINER
	_hideElement( DIV_FILE_LISTING_CONTAINER );

	// NOW SHOW THE ELEMENT
	if( ok )
		_showElement( formId );
	else
		_showElement( errorNoteId );

	return ok;
	}

function downloadAction( errorNoteId ){
	var ok = false;

	filesArray = _getSelectedFiles();
	if( filesArray.length > 0 )
		ok = true;

	// SHOW THE ERROR
	if( ! ok ){
		// HIDE FILE LISTING CONTAINER
		_hideElement( DIV_FILE_LISTING_CONTAINER );

		_showElement( errorNoteId );
		}

	return ok;
	}

//hideActionForm
function hdaf( formId, fileListId ){
	if( fileListId ){
		fileList = new myDiv( fileListId );
		fileList.setContent( '' );
		}

	_hideElement( formId );

	// SHOW FILE LISTING CONTAINER
	_showElement( DIV_FILE_LISTING_CONTAINER );

	return true;
	}

//setFileCheckbox
function sfc( ctl, selectTrue ){
	ctl.checked = selectTrue;
	return true;
	}

//setAllFileCheckboxes
function safc( selectTrue ){
	filesCheckboxes = _getFilesCheckboxes();
	for( i = 0; i < filesCheckboxes.length; i++ ){
		el = filesCheckboxes[ i ];
		sfc( el, selectTrue )
		}
	return true;
	}

//setControlValue
function scv( ctl, val ){
	ctl.value = val;
	return true;
	}

function countSelectedItems(){
	filesArray = _getSelectedFiles();
	return filesArray.length;
	}

/*
* PRIVATE FILE ACTION FUNCTIONS
*/
function _showElement( elementId ){
	var thisElement = new myDiv( elementId );
	if( thisElement )
		thisElement.show();
	return true;
	}

function _hideElement( elementId ){
	var thisElement = new myDiv( elementId );
	if( thisElement )
		thisElement.hide();
	return true;
	}

function _getFilesCheckboxes(){
	checkboxes = new Array();

	thisForms = document.forms;
	for( i = 0; i < thisForms.length; i++ ){
		thisElements = thisForms[ i ].elements;
		for( j = 0; j < thisElements.length; j++ ){
			el = thisElements[ j ];
			if( el.type == "checkbox" && el.name == CHNDL_FILE_NAME )
				checkboxes.push( el );
			}
		}
	return checkboxes;
	}

function _getSelectedFiles(){
	selectedFiles = new Array();

	filesCheckboxes = _getFilesCheckboxes();
	for( i = 0; i < filesCheckboxes.length; i++ ){
		el = filesCheckboxes[ i ];
		if( el.checked )
			selectedFiles.push( el.value );
		}
	return selectedFiles;
	}

function _buildSelectedFilesListHTML( filesArray ){
	var fileTemplateString = new String( SELECTED_FILE_TEMPLATE );
	var filesContainerTemplateString = new String( SELECTED_FILES_CONTAINER_TEMPLATE );

	var allFilesString = "";
	for( i = 0; i < filesArray.length; i++ ){
		thisFileString = fileTemplateString.replace( /{FILE_NAME}/g, filesArray[i] );
		allFilesString += thisFileString;
		}

	thisString = filesContainerTemplateString.replace( /{FILES}/g, allFilesString );
	return thisString;
	}

/*
* CHMOD FUNCTIONS
*/
function ctl_inc( ctl, val, inc){
	if( ! inc )
		val = -val;

	var old_val = ctl.value;
	if( ! old_val)
		old_val = 0;
//	ctl.value = parseInt(old_val) + parseInt(val);
	ctl.value = format_chmod( parseInt(old_val, 10) + parseInt(val, 10) );
	}

function format_chmod(dig){
	var str = new String('' + dig);
	var final_length = 3;
	var add_length = final_length - str.length;
	for(var i=0; i < add_length; i++){
		str = '0' + str;
		}
	return str;
	}

function fill_chmod( dig, r_ctl, w_ctl, x_ctl){
	var r_mask = 4; var w_mask = 2; var x_mask = 1;
	r_ctl.checked = ( dig & r_mask ) ? true : false;
	w_ctl.checked = ( dig & w_mask ) ? true : false;
	x_ctl.checked = ( dig & x_mask ) ? true : false;
	}

function btnCancel_Click(){
	window.close();
	}

function transferControlValue( srcControl, trgControl ){
//	window.opener.document.mwForm[trgControlName].value = srcControl.value;
	trgControl.value = srcControl.value;
	window.close();
	}

function transferControlValue_old( srcControlName, trgControlName ){
	window.opener.document.mwForm[trgControlName].value = document.mwForm[srcControlName].value;
	window.close();
	}

function openWindow( url ){
	nw = window.open(url, 'newWin', 'scrollbars=yes,status=yes,menubar=no,location=no,resizable=yes,width=580,height=300');
//	nw = window.open(url, 'newWin', 'scrollbars=yes,status=no,menubar=no,location=no,resizable=yes,width=510,height=300');
	}

function fetchObjectPosLeft(elm){
	var left = elm.offsetLeft;
	while((elm = elm.offsetParent) != null){
		left += elm.offsetLeft;
		}
	return left;
	}

function fetchObjectPosTop(elm){
	var top = elm.offsetTop;
	while((elm = elm.offsetParent) != null){
		top += elm.offsetTop;
		}
	return top;
	}

function myDiv( htmlDivID ){
	htmlDiv = document.getElementById( htmlDivID );
	if( ! htmlDiv ){
		alert( "No div: " + htmlDivID );
		return false;
		}
	else {
//		alert( htmlDivID + ': OK' );
		}

	this.htmlDiv = document.getElementById( htmlDivID );
	this.setLeft = setLeft;
	this.setTop = setTop;
	this.getLeft = getLeft;
	this.getTop = getTop;
	this.getWidth = getWidth;
	this.getHeight = getHeight;
	this.show = show;
	this.hide = hide;
	this.isHidden = isHidden;
	this.setContent = setContent;
	}
function setContent( content ){
//	alert( this.htmlDiv.innerHTML );
	this.htmlDiv.innerHTML = content;
//	this.htmlDiv.childNodes[0].innerHTML = content;
	}
function getLeft(){
	return fetchObjectPosLeft( this.htmlDiv );
	}
function setLeft( left ){
	if( left < 0 )
		left = 5;
	this.htmlDiv.style.left = left;
	}
function getTop(){
	return fetchObjectPosTop( this.htmlDiv );
	}
function setTop( top ){
	this.htmlDiv.style.top = top;
	}
function getWidth(){
	return this.htmlDiv.offsetWidth;
	}
function getHeight(){
	return this.htmlDiv.offsetHeight;
	}
function show(){
//	this.htmlDiv.style.display = "";
	this.htmlDiv.style.display = "block";
	}
function hide(){
	this.htmlDiv.style.display = "none";
	}
function isHidden(){
	if( this.htmlDiv.style.display == "none" )
		return true;
	else
		return false;
	}

/*
* SOME CONSTANTS SHOULD BE DEFINED BEFORE
*/
function showNextFileField( fieldHandle ){
	var maxFields = HTML_MAX_FILE_FIELDS;

	for( i = 2; i <= maxFields; i++ ){
		thisDiv = new myDiv( fieldHandle + i );
		if( ! thisDiv )
			continue;

		if( thisDiv.isHidden() ){
			thisDiv.show();
			break;
			}
		}
	}

function checkFields(){
	for(var i = 0; i < arguments.length; i++){
//		if(! f.elements[ arguments[i] ].value){
		var ctl = arguments[i];
		if(! ctl.value ){
			alert('Please fill all the required fields!');
			return false;
			}
		}
	return true;
	}

function sprintf()
{
	if (!arguments || arguments.length < 1 || !RegExp)
	{
		return;
	}
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str))
	{
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];

		//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
				alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
			       if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			  else if (pPad) pad = pPad;
			var justifyRight = true;
			       if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
			       if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
			       if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			var subst = param;
			       if (pType == 'b') subst = parseInt(param).toString(2);
			  else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			  else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			  else if (pType == 'u') subst = Math.abs(param);
			  else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
			  else if (pType == 'o') subst = parseInt(param).toString(8);
			  else if (pType == 's') subst = param;
			  else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			  else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
	return str;
}

function makeHttpRequest(url, callback_function, fParamString, return_xml){
   var http_request = false;

   if (window.XMLHttpRequest) { // Mozilla, Safari,...
       http_request = new XMLHttpRequest();
       if (http_request.overrideMimeType) {
           http_request.overrideMimeType('text/xml [15]');
       }
   } else if (window.ActiveXObject) { // IE
       try {
           http_request = new ActiveXObject("Msxml2.XMLHTTP");
       } catch (e) {
           try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
       }
   }

   if (!http_request) {
       alert('Unfortunatelly you browser doesn\'t support this feature.');
       return false;
   }
   http_request.onreadystatechange = function() {
       if (http_request.readyState == 4) {
           if (http_request.status == 200) {
				if (return_xml) {
					if( fParamString != "" )
						evalCode = callback_function + '(' + fParamString + ', http_request.responseXML)';
					else
						evalCode = callback_function + '(http_request.responseXML)';
					}
				else {
					if( fParamString != "" )
						evalCode = callback_function + '(' + fParamString + ', http_request.responseText)';
					else
						evalCode = callback_function + '(http_request.responseText)';
					}
				eval( evalCode );
           } else {
               alert('There was a problem with the request.(Code: ' + http_request.status + ')');
           }
       }
   }
	http_request.open('GET', url, true);
	http_request.send(null);
	}
// how may be 'insert', 'append', 'prepend'
function AjaxCall( url2fetch, div2update, how ){
	functionParamsString = '"' + div2update + '", "' + how + '"';
	makeHttpRequest( url2fetch, 'addHtmlToElement', functionParamsString, false );
	}
// how may be 'insert', 'append', 'prepend'
function addHtmlToElement( elementName, how, code ){
	ele = document.getElementById( elementName );
	switch( how ){
		case 'insert':
			ele.innerHTML = code;
			break;
		case 'append':
			ele.innerHTML += code;
			break;
		case 'prepend':
			ele.innerHTML = code + ele.innerHTML;
			break;
		}
	}

function openStatusWindow(){
	displayUploadStatus();
	setTimeout("displayUploadStatus();", 2000);
	}

function displayUploadStatus(){
	AjaxCall( 'status.php', 'mwfUploadStatus', 'insert');
	}

function hideShowStatus(){
	svn=document.getElementsByTagName("DIV");
	for( a=0; a < svn.length; a++ ){
		if( svn[a].className == 'hcShowStatus' ){
			svn[a].style.display = "none";
			}
		}
	}