function Editor() {
	
	this.isEditable = false;
	this.browser = navigator.userAgent.toLowerCase();
	this.startResize = null;
	this.resizedId = null;
	this.textStyle = null;
	this.editFirstTime = false;	
	
	this.initiateEditor = function() {
		this.isEditable = true;
	};
	
	/*
	 * Javascript function dislpayEditor will create the textarea or iframe.
	 */ 
	this.displayEditor = function(id, html) {
		var div = document.getElementById("divForIframe" + id);
		if(this.isEditable){
			var iframe = document.createElement("iframe");
			iframe.name = "iframe" + id;
			iframe.id = "iframe" + id;
			iframe.frameborder = 0;
			
			jQuery(".Text").bind("mouseover", 
					function() {
				jQuery(this).find(".textForm").css("display", "block");
			}).bind("mouseout", 
					function() {
				jQuery(this).find(".textForm").css("display", "none");
			});
			
			var input = document.createElement("input");
			input.type = "hidden";
			input.name = "hidden" + id;
			input.id = "hidden" + id;
			input.value = html;

			div.appendChild(iframe);
			div.appendChild(input);
			
			this.designer(id, html);
		}
	};

	/*
	 * this is designer function that enables designMode and writes 
	 * defalut text to the text area
	 */
	this.designer = function(id, text) {
		if (text) {
			text = this.base64_decode(text);
		}
//		if (!text.match("^<span\.*<\/span>$")) {
//			text = "<span _moz_dirty=''>" + text + "</span>"; 
//		}

		var mainContent = "<html id=" + id + "><head>" +
							"<meta 	 http-equiv='Content-Type' " +
									"content='text/html; charset=utf-8' />" + 
							"<meta 	 http-equiv='Content-Language' " +
									"content='pl' />" +
							"</head><body style='padding: 0px; margin: 0px'>" +
							text +  
     						"</body></html>" ;
		//assign the frame(textarea) to the edit variable using that frames id
		var edit = document.getElementById("iframe" + id).contentWindow.document;
		//write the content to the textarea
		edit.write(mainContent);
		edit.close();
		//enable the designMode	
		edit.designMode =  "On" ;
	};

	//To execute command we will use javascript function editorCommand. 
	this.editorCommand = function(id, command, option) {
		// first we assign the content of the textarea to the variable mainField
	    var mainField;
		mainField = document.getElementById("iframe" + id).contentWindow;
		// then we will use execCommand to execute the option on the textarea 
		// making sure the textarea stays in focus
		try {
			mainField.focus();
			mainField.document.execCommand(command, false, option);
			mainField.focus();
		} catch (e) {
			throw new Error(e);
		}
	};

	this.updateEditor = function(id) {
		if (!this.isEditable) {
			return;
		}
		
		//assign the value of the textarea to the hidden field. 
		var hiddenField = document.getElementById("hidden" + id);
		if (hiddenField.value === null) {
			hiddenField.value = "";
		}
		
		var iframe = document.getElementById("iframe" + id);
		hiddenField.value = iframe.contentWindow.document.body.innerHTML;
	};
	
	this.attacheeventsToInputs = function() {		
		jQuery(".textFormButtons input[type=button]").bind("click", function(e) {
			var id = this.form.name.substr(8);
			if (this.name == "heading") {
				
			} else {
				editor.editorCommand(id, this.name, null);
			}
		});
			
		jQuery(".textFormButtons select").bind("change", function(e) {
			var id = this.form.name.substr(8);		
			editor.editorCommand(id, this.name, this.value);
		});
		
		jQuery(".langsButton").bind("mouseover", function(e) {
			jQuery(this).find(".langsSelection").show();
			jQuery(".ui-resizable-handle").hide();
		});
		
		jQuery(".langsButton").bind("mouseout", function(e) {
			jQuery(this).find(".langsSelection").hide();
			jQuery(".ui-resizable-handle").show();
		});
		
		jQuery(".Text").bind("resize", function(e) { 
			var iframe = jQuery(this).find("iframe");
			iframe.css("position", "absolute");
			iframe.css("zIndex", "-10");
		});
		
		jQuery(document).ready( function() {
			jQuery(".Text").resizable();
		});
		
		jQuery(".Text").bind("mouseup", function(e) {
			var iframe = jQuery(this).find("iframe");
			iframe.css("zIndex", "0");
			iframe.css("position", "relative");
			
			var div = jQuery(this).find(".divForIframe");
			var data = [];
				data.height = parseInt(div.css("height"), 10);
				data.width = parseInt(div.css("width"), 10);
				
			xajax_saveWidgetSize(div[0].id.substr(12), data);
		});
		
		jQuery(".Text input[name=save]").bind("click", function(e) {
			var id = e.currentTarget.form.name.substr(8);
			var body = jQuery("#iframe" + id)[0].contentWindow.document.body;
			var lang  = jQuery(this.parentNode).find(".activeLang")[0].innerHTML;
			
			xajax_saveText(id, body.innerHTML, lang);
		});
		
		jQuery(".langsSelection").bind("click", function(e) {
			var target = e.originalTarget;
			var lang = target.innerHTML;
			var oldTarget = jQuery(this.parentNode).find(".activeLang");
				oldTarget.removeClass("activeLang");
			var oldLang = oldTarget[0].innerHTML;
			jQuery(target).addClass("activeLang");
			var id = jQuery(this.parentNode.parentNode)[0].name.substr(8);
			var body = jQuery("#iframe" + id)[0].contentWindow.document.body;
			
			xajax_saveText(id, body.innerHTML, oldLang);
			xajax_getTextTranslations(id, lang);
		});
	};
	
	this.loadTextStyle = function(data) {		
		this.textStyle = data;

		var elements = jQuery(".Text .divForIframe iframe");
		var len = elements.length;
		
		for (var i = len; i--; ) {
			var id = elements.eq(i)[0].id.substr(6);
			var edit = elements.eq(i)[0].contentWindow.document;
			
			if (data.textFontWeight.toLowerCase() == "bold") {
				editor.editorCommand(id, "bold" , null);
			}
			
			if (data.textFontStyle.toLowerCase() == "italic") {
				editor.editorCommand(id, "italic" , null);
			}
			
			editor.editorCommand(id, "forecolor", data.textFontColor);
			editor.editorCommand(id, "fontname", data.textFontFamily);
			editor.editorCommand(id, "fontsize", (data.textFontSize - 1.5) / 3 - 1);
			
			jQuery(".fontName").attr("value", data.textFontFamily);
			
			if(data.textFontColor.substr(0,1) != "#") {
				var commonColors = new Array();
					commonColors['black'] = "#000000";
					commonColors['gray'] = "#808080";
					commonColors['silver'] = "#C0C0C0";
					commonColors['white'] = "#FFFFFF";
					commonColors['red'] = "#FF0000";
					commonColors['maroon'] = "#800000";
					commonColors['purple'] = "#800080";
					commonColors['fuchsia'] = "#FF00FF"; 
					commonColors['green'] = "#008000";
					commonColors['lime'] = "#00FF00";
					commonColors['olive'] = "#808000";
					commonColors['yellow'] = "#FFFF00";
					commonColors['blue'] = "#0000FF";
					commonColors['navy'] = "#000080";
					commonColors['teal'] = "#008080";
					commonColors['aqua'] = "#00FFFF";
				var temp = commonColors[data.textFontColor.toLowerCase()];
				jQuery(".foreColor").attr("value", temp);
			} else {
				jQuery(".foreColor").attr("value", data.textFontColor);
			}
			
			switch (data.textFontDecoration.toLowerCase()) {
				case "underline":
					editor.editorCommand(id, "underline" , null);
					break;
				case "line-through":
					editor.editorCommand(id, "strikethrough" , null);
					break;
				default:
					break;
			}
		}
	};
	
	/*
	 * @author Nicolas Zakas
	 */
	this.base64_decode = function(text) {
		text = text.replace(/\s/g,"");

	    if(!(/^[a-z0-9\+\/\s]+\={0,2}$/i.test(text)) || text.length % 4 > 0) {
	        throw new Error("Not a base64-encoded string.");
	    }   

	    var digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
        cur, prev, digitNum,
        i=0,
        result = [];

	    text = text.replace(/=/g, "");
	
	    while(i < text.length) {
	
	        cur = digits.indexOf(text.charAt(i));
	        digitNum = i % 4;
	
	        switch(digitNum) {
	
	            //case 0: first digit - do nothing, not enough info to work with
	            case 1: //second digit
	                result.push(String.fromCharCode(prev << 2 | cur >> 4));
	                break;
	
	            case 2: //third digit
	                result.push(String.fromCharCode((prev & 0x0f) << 4 | cur >> 2));
	                break;
	
	            case 3: //fourth digit
	                result.push(String.fromCharCode((prev & 3) << 6 | cur));
	                break;
	        }
	
	        prev = cur;
	        i++;
	    }
	    
	    return this.utf8_decode(result.join(""));
	};
	
	this.utf8_decode = function (str_data) {
	    // Converts a UTF-8 encoded string to ISO-8859-1  
	    // 
	    // version: 909.322
	    // discuss at: http://phpjs.org/functions/utf8_decode    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
	    // +      input by: Aman Gupta
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +   improved by: Norman "zEh" Fuchs
	    // +   bugfixed by: hitwork    // +   bugfixed by: Onno Marsman
	    // +      input by: Brett Zamir (http://brett-zamir.me)
	    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // *     example 1: utf8_decode('Kevin van Zonneveld');
	    // *     returns 1: 'Kevin van Zonneveld'    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
	    
	    str_data += '';
	    var i = 0;
	    var ac = 0;
	    var tmp_arr = [];
	    while ( i < str_data.length ) {  
	    	c1 = str_data.charCodeAt(i);
	        if (c1 < 128) {
	            tmp_arr[ac++] = String.fromCharCode(c1);
	            i++;
	        } else if ((c1 > 191) && (c1 < 224)) {            
	        	c2 = str_data.charCodeAt(i+1);
	            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
	            i += 2;
	        } else {
	            c2 = str_data.charCodeAt(i+1);            
	            c3 = str_data.charCodeAt(i+2);
	            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
	            i += 3;
	        }
	    } 
	    
	    return tmp_arr.join('');
	};
}

editor = new Editor();

