/*################################
#                                #
#       PORTAL FUNCTIONS         #
#                                #
#  ?2005-2008 Mitrichev Sergey   #
#                                #
################################*/

function ShowId(x) {document.getElementById(x).style.display = "inline";}
function HideId(x) {document.getElementById(x).style.display = "none";}

function check_changed(chField)
{
	 if (typeof(document.getElementById(chField + '_changed')) != 'undefined') {
        document.getElementById(chField + '_changed').checked = true;
	 }
    return true;
}

function del_c(message,url) {
	if (confirm(message)) {
	window.location.href = url;
	}
}

function check_form(chForm)
{
	if(!chForm) return true;
	var fieldCheck   = true;
   var fieldsNeeded = "\nНеобходимо заполнить следущие поля:\n\n\t";
   if (idTa) syncTextarea();

	for(var i=0; i< chForm.length; i++) {
        if ((chForm.elements[i].alt) && (chForm.elements[i].alt.substr(0,1) == "!") && (chForm.elements[i].value == "")) {
            fieldsNeeded += chForm.elements[i].alt.substr(1)  + "\n\t";
            fieldCheck = false;
        }
    }

    if (fieldCheck == true)
    {
        return true;
    }
    else
    {
        alert(fieldsNeeded);
        return false;
    }
}

// default settins
var A_TCALDEF = {
	'months' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	'weekdays' : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
	'yearscroll': true, // show year scroller
	'weekstart': 1, // first day of week: 0-Su or 1-Mo
	'centyear'  : 70, // 2 digit years less than 'centyear' are in 20xx, othewise in 19xx.
	'imgpath' : 'modules/img/' // directory with calendar images
}
// date parsing function
function f_tcalParseDate (s_date) {

	var re_date = /^\s*(\d{2,4})\-(\d{1,2})\-(\d{1,2})\s*$/;
	if (!re_date.exec(s_date))
		return alert ("Invalid date: '" + s_date + "'.\nAccepted format is yyyy-mm-dd.")
	var n_day = Number(RegExp.$3),
		n_month = Number(RegExp.$2),
		n_year = Number(RegExp.$1);

	if (n_year < 100)
		n_year += (n_year < this.a_tpl.centyear ? 2000 : 1900);
	if (n_month < 1 || n_month > 12)
		return alert ("Invalid month value: '" + n_month + "'.\nAllowed range is 01-12.");
	var d_numdays = new Date(n_year, n_month, 0);
	if (n_day > d_numdays.getDate())
		return alert("Invalid day of month value: '" + n_day + "'.\nAllowed range for selected month is 01 - " + d_numdays.getDate() + ".");

	return new Date (n_year, n_month - 1, n_day);
}
// date generating function
function f_tcalGenerDate (d_date) {
	return (
		d_date.getFullYear() + "-"
		+ (d_date.getMonth() < 9 ? '0' : '') + (d_date.getMonth() + 1) + "-"
		+ (d_date.getDate() < 10 ? '0' : '') + d_date.getDate()
	);
}

// implementation
function tcal (a_cfg, a_tpl) {

	// apply default template if not specified
	if (!a_tpl)
		a_tpl = A_TCALDEF;

	// register in global collections
	if (!window.A_TCALS)
		window.A_TCALS = [];
	if (!window.A_TCALSIDX)
		window.A_TCALSIDX = [];

	this.s_id = a_cfg.id ? a_cfg.id : A_TCALS.length;
	window.A_TCALS[this.s_id] = this;
	window.A_TCALSIDX[window.A_TCALSIDX.length] = this;

	// assign methods
	this.f_show = f_tcalShow;
	this.f_hide = f_tcalHide;
	this.f_toggle = f_tcalToggle;
	this.f_update = f_tcalUpdate;
	this.f_relDate = f_tcalRelDate;
	this.f_parseDate = f_tcalParseDate;
	this.f_generDate = f_tcalGenerDate;

	// create calendar icon
	this.s_iconId = 'tcalico_' + this.s_id;
	this.e_icon = f_getElement(this.s_iconId);
	if (!this.e_icon) {
		document.write('<img src="' + a_tpl.imgpath + 'cal.gif" id="' + this.s_iconId + '" onclick="A_TCALS[\'' + this.s_id + '\'].f_toggle()" class="tcalIcon" alt="Open Calendar" />');
		this.e_icon = f_getElement(this.s_iconId);
	}
	// save received parameters
	this.a_cfg = a_cfg;
	this.a_tpl = a_tpl;
}

function f_tcalShow (d_date) {

	// find input field
	if (!this.a_cfg.controlname)
		throw("TC: control name is not specified");
	if (this.a_cfg.formname) {
		var e_form = document.forms[this.a_cfg.formname];
		if (!e_form)
			throw("TC: form '" + this.a_cfg.formname + "' can not be found");
		this.e_input = e_form.elements[this.a_cfg.controlname];
	}
	else
		this.e_input = f_getElement(this.a_cfg.controlname);

	if (!this.e_input || !this.e_input.tagName || this.e_input.tagName != 'INPUT')
		throw("TC: element '" + this.a_cfg.controlname + "' does not exist in "
			+ (this.a_cfg.formname ? "form '" + this.a_cfg.controlname + "'" : 'this document'));

	// dynamically create HTML elements if needed
	this.e_div = f_getElement('tcal');
	if (!this.e_div) {
		this.e_div = document.createElement("DIV");
		this.e_div.id = 'tcal';
		document.body.appendChild(this.e_div);
	}
	this.e_shade = f_getElement('tcalShade');
	if (!this.e_shade) {
		this.e_shade = document.createElement("DIV");
		this.e_shade.id = 'tcalShade';
		document.body.appendChild(this.e_shade);
	}
	this.e_iframe =  f_getElement('tcalIF')
	if (b_ieFix && !this.e_iframe) {
		this.e_iframe = document.createElement("IFRAME");
		this.e_iframe.style.filter = 'alpha(opacity=0)';
		this.e_iframe.id = 'tcalIF';
		this.e_iframe.src = this.a_tpl.imgpath + 'pixel.gif';
		document.body.appendChild(this.e_iframe);
	}

	// hide all calendars
	f_tcalHideAll();

	// generate HTML and show calendar
	this.e_icon = f_getElement(this.s_iconId);
	if (!this.f_update())
		return;

	this.e_div.style.visibility = 'visible';
	this.e_shade.style.visibility = 'visible';
	if (this.e_iframe)
		this.e_iframe.style.visibility = 'visible';

	// change icon and status
	this.e_icon.src = this.a_tpl.imgpath + 'no_cal.gif';
	this.e_icon.title = 'Close Calendar';
	this.b_visible = true;
}

function f_tcalHide (n_date) {
	if (n_date)
		this.e_input.value = this.f_generDate(new Date(n_date));

	// no action if not visible
	if (!this.b_visible)
		return;

	// hide elements
	if (this.e_iframe)
		this.e_iframe.style.visibility = 'hidden';
	if (this.e_shade)
		this.e_shade.style.visibility = 'hidden';
	this.e_div.style.visibility = 'hidden';

	// change icon and status
	this.e_icon = f_getElement(this.s_iconId);
	this.e_icon.src = this.a_tpl.imgpath + 'cal.gif';
	this.e_icon.title = 'Open Calendar';
	this.b_visible = false;
}

function f_tcalToggle () {
	return this.b_visible ? this.f_hide() : this.f_show();
}

function f_tcalUpdate (d_date) {

	var d_client = new Date();
	d_client.setHours(0);
	d_client.setMinutes(0);
	d_client.setSeconds(0);
	d_client.setMilliseconds(0);

	var d_today = this.a_cfg.today ? this.f_parseDate(this.a_cfg.today) : d_client;
	var d_selected = this.e_input.value == ''
		? (this.a_cfg.selected ? this.f_parseDate(this.a_cfg.selected) : d_today)
		: this.f_parseDate(this.e_input.value);

	// figure out date to display
	if (!d_date)
		// selected by default
		d_date = d_selected;
	else if (typeof(d_date) == 'number')
		// get from number
		d_date = new Date(d_date);
	else if (typeof(d_date) == 'string')
		// parse from string
		this.f_parseDate(d_date);

	if (!d_date) return false;

	// first date to display
	var d_firstday = new Date(d_date);
	d_firstday.setDate(1);
	d_firstday.setDate(1 - (7 + d_firstday.getDay() - this.a_tpl.weekstart) % 7);

	var a_class, s_html = '<table class="ctrl"><tbody><tr>'
		+ (this.a_tpl.yearscroll ? '<td' + this.f_relDate(d_date, -1, 'y') + ' title="Previous Year"><img src="' + this.a_tpl.imgpath + 'prev_year.gif" /></td>' : '')
		+ '<td' + this.f_relDate(d_date, -1) + ' title="Previous Month"><img src="' + this.a_tpl.imgpath + 'prev_mon.gif" /></td><th>'
		+ this.a_tpl.months[d_date.getMonth()] + ' ' + d_date.getFullYear()
			+ '</th><td' + this.f_relDate(d_date, 1) + ' title="Next Month"><img src="' + this.a_tpl.imgpath + 'next_mon.gif" /></td>'
		+ (this.a_tpl.yearscroll ? '<td' + this.f_relDate(d_date, 1, 'y') + ' title="Next Year"><img src="' + this.a_tpl.imgpath + 'next_year.gif" /></td></td>' : '')
		+ '</tr></tbody></table><table><tbody><tr class="wd">';

	// print weekdays titles
	for (var i = 0; i < 7; i++)
		s_html += '<th>' + this.a_tpl.weekdays[(this.a_tpl.weekstart + i) % 7] + '</th>';
	s_html += '</tr>' ;

	// print calendar table
	var d_current = new Date(d_firstday);
	while (d_current.getMonth() == d_date.getMonth() ||
		d_current.getMonth() == d_firstday.getMonth()) {

		// print row heder
		s_html +='<tr>';
		for (var n_wday = 0; n_wday < 7; n_wday++) {

			a_class = [];
			// other month
			if (d_current.getMonth() != d_date.getMonth())
				a_class[a_class.length] = 'othermonth';
			// weekend
			if (d_current.getDay() == 0 || d_current.getDay() == 6)
				a_class[a_class.length] = 'weekend';
			// today
			if (d_current.valueOf() == d_today.valueOf())
				a_class[a_class.length] = 'today';
			// selected
			if (d_current.valueOf() == d_selected.valueOf())
				a_class[a_class.length] = 'selected';

			s_html += '<td onclick="A_TCALS[\'' + this.s_id + '\'].f_hide(' + d_current.valueOf() + ')"' + (a_class.length ? ' class="' + a_class.join(' ') + '">' : '>') + d_current.getDate() + '</td>'
			d_current.setDate(d_current.getDate() + 1);
		}
		// print row footer
		s_html +='</tr>';
	}
	s_html +='</tbody></table>';

	// update HTML, positions and sizes
	this.e_div.innerHTML = s_html;

	var n_width  = this.e_div.offsetWidth;
	var n_height = this.e_div.offsetHeight;
	var n_top  = f_getPosition (this.e_icon, 'Top') + this.e_icon.offsetHeight;
	var n_left = f_getPosition (this.e_icon, 'Left') - n_width + this.e_icon.offsetWidth;
	if (n_left < 0) n_left = 0;

	this.e_div.style.left = n_left + 'px';
	this.e_div.style.top  = n_top + 'px';

	this.e_shade.style.width = (n_width + 8) + 'px';
	this.e_shade.style.left = (n_left - 1) + 'px';
	this.e_shade.style.top = (n_top - 1) + 'px';
	this.e_shade.innerHTML = b_ieFix
		? '<table><tbody><tr><td rowspan="2" colspan="2" width="6"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td width="7" height="7" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_tr.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tr><td height="' + (n_height - 7) + '" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_mr.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tr><td width="7" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_bl.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_bm.png\', sizingMethod=\'scale\');" height="7" align="left"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + this.a_tpl.imgpath + 'shade_br.png\', sizingMethod=\'scale\');"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tbody></table>'
		: '<table><tbody><tr><td rowspan="2" width="6"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td rowspan="2"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td width="7" height="7"><img src="' + this.a_tpl.imgpath + 'shade_tr.png"></td></tr><tr><td background="' + this.a_tpl.imgpath + 'shade_mr.png" height="' + (n_height - 7) + '"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td></tr><tr><td><img src="' + this.a_tpl.imgpath + 'shade_bl.png"></td><td background="' + this.a_tpl.imgpath + 'shade_bm.png" height="7" align="left"><img src="' + this.a_tpl.imgpath + 'pixel.gif"></td><td><img src="' + this.a_tpl.imgpath + 'shade_br.png"></td></tr><tbody></table>';

	if (this.e_iframe) {
		this.e_iframe.style.left = n_left + 'px';
		this.e_iframe.style.top  = n_top + 'px';
		this.e_iframe.style.width = (n_width + 6) + 'px';
		this.e_iframe.style.height = (n_height + 6) +'px';
	}
	return true;
}

function f_getPosition (e_elemRef, s_coord) {
	var n_pos = 0, n_offset,
		e_elem = e_elemRef;

	while (e_elem) {
		n_offset = e_elem["offset" + s_coord];
		n_pos += n_offset;
		e_elem = e_elem.offsetParent;
	}
	// margin correction in some browsers
	if (b_ieMac)
		n_pos += parseInt(document.body[s_coord.toLowerCase() + 'Margin']);
	else if (b_safari)
		n_pos -= n_offset;

	e_elem = e_elemRef;
	while (e_elem != document.body) {
		n_offset = e_elem["scroll" + s_coord];
		if (n_offset && e_elem.style.overflow == 'scroll')
			n_pos -= n_offset;
		e_elem = e_elem.parentNode;
	}
	return n_pos;
}

function f_tcalRelDate (d_date, d_diff, s_units) {
	var s_units = (s_units == 'y' ? 'FullYear' : 'Month');
	var d_result = new Date(d_date);
	d_result['set' + s_units](d_date['get' + s_units]() + d_diff);
	if (d_result.getDate() != d_date.getDate())
		d_result.setDate(0);
	return ' onclick="A_TCALS[\'' + this.s_id + '\'].f_update(' + d_result.valueOf() + ')"';
}

function f_tcalHideAll () {
	if (!window.A_TCALSIDX) return;
	for (var i = 0; i < window.A_TCALSIDX.length; i++)
		window.A_TCALSIDX[i].f_hide();
}

f_getElement = document.all ?
	function (s_id) { return document.all[s_id] } :
	function (s_id) { return document.getElementById(s_id) };

if (document.addEventListener)
	window.addEventListener('scroll', f_tcalHideAll, false);
if (window.attachEvent)
	window.attachEvent('onscroll', f_tcalHideAll);

// global variables
var s_userAgent = navigator.userAgent.toLowerCase(),
	re_webkit = /WebKit\/(\d+)/i;
var b_mac = s_userAgent.indexOf('mac') != -1,
	b_ie5 = s_userAgent.indexOf('msie 5') != -1,
	b_ie6 = s_userAgent.indexOf('msie 6') != -1 && s_userAgent.indexOf('opera') == -1;
var b_ieFix = b_ie5 || b_ie6,
	b_ieMac  = b_mac && b_ie5,
	b_safari = b_mac && re_webkit.exec(s_userAgent) && Number(RegExp.$1) < 500;

// Visual HTML Editor - Whizzywig

var buttonPath="textbuttons";  //path to toolbar button images;  unset or "textbuttons" means don't use images
var buttonStrip=[]; //object containing button strip information (optional)
var cssFile;     //url of CSS stylesheet to attach to edit area
var imageBrowse; //path to page for image browser
var linkBrowse;  //path to page for link browser
var idTa;        //id of the textarea to whizzywig (param to makeWhizzyWig)
var gentleClean="false";  //true: cleanUp preserves spans, inline styles and classes; false: deletes same; ask: asks.
//OTHER GLOBALS
var oW, sel, rng, papa, trail, ppw; //Whizzy contentWindow, current sel, range, parent, DOM path, popwindow;
var sels='';
var buts='';
var vals=new Array();
var opts=new Array();
var dobut=new Array();
var whizzies=new Array();

function makeWhizzyWig(txtArea, controls, pathtoimg){ // make a WhizzyWig from the textarea
 buttonPath=pathtoimg;
 idTa=txtArea;
 whizzies[whizzies.length]=idTa;
 if (!document.designMode) {// (Safari ???)
  if (idTa.nodeName=="TEXTAREA") tagButs();
  alert(t("editor not available for your browser"));
  return;
 }
 var taContent=o(idTa).defaultValue ? o(idTa).defaultValue : o(idTa).innerHTML ? o(idTa).innerHTML: ''; //anything in the textarea?
 if (!o(idTa).rows < 5) o(idTa).rows='15';//IE won't use % from style
 taWidth=o(idTa).style.width ? o(idTa).style.width : o(idTa).cols + "ex";  //grab the width and...
 taHeight=o(idTa).style.height ? o(idTa).style.height : o(idTa).rows + "em";  //...height from the textarea
 if (o(idTa).nodeName=="TEXTAREA"){
 o(idTa).style.color='#060';
 o(idTa).style.zIndex='2';
 } else w('<input type="hidden" id="wzhid_'+idTa+'" name="'+idTa+'" />');
 h(idTa);
 var frm=o(idTa).parentNode;
 while (frm.nodeName != 'FORM') frm=frm.parentNode;//if not form, keep trying
 addEvt(frm,"submit",syncTextarea);
 w('<style type="text/css">button {vertical-align:middle;padding:0;margin:1px 0} button img{vertical-align:middle;margin:-1px} select{vertical-align:middle;margin:1px}  .wzCtrl {background:ButtonFace; border:2px outset ButtonShadow; padding:5px;} #sourceTa{color:#060;font-family:mono;} #whizzyWig {border-width:1px}</style>');
 var dsels='fontname fontsize formatblock';
 var dbuts=' bold italic underline | left center right | number bullet indent outdent | undo redo  | color hilite rule | link image table | html word clean spellcheck ';
 var tbuts=' tstart add_row_above add_row_below delete_row | add_column_before add_column_after delete_column | table_in_cell';
 var t_end=''; //table controls end, if needed
 controls=controls ? controls.toLowerCase() : "all";
 if (controls == "all") controls=dsels +' newline '+ dbuts + tbuts;
 else controls += tbuts;
 w('<div style="width:'+taWidth+'" onmouseover="c(\''+idTa+'\')"><div id="CONTROLS'+idTa+'" class="wzCtrl" unselectable="on">');
 gizmos=controls.split(' ');
 for (var i=0; i < gizmos.length; i++) {
  if (gizmos[i]){ //make buttons and selects for toolbar, in order requested
   if (gizmos[i] == 'tstart') {
    w('<div id="TABLE_CONTROLS'+idTa+'" style="display:none" unselectable="on">');
    t_end='</div>';
   }
   else if (gizmos[i] == '|') w('&nbsp;<big style="padding-bottom:2em">|</big>&nbsp;');
   else if (gizmos[i] == 'newline') w('<br>');
   else if ((dsels+sels).indexOf(gizmos[i]) != -1) makeSelect(gizmos[i])
   else if ((dbuts+buts+tbuts).indexOf(gizmos[i]) != -1) makeButton(gizmos[i]);
  }
 }
 w(t_end) //table controls end
 w(fGo('LINK'));
 if (linkBrowse) w('<input type="button" onclick=doWin("'+linkBrowse+'?rtn=lf_url'+idTa+'"); value="'+t("Browse")+'"> ');
 w(t('Link address (URL)')+': <input type="text" id="lf_url'+idTa+'" size="60"><br><input type="button" value="http://" onclick="o(\'lf_url'+idTa+'\').value=\'http://\'+o(\'lf_url'+idTa+'\').value"> <input type="button" value="mailto:" onclick="o(\'lf_url'+idTa+'\').value=\'mailto:\'+o(\'lf_url'+idTa+'\').value"><input type="checkbox" id="lf_new'+idTa+'">'+t("Open link in new window")+fNo(t("OK"),"insertLink()"));//LINK_FORM end
 w(fGo('IMAGE'));
 if (imageBrowse) w('<input type="button" onclick=doWin("'+imageBrowse+'?rtn=if_url'+idTa+'"); value="'+t("Browse")+'"> ');
 w(t('Image address (URL)')+': <input type="text" id="if_url'+idTa+'" size="50"> <label title='+t("to display if image unavailable")+'><br>'+t("Alternate text")+':<input id="if_alt'+idTa+'" type="text" size="50"></label><br>'+t("Align")+':<select id="if_side'+idTa+'"><option value="none">_&hearts;_ '+t("normal")+'</option><option value="left">&hearts;= &nbsp;'+t("left")+'</option><option value="right">=&hearts; &nbsp;'+t("right")+'</option></select> '+t("Border")+':<input type="text" id="if_border'+idTa+'" size="20" value="0" title="'+t("number or CSS e.g. 3px maroon outset")+'"> '+t("Margin")+':<input type="text" id="if_margin'+idTa+'" size="20" value="0" title="'+t("number or CSS e.g. 5px 1em")+'">'+fNo(t("Insert Image"),"insertImage()"));//IMAGE_FORM end
 w(fGo('TABLE')+t("Rows")+':<input type="text" id="tf_rows'+idTa+'" size="2" value="3"> <select id="tf_head'+idTa+'"><option value="0">'+t("No header row")+'</option><option value="1">'+t("Include header row")+'</option></select> '+t("Columns")+':<input type="text" id="tf_cols'+idTa+'" size="2" value="3"> '+t("Border width")+':<input type="text" id="tf_border'+idTa+'" size="2" value="1"> '+fNo(t("Insert Table"),"makeTable()"));//TABLE_FORM end
 w(fGo('COLOR')+'<input type="hidden" id="cf_cmd'+idTa+'"><div style="background:#000;padding:1px;height:22px;width:125px;float:left"><div id="cPrvw'+idTa+'" style="background-color:red; height:100%; width:100%"></div></div> <input type=text id="cf_color'+idTa+'" value="red" size=17 onpaste=vC(value) onblur=vC(value)> <input type="button" onmouseover=vC() onclick=sC() value="'+t("OK")+'">  <input type="button" onclick="hideDialogs();" value="'+t("Cancel")+'"><br> '+t("click below or enter a")+' <a href="http://www.unverse.net/colortable.htm" target="_blank">'+t("color name")+'</a><br clear=all> <table border=0 cellspacing=1 cellpadding=0 width=480 bgcolor="#000000">'+"\n");
 var wC=new Array("00","33","66","99","CC","FF")  //color table
 for (i=0; i<wC.length; i++){
  w("<tr>");
  for (j=0; j<wC.length; j++){
   for (k=0; k<wC.length; k++){
    var clr=wC[i]+wC[j]+wC[k];
    w(' <td style="background:#'+clr+';height:12px;width:12px" onmouseover=vC("#'+clr+'") onclick=sC("#'+clr+'")></td>'+"\n");
   }
  }
  w('</tr>');
 }
 w("</table></div>\n"); //end color table,COLOR_FORM
 w("</div>\n"); //controls end
 w('<div class="wzCtrl" id="showWYSIWYG'+idTa+'" style="display:none"><input type="button" onclick="showDesign();" value="'+t("Hide HTML")+'">');
 tagButs();
 w('</div>'+"\n");

 w('<iframe style="border:1px inset ButtonShadow;width:100%;height:'+taHeight+'" src="javascript:;" id="whizzy'+idTa+'"></iframe></div>'+"\n");

 var startHTML="<html>\n<head>\n";
 if (cssFile) startHTML += '<link media="all" type="text/css" href="'+cssFile+'" rel="stylesheet">\n';
 startHTML += '</head>\n<body id="'+idTa+'" style="background-image:none">\n'+tidyD(taContent)+'</body>\n</html>';
 oW=o("whizzy"+idTa).contentWindow;

 var d=oW.document;
 try{d.designMode="on";} catch(e){ setTimeout('oW.designMode="on";', 100);}
 d.open();
 d.write(startHTML);
 d.close();
 if (oW.addEventListener) oW.addEventListener("keypress", kb_handler, true); //keyboard shortcuts for Moz
 else {d.body.attachEvent("onpaste",function(){setTimeout('cleanUp()',10);});}
 addEvt(d,"mouseup", whereAmI);
 addEvt(d,"keyup", whereAmI);
 addEvt(d,"dblclick", doDbl);
 idTa=null;
} //end makeWhizzyWig
function addEvt(o,e,f){ if(window.addEventListener) o.addEventListener(e, f, false); else o.attachEvent("on"+e,f);}
function doDbl(){if (papa.nodeName == 'IMG') doImage(); else if (papa.nodeName == 'A') doLink();}
function makeButton(button){  // assemble the button requested
 var butHTML, ucBut=button.substring(0,1).toUpperCase();
 ucBut += button.substring(1);
 ucBut=t(ucBut.replace(/_/g,' '));
 if (!document.frames && (button=="word" ||button=="spellcheck")) return; //Not allowed from Firefox
 if (o(idTa).nodeName!="TEXTAREA" && button=="html") return;
 if (!buttonPath || buttonPath == "textbuttons")
   butHTML='<button type=button onClick=makeSo("'+button+'")>'+ucBut+"</button>\n";
 else butHTML='<button  title="'+ucBut+'" type=button onClick=makeSo("'+button+'")>'+(buttonStrip[button]!=undefined?'<div style="width:'+buttonStrip._w+'px;height:'+buttonStrip._h+'px;background-image:url('+buttonStrip._f+');background-position:'+buttonStrip[button]+'px 0px"></div>':'<img src="'+buttonPath+button+'.gif" alt="'+ucBut+'" onError="this.parentNode.innerHTML=this.alt">')+'</button>';
 //if space in name include text as well
 w(butHTML);
}
function fGo(id){ return '<div id="'+id+'_FORM'+idTa+'" unselectable="on" style="display:none" onkeypress="if(event.keyCode==13) {return false;}"><hr>'+"\n"; }//new form
function fNo(txt,go){ //form do it/cancel buttons
 return ' <input type="button" onclick="'+go+'" value="'+txt+'"> <input type="button" onclick="hideDialogs();" value='+t("Cancel")+"></div>\n";
}
function makeSelect(select){ // assemble the <select> requested
 if (select == 'formatblock') {
  var h="Heading";
 var values=["<p>", "<p>", "<h1>", "<h2>", "<h3>", "<h4>", "<h5>", "<h6>", "<address>",  "<pre>"];
 var options=[t("Choose style")+":", t("Paragraph"), t(h)+" 1 ", t(h)+" 2 ", t(h)+" 3 ", t(h)+" 4 ", t(h)+" 5 ", t(h)+" 6", t("Address"), t("Fixed width<pre>")];
 } else if (select == 'fontname') {
var values=["Arial, Helvetica, sans-serif", "Arial, Helvetica, sans-serif","'Arial Black', Helvetica, sans-serif", "'Comic Sans MS' fantasy", "Courier New, Courier, monospace", "Georgia, serif", "Impact,sans-serif","'Times New Roman', Times, serif", "'Trebuchet MS',sans-serif", "Verdana, Arial, Helvetica, sans-serif"];
 var options=[t("Font")+":", "Arial","Arial Black", "Comic", "Courier", "Georgia", "Impact","Times New Roman", "Trebuchet","Verdana"];
 } else if (select == 'fontsize') {
  var values=["3", "1", "2", "3", "4", "5", "6", "7"];
  var options=[t("Font size")+":", "1 "+t("Small"), "2", "3", "4", "5", "6", "7 "+t("Big")];
 } else {
  var values=vals[select];
  var options=opts[select];
 }
 w('<select id="'+select+idTa+'" onchange="doSelect(this.id);">'+"\n");
 for (var i=0; i < values.length; i++) {
  w(' <option value="' + values[i] + '">' + options[i] + "</option>\n");
 }
 w("</select>\n");
}
function tagButs() {
 w('<input type="button" onclick=\'doTag("<h1>")\' value="H1" title="<H1>"><input type="button" onclick=\'doTag("<h2>")\' value="H2" title="<H2>"><input type="button" onclick=\'doTag("<h3>")\' value="H3" title="<H3>"><input type="button" onclick=\'doTag("<h4>")\' value="H4" title="<H4>"><input type="button" onclick=\'doTag("<p>")\' value="P" title="<P>"><input type="button" onclick=\'doTag("<strong>")\' value="S" title="<STRONG>" style="font-weight:bold"><input type="button" onclick=\'doTag("<em>")\' value="E" title="<EM>" style="font-style:italic;"><input type="button" onclick=\'doTag("<li>")\' value="&bull;&mdash;" title="<LI>"><input type="button" onclick=\'doTag("<a>")\' value="@" title="<A HREF= >"><input type="button" onclick=\'doTag("<img>")\' value="[&hearts;]" title="<IMG SRC= >"><input type="button" onclick=\'doTag("<br />")\' value="&larr;" title="<BR />">');
}
function makeSo(command, option) {  //format selected text or line in the whizzy
 hideDialogs();
// if (buts.indexOf(command)!=-1) {insHTML(dobut[command]); return;} //user button
 if(dobut[command]) {insHTML(dobut[command]); return;}
 if (!document.all) oW.document.execCommand('useCSS',false, true); //no spans for bold, italic
 if ("leftrightcenterjustify".indexOf(command) !=-1) command="justify" + command;
 else if (command == "number") command="insertorderedlist";
 else if (command == "bullet") command="insertunorderedlist";
 else if (command == "rule") command="inserthorizontalrule";
 switch (command) {
  case "color": o('cf_cmd'+idTa).value="forecolor"; if (textSel()) s('COLOR_FORM'+idTa); break;
  case "hilite" : o('cf_cmd'+idTa).value="backcolor"; if (textSel()) s('COLOR_FORM'+idTa); break;
  case "image" : doImage(); break;
  case "link" : doLink(); break;
  case "html" : showHTML(); break;
  case "table" : doTable(); break;
  case "delete_row" : doRow('delete','0'); break;
  case "add_row_above" : doRow('add','0'); break;
  case "add_row_below" : doRow('add','1'); break;
  case "delete_column" : doCol('delete','0'); break;
  case "add_column_before" : doCol('add','0'); break;
  case "add_column_after" : doCol('add','1'); break;
  case "table_in_cell" : hideDialogs(); s('TABLE_FORM'+idTa); break;
  case "clean" : cleanUp(); break;
  case "word" : oW.document.execCommand("paste", false, false); gentleClean=false; cleanUp(); break;
  case "spellcheck" : spellCheck(); break;
  default: oW.document.execCommand(command, false, option);
 }
}
function doSelect(selectname) {  //select on toolbar used - do it
 var idx=o(selectname).selectedIndex;
 var selected=o(selectname).options[idx].value;
 o(selectname).selectedIndex=0;
 selectname=selectname.replace(idTa,"");
 if (" _formatblock_fontname_fontsize".indexOf('_'+selectname) > 0) {
  var cmd=selectname;
  oW.document.execCommand(cmd, false, selected);
 } else {
  insHTML(selected);
 }
 oW.focus();
}
function vC(colour) { // view Color
 if (!colour) colour=o('cf_color'+idTa).value;
 o('cPrvw'+idTa).style.backgroundColor=colour;
 o('cf_color'+idTa).value=colour;
}
function sC(color) {  //set Color
 hideDialogs();
 var cmd=o('cf_cmd'+idTa).value;
 if  (!color) color=o('cf_color'+idTa).value;
 if (rng) rng.select();
 oW.document.execCommand(cmd, false, color);
 oW.focus();
}
function doLink(){
 if (textSel()) {
  if (papa.nodeName == 'A') o("lf_url"+idTa).value=papa.href;
  s('LINK_FORM'+idTa);
 }
}
function insertLink() {
 if (rng) rng.select();
 URL=o("lf_url"+idTa).value;
 if (URL.replace(/ /g,"") == "") oW.document.execCommand('Unlink',false,null);
 else if (o("lf_new"+idTa).checked) insHTML('<a href="'+URL+'" target="_blank">');
 else oW.document.execCommand('CreateLink',false,URL);
 hideDialogs();
}
function doImage(){
 if (papa && papa.nodeName == 'IMG'){
  o("if_url"+idTa).value=papa.src;
  o("if_alt"+idTa).value=papa.alt;
  o("if_side"+idTa).selectedIndex=(papa.align=="left")?1:(papa.align=="right")?2:0;
  o("if_border"+idTa).value=papa.style.border?papa.style.border:papa.border>0?papa.border:0;
  o("if_margin"+idTa).value=papa.style.margin?papa.style.margin:papa.hspace>0?papa.hspace:0;
 }
 s('IMAGE_FORM'+idTa);
}
function insertImage(URL, side, border, margin, alt) { // insert image as specified
 hideDialogs();
 if (!URL) URL=o("if_url"+idTa).value;
 if (URL) {
  if (!alt) alt=o("if_alt"+idTa).value ? o("if_alt"+idTa).value: URL.replace(/.*\/(.+)\..*/,"$1");
  img='<img alt="' + alt + '" src="' + URL +'" ';
  if (!side) side=o("if_side"+idTa).value;
  if ((side == "left") || (side == "right")) img += 'align="' + side + '"';
  if (!border)  border=o("if_border"+idTa).value;
  if (border.match(/^\d+$/)) border+='px solid';
  if (!margin) margin=o("if_margin"+idTa).value;
  if (margin.match(/^\d+$/)) margin+='px';
  if (border || margin) img += ' style="border:' + border + ';margin:' + margin + ';"';
  img += '/>';
  insHTML(img);
 }
}
function doTable(){ //show table controls if in a table, else make table
 if (trail && trail.indexOf('TABLE') > 0) s('TABLE_CONTROLS'+idTa);
  else s('TABLE_FORM'+idTa);
}
function doRow(toDo,below) { //insert or delete a table row
 var paNode=papa;
 while (paNode.tagName != "TR") paNode=paNode.parentNode;
 var tRow=paNode.rowIndex;
 var tCols=paNode.cells.length;
 while (paNode.tagName != "TABLE") paNode=paNode.parentNode;
 if (toDo == "delete") paNode.deleteRow(tRow);
 else {
  var newRow=paNode.insertRow(tRow+parseInt(below)); //1=below  0=above
   for (i=0; i < tCols; i++){
    var newCell=newRow.insertCell(i);
    newCell.innerHTML="#";
   }
 }
}
function doCol(toDo,after) { //insert or delete a column
 var paNode=papa;
 while (paNode.tagName != 'TD') paNode=paNode.parentNode;
 var tCol=paNode.cellIndex;
 while (paNode.tagName != "TABLE") paNode=paNode.parentNode;
 var tRows=paNode.rows.length;
 for (i=0; i < tRows; i++){
  if (toDo == "delete") paNode.rows[i].deleteCell(tCol);
  else {
   var newCell=paNode.rows[i].insertCell(tCol+parseInt(after)); //if after=0 then before
   newCell.innerHTML="#";
  }
 }
}
function makeTable() { //insert a table
 hideDialogs();
 var rows=o('tf_rows'+idTa).value;
 var cols=o('tf_cols'+idTa).value;
 var border=o('tf_border'+idTa).value;
 var head=o('tf_head'+idTa).value;
 if ((rows > 0) && (cols > 0)) {
  var table='<table border="' + border + '">';
  for (var i=1; i <= rows; i++) {
   table=table + "<tr>";
   for (var j=1; j <= cols; j++) {
    if (i==1) {
     if (head=="1") table += "<th>Title"+j+"</th>"; //Title1 Title2 etc.
     else table += "<td>"+j+"</td>";
    }
    else if (j==1) table += "<td>"+i+"</td>";
   else table += "<td>#</td>";
   }
   table += "</tr>";
  }
  table += " </table>";
  insHTML(table);
 }
}
function doWin(URL) {  //popup  for browse function
 ppw=window.open(URL,'popWhizz','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=640,height=480,top=100');
 ppw.focus();
}
function spellCheck() {  //check spelling with ieSpell if available
 try {
  var axo=new ActiveXObject("ieSpell.ieSpellExtension");
  axo.CheckAllLinkedDocuments(document);
 } catch(e) {
  if(e.number==-2146827859) {
  if (confirm("ieSpell is not installed on your computer. \n Click [OK] to go to download page."))
    window.open("http://www.iespell.com/download.php","DownLoad");
  } else {
   alert("Error Loading ieSpell: Exception " + e.number);
  }
 }
}
function cleanUp(){
 oW.document.execCommand("removeformat",false,null);
 var h=oW.document.body.innerHTML;
 var vicious=false;
 if (gentleClean=="ask") vicious=confirm(t('Remove all styles and classes?'));
 if (!gentleClean || vicious){
 h=h.replace(/<\/?(SPAN|DEL|INS|U|DIR)[^>]*>/gi, "")
 .replace(/\b(CLASS|STYLE)=\"[^\"]*\"/gi, "")
 .replace(/\b(CLASS|STYLE)=\w+/gi, "");
 }
 if(!o('fontname'+idTa) || !o('fontsize'+idTa)) h=h.replace(/<\?FONT[^>]*>/gi, "");
 h=h.replace(/<\/?(SPAN|COL|XML|ST1|SHAPE|V:|O:|F:|F |PATH|LOCK|IMAGEDATA|STROKE|FORMULAS)[^>]*>/gi, "")
 .replace(/\bCLASS=\"?MSO\w*\"?/gi, "")
 .replace(/[?]/g,'-') //long ?
 .replace(/[??]/g, "'") //single smartquotes ??
 .replace(/[??]/g, '"') //double smartquotes ??
 .replace(/align="?justify"?/gi, "") //justify sends some browsers mad
 .replace(/<(TABLE|TD|TH|COL)(.*)(WIDTH|HEIGHT)=["'0-9A-Z]*/gi, "<$1$2") //no fixed size tables (%OK) [^A-Za-z>]
 .replace(/<([^>]+)>\s*<\/\1>/gi, "") //empty tag
 .replace(location.href+'#','#'); //anchor bug
 oW.document.body.innerHTML=h;
}
function hideDialogs() {
 h('LINK_FORM'+idTa);
 h('IMAGE_FORM'+idTa);
 h('COLOR_FORM'+idTa);
 h('TABLE_FORM'+idTa);
 h('TABLE_CONTROLS'+idTa);
}
function showDesign() {
 oW.document.body.innerHTML=tidyD(o(idTa).value);
 h(idTa);
 h('showWYSIWYG'+idTa);
 s('CONTROLS'+idTa);
 s('whizzy'+idTa);
 if(o("whizzy"+idTa).contentDocument) o("whizzy"+idTa).contentDocument.designMode="on"; //FF loses it on hide
 oW.focus();
}
function showHTML() {
 var t=(window.get_xhtml) ? get_xhtml(oW.document.body) : oW.document.body.innerHTML;
 o(idTa).value=tidyH(t);
 h('CONTROLS'+idTa);
 h('whizzy'+idTa);
 s(idTa);
 s('showWYSIWYG'+idTa);
 o(idTa).focus();
}

function syncTextarea() { //tidy up before we go-go
 for (var i=0;i<whizzies.length;i++){
  var t=whizzies[i];
  var b=o("whizzy"+t).contentWindow.document.body;
  if (o(t).style.display == 'block') b.innerHTML=o(t).value;
  b.innerHTML=tidyH(b.innerHTML);
  var r=(o(t).nodeName!="TEXTAREA") ? o('wzhid_'+o(t).id) : o(t);
  r.value=(window.get_xhtml) ? get_xhtml(b) : b.innerHTML;
  r.value=r.value.replace(location.href+'#','#'); //IE anchor bug
 }
}
function tidyD(h){ //FF designmode likes <B>,<I>...
 h=h.replace(/<(\/?)strong([^>]*)>/gi, "<$1B$2>");
 h=h.replace(/<(\/?)em>/gi, "<$1I>");
 return h;
}
function tidyH(h){ //...but <B>,<I> deprecated
 h=h.replace(/<(\w+)[^>]*>\s*<\/\1>/gi, ""); //empty tag <([^>]+)>\s*<\/\1>
 h=h.replace(/(<\/?)[Bb]>/g, "$1strong>");
 h=h.replace(/(<\/?)[Ii]>/g, "$1em>");
 h=h.replace(/(<\/?)[Bb](\s+[^>]*)>/g, "$1strong$2>");
 h=h.replace(/(<\/?)[Ii](\s+[^>]*)>/g, "$1em$2>");
 h=h.replace(location.href+'#','#'); //IE anchor bug
 return h;
}
function kb_handler(e) { // keyboard controls for Moz
 var cmd=false, prm=false;
 if (e && (e.ctrlKey && e.keyCode == e.DOM_VK_V)||(e.shiftKey && e.keyCode == e.DOM_VK_INSERT))
  {setTimeout('cleanUp()',10);}
 else if (e && e.keyCode==13 && !e.shiftKey &&papa.nodeName=="BODY") {cmd="formatblock";prm="<p>";}
 else if (e && e.ctrlKey) {
  var k=String.fromCharCode(e.charCode).toLowerCase();
  var cmd=(k=='b')?'bold':(k=='i')?'italic':(k=='l')?'link':(k=='m')?'image':false;
 }
 if (cmd) {
  makeSo(cmd, prm);
  e.preventDefault();  // stop the event bubble
  e.stopPropagation();
 }
 if (prm=="<p>"){
  var h=oW.document.body.innerHTML; h=h.replace(/<p><br><\/p>/gi,'<p>&nbsp;</p>');// oW.focus();
  //alert("here <p>&nbsp;</p>");
 }
}
function doTag(html) { // insert HTML into text area
 var url;
 if (!html) html=prompt("Enter some HTML or text to insert:", "");
 o(idTa).focus();
 if (html == '<a>') {
  url=prompt("Link address:","http://");
  html='<a href="'+url+'">';
 }
 if (html == '<img>') {
  url=prompt("Address of image:","http://");
  var alt=prompt("Description of image");
  html ='<img src="'+url+'" alt="'+alt+'">';
 }
 var close='';
 if (html.indexOf('<') == 0 && html.indexOf('br') != 1 && html.indexOf('img') != 1)
  close=html.replace(/<([a-z0-6]+).*/,"<\/$1>");
 if (html != '<strong>' && html != '<em>') close += '\n';
 if (document.selection) {
  sel=document.selection.createRange();
  sel.text=html+sel.text+close;
 } else {
   before=o(idTa).value.slice(0,o(idTa).selectionStart);
   sel=o(idTa).value.slice(o(idTa).selectionStart,o(idTa).selectionEnd);
   after=o(idTa).value.slice(o(idTa).selectionEnd);
   o(idTa).value =before+html+sel+close+after;
 }
 o(idTa).focus();
}
function insHTML(html) { //insert HTML at current selection
 if (!html) html=prompt("Enter some HTML or text to insert:", "");
 if (html.indexOf('js:') == 0) {
  try{eval(html.replace(/^js:/,''))} catch(e){};
  return;
 }
 try {
  if(sel.type && sel.type!="Text") sel="";
  oW.document.execCommand("inserthtml", false, html + sel);
 }
 catch (e) {
  if (document.selection) {
   if(papa && papa.nodeName == 'IMG') {papa.outerHTML=html;}
   else if(rng) {rng.select(); rng.pasteHTML(html+rng.htmlText);}
  }
 }
 whereAmI();
}
function whereAmI(e){//070322
 if (!e) var e=window.event;
 if (window.getSelection){
  sel=oW.getSelection();
  papa=(e && e.type=='mouseup') ? e.target : (sel.anchorNode.nodeName == '#text') ? sel.anchorNode.parentNode : sel.anchorNode;
 } else {
  sel=oW.document.selection;
  rng=sel.createRange();
  papa=(e && e.type=='mouseup')? e.srcElement : (sel.type == "Control") ? rng.item(0) : rng.parentElement();
 }
 var paNode=papa;
 trail=papa.nodeName;
 while (!paNode.nodeName.match(/^(HTML|BODY)/) && paNode.className!="wzCtrl") {
  paNode=paNode.parentNode;
  trail=paNode.nodeName + '>' + trail;
 }
 if (paNode.className=="wzCtrl") trail=sel=rng=null;
 var id=paNode.nodeName=="HTML" ? paNode.getElementsByTagName("BODY")[0].id : paNode.id.replace("CONTROL","");
 c(id);
 window.status=id+":"+trail;
 if (trail.indexOf('TABLE') > 0) s('TABLE_CONTROLS'+idTa); else h('TABLE_CONTROLS'+idTa);
}
function c(id) {//set current whizzy
 if (id=="" || whizzies.join().indexOf(id)=='-1') return;
 if (id!=idTa){
  idTa=id;
  try {oW=o("whizzy"+id).contentWindow;} catch(e){alert('set current: '+id);}
  if (oW) {if(oW.focus)oW.focus();window.status=oW.document.body.id; }
 }
}
function textSel() { if (sel  && sel.type != "None") return true;  else {alert(t("Select some text first")); return false;}}
function s(id) {o(id).style.display='block';} //show element
function h(id) {o(id).style.display='none';} //hide element
function o(id) { return document.getElementById(id); } //get element by ID
function w(str) { return document.write(str); } //document write
function t(key) {return (window.language && language[key]) ? language[key] :  key;} //translation

function apRPC(url, pageElement) {
     document.getElementById(pageElement).innerHTML = "Loading...";
     try {
     req = new XMLHttpRequest(); /* e.g. Firefox */
     } catch(e) {
       try {
       req = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
       } catch (e) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
         } catch (E) {
          req = false;
         }
       }
     }
     req.onreadystatechange = function() {apRPCresponse(pageElement, "ERROR: Cannot load " + url);};
     req.open("GET",url,true);
     req.send(null);
  }

function apRPCresponse(pageElement, errorMessage) {
   var output = '';
   if(req.readyState == 4) {
      if(req.status == 200) {
         output = req.responseText;
         document.getElementById(pageElement).innerHTML = output;
         } else {
         document.getElementById(pageElement).innerHTML = errorMessage+"\n"+output;
         }
      }
  }

 /**
 * X-browser event handler attachment and detachment
 * @argument obj - the object to attach event to
 * @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
 * @argument fn - function to call
 */
function addEvent(obj, evType, fn){
 if (obj.addEventListener){
    obj.addEventListener(evType, fn, false);
    return true;
 } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
 } else {
    return false;
 }
}
function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight;

	return window.undefined;
}
function getViewportWidth() {
	var offset = 17;
	var width = null;
	if (window.innerWidth!=window.undefined) return window.innerWidth;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth;
	if (document.body) return document.body.clientWidth;
}

/**
 * Gets the real scroll top
 */
function getScrollTop() {
	if (self.pageYOffset) // all except Explorer
	{
		return self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollTop;
	}
}
function getScrollLeft() {
	if (self.pageXOffset) // all except Explorer
	{
		return self.pageXOffset;
	}
	else if (document.documentElement && document.documentElement.scrollLeft)
		// Explorer 6 Strict
	{
		return document.documentElement.scrollLeft;
	}
	else if (document.body) // all other Explorers
	{
		return document.body.scrollLeft;
	}
}

// Popup code
var gPopupMask = null;
var gPopupContainer = null;
var gPopFrame = null;
var gReturnFunc = null;
var gPopupIsShown = false;
var gDefaultPage = "";
var gHideSelects = false;

var gTabIndexes = new Array();
// Pre-defined list of tags we want to disable/enable tabbing into
var gTabbableTags = new Array("A","BUTTON","TEXTAREA","INPUT","IFRAME");

// If using Mozilla or Firefox, use Tab-key trap.
if (!document.all) {
	document.onkeypress = keyDownHandler;
}

/**
 * Initializes popup code on load.
 */
function initPopUp() {
	// Add the HTML to the body
	theBody = document.getElementsByTagName('BODY')[0];
	popmask = document.createElement('div');
	popmask.id = 'popupMask';
	popcont = document.createElement('div');
	popcont.id = 'popupContainer';
	popcont.innerHTML = '' +
		'<div id="popupInner">' +
					'<iframe src="'+ gDefaultPage +'" style="width:100%;height:100%;background-color:transparent;" scrolling="auto" frameborder="0" allowtransparency="true" id="popupFrame" name="popupFrame" width="100%" height="100%"></iframe>' +
		'</div>';
	theBody.appendChild(popmask);
	theBody.appendChild(popcont);

	gPopupMask = document.getElementById("popupMask");
	gPopupContainer = document.getElementById("popupContainer");
	gPopFrame = document.getElementById("popupFrame");

	// check to see if this is IE version 6 or lower. hide select boxes if so
	// maybe they'll fix this in version 7?
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
		gHideSelects = true;
	}
}
addEvent(window, "load", initPopUp);

 /**
	* @argument url - url to display
	* @argument returnFunc - function to call when returning true from the window.
	* @argument showCloseBox - show the close box - default true
	*/
function showPopWin(url, returnFunc) {
	gPopupIsShown = true;
	disableTabIndexes();
	gPopupMask.style.display = "block";
	gPopupContainer.style.display = "block";

	var height = getViewportHeight() * 4 / 5;
	var width = getViewportWidth() * 4 / 5;

	// calculate where to place the window on screen
	centerPopWin(width, height);

	gPopupContainer.style.width = width + "px";
	gPopupContainer.style.height = height + "px";

	setMaskSize();

	gPopFrame.style.width = (width-4) + "px";
	gPopFrame.style.height = (height) + "px";

	// set the url
	gPopFrame.src = url;

	gReturnFunc = returnFunc;
	// for IE
	if (gHideSelects == true) {
		hideSelectBoxes();
	}

}

//
var gi = 0;
function centerPopWin(width, height) {
	if (gPopupIsShown == true) {
		if (width == null || isNaN(width)) {
			width = gPopupContainer.offsetWidth;
		}
		if (height == null) {
			height = gPopupContainer.offsetHeight;
		}

		var theBody = document.getElementsByTagName("BODY")[0];
		var scTop = parseInt(getScrollTop(),10);
		var scLeft = parseInt(theBody.scrollLeft,10);

		setMaskSize();

		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();

		gPopupContainer.style.top = (scTop + ((fullHeight - (height)) / 2)) + "px";
		gPopupContainer.style.left =  (scLeft + ((fullWidth - width) / 2)) + "px";
	}
}
addEvent(window, "resize", centerPopWin);
addEvent(window, "scroll", centerPopWin);
window.onscroll = centerPopWin;

/**
 * Sets the size of the popup mask.
 *
 */
function setMaskSize() {
	var theBody = document.getElementsByTagName("BODY")[0];

	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();

	// Determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) {
		popHeight = fullHeight;
	} else {
		popHeight = theBody.scrollHeight;
	}

	if (fullWidth > theBody.scrollWidth) {
		popWidth = fullWidth;
	} else {
		popWidth = theBody.scrollWidth;
	}

	gPopupMask.style.height = popHeight + "px";
	gPopupMask.style.width = popWidth + "px";
}

/*
 * Hide popup window
 */
function hidePopWin(vReturn,sReturn) {
	if (gPopupMask == null) {
		return;
	}
	var theBody = document.getElementsByTagName("BODY")[0];
	theBody.style.overflow = "";
	restoreTabIndexes();
	gPopupMask.style.display = "none";
	gPopupContainer.style.display = "none";
	gPopFrame.src = gDefaultPage;
	if (gHideSelects == true) {
		displaySelectBoxes();
	}
	gPopupIsShown = false;

	if (gReturnFunc != null && vReturn != null) {
		document.getElementById(gReturnFunc).value=vReturn;
		if (sReturn != null) {
			document.getElementById(gReturnFunc + "_show").value=sReturn;
		}
	}
}

// Tab key trap. if popup is shown and key was [TAB], suppress it.
// @argument e - event - keyboard event that caused this function to be called.
function keyDownHandler(e) {
    if (gPopupIsShown && e.keyCode == 9)  return false;
}

// For IE.  Go through predefined tags and disable tabbing into them.
function disableTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				gTabIndexes[i] = tagElements[k].tabIndex;
				tagElements[k].tabIndex="-1";
				i++;
			}
		}
	}
}

// For IE. Restore tab-indexes.
function restoreTabIndexes() {
	if (document.all) {
		var i = 0;
		for (var j = 0; j < gTabbableTags.length; j++) {
			var tagElements = document.getElementsByTagName(gTabbableTags[j]);
			for (var k = 0 ; k < tagElements.length; k++) {
				tagElements[k].tabIndex = gTabIndexes[i];
				tagElements[k].tabEnabled = true;
				i++;
			}
		}
	}
}

/**
 * Hides all drop down form select boxes on the screen so they do not appear above the mask layer.
 */
function hideSelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++) {
    x[i].style.visibility = "hidden";
  }
}

/**
 * Makes all drop down form select boxes on the screen visible so they do not
 * reappear after the dialog is closed.
 */
function displaySelectBoxes() {
  var x = document.getElementsByTagName("SELECT");

  for (i=0;x && i < x.length; i++){
    x[i].style.visibility = "visible";
  }
}
