//v1
(function( $ ){
	$.uploaderMgr = {
		counter : 0,
		_managers : []
	};

	$.fn.configUploader = function(options) {
		var uploaderMap = {};

		var defaultUploader = {
			timeout : 0,
			maxUploaders : 1,
			uploadUrl : '',
			uploaders : [],
			validUpload : 0,
			originalUploadWidget : null,
			_activeEntry : null,
			genericError : 'Try again', // must be provided by caller
			swfuploadInstance : null,
			enableFlash : false,
			file_size_limit : "",
	        flash_button_text : '<span class="button">Select Images</span>',
	        flash_button_image_url : null,
	        flash_button_width: 111,
	        flash_button_height: 18,
	        flash_button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt;} .buttonSmall { font-size: 10pt; }',
	        flash_button_text_top_padding: 0,
	        flash_button_text_left_padding: 10,
			onChange : function() {
			},
			defaultUploadEntry : {
				id : null,
				fileToken : '',
				status : 'none',
				jqForm : null,
				jqFrame : null,
				validUpload : true,
				startUpload : function(input) {
					var uploader = this;
					var idx = $.uploaderMgr.counter++;
					var frameId = 'jUploadFrame' + idx;
					var formId = 'jUploadForm' + idx;
					uploaderMap[frameId] = this;
					this.jqForm = this.owner.createUploadForm(formId);
					this.jqForm.appendTo('body').css( {
						position : 'absolute',
						top : '-1000px',
						left : '-1000px'
					});
					this.jqFrame = createUploadIframe(frameId);
					this.jqForm.attr('target', frameId);
					this.jqFrame.bind('load', function() {
						uploader.uploadCallback();
					});
					// clone orginal file input and move original iput to the
					// form
					var oldElement = $(input);
					this.file = oldElement.val();
					var idx = this.file.lastIndexOf('\\');
					if (idx >= 0)
						this.file = this.file.substring(idx + 1, this.file.length);
					var newElement = $(this.owner.originalFileInput).clone();
					var mgr = this.owner;
					mgr.validUpload++;
					$(newElement).bind('change', function(e) {
						mgr.startUpload(this);
					});
					// var newElement = oldElement.clone();
					oldElement.before(newElement);
					oldElement.appendTo(this.jqForm);
					this.upload();

				},
				startUploadFromUrl : function(input,url) {
					var uploader = this;
					var idx = counter++;
					var frameId = 'jUploadFrame' + idx;
					var formId = 'jUploadForm' + idx;
					uploaderMap[frameId] = this;
					this.jqForm = this.owner.createPostUrlForm(formId,url);
					this.jqForm.appendTo('body').css( {
						position : 'absolute',
						top : '-1000px',
						left : '-1000px'
					});
					this.jqFrame = createUploadIframe(frameId);
					this.jqForm.attr('target', frameId);
					this.jqFrame.bind('load', function() {
						uploader.uploadCallback();
					});
					this.file = url;
					var idx = this.file.lastIndexOf('/');
					if (idx >= 0)
						this.file = this.file.substring(idx + 1, this.file.length);
					var mgr = this.owner;
					mgr.validUpload++;
					this.upload();

				},

				upload : function() {
					var uploader = this;
					// Timeout checker
					if (this.owner.timeout > 0) {
						this.timeout = setTimeout(function() {
							if (!uploader.status == 'uploading')
								uploader.uploadCallback("timeout");
						}, this.owner.timeout);
					}

					try {
						this.status = 'upload';
						this.owner.uploading(this);
						uploader.jqForm.submit();
					} catch (e) {
						// this.uploadError(e);
					}
				},
				remove : function() {
					if (this.status == 'upload')
						this.status = 'cancel';
					this.jqActiveWidget.remove();
					// JSY - restore later after fixing EpsPostProcess.jsp
					// if ( this.jqFrame )
					// this.jqFrame.remove();
					if (this.jqForm)
						this.jqForm.remove();
					this.owner.remove(this);
				},
				switchActiveWidget : function(jqWidget) {
					this.jqActiveWidget.replaceWith(jqWidget);
					this.jqActiveWidget = jqWidget;
				},
				uploadCallback : function(isTimeout) {
					if (this.status == 'upload') {
						// still uploading
						if (isTimeout != 'timeout') {
							var doc = null;
							try {
								doc = this.jqFrame.document();
								this.status = 'response';
							} catch (e) {
								this.status = 'error';
							}
							this.owner.processResponse(this, doc);
						} else {
							this.status = 'timeout';
							this.owner.displayError(this, 'timeout');
						}
					}
				}

			},
			flashUploadEntry : {
				swfuploadInstance: null,
				startUpload : function(file) {
					var uploader = this;
					//var idx = this.file.lastIndexOf('\\');
					//if (idx >= 0)
					this.file = file.name
					this.fileID = file.id;
					this.status == 'upload';
					var mgr = this.owner;
					mgr.validUpload++;
					mgr.uploading(this);

				},
				remove : function() {
					if ( this.status == 'upload')
						this.swfuploadInstance.cancelUpload(this.fileID);
					this.jqActiveWidget.remove();
					this.owner.remove(this);
				}
			},
			startUpload : function(input) {
				// create form and switch file inout
				this._activeEntry = $.extend( {}, this.defaultUploadEntry);
				this.uploaders.push(this._activeEntry);
				this._activeEntry.owner = this;
				this._activeEntry.startUpload(input);
			},
			uploading : function(uploader) {
				var jqProgressWidget = this
						.createUploadProgressIndicator(uploader);

				if (uploader == this._activeEntry) {
					$(this.originalUploadWidget).before(jqProgressWidget);
					uploader.jqActiveWidget = jqProgressWidget;
					this._activeEntry = null;
				} else {
					uploader.switchActiveWidget(jqProgreeWidget);
				}
				this.checkMaximumUpload();
			},
			removeUploadedData : function(uploader) {
				// client must provide this
			},
			remove : function(uploader) {
				if (uploader.validUpload)
					this.validUpload--;
				if (uploader.fileToken != '') {
					this.removeUploadedData(uploader);
					uploader.fileToken = '';
					this.updatePostData();
				}
				// remove from stack
				var index = this.uploaders.indexOf(uploader);
				if (index >= 0)
					this.uploaders.splice(index, 1);
				if (this.uploaders.length < this.maxUploaders) {
					if ( this.swfuploadInstance) {
						$(this.originalUploadWidget).css({position:''});
					} else {
						$(this.originalUploadWidget).show();
					}
				}
			},
			createUploadForm : function(formId) {
				/* must be provided by client */
				return null;
			},
			createPostUrlForm : function(formId,url) {
				/* must be provided by client */
				return null;
			},
			createUploadProgressIndicator : function(uploader) {
				/* must be provided by client */
				return null;
			},
			processResponse : function(uploader, response) {
				// parse response and set uploader.status = 'success' or 'error'
				if ( uploader.swfuploadInstance)
					this.parseFlashResponse(uploader, response);
				else
					this.parseResponse(uploader, response);
				if (uploader.status == 'success') {
					this.displayUploadedData(uploader);
					this.updatePostData();
				} else {
					this.displayError(uploader);
				}

			},
			parseResponse : function(uploader, response) {
			// must be provided by the client
			},
			parseFlashResponse : function(uploader, response) {
				// must be provided by the client
			},
			createUploadedDataDisplay : function(uploader) {
				// must be provided by the client
				return null;
			},
			displayUploadedData : function(uploader) {
				jqSuccessWidget = this.createUploadedDataDisplay(uploader);
				uploader.switchActiveWidget(jqSuccessWidget);
			},
			addOriginalData : function(urlsString) {
				if (urlsString != '') {
					var urls = urlsString.splitUrls();
					for ( var i = 0; i < urls.length; i++) {
						var uploader = $.extend( {}, this.defaultUploadEntry);
						this.uploaders.push(uploader);
						uploader.fileToken = urls[i];
						uploader.owner = this;
						jqSuccessWidget = this.createUploadedDataDisplay(uploader);
						// uploader.switchActiveWidget(jqSuccessWidget);
						uploader.jqActiveWidget = jqSuccessWidget;
						$(this.originalUploadWidget).before(jqSuccessWidget);
					}
					this.checkMaximumUpload();
				}
			},
			uploadFromUrls : function(urlsString) {
				if (urlsString != '') {
					var urls = urlsString.splitUrls();
					var maxUrls = urls.length;
					if ( maxUrls > mgr.maxUploaders ) maxUrls = mgr.maxUploaders;
					for ( var i = 0; i < maxUrls; i++) {
						// create form and switch file inout
						this._activeEntry = $.extend( {}, this.defaultUploadEntry);
						this.uploaders.push(this._activeEntry);
						this._activeEntry.owner = this;
						this._activeEntry.startUploadFromUrl(null,urls[i]);
					}
					this.checkMaximumUpload();	
				}
			},
			uploadFromFlash : function(file,error) {
				this._activeEntry = $.extend( {}, this.defaultUploadEntry,this.flashUploadEntry);
				var uploader = this._activeEntry;
				this.uploaders.push(this._activeEntry);
				this._activeEntry.owner = this;
				this._activeEntry.swfuploadInstance = this.swfuploadInstance;
				uploader.file = file.name
				uploader.fileID = file.id;
				uploader.status = 'upload';
				this.validUpload++;
				if ( error == null )  {
					error = this.flashUpload(file);
				} else {
					uploader.status == 'error';
				}
				this.uploading(uploader);
				if ( error != null ) {
					uploader.error = error;
					uploader.status = 'error';
					this.displayError(uploader);
				}
				//this.checkMaximumUpload();
			},
			flashUpload : function(file) {
				this.swfuploadInstance.startUpload();
				return null;
			},
			findFlashUploadEntry : function ( file){
				for(var i = 0; i < this.uploaders.length; i++){
					if ( this.uploaders[i].swfuploadInstance &&
							this.uploaders[i].fileID == file.id &&
							this.uploaders[i].file == file.name)
						return this.uploaders[i];
				}
			},
			updatePostData : function() {
				var urls = '';
				for ( var i = 0; i < this.uploaders.length; i++) {
					if (this.uploaders[i].fileToken != "") {
						if (urls != '')
							urls += ',';
						urls += this.uploaders[i].fileToken;
					}
				}
				this.jqPostField.val(urls);
				if (this.onChange != "")
					this.onChange();
			},
			displayError : function(uploader, timeout) {
				// must be provided by the client
			},
			uploadingData : function() {
				for ( var i in this.uploaders) {
					if (this.uploaders[i].status == 'upload')
						return true;
				}
				return false;
			},
			checkMaximumUpload : function() {
				if (this.uploaders.length >= this.maxUploaders) {
					if ( this.swfuploadInstance) {
						if ( !this.uploadingData() ) {
							$(this.originalUploadWidget).css({position:"absolute",top:'-1000px'});
						}
					} else {
						$(this.originalUploadWidget).hide();
					}
				}
			}

		};

		function createUploadIframe(frameId) {
			return $(
					'<iframe width="100" height="100" name="' + frameId
							+ '" id="' + frameId + '"></iframe>') // src="javascript:false;">')
					.css( {
						position : 'absolute',
						top : '-1000px',
						left : '-1000px'
					}).appendTo('body');
		}
		var enableFlash = options.enableFlash && DetectFlashVer(9,9,28);
		var mgr = $.extend( {}, defaultUploader, options);
		if (!enableFlash && $.browser.opera) { 
			$(this).parent().hide();
			return;
		} 

		jQuery.data(this, mgr.id, mgr);
		mgr.originalUploadWidget = $('.upload-action', this)[0];
		mgr.jqPostField = $(':hidden[name = "' + mgr.dataField + '"]', this);
		//mgr.addOriginalData(mgr.jqPostField.val());
		$.uploaderMgr._managers.push(mgr);
		var jqFileInput = $(':file', this);
		//var jqFileInput = $('input[@type = "file"]',this);
		if ( enableFlash ){
			//for resizing start with 10,0,0
			jqFileInput.replaceWith('<div class="flashUpload newButton"><div id="flashButton"></div></div>');
			mgr.swfuploadInstance = new SWFUpload({
				numFilesQueued : 0,
				// Backend Settings
				file_post_name : mgr.file_post_name,
				upload_url: mgr.uploadUrl,
	            post_params: mgr.post_params,

	            // File Upload Settings
	            file_size_limit : mgr.file_size_limit,
	            file_types : mgr.file_types,
	            file_types_description : mgr.file_types_description,
	            file_upload_limit : 0,

	            // Event Handler Settings - these functions as defined in Handlers.js
	            //  The handlers are not part of SWFUpload but are part of my website and control how
	            //  my website reacts to the SWFUpload events.
	            swfupload_preload_handler : function() {},
	            swfupload_load_failed_handler : function() {
					alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative");
				},
				file_queue_error_handler : function (file, errorCode, message) {
					//alert(errorCode + ":----" + message);
					var error = 'ERROR';
					if ( errorCode == -110 ) error = 'FS';
					this.mgr.uploadFromFlash(file,error);

				},
				file_dialog_complete_handler :function(numFilesSelected, numFilesQueued){	
					try {
						if (numFilesQueued > 0) {
							if ( numFilesQueued >= this.getStats().files_queued) {
								if ( mgr.uploaders.length < mgr.maxUploaders) 
									this.mgr.uploadFromFlash(this.getQueueFile(0));
							}
						}
					} catch (ex) {
						this.debug(ex);
					}
				},
	            upload_progress_handler : function(file, bytesLoaded) {
				},
	            upload_error_handler : function(file, errorCode, message){
	            //alert(errorCode + ":" + message);
	            	var loader = this.mgr.findFlashUploadEntry(file); 
	            	if ( loader != null ) {
	            		loader.fileID = null;
	            		loader.status = 'error';
	            		if (errorCode = 230 )
	            			loader.error = message;
	            		else
	            			loader.error = 'ERROR';
						loader.owner.displayError(loader, 'error');
					}
	            },
	            upload_success_handler : function (file, serverData) {
	            //alert("serverdata:" + serverData);
	            	var loader = this.mgr.findFlashUploadEntry(file);
	            	if ( loader != null ) {
						this.mgr.processResponse(loader,serverData);
						loader.fileID = null;
					}
				},
	            upload_complete_handler : function (file) {
	            //alert('xxx');
	            	var loader = this.mgr.findFlashUploadEntry(file);
	            	if ( loader != null ) {
					if ( loader.status == 'upload') {
		            	loader.status = 'error';
		            	loader.error = 'ERROR';
						loader.owner.displayError(loader, 'error');
					}
					}
					try {
						/*  I want the next upload to continue automatically so I'll call startUpload here */
						if (this.getStats().files_queued > 0 ) {
							if ( this.mgr.uploaders.length < this.mgr.maxUploaders) {
								this.mgr.uploadFromFlash(this.getQueueFile(0));
								return;
							} else {
								while (this.getStats().files_queued > 0 ) {
									this.cancelUpload();
								}
							}
						}
						if ( !this.mgr.uploadingData() && this.mgr.uploaders.length >= this.mgr.maxUploaders ) {
							$(this.mgr.originalUploadWidget).css({position:"absolute",top:'-1000px'});
						}
					} catch (ex) {
						this.debug(ex);
					}
				},

	            // Button Settings
	            button_image_url : mgr.flash_button_image_url,
	            button_placeholder_id : "flashButton",
	            button_width: mgr.flash_button_width,
	            button_height: mgr.flash_button_height,
	            button_text : mgr.flash_button_text,
	            button_text_style : mgr.flash_button_text_style,
	            button_text_top_padding: mgr.flash_button_text_top_padding,
	            button_text_left_padding: mgr.flash_button_text_left_padding,
	            button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
	            button_cursor: SWFUpload.CURSOR.HAND,
	                
	            // Flash Settings
	            flash_url : staticPath + "FLASH/swfupload.swf",
	            flash9_url : staticPath + "FLASH/swfupload_fp9.swf",

	            // Debug Settings
	            debug: false
	        });
	        mgr.swfuploadInstance.mgr = mgr;

	    } else {
			mgr.originalFileInput = jqFileInput.clone();
			jqFileInput.bind('change', function(e) {
				mgr.startUpload(this);
			});
		}
		mgr.addOriginalData(mgr.jqPostField.val());
		$(mgr.originalUploadWidget).parents("form").bind('submit', function() {
			if (mgr.uploadingData()) {
		        $(mgr.popupMsg).hide().appendTo('body').modal();
		        return false;
				//var answer = confirm(mgr.popupMsg)
				//return answer;
			}
			return true;
		});
		if ( options.importDataField)
			mgr.uploadFromUrls(options.importDataField);
		mgr.checkMaximumUpload();
		//alert($(mgr.originalUploadWidget).parent().html());	
	};
	$.fn.configEpsUploader = function(options) {
		var defaultEpsUploader = {
			removeText : 'Remove',
			cancelText : 'Cancel',
			retryText : 'Retry upload',
			uploadingText : 'Image uploading',
            file_size_limit : "4 MB",
	        file_types : "*.jpg;*.png;*.bmp;*.jpeg;*.gif;",
	        file_types_description : "Images",
			file_post_name : "u",
			maxWidth : 810,
			maxHeight : 610,
			disableFlashResize : false,
			errorTexts : {
				'ERROR' : 'There was an error uploading your picture.',
				'FS' : 'The file size of the picture you attempted to add is too large. Please reduce your picture\'s file size before adding it again.',
				'FP' : 'You specified a picture file that could not be found on your computer.',
				'ME' : 'There was an error uploading your picture. ',
				'FC' : 'The content of your picture file is corrupted.',
				'FF' : 'There was a problem with the format of your picture file.',
				'SD' : 'There was a problem connecting to Picture Services.'
				},
			popupMsg :"Some photos are still being uploaded. If you continue, you will loose those photos. Do you want to continue?",
			createUploadForm : function(formId) {
				return $('<form method="post" action="' + this.uploadUrl
						+ '" name="' + formId + '" id="' + formId
						+ '" enctype="multipart/form-data">'
						+ '<input type="hidden" name="s" value="' + this.setId
						+ '"/><input type="hidden" name="v" value="'
						+ this.epsVersion + '"/>'
						+ '<input type="hidden" name="b" value="'
						+ this.defaultSizeId
						+ '"><input type="hidden" name="n" value="k"/>'
						+ '<input type="hidden" name="a" value="'
						+ this.epsToken + '"/>' + '</form>');
			},
			createPostUrlForm : function(formId,url) {
				return $('<form method="post" action="' + this.importUrl
						+ '" name="' + formId + '" id="' + formId
						+ '" >'
						+ '<input type="hidden" name="u" value="' + url
						+ '"/>'
						+ '<input type="hidden" name="s" value="' + this.setId
						+ '"/>'
						+ '<input type="hidden" name="b" value="'
						+ this.defaultSizeId
						+ '">'
						+ '<input type="hidden" name="a" value="'
						+ this.epsToken + '"/>' + '</form>');
			},
			createUploadProgressIndicator : function(uploader) {
				var jqProgress = $('<div class="loadingSmall" style="padding-left:20px;margin-left:2px;margin-top:8px;margin-bottom:12px;">'
						+ '<span>'
						+ uploader.file
						+ ' : '
						+ this.uploadingText
						+ '... [<a href="#">'
						+ this.cancelText
						+ '</a>]</span></div>');
				$('a', jqProgress).click(function(e) {
					e.preventDefault();
					uploader.remove();
				});
				return jqProgress;
			},
			displayError : function(uploader, timeout) {
				var errorText = null;
				if (uploader.error) {
					var errorCode = uploader.error.substring(0, 2);
					errorText = this.errorTexts[errorCode];
				}
				if (errorText == null)
					errorText = this.errorTexts["ERROR"];
				var allowRetry = errorCode == "SD" || errorCode == "ME";
				var allowRemove = this.removeText != "Skip";				
				var jqErrorWidget = $('<div class="error_field" style="padding-left:5px;padding-top:5px;padding-bottom:5px;margin-bottom:10px;padding-right:5px">'
						+ uploader.file
						+ ' - '
						+ (allowRetry ? '[<a href="#" class="upload-retry">' + this.retryText + '</a>] '
								: '')
						+ (allowRemove ? '[<a href="#" class="upload-cancel">' + this.removeText + '</a>]' : '') 
						+ '<br/><span class="error">'
						+ errorText + '</span></div>');
				$('.upload-cancel', jqErrorWidget).click(function(e) {
					e.preventDefault();
					uploader.remove();
				});
				$('.upload-retry', jqErrorWidget).click(function(e) {
					e.preventDefault();
					uploader.upload();
				});
				uploader.switchActiveWidget(jqErrorWidget);
				if (!allowRetry) {
					uploader.validUpload = false;
					this.validUpload--;
					$(this.originalUploadWidget).show();
				}

			},
			createUploadedDataDisplay : function(uploader) {
				// must be provided by the client
				var file = uploader.fileToken;
				// remove setid
				var idx = file.indexOf('?set_id=');
				if (idx > 0)
					file = file.substring(0, idx);
				idx = file.lastIndexOf('_');
				var eidx = file.lastIndexOf('.');
				file = file.substring(0, idx) + "_" + this.thumbnailSizeId
						+ file.substring(eidx);
				var allowRemove = this.removeText != "Skip";
				jqSuccessWidget = $('<div class="uploadedImage"><img src="'
						+ file
						+ '" > ' 
						+ (allowRemove ? '<a href="#" class="upload-cancel">' + this.removeText + '</a>' : '') 
						+ '</div>');
				$('.upload-cancel', jqSuccessWidget).click(function(e) {
					e.preventDefault();
					uploader.remove();
				});
				return jqSuccessWidget;
			},
			parseResponse : function(uploader, doc) {
				if (doc != null) {
					var url = doc.location.toString();
					var idx = url.indexOf('?');
					if (idx >= 0) {
						url = url.substring(idx + 1);
						var list = url.split('&');
						for ( var i = 0; i < list.length; i++) {
							var param = list[i];
							idx = param.indexOf('=');
							var key = param.substring(0, idx);
							var value = param.substring(idx + 1);
							if (key == 'picurl') {
								uploader.fileToken = decodeURIComponent(param
										.substring(idx + 1));
							}
							if (key == 'error') {
								uploader.error = param.substring(idx + 1);
							}
						}
					}
				}
				if (uploader.fileToken != '') {
					uploader.status = 'success';
				} else {
					if (uploader.error == '')
						uploader.error = 'ERROR';
					uploader.status = 'error';
				}	

			},
			parseFlashResponse : function(uploader, response) {
				var idx = response.indexOf('http:/');
				if (idx >= 0 ) {
					uploader.fileToken = response;
					uploader.status = 'success';
				} else {
					//idx = response.indexOf('error:');
					uploader.error = response;
					if ( uploader.error == '')
						uploader.error = 'ERROR';
					uploader.status = 'error';
				}
			},
			flashUpload : function(file) {
				if ( file.size > 4000000) {
					if ( this.canResize	&& (file.type == '.jpg' || file.type == '.png' || file.type == '.jpeg' || file.type == '.gif')) {
						this.swfuploadInstance.startResizedUpload(file.id, this.maxWidth, this.maxHeight, SWFUpload.RESIZE_ENCODING.JPEG, 80, false);
					} else {
						this.swfuploadInstance.cancelUpload(file.id,false);
						return 'FS';
					}
				} else {
					this.swfuploadInstance.startUpload();
				}
				return null;
			}
		};
		if ( !options.epsToken )
options.epsToken = epsToken;
if ( options.thumbnailSizeId.indexOf('_') >= 0 ) options.thumbnailSizeId = options.thumbnailSizeId.substring(1);
		options = $.extend( {}, defaultEpsUploader, options);
		options.post_params = {
            "s" : options.setId,"r":"0","v":"k","b":options.defaultSizeId,"n":"k","a": options.epsToken};

		options.canResize = DetectFlashVer(10,0,0) && !options.disableFlashResize;
        if ( options.canResize)
        	options.file_size_limit = "20 MB";
		this.configUploader(options);
		return this;
	};

	$.fn.configAttachmentUploader = function(options) {
		var defaultAttachmentUploader = {
        	file_size_limit : "1 MB",
			file_post_name : "datafile",
			createUploadForm : function(formId) {
				return $('<form method="post" action="' + this.uploadUrl
						+ '" name="' + formId + '" id="' + formId
						+ '" enctype="multipart/form-data">'
						+ '<input type="hidden" name="adId" value="'
						+ this.adId + '"/>' + '</form>');
			},
			createUploadProgressIndicator : function(uploader) {
				var jqProgress = $('<div class="loadingSmall" style="padding-left:20px;margin-left:2px;margin-top:8px;margin-bottom:12px;">'
						+ '<span>'
						+ uploader.file
						+ ' : '
						+ this.uploadingText
						+ '... [<a href="#">'
						+ this.cancelText
						+ '</a>]</span></div>');
				$('a', jqProgress).click(function(e) {
					e.preventDefault();
					uploader.remove();
				});
				return jqProgress;
			},
			displayError : function(uploader, timeout) {
				// must be provided by the client
				var error = uploader.error;
				var errorText = this.errorTexts[error] || error;
				var allowRetry = false;
				var allowRemove = this.removeText != "Skip";
				var jqErrorWidget = $('<div class="error_field" style="padding-left:5px;padding-top:5px;padding-bottom:5px;margin-bottom:10px;padding-right:5px">'
						+ uploader.file
						+ ' - '
						+ (allowRetry ? '[<a href="#" class="upload-retry">' + this.retryText + '</a>] '
								: '')
						+ (allowRemove ? '[<a href="#" class="upload-cancel">' + this.removeText + '</a>]' : '') 
						+ '<br/><span class="error">'
						+ errorText + '</span></div>');
				$('.upload-cancel', jqErrorWidget).click(function(e) {
					e.preventDefault();
					uploader.remove();
				});
				$('.upload-retry', jqErrorWidget).click(function(e) {
					e.preventDefault();
					uploader.upload();
				});
				uploader.switchActiveWidget(jqErrorWidget);
				if (!allowRetry) {
					uploader.validUpload = false;
					this.validUpload--;
					$(this.originalUploadWidget).show();
				}

			},
			createUploadedDataDisplay : function(uploader) {
				var allowRemove = this.removeText != "Skip";
				jqSuccessWidget = $('<div style="margin-left:2px;margin-top:8px;margin-bottom:10px;"><img src="'
						+ picsPath
						+ 'attachment.gif" > '
						+ uploader.file
						+ (allowRemove ? '<a href="#" class="upload-cancel">' + this.removeText + '</a>' : '') 
						+ '</div>');
				$('.upload-cancel', jqSuccessWidget).click(function(e) {
					e.preventDefault();
					uploader.remove();
				});
				return jqSuccessWidget;
			},
			parseResponse : function(uploader, doc) {
				var content = null;
				if (doc != null) 
					content = $(doc).find('head').html();
				this.processContent(uploader,content);
			},
			processContent : function(uploader,content) {
				if (content != null) {
					var errorIndex = content.lastIndexOf("email_errormsg");
					if (errorIndex >= 0) {
						errorIndex = content.indexOf('"', errorIndex + 16);
						var errorEnd = content.indexOf('"', errorIndex + 1);
						if (errorIndex >= 0 && errorEnd > 0 && errorEnd > errorIndex + 1) {
							uploader.error = content.substring(errorIndex + 1,
									errorEnd);
							uploader.status = 'error';
							return;
						}
					}
					var randIndex = content.lastIndexOf("email_rand");
					if (randIndex > 0) {
						randIndex = content.indexOf('"', randIndex + 12);
						var randEnd = content.indexOf('"', randIndex + 1);
						if (randIndex >= 0 && randEnd > 0) {
							uploader.fileToken = content.substring(
									randIndex + 1, randEnd);
							uploader.status = 'success';
							return;
						}
					}
				}
				uploader.status = 'error';
				uploader.error = this.genericError;
				// must provide for a generic error
			},
			addOriginalData : function(urlsString) {
				if (urlsString != '') {
					var filename = this.jqFileNameField.val();
					var uploader = $.extend( {}, this.defaultUploadEntry);
					this.uploaders.push(uploader);
					uploader.fileToken = urlsString;
					uploader.file = filename;
					uploader.owner = this;
					jqSuccessWidget = this.createUploadedDataDisplay(uploader);
						// uploader.switchActiveWidget(jqSuccessWidget);
					uploader.jqActiveWidget = jqSuccessWidget;
					$(this.originalUploadWidget).before(jqSuccessWidget);
				}
				this.checkMaximumUpload();
			},
			parseFlashResponse : function(uploader, response) {
				this.processContent(uploader, response);
			},
			flashUpload : function(file) {
				/*if ( file.size == 0 ) {
					this.swfuploadInstance.cancelUpload(file.id,false);
					return 'ERROR';
				}*/
				this.swfuploadInstance.startUpload();
				return null;
					
			},
			updatePostData : function() {
				var urls = '';
				var files = '';
				for ( var i = 0; i < this.uploaders.length; i++) {
					if (this.uploaders[i].fileToken != "") {
						if (urls != '') {
							urls += ',';
							files += ',';
						}
						urls += this.uploaders[i].fileToken;
						files += this.uploaders[i].file;
					}
				}
				this.jqPostField.val(urls);
				this.jqFileNameField.val(files);
				this.onChange();
			}
		};
		options.jqFileNameField = $(
				'input[@name = "' + options.filenameField + '"]', this);
		options = $.extend( {}, defaultAttachmentUploader, options);
		options.post_params = {"adId" : options.adId,"v":1};
		this.configUploader(options);
		return this;
	};

	/*
	 * $(eventSrc).popupColorPicker(options)
	 */
	$.fn.popupColorPicker = function (options) {
		var id = 'rteColorPalette';
		var palette = $('#' + id);
		if ( palette.length == 0 ) {
			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 str = '<div id="' + id + '" style="width:150px;height:100px"><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>';
			palette = $(str).appendTo('body');
			$('td',palette).each(function () {
				$(this).bind('mouseover',function() { this.style.border = '1px dotted white';})
						.bind('mouseout',function() { this.style.border = '1px solid gray';});
			});
		}
		var colorPickerDefault = {
			setColor : function (color) {
			},
			bindEvents: function () {
				var popup = this;
				$('td',this.jqContent).each(function () {
					$(this).bind('click',function(e) {popup.setColor(this.id);popup.close();});
				});

				this.jqContent.bind('click', function(e) {
					e.preventDefault();
					popup.close();
				});
				this.jqContent.bind('mouseleave', function(e) {
					e.preventDefault();
					popup.close();
				});

			}
		};
		var opts = $.extend({}, colorPickerDefault, options);
		palette.popup(this,opts);
	};
	
	$.fn.wysiwyg = function (options) {
		var rteDefault = {
			css : [],
			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"]],
			buttons : [
				["Bold","bold","bold"],
				["Italic","italic","italic"],
				["Underline","underline","underline"],
				[null,"sep","blackdot"],
				["Align Left","justifyleft","left_just"],
				["Center","justifycenter","centre"],
				["Align Right","justifyright","right_just"],
				["Justify Full","justifyfull","justifyfull"],
				[null,"sep","blackdot"],
				["Horizontal Rule","inserthorizontalrule","hr"],
				[null,"sep","blackdot"],
				["Ordered List","insertorderedlist","numbered_list"],
				["Unordered List","insertunorderedlist","list"],
				[null,"sep","blackdot"],
				["Outdent","outdent","outdent"],
				["Indent","indent","indent"],
				["Text Color","forecolor","textcolor"],
				["Background Color","hilitecolor","bgcolor"]],
			createToolbar : function () {
				var html = '<div class="rteDiv"><table class="rteToolbar" cellpadding="2" cellspacing="0"><tbody><tr><td class="rteMenu">';

				for( var i = 0 ; i < this.buttons.length; i++ ) {
					html += '<img class="rte-' + this.buttons[i][1] + '" ' + (this.buttons[i][0] ? ('title="' + this.buttons[i][0] + '"'): '') + ' src="http://pic.classistatic.com/image/pics/classifieds/wysiwyg_editor/' + this.buttons[i][2] + '.gif"/>';
				}
				html += '</td></tr></tbody></table>';
				html += '<table class="rteToolbar" cellpadding="2" cellspacing="0"><tbody><tr><td>' +
					'<select name="fontType" id="fontname_Description">'
					'<option value="Font" selected="selected">[Font]</option>';
				for(var i = 0 ; i < this.fonts.length; i++ ) {
					html += '<option value="' + this.fonts[i][0] + '">' + this.fonts[i][1] + '</option>';
				}
				html += '</select>' + 
					'<select name="fontSize" unselectable="on" id="fontsize_Description">' +
					'<option value="Size">[Size]</option>';
				for( i = 1; i < 3; i++)
					html += '<option value="' + i + '">' + i + '</option>';
				for( i = 3; i < 6; i++)
					html += '<option value="' + (i+1) + '">' + i + '</option>';
				html += '</select></td></tr></tbody></table>';

				html += '</div>';
				return html;
			},
			initialDoc : function (html) {
				var frameHtml = "<html><head><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
				for( var i = 0; i < this.css.length; i++ ) {
					frameHtml += '<link href="' + this.css[i] + '" rel="stylesheet" type="text/css">';
				}
				frameHtml += "<style> body { background: #FFFFFF;margin: 0px;padding: 0px;text-align:left;}\n";
				frameHtml += " P {margin-top:0;margin-bottom:0}\n"; 
				frameHtml += " a{text-decoration: none;color:#000}\n";
				frameHtml += "</style></head><body>\n";
				frameHtml += html + "\n";
				frameHtml += "</body></html>";
				return frameHtml;
			},
			init : function(original){
				var self = this;
				self.original = original;
				original = $(original);
				var toolbar = $(self.createToolbar());
				original.before(toolbar);

				this.editor = $('<iframe height="200" width="500"></iframe>')[0];
				original.before(this.editor);

				$('.rteMenu > img',toolbar).each(function () {
					var button = $(this);
					var cls = button.attr('class');
					var list = cls.split('-');
					if ( list[1] != 'sep' ) {
						button.bind('click',function(e) {
							e.preventDefault();
							self.doCommand (list[1],this);
						});
					}
				});
				$('select',toolbar).each(function () {
					$(this).bind('change',function() {
						self.selectFont(this);
					});
				});            

            		self.editorDoc = $(self.editor).document();
            		self.editorDoc_designMode = false;

            		try {
                			self.editorDoc.designMode = 'on';
                			self.editorDoc_designMode = true;
            		} catch ( e ) {
                			// Will fail on Gecko if the editor is placed in an hidden container element
                			// The design mode will be set ones the editor is focused

                			$(self.editorDoc).focus(function(){self.designMode();});
            		}

            		self.editorDoc.open();
            		self.editorDoc.write(self.initialDoc($(self.original).val()));
            		self.editorDoc.close();
            		self.editorDoc = $(self.editor).document();
            		self.editorDoc.contentEditable = 'true';
        		},
			getSelection : function() {
            		return ( window.getSelection ) ? window.getSelection() : document.selection;
			},
        		getSelectionRange : function(){
            		var selection = this.getSelection();
            		if ( selection ) {
					if (document.all) {
						return selection.createRange();
					} else {
						if ( selection.rageCount > 0 )
							return selection.getRangeAt(selection.rangeCount - 1).cloneRange();
					}
				}

				return null;

            	//return ( selection.rangeCount > 0 ) ? selection.getRangeAt(0) : selection.createRange();
        		},
			execCommand : function(command, option) {
				var win = this.editor.contentWindow;
				try {
					win.focus();
	  				win.document.execCommand(command, false, option);
					win.focus();
				} catch (e) {
				}
			},
			translate : function () {
 				$($(this.editor).document() ).find('body').translate('en', 'de');
			},
        		getContent : function(){
            		return $( $(this.editor).document() ).find('body').html();
        		},
			doCommand : function(command,src) {
				var rte = this;
				if ( command == "hilitecolor" || command == "forecolor") {
					this.range = this.getSelectionRange();
					this.rteCommand = command;
					var opts = {
						setColor : function (color ) {
							rte.setColor(color);
						}
					};
					$(src).popupColorPicker(opts);
				} else {
					this.execCommand(command,"");
				}

			},
			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.execCommand(cmd, selected);
					sel.selectedIndex = 0;
				}
			},
			setColor:function(color) {
				if (document.all) {
					if (this.rteCommand == "hilitecolor") this.rteCommand = "backcolor";
					//retrieve selected range
					this.range.select();
				}
				this.execCommand(this.rteCommand,color);
			},
			designMode : function(){
            		if ( !( this.editorDoc_designMode ) ){
                			try {
                    			this.editorDoc.designMode = 'on';
                    			this.editorDoc_designMode = true;
                			} catch ( e ) {}
            		}
        		}
		};
		function Wysiwyg() {};
		return this.each(function(){
			var options = $.extend({}, rteDefault, options);
			var editor = new Wysiwyg();
			$.extend(editor,rteDefault,options);
			editor.init(this);
		});

	};	

})(jQuery);

