//Standard characters
var dot = '.';
var and = '&';
var qstn = '?';
var eql = '=';
var or = "||";

//Standard strings
var http = "http://";
var www = "www";
var httpwww = http + www;
var https = "https://";
var cgi = "cgi";
var scgi = "s"+cgi;
var jsExt = dot+"js";
var tclExt = dot+"tcl";
var com = "com";
var dotCom = dot+com;
var scriptOpen = '<SC' + 'RIPT SRC="';
var scriptClose = '"></SC' + 'RIPT>';

//eBay standard strings
var ebStr = "ebay";
var ebDom = dot+ebStr;
var ebInclude = "include";
var qaDom = dot+"qa"+dot;

var countryDomain = ".ebay.com/";
var countries = new Array(//Each array has prod and qa def
					new Array(".ebay.com.au/",".com.au/","au","Australia"),
					new Array(".ebay.at/",".at/","at","AT"),
					new Array(".befr.ebay.be/",".befr.","befr","Belgium"),	//jad092903
					new Array(".benl.ebay.be/",".benl.","benl","Belgium"),	//jad092903
					new Array(".ebay.ca/",".ca/","ca","Canada"),
					new Array(".ebay.ch/",".ch/","ch","CH"),
					new Array(".es.ebay.com/",".es.","es","Spain"),
					new Array(".ebay.fr/",".fr/","fr","France"),
					new Array(".ebay.de/",".de/","de","Germany"),
					new Array(".ebay.it/",".it/","it","Italy"),
					new Array(".ebay.co.in/",".in/","in","India"),		//gdc102704
					new Array(".ebay.nl/",".nl/","nl","Netherlands"),
					new Array(".tw.ebay.com/",".tw.","tw","Taiwan"),	//jad032703
					new Array(".ebay.com.cn/",".cn.","cn","China"),	//ank012604
					new Array(".ebay.co.uk/",".co.uk/","uk","UK"),
					new Array(".ebay.com/",".","us","US"));	//Default

//Location strings
var thisPage = location.href.toLowerCase();
var lastPage = "";												//jad010304
if (history.length > 1)
	lastPage = document.referrer.toLowerCase();
var thisPageURL, thisPageURI, lastPageURL, lastPageURI;

//QA machine variable
var qaMachineName = "";

//JS file specific includes
var includeDir = "", cobrandDir = "", countryCobrandDir = "";	//jad061603
var picsDir = "pics.ebaystatic.com/aw/pics/";					//jad111703, jad050504
var countryIncludeDir = "";	//jad032003
//jad030204 - Check for existence of includeHost before defaulting
var includeHost;
if (!includeHost)
	includeHost = http + ebInclude + ebDom + dotCom + "/";



function ebayUpdateLocationVars()

{

	var qInd = thisPage.indexOf(qstn);

	if (qInd == -1)

	{

		thisPageURL = thisPage;

		thisPageURI = "";

	}

	else

	{

		thisPageURL = thisPage.substring(0,qInd);

		thisPageURI = thisPage.substring(qInd);

	}

	qInd = lastPage.indexOf(qstn);

	if (qInd == -1)

	{

		lastPageURL = lastPage;

		lastPageURI = "";

	}

	else

	{

		lastPageURL = lastPage.substring(0,qInd);

		lastPageURI = lastPage.substring(qInd);

	}

	

	//Set the country variable

	var qaCountryDomain = countryDomain, c;		//jad032403

	country = "";

	for (var i=0; i<countries.length && (country == ""); i++)

	{

		c = "." + countries[i][2] + ".";

		if (thisPageURL.containsAny(c,countries[i][0],countries[i][1]))

		{

			countryDomain = countries[i][0];	//jad091103

			country = countries[i][2];

			countryDesc = countries[i][3];

			qaCountryDomain = (c == ".us.")?".":c;	//jad032403, jad101603

		}

	}



	//Set file location variables, jad050504 - Begin

	var isSecure = false;

	var isQA = thisPageURL.contains(qaDom);

	if (thisPageURL.indexOf(https) == 0)

	{

		isSecure = true;

		ebInclude = "secure" + ebInclude;

		picsDir = "secure" + picsDir;	//jad061603

	}

	

	if (isQA)

	{

		//jad032403 - Determine QA machine name, jad072103 - Use PERL var

		var qaInd = includeHost.indexOf(qaDom);

		var dotInd = includeHost.lastIndexOf(dot,qaInd-1)+1;

		if (dotInd != 0)

			qaMachineName = includeHost.substring(dotInd,qaInd);



		//jad101603 - Begin

		countryDomain = (qaMachineName == "")?"":qaCountryDomain;

		//jad101603 - End



		countryDomain += qaMachineName + qaDom + ebStr + dotCom + "/";	//jad091103

		//jad032403 - End

	}



	//jad111703 - Ensure that the protocol is http or https

	var protocol = thisPageURL.substring(0,thisPageURL.indexOf("://")+3);

	if (!protocol.isAny(http,https))

		protocol = http;



	picsDir = protocol + picsDir;

	includeDir = protocol + ebInclude + dot;

	if (isQA)

	{

		//jad062503 - Use local include pool for this unit machine

		if (qaMachineName != "")

			includeDir += qaMachineName + dot;



		includeDir += "qa" + dot;

	}



	includeDir += ebStr + "static" + dotCom + "/aw/pics/";	//jad061604

	//jad050504 - End



	cobrandDir = includeDir + "js/cobrand/";

	countryIncludeDir = includeDir + country + "/js/";	//jad032003

	countryCobrandDir = countryIncludeDir + "cobrand/";

	includeDir += "js/";

	

	//jad083004

	countryDoubleByte = country.isAny("tw","cn","ja");		

}





var DOM = document;


/*
 * Base component
 */
function Component(name) {
	this.id = name;
	this.eElement = null;
	this.bind = function () {
		this.eElement = DOM.getElementById(this.id);
	}
	this.instanceOfType = function _instanceOfType(type) {
		if ( this.type == type )
			return true;
		/*if ( this.base != null ) {
			return this.base.prototype.instanceOfType(type);
		} */
		return false;
	}
}
Component.prototype.type = "Component";
function Form(name) 
{
 	this.base = Component;
 	this.base(name);
	this.fields = new Array();
	this.controls = new Array();
	addOnLoadFunction(name + 'Obj.bind()');
	this.bind = function (){
		this.submitForm = this.eElement = DOM.getElementById(this.id);
		var i;
		for(i = 0; i < this.fields.length; i++ ) {
		//alert(this.eLement.id);
			this.fields[i].bind(this.eElement);
		}
		for(i = 0; i < this.controls.length; i++ ) {
			this.eElement[this.controls[i]].value = "";
		}
		//this.eElement["Action"].value = "";
	}
	this.addField = function(field) {
		this.fields[this.fields.length] = field;
	}
	this.addControl = function(c) {
		this.controls[this.controls.length] = c;
	}
	this.submit = function() {
		for(var i = 0; i < this.fields.length; i++ ) {
			if ( this.fields[i].beforeSubmit(this.eElement) == false ) {
				return false;
			}
		}
		/*
		for(var j = 0; j < this.submitForm.elements.length; j++ ) {
			alert(this.submmitForm.elements[j].name + "==" + this.submitForm.elements[j].value);
		} */
		this.submitForm.submit();
		return false;
	}

	this.submitAction = function(action) {
		this.eElement[action].value = action;
		this.submit();
	}
	this.setSubmitForm = function(form) {
		this.submitForm = form;
	}
}
Form.prototype.type = "Component";

function FormField(name,frm) 
{
 	this.base = Component;
 	this.base(name);
	this.form = frm;
    this.tipColor = '#666666';

	frm.addField(this);

	this.bind = function (frm) {
		this.eElement = frm[this.id];
		if ( this.eElement == null )
			this.eElement = this.form.submitForm[this.id];
	};	
	this.valueChanged=function(val) {
		//if ( this.eElement.onchange != "undefined" ) 
		//	this.eElement.onchange();
	}
	this.getValue=function () {
		return this.eElement.value;
	}

	this.setVisibility=function(show) {
		if ( show == "show" ) {
			this.eElement.style.visibility = "visible";
		} else if (show == "hide") {
			this.eElement.style.visibility = "hidden";
		}
	}

	this.beforeSubmit = function(frm) {
		return true;
	}

	this.disable = function(disabled) {
		var u = "undefined";
		var cntrl = this.eElement;
		//disabling control
		if(typeof(cntrl.disabled)!=u)
			cntrl.disabled = disabled;
		if(typeof(cntrl.style)!=u);
		{
			if(disabled)
				cntrl.style.background = "rgb(178,178,178)";
			else
				cntrl.style.background = "#fff";
		}
	}


}
FormField.prototype.type = "FormField";

function TextInput(name,frm,tip) 
{
 	this.base=FormField;
 	this.base(name,frm);
 	this.tip = tip;
	this.setValue=function(val) {
		this.eElement.value = val;
		this.valueChanged();
	}
	
	this.bind = function (frm) {
		this.eElement = frm[this.id];
		if ( typeof(this.eElement) == "undefined" ){
			this.eElement = this.form.submitForm[this.id];
		}
		if ( this.tip && this.tip != '') {
		    this.eElement.focusEvent = function(e) {
                if (!e) e = window.event;
                var targ;
                if (e.target) targ = e.target;
	            else if (e.srcElement) targ = e.srcElement;
	            if ( targ.value == targ.tip )
	                targ.value = '';
	            //targ.onfocus = '';
	            //var re = new RegExp('(?:^|\\s+)' + targ.tip + '(?:\\s+|$)', 'g');
        		//targ.value = targ.value.replace(re, '');
		        targ.style.color = '';
		    }
		    this.eElement.ondrop = function(e) {
                if (!e) e = window.event;
                var targ;
                if (e.target) targ = e.target;
	            else if (e.srcElement) targ = e.srcElement;
	            if ( targ.value == targ.tip )
	                targ.value = '';
	            //targ.onfocus = '';
		        targ.style.color = '';		    
		    }
		    var re= "\u00A0";
		    this.tip = this.tip.replace(re," ");
		    this.eElement.tip = this.tip;
		    this.eElement.tipColor = this.tipColor;
		    if ( this.eElement.value == '' || this.eElement.value == this.tip ) {
		        this.eElement.value = this.tip;
		        this.eElement.style.color = this.tipColor;
		        this.eElement.blur();
		        this.eElement.onfocus = this.eElement.focusEvent;
		        /*
		        this.eElement.onfocus = function(e) {
                    if (!e) e = window.event;
                    var targ;
                    if (e.target) targ = e.target;
	                else if (e.srcElement) targ = e.srcElement;
	                targ.value = '';
	                targ.onfocus = '';
		            targ.style.color = '';
		        }*/
		    }
		    this.eElement.onblur = function(e) {
		        if (!e) e = window.event;
                var targ;
                if (e.target) targ = e.target;
	            else if (e.srcElement) targ = e.srcElement;
	            /*
	             targ.value = '';
	                targ.onfocus = '';
		            targ.style.color = '';
		            */
                if ( this.value == '' || this.value == this.tip) {
                    this.value = this.tip;
		            this.style.color = this.tipColor;
		            this.onfocus = this.focusEvent
                }
		    }
		}
	};
	this.beforeSubmit = function(frm) {
	    if ( this.eElement.value == this.tip )
	        this.eElement.value = "";
		return true;
	}


}
TextInput.prototype.type = "TextInput";

function TextAreaInput(name,frm) 
{
 	this.base=TextInput;
 	this.base(name,frm);
}
TextAreaInput.prototype.type = "TextAreaInput";
 
function RadioInput(name,frm) 
{
 	this.base=FormField;
 	this.base(name,frm);
	this.bind = function(frm){
		this.eElements = frm[this.id];
		if (typeof(this.eElements.length) != "undefined")  {
			this.eElement = this.eElements[0];
		} else {
			this.eElement = this.eElements;
			this.eElements = new Array();
			this.eElements[0] = this.eElement;
		} 
   	}

	this.getValue = function () {
		for( var i = 0; i < this.eElements.length;i++)
			if ( this.eElements[i].checked)
				return this.eElements[i].value;
		return null;
	}

	this.setValue = function(val) {
		for( var i = 0; i < this.eElements.length;i++) {
			this.eElements[i].checked = this.eElements[i].value == val;
		}
		this.valueChanged();
	} 

}
RadioInput.prototype.type = "FormField";

function CheckboxInput(name,frm) 
{
 	this.base = RadioInput;
 	this.base(name,frm);



/*
	function _getValues() {
		var list = new Array();
		for( var i = 0; i < this.eElements.length;i++) {
			if ( this.eElements[i].checked)	{
				list[list.length] = this.eElements[i].value;
			}
		}
		return list;
	}

	function _setValues(values) {
		for( var i = 0; i < this.eElements.length;i++) {
			this.eElements[i].checked = this.eElements[i].value == val;
		}
	} 
	  */
}


function SelectInput(name,frm) 
{
 	this.base = FormField;
 	this.base(name,frm);

   /*	this.bind = function (frm) {
		this.eElement = frm[this.id];
	};	*/

	this.getValue = function () {
		var selectedIndex = this.eElement.selectedIndex;
		if ( selectedIndex != null && selectedIndex >= 0 )
			return this.eElement.options[selectedIndex].value;
		return null;
	}

	this.setValue = function(val) {
		var options = this.eElement.options;
		for( var i = 0; i < options.length;i++) {
			if ( options[i].value == val ) {
				this.eElement.selectedIndex = i;
				break;
			}
		}
		this.valueChanged();
	} 

	this.replaceOptions = function (list) {
		this.clearOptions();
		var options = this.eElement.options;
		if ( list != null ) {
			for( var i = 0; i < list.length; i++ ) {
				options[i] = new Option(list[i][1],list[i][0]);
			}
		}
		this.disable(options.length == 0 );
	}

	this.clearOptions = function () {
		var options = this.eElement.options;
		for( var i = options.length - 1; i >= 0; i-- ) {
			options[i] = null;
		}
		this.eElement.selectedIndex = -1;
	}	  
		  
}
SelectInput.prototype.type = "SelectInput";

function IFrameObj(name,nobind) 
{
 	this.base = Component;
 	this.base(name);
	this.domain  = null;
	if ( nobind != true )
		addOnLoadFunction(name + '.bind()');
	this.bind = function () {
		var frm = this.eElement = DOM.getElementById(this.id);
		this.doc = null;
		if (frm.contentDocument) {
    		// For NS6, opera, firefox
    		this.doc = frm.contentDocument; 
  		} else if (frm.contentWindow) {
   			// For IE5.5 and IE6
    		this.doc = frm.contentWindow.document;
  		} else if (frm.document) {
    		// For IE5
    		this.doc = frm.document;
  		}
	}

	this.setDomain= function(domain) {
		this.domain = domain;
	}	

	this.getWindow = function() {
		if (document.all) {
			return this.eElement;
		} else {
			return this.eElement.contentWindow;
		}
	}

	this.writeDocument = function(content,design) {
		this.doc.open();
		this.doc.write(content);
		this.doc.close();
		if ( design )
			this.doc.designMode = "On";
		this.resetDocument(this.eElement);
		/*
		if ( this.domain != null )
			this.doc.domain = this.domain;
			*/
	}

	this.getBodyContent = function() {
		return this.doc.body.innerHTML;
	}
		
	this.getDocBody = function() {
		return this.doc.body;
	}		
		
	this.getSelection = function() {
		if (document.all) {
			return this.doc.selection; 
		} else {
			return this.eElement.contentWindow.getSelection();
		}
	}
	
	this.getSelectionRange = function() {
		var selection = this.getSelection();
		if ( selection != null ) {
			if (document.all) {
				return selection.createRange();
			} else {
				return selection.getRangeAt(selection.rangeCount - 1).cloneRange();
			}
		}
		return null;
	}

	this.setVisibility=function(show) {
		if ( show == "show" ) {
			this.eElement.style.visibility = "visible";
		} else if (show == "hide") {
			this.eElement.style.visibility = "hidden";
		}
	}
	this.toggleVisibility=function() {
		this.setVisibility(this.eElement.style.visibility == "visible"? "hide" : "show");
	}

	this.setLeft=function(l) {
		this.eElement.style.left = l;
	}

	this.setTop=function(t) {
		this.eElement.style.top = t;
	}

	this.execCommand = function(command, option) {
		var win;
		if (document.all) {
			win = frames[this.id];
		} else {
			win = document.getElementById(this.id).contentWindow;
			win.focus();
		}
		try {
			win.focus();
	  		win.document.execCommand(command, false, option);
			win.focus();
		} catch (e) {
//		setTimeout("rteCommand('" + rte + "', '" + command + "', '" + option + "');", 10);
		}
	}

	this.resetDocument = function(frm) {
		if (frm.contentDocument) {
    		// For NS6, opera, firefox
    		this.doc = frm.contentDocument; 
  		} else if (frm.contentWindow) {
   			// For IE5.5 and IE6
    		this.doc = frm.contentWindow.document;
  		} else if (frm.document) {
    		// For IE5
    		this.doc = frm.document;
  		}
	}
		
}
IFrameObj.prototype.type = "IFrameObj";

function RichTextEdit(name,frm,width,height,css,localeCss,wysiwygImagesPath,showFont,hasError,hide,showButtons,hideEditorBorder) 
{
 	this.base = TextAreaInput;
 	this.base(name,frm);
	this.isRichTextEdit = document.designMode && (client.nav || client.ie);
 	this.css = css;
 	this.localeCss = localeCss;
	//this.css =	"http://include.ebaystatic.com/aw/pics/c3css/kijiji/rel2/c3common.css";
	//this.localeCss = "http://include.ebaystatic.com/aw/pics/c3css/kijiji/rel2/de-DE/classifieds.css";
	this.range = null;
	this.hide = hide;
	this.binded = false;
	this.originalDomain = document.domain;
	this.domain = null;

	/*var poolIdx = document.domain.indexOf(".");
	if (poolIdx != -1) 
		this.domain =  new String(document.domain).substr(poolIdx+1); 
   	else
		this.domain = document.domain; */
	if ( this.isRichTextEdit ) {
		/*
		if ( client.ie ) {
			document.onmouseover = raiseButton;
			document.onmouseout  = normalButton;
			document.onmousedown = lowerButton;
			document.onmouseup   = raiseButton;
		} */


 		//wysiwygImagesPath = "http://pics.ebaystatic.com/aw/pics/classifieds/wysiwyg_editor/";
		 
		if (width < 410) width = 410;
		var tablewidth = width;
		if (!client.ie) {
			tablewidth += 4;
		}
		
		var aolBorder = "";
		if(client.aol){
			aolBorder = "border:1px solid;";
		}
	
		var styles = [ 
			["<p>","Paragraph &lt;p&gt;"],
			["<h1>","Heading 1 &lt;h1&gt;"],
			["<h2>","Heading 2 &lt;h2&gt;"],
			["<h3>","Heading 3 &lt;h3&gt;"],
			["<h4>","Heading 4 &lt;h4&gt;"],
			["<h5>","Heading 5 &lt;h5&gt;"],
			["<h6>","Heading 6 &lt;h6&gt;"]];
		var fonts = [
			["Arial, Helvetica, sans-serif","Arial"],
			["Courier New, Courier, mono","Courier New"],
			["Times New Roman, Times, serif","Times New Roman"],
			["Verdana, Arial, Helvetica, sans-serif","Verdana"]];
		var buttons = [
			["bold.gif","Bold","bold"],
			["italic.gif","Italic","italic"],
			["underline.gif","Underline","underline"],
			["sep",null],
			["left_just.gif","Align Left","justifyleft"],
			["centre.gif","Center","justifycenter"],
			["right_just.gif","Align Right","justifyright"],
			["justifyfull.gif","Justify Full","justifyfull"],
			["sep",null],
			["hr.gif","Horizontal Rule","inserthorizontalrule"],
			["sep",null],
			["numbered_list.gif","Ordered List","insertorderedlist"],
			["list.gif","Unordered List","insertunorderedlist"],
			["sep",null],
			["outdent.gif","Outdent","outdent"],
			["indent.gif","Indent","indent"],
			["textcolor.gif","Text Color","forecolor"],
			["bgcolor.gif","Background Color","hilitecolor"]];


	   var rteObj = "rte" + name + "Obj";	
		document.writeln('<div id="rteRoot" class="rteDiv">');
		
		// default behavior is to show formatting buttons, so if showButtons is not specified formatting will be displayed		
		var displayFormatting = (showButtons==undefined || showButtons!=false);
		if (displayFormatting) {
			document.writeln('<table class="rteBack" cellpadding="0" cellspacing="0" id="Buttons2_' + name + '" width="' + tablewidth + '">');
			document.writeln('	<tr>');
			for(i = 0; i < buttons.length; i++ ) {
				var img = buttons[i][0];
				if ( img == "sep" ) {
					document.writeln('<td><img class="rteVertSep" src="' + wysiwygImagesPath + 'blackdot.gif" width="1" height="20" border="0" alt=""></td>');
				} else {
					document.writeln('<td><img id="bold" class="rteImage" src="' + wysiwygImagesPath + buttons[i][0] + '" width="25" height="24" alt="' + buttons[i][1] +'" title="' + buttons[i][1] + '" onClick="' + rteObj + '.btn(\'' + buttons[i][2] + '\',this,event)"></td>');
				}
			}
			document.writeln('		<td width="100%"></td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
			document.writeln('<table class="rteBack" cellpadding=2 cellspacing=0 id="Buttons1_' + name + '" width="' + tablewidth + '">');
			document.writeln('	<tr>');
			/*
			document.writeln('		<td>');
			document.writeln('			<select name="styleType" id="formatblock_' + name + '" onchange="' + rteObj + '.selectFont(this);">');
			document.writeln('				<option value="">[Style]</option>');
			for(i = 0; i < styles.length; i++ )
				document.writeln('<option value="' + styles[i][0] + '">' + styles[i][1] + '</option>');
			document.writeln('			</select>');
			document.writeln('		</td>');
			*/
			if ( showFont ) {	
				document.writeln('		<td>');
				document.writeln('			<select name="fontType" id="fontname_' + name + '" onchange="' + rteObj + '.selectFont(this)">');
				document.writeln('				<option value="Font" selected>[Font]</option>');
				for(i = 0; i< fonts.length;i++)
					document.writeln('<option value="' + fonts[i][0] + '">' + fonts[i][1] + '</option>');
				document.writeln('			</select>');
				document.writeln('		</td>');
			}
			document.writeln('		<td>');

			document.writeln('			<select name="fontSize" unselectable="on" id="fontsize_' + name + '" onchange="' + rteObj + '.selectFont(this)">');
			document.writeln('				<option value="Size">[Size]</option>');
			for( i = 1; i < 3; i++)
				document.writeln('<option value="' + i + '">' + i + '</option>');



			for( i = 3; i < 6; i++)

				document.writeln('<option value="' + (i+1) + '">' + i + '</option>');


			document.writeln('			</select>');
			document.writeln('		</td>');
			document.writeln('		<td width="100%">');
			document.writeln('		</td>');
			document.writeln('	</tr>');
			document.writeln('</table>');
		}
		
		//document.write('<iframe id="' + rte + '" name="' + rte + '" width="' + width + 'px" height="' + height + 'px" src="'+wysiwygInitPage+'" ');
		
		document.write('<iframe style="' + aolBorder + '" id="rte' + name + '" name="rte' + name + '" width="' + width + 'px" height="' + height + 'px" ');
		if (hasError) {
			document.write('class="error_field" ');			
		}
		if (hideEditorBorder==true) {
			document.write('frameborder="0" ');
		}
		document.writeln('></iframe>');
		document.writeln('<iframe width="154" height="104" id="cp' + name + '" name="cp' + name + '" marginwidth="0" marginheight="0" scrolling="no" style="visibility:hidden; position: absolute;"></iframe>');
		document.writeln('</div>');
		/*
		document.writeln('<div id="createLink" class="modalWindow2"><div class="modalTitle">Enter Link</div><div class="modalContent"><center>' +
			'<table cellpadding="4" cellspacing="0" border="0">' +
			'<tr><td colspan="2"><b>Tip:</b> To insert an email link, start your URL with "mailto:"</td></tr>' +
			'<tr><td align="right">URL:</td><td><input name="linkUrl" type="text" id="url" size="40"></td></tr>' +
			'<tr><td colspan="2" align="center"><input type="button" value="Insert Link" onClick="' + rteObj + '.createLink();_popup.hide();"/>&nbsp;<input type="button" value="Cancel" onClick="_popup.hide();" /></td></tr>' +
			'</table></center></div></div>');
			*/

		if (displayFormatting) {
			CreateColorPalette();
		}	
	}

	this.selectFont = function(sel) {
		var idx = sel.selectedIndex;
		
		// First one is always a label
		if (idx != 0) {
			var selected = sel.options[idx].value;
			idx = sel.id.indexOf("_");
			var cmd = sel.id.substring(0,idx);
			this.contentFrame.execCommand(cmd, selected);
			sel.selectedIndex = 0;
		}
	}

	this.btn = function(command,button,ev) {
		if ( command == "hilitecolor" || command == "forecolor") {
			this.range = this.contentFrame.getSelectionRange();
			rteCommand = command;
			rteActive = this;
			_popup.showMenu(document.getElementById("colorPalette"),button,ev);
		} else if ( command == "link") {
			this.range = this.contentFrame.getSelectionRange();
			rteCommand = command;
			rteActive = this;
			var linkText;
			var urlText = "";
			if ( client.ie)
				linkText = this.range.htmlText;
			else
				linkText = this.range.toString();
			var parent = this.range.parentElement();
			if ( parent.tagName.toLowerCase() == "a" )



				urlText = parent.getAttribute("href");

			document.getElementById("linkUrl").value = urlText;
			_popup.show(document.getElementById("createLink"),true,450);
		} else {
			this.contentFrame.execCommand(command,"");
		}
	}

	this.createLink = function() {
		var link = document.getElementById("linkUrl").value;
		var parent = this.range.parentElement();
		if ( parent.tagName.toLowerCase() == "a" )
			parent.setAttribute("href",link);
		else {
			this.contentFrame.getWindow().focus();
			this.range.select();
			this.contentFrame.execCommand("createlink",link);
		}
			
	}
	
	this.beforeSubmit = function(frm) {
		if ( this.isRichTextEdit && this.binded) {
			this.eElement.value = cleanUpHTML(this.contentFrame.getBodyContent());
		}
		return true;
	}

	this.bind = function (frm) {
		this.eElement = frm[this.id];
		if ( typeof(this.eElement) == "undefined" ) {
			// form sliced into multi forms dues to EPS
			this.eElement = this.form.submitForm[this.id];
		}
		if ( this.isRichTextEdit ) {
		    if ( this.hide )
		        return;
	        this.binded = true;
			this.eElement.style.display = "none"; 

 	 	
			this.contentFrame = new IFrameObj("rte" + this.id,true);
			this.contentFrame.bind();
			if ( this.domain != null )
		   		this.contentFrame.setDomain(this.domain);					
			this.contentFrame.writeDocument(rteInitialDoc(this.getValue()),true);

			if ( this.domain != null ) {
				document.domain = this.domain;
			}
			
			/*alert(this.contentFrame.doc.nodeName);
			var child = this.contentFrame.doc.firstChild;
			
			alert(child);
			child = child.getElementsByTagName("body")[0];
			client.addSimpleEventListener(child,"paste",testEvent,false);
			client.addSimpleEventListener(child,"drop",testEvent,false);*/

		} 
	}
	
	this.show = function() {
	    if ( !this.binded ) {
	        this.hide = false;
	        this.bind(this.form);
	    }
	}

	this.setColor=function(command,color) {
		if (document.all) {
			if (command == "hilitecolor") command = "backcolor";
		
			//retrieve selected range
			this.range.select();
		}
		this.contentFrame.execCommand(command,color);
	}

	function rteInitialDoc(html) {
		var frameHtml = "<html>\n";
		frameHtml += "<head>\n";
		frameHtml += "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>\n";
		
		//to reference your stylesheet, set href property below to your stylesheet path and uncomment
		if (css != null && css != "") {
			frameHtml += '<link href="' + css + '" rel="stylesheet" type="text/css">';
		}
		if (localeCss != null && localeCss != "") {
			frameHtml += '<link href="' + localeCss + '" rel="stylesheet" type="text/css">';
		}
		frameHtml += "<style>\n";
		frameHtml += "body {\n";
		frameHtml += "	background: #FFFFFF;\n";
		frameHtml += "	margin: 0px;\n";
		frameHtml += "	padding: 0px;\n";
		frameHtml += "  text-align:left;\n";
		frameHtml += "}\n";
		frameHtml += " P {margin-top:0;margin-bottom:0}\n"; 
		frameHtml += "}\n"; 
		frameHtml += " a{text-decoration: none;color:#000}\n";
		frameHtml += "</style>\n";
		frameHtml += "</head>\n";
		frameHtml += "<body>\n";
		frameHtml += html + "\n";
		frameHtml += "</body>\n";
		frameHtml += "</html>";
		return frameHtml;
	}
	
	this.updateDocument = updateDocumentFunction;
	
	function updateDocumentFunction(updatedHtml) {
		try {
			if (this.contentFrame.getDocBody()) {
				$(this.contentFrame.getDocBody()).html(updatedHtml);
			}			
		} catch(e) {
			//alert('error: '+e.description);
		}
	}
	
	this.getBodyText = function() {
		if (this.contentFrame.getDocBody()) {
			return $(this.contentFrame.getDocBody()).text();
		}
		return "";
	}
	
	function cleanUpHTML(htmlContent) {
		var regKijijiHref = new RegExp('<A href="#" src=\"([^\"]+)\"([^<]*)>[^<]*</A>','gi');
		htmlContent = htmlContent.replace(regKijijiHref, ' $1 ');
		var regHref = new RegExp('<A href=\"([^\"]+)\"([^<]*)>[^<]*</A>','gi');
		htmlContent = htmlContent.replace(regHref, ' $1 ');
		var regHref2 = new RegExp('<A href=\'([^\']+)\'([^<]*)>[^<]*</A>','gi');
		htmlContent = htmlContent.replace(regHref2, ' $1 ');

		var regScript = new RegExp('<script([^<]*)>[^<]*</' + 'script>','gi');
		htmlContent = htmlContent.replace(regHref, '');

		if (client.ie) {
			//Fix IE's default behaviour, i.e. enter == <p></p>: replace paragraphs by divs
			htmlContent = htmlContent.replace(/<P([^>]*)>/gi, '<DIV $1>') ; 
			htmlContent = htmlContent.replace(/<\/P>/gi, '</DIV>') ; 
				
			//MSHTML (IE) auto-detects URLs and make them click-able!! Undo it.
			/*var regEx = new RegExp('<A href=\"(http|https|ftp|gopher|new|snews|telnet|wasis|file|nntp|newsrc|ldap|ldaps|outlook|mic|url){1}(\:){1}(\/\/)?([^\"]+)\">[^<]*</A>','gi');
			htmlContent = htmlContent.replace(regEx, ' $1$2$3$4 ');
	

			var regEx = new RegExp('<A href=\"mailto:([^\"]+)\">[^<]*</A>','gi');
			htmlContent = htmlContent.replace(regEx, ' $1 ');*/
		}
		
		var regEx = new RegExp('<\\?xml:namespace [^>]*>','gi');
		htmlContent = htmlContent.replace(regEx, ' ');
	
		//Remove newlines otherwise backend will add extra <p> per newline.
		htmlContent = htmlContent.replace(/\n/g," ");
		htmlContent = htmlContent.replace(/\r/g," ");
		htmlContent = htmlContent.replace(/\f/g," ");

		//Asian countries disreagrd <strong>, only work with <b>
		htmlContent = htmlContent.replace(/<STRONG>/gi, '<B>'); 
		htmlContent = htmlContent.replace(/<\/STRONG>/gi, '</B>'); 

		//Windows Word return tags
		htmlContent = htmlContent.replace(/<o:p>/gi,  " "); 
		htmlContent = htmlContent.replace(/<\/o:p>/gi, " "); 
		return htmlContent;
	}
 
		
}

RichTextEdit.prototype.type = "RichTextEdit";
var rteInit = false;




















//********************
//Gecko-Only Functions
//********************
function geckoKeyPress(evt) {
	//function to add bold, italic, and underline shortcut commands to gecko RTEs
	//contributed by Anti Veeranna (thanks Anti!)
	var rte = evt.target.id;
	
	if (evt.ctrlKey) {
		var key = String.fromCharCode(evt.charCode).toLowerCase();
		var cmd = '';
		switch (key) {
			case 'b': cmd = "bold"; break;
			case 'i': cmd = "italic"; break;
			case 'u': cmd = "underline"; break;
		};

		if (cmd) {
			rte.btn(cmd);
			
			// stop the event bubble
			evt.preventDefault();
			evt.stopPropagation();
		}
 	}
}
//*****************
//IE-Only Functions
//*****************
function ieKeyPress(evt, rte) {
	var key = (evt.which || evt.charCode || evt.keyCode);
	var stringKey = String.fromCharCode(key).toLowerCase();
	
//the following breaks list and indentation functionality in IE (don't use)
//	switch (key) {
//		case 13:
//			//insert <br> tag instead of <p>
//			//change the key pressed to null
//			evt.keyCode = 0;
//			
//			//insert <br> tag
//			currentRTE = rte;
//			insertHTML('<br>');
//			break;
//	};
}


var bgColors = [
		["#FFFFFF","#FFCCCC","#FFCC99","#FFFF99","#FFFFCC","#99FF99","#99FFFF","#CCFFFF","#CCCCFF","#FFCCFF"],
		["#CCCCCC","#FF6666","#FF9966","#FFFF66","#FFFF33","#66FF99","#33FFFF","#66FFFF","#9999FF","#FF99FF"],
		["#C0C0C0","#FF0000","#FF9900","#FFCC66","#FFFF00","#33FF33","#66CCCC","#33CCFF","#6666CC","#CC66CC"],
		["#999999","#CC0000","#FF6600","#FFCC33","#FFCC00","#33CC00","#00CCCC","#3366FF","#6633FF","#CC33CC"],
		["#666666","#990000","#CC6600","#CC9933","#999900","#009900","#339999","#3333FF","#6600CC","#993399"],
		["#333333","#660000","#993300","#996633","#666600","#006600","#336666","#000099","#333399","#663366"],
		["#000000","#330000","#663300","#663333","#333300","#003300","#003333","#000066","#330099","#330033"]];


var rteCommand = null;
var rteActive = null;

function subAreaChanged(hideSubArea) {
	var sa = SubAreaObj.getValue();
	var slList = subLocationArrays[sa];
	if ( sa && sa != "" && slList.length > 0 ) {
	    var list = hideSubArea ? [['','..........']] : [];
	    list = list.concat(subLocationArrays[sa]);
	    NeighborhoodObj.replaceOptions(list);
	    NeighborhoodObj.setValue('');
	    var nb = document.getElementById("nb");
	    if ( nb) 
	        nb.style.display = "inline";
	 } else {
	    //clear 
	    NeighborhoodObj.replaceOptions([]);
	    if (hideSubArea) 
	        document.getElementById("nb").style.display = "none";
	 }
	//NeighborhoodObj.replaceOptions(subLocationArrays[sa]);
}

function initNeighborhood(hideSubArea) {
	var nh = NeighborhoodObj.getValue();
	var sa = SubAreaObj.getValue();
	if ( sa && sa != "" ) {
	    var slList = subLocationArrays[sa];
	    if ( slList && slList.length > 0 ) {
					var list = hideSubArea ? [['','..........']] : [];
					list = list.concat(subLocationArrays[sa]);
	        NeighborhoodObj.replaceOptions(list);
	        NeighborhoodObj.setValue(nh);
	        var nb = document.getElementById("nb");
	        if ( nb )
	            nb.style.display = "inline";
	        return;
	    }
	} 
	NeighborhoodObj.replaceOptions([]);
	if ( hideSubArea )
	    document.getElementById("nb").style.display = "none";

}


function replaceContent(id,content) {
	var element = document.getElementById(id);
	if ( element != null ) {
		element.innerHTML = content;
	}
}


function CalendarWidget(n,minY,maxY) {
	this.name = n;
	this.dayElement = document.getElementById(this.name +'Day');
	this.monthElement = document.getElementById(this.name +'Month');
	this.yearElement = document.getElementById(this.name +'Year');
	var yr = this.yearElement.options[0].value;
	if ( yr == "" )
	    yr = this.yearElement.options[1].value;
	this.minYear = parseInt(yr,10);
	yr = this.yearElement.options[this.yearElement.length-1].value;
	this.maxYear = parseInt(yr,10);
        this.eventListener = [];
	this.createWidget = function() {
		document.write('<img src="' + ImageURL + '" align="baseline" title="Calendar" border="0" onclick="' + this.name + 'Obj.show(this,event)">&nbsp;');
		this.monthChanged(this.monthElement);
	}
	
   	this.setCalendarContent = function(y,m) {
		var nextMonthName = MonthNames[(m < 11 ? m+1 :0)];
		var monthName = MonthNames[m];
		var prevMonthName = MonthNames[(m > 0 ? m -1 :11)];
		var dt = new Date(y, m, 1);
		this.firstDay = dt.getDay();
		this.dayCount = GetDaysCountForMonth(y,m);
		this.displayedYear = y;
		this.displayedMonth = m;

		var HTML = '<table class="calendar" cellspacing="0" cellpadding="1"><tr class="caltitle"><td>';
		if ( y > this.minYear || m > 0 ) {
			HTML += '<a href="javascript:_popup.dispatchEvent(\'prev\')"><img src="' + PrevURL + '" title="' + prevMonthName + '" border="0"></a>';
		} else {
			HTML += '&nbsp;';
		}
		HTML += '</td><td nowrap align="center" colspan="5">' + monthName + '&nbsp;' + y + '</td><td>';
		if ( y < this.maxYear || m < 11 ) {
        	HTML += '<a href="javascript:_popup.dispatchEvent(\'next\')"><img src="' + NextURL + '" title="' + nextMonthName + '" border="0"></a>';
        } else {
			HTML += '&nbsp;';
        }
        HTML += '</td></tr><tr>';
        for (var w=0;w<7;w++) 
         	HTML += '<td class="calhd">' + WeekDays[w] + '</td>';
		HTML += '</tr>';
		var sameMonthAndYear = this.displayedYear == this.valueYear && this.displayedMonth == this.valueMonth;
		var todayMonthAndYear = this.displayedYear == this.todayYear && this.displayedMonth == this.todayMonth;
   	   	for (var j=0;j< 6;j++) {
      		HTML += '<tr>';
      	   	for (var i=1;i<=7;i++) {
         		var Day = (j * 7) + (i - this.firstDay);
         		if ((Day >= 1) && (Day <= this.dayCount)) {
					var cls = null;
            		if ( sameMonthAndYear && (Day == this.valueDay)) {
			   			cls = "calseldate";
            		}
            		if ( todayMonthAndYear && (Day == this.todayDay)){
						if ( cls == null )
							cls = "caltoday";
						else
							cls += " caltoday";
            		};	
					if ( cls == null )
						cls = '';
					else 
						cls ='class="' + cls + '"';	
            		HTML += '<td align="center" ' + cls + ' onMouseOver="client.addClass(this,\'calhover\')" onMouseOut="client.removeClass(this,\'calhover\')" onclick="_popup.dispatchEvent(\'select\',' + Day + ')">' + Day + '</td>';
         		}
         		else HTML += '<td>&nbsp;</td>'; 
      		}
      		HTML += '</tr>';
   		}
   		HTML += '</table>';
		setElementContent("CalendarPopup",HTML);
	 
	}

	this.next = function(param,src) {
		var m = this.displayedMonth;
		var y = this.displayedYear;
		if ( m < 11 ) {
			m++;
		} else {
			m = 0;
			y++;
		}
		this.setCalendarContent(y,m);
	}
	
	this.previous = function(param,src) {
		var m = this.displayedMonth;
		var y = this.displayedYear;
		if ( m > 0 ) {
			m--;
		} else {
			m = 11;
			y--;
		}
		this.setCalendarContent(y,m);
	}
	
	this.select = function(param,src) {

		//if ( this.valueYear != this.displayedYear ) {
		var yearElement = document.getElementById(this.name + 'Year');
		for(var i = 0;i<yearElement.options.length;++i){
			if(yearElement.options[i].value == this.displayedYear){
				yearElement.selectedIndex = i;
				 break;
			}
		}
		//}
		
		//if ( this.valueMonth != this.displayedMonth ) {
		var monthElement = document.getElementById(this.name + 'Month');
		var m = "" + this.displayedMonth;
		for(var i = 0;i<monthElement.options.length;++i){
			if(monthElement.options[i].value == m){
				monthElement.selectedIndex = i;
				break;
			}
		}
		this.monthChanged();
		var dayElement = document.getElementById(this.name + 'Day');
		
		for(var i = 0;i<dayElement.options.length;++i){
			if(dayElement.options[i].value == src){
				dayElement.selectedIndex = i;
				 break;
			}
		}

		_popup.hide();
		this.dispatchEvent('datechange');
		
	}
	
	this.yearChanged = function (elm) {
		this.monthChanged(elm);
	}
	
	this.monthChanged = function (elm) {
		if ( this.monthElement.options[this.monthElement.selectedIndex].value != '' && 
			this.yearElement.options[this.yearElement.selectedIndex].value != '' ) {
			this.setCurrentValues();
			var newDays = GetDaysCountForMonth(this.valueYear,this.valueMonth);
			var dayList = this.dayElement;
			var dayInc = 1;
			if ( dayList.options[0].value == '') {
			    dayInc = 0;
			    newDays++;
			}
			if ( newDays != dayList.length ) {
				var oldSize = dayList.length;
				for (var k=Math.min(newDays,oldSize);k<Math.max(newDays,oldSize);k++) {
					(k >= newDays) ? dayList.options[newDays] = null : dayList.options[k] = new Option(dayInc + k, dayInc + k);
				}
				var dayPick = Math.min(this.valueDay, newDays);
				if ( dayList.options[0].value != '')
					dayPick--;
				if ( dayPick >= dayList.length)
				    dayPick = dayList.length-1;
				dayList.options[dayPick].selected = true;
			}
		}	
   	}
	
	this.show = function(e,ev) {
		var Today = new Date();
		this.todayYear = Today.getFullYear();
		this.todayMonth = Today.getMonth();
		this.todayDay = Today.getDate();
		
		this.setCurrentValues();
		this.setCalendarContent(this.valueYear,this.valueMonth);
		_popup.addListener('next',this.next,this);
		_popup.addListener('prev',this.previous,this);
		_popup.addListener('select',this.select,this);
		_popup.showMenu(document.getElementById("CalendarPopup"),e ,ev);
	} 
	
	this.setCurrentValues = function(t) {
		var Today = new Date();
		var yr = this.yearElement.options[this.yearElement.selectedIndex].value;
		if ( yr == '' )
			yr = this.yearElement.options[1].value;
		this.valueYear = parseInt(yr,10);
		if ( this.monthElement.options.length > 12 ) {
			this.valueMonth = this.monthElement.selectedIndex > 0 ? this.monthElement.selectedIndex - 1 : Today.getMonth();
		} else {
			this.valueMonth = this.monthElement.selectedIndex;
		}
		if ( this.dayElement.options[0].value == '') {
			this.valueDay = this.dayElement.selectedIndex > 0 ? this.dayElement.selectedIndex : Today.getDate();
		} else {
			this.valueDay = this.dayElement.selectedIndex + 1;
		}
	}
	this.addListener = function(n,f,s,p){
		this.eventListener[this.eventListener.length] = {name:n,method:f,scope:s,parameter:p};
	}
	this.dispatchEvent = function(e,elm) {
		for( var i = 0; i < this.eventListener.length; i++ ) {
			var listener = this.eventListener[i];
			if ( e == listener.name ) {
				listener.method.call(listener.scope,listener.parameter,elm);	
			}
		}
	}

}
  
function CreateColorPalette() {
	var id = "colorPalette";
	var str = '<div id="' + id + '" class="popupWindow"><table width="150" height="100" cellpadding="0" cellspacing="1" border="1">';
  	for(var i = 0; i < bgColors.length; i++ ) {
		str += '<tr>';
		var row = bgColors[i];
		for(var j = 0; j < row.length; j++) {
			str += '<td id="' + row[j] + '" bgcolor="' + row[j] + '" width="10" height="10"><img width="1" height="1"></td>';
		}
		str += '</tr>';
	} 
	str += '</table></div>';
	document.write(str);
	var f = function(el) {
		el.onmouseover = function() { this.style.border = '1px dotted white';};
		el.onmouseout = function() { this.style.border = '1px solid gray';};
		el.onclick = function() {rteActive.setColor(rteCommand,this.id);_popup.hide();};
	}
	
	var elements = document.getElementById(id).getElementsByTagName("td");
	client.applyMethod(elements,f,window);
}

function testEvent(e) {
//beforepaste/drop
	e = e || window.event;
	//alert(e.srcElement.getData());
return true;
}
