/* 
Turns given control (button or input[type=submit] into browser. The initial value will
read from and will be written to input 'entryelt'. Basedir is assumed to be 'basedir'.

basedir can be empty.

entryelt's content can be empty too
*/


//these vars are used by 'add_xxx_browser()' for default values
var fsbrowser_button_title = 'Browse for..';
var fsbrowser_button_class = 'button';

//these functions are public interface.
function fsb_turn_into_dir_browser(btnelt,entryelt,basedir)
{
    _fsb_turn_into_fs_browser('dir',btnelt,entryelt,basedir)
};

function fsb_turn_into_file_browser(btnelt,entryelt,basedir)
{
    _fsb_turn_into_fs_browser('file',btnelt,entryelt,basedir)
};


function fsb_add_dir_browser(entryelt,basedir)
{
    _fsb_add_fs_browser('dir',entryelt,basedir);
};
function fsb_add_file_browser(entryelt,basedir)
{
    _fsb_add_fs_browser('file',entryelt,basedir);
}

/* PRIVATE IMPLEMENTATION FOLLOWS*/
var _fsb_os_supported = (navigator.platform == 'Win32' || 
    navigator.platform == 'MacIntel' || navigator.platform == 'MacPPC') ? 1 : 0 ;
if (_fsb_os_supported)
{
    document.write('<iframe src=/stunnix-websrv-utils/browse-files/dummyfile.html width=0 height=0 frameborder=0 id=_fsbrowser_iframe></iframe>');
};


var _fsb_btn_idx = 1;
var _fsb_btn_pfx = '_fsb_btn_';
function _fsb_add_fs_browser(type_,entryelt,basedir)
{
    if (!_fsb_os_supported) return;    
    document.write('<span class=_fsb_button><input type=button class=' + fsbrowser_button_class + ' id=' +
	_fsb_btn_pfx + _fsb_btn_idx + ' value="' + fsbrowser_button_title +
	'"></input></span>');
    btnelt = document.getElementById(_fsb_btn_pfx + _fsb_btn_idx);
    ++_fsb_btn_idx;
    _fsb_turn_into_fs_browser(type_,btnelt,entryelt,basedir);
};

function _fsb_turn_into_fs_browser(type_,btnelt,entryelt,basedir)
{
    btnelt.onclick = !_fsb_os_supported ? function () {alert(
	'Browsing for files and directories is not supported on this platform. Please type the path manually!');} 
    : function () { _fsb_button_clicked(type_,entryelt,basedir); };
}

var _fsb_target_entry;
function _fsb_button_clicked(type_,entryelt,basedir)
{
    if (!_fsb_os_supported) return;      
    var ifr = document.getElementById('_fsbrowser_iframe');
    if (!ifr)
    {
	alert('iframe not found. aborting');
	return;
    };
    var curval = entryelt.value;

    window['on_filesel_done'] = _fsb_on_seldone;
    _fsb_target_entry = entryelt;

    var newsrc;
    newsrc = '/stunnix-websrv-utils/browse-files/selectfile.' +
	(navigator.platform == 'Win32' ? 'exe' : 'pl') +
	'?type=' + 
	(type_ == 'dir' ? 'dirquery' : 'filequery') + '&basedir=' + 
	escape(basedir) + '&curval=' + escape(curval);
    ifr.src = newsrc;
};

function _fsb_on_seldone(newval)
{
    if (newval.length)
	_fsb_target_entry.value=newval;
    var ifr = document.getElementById('_fsbrowser_iframe');
    ifr.src = '/stunnix-websrv-utils/browse-files/dummyfile.html';
}

