/**
 * $RCSfile: editor_plugin_src.js,v $
 * $Revision: 1.30 $
 * $Date: 2006/02/10 16:29:37 $
 *
 * @author Sitefactory Oy
 */

/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('su3advideo', 'en,fi,tr,de,sv,zh_cn,cs,fa,fr_ca,fr,pl,pt_br,nl,he,nb,ru,ru_KOI8-R,ru_UTF-8,nn,cy,es,is,zh_tw,zh_tw_utf8,sk,da');

var TinyMCE_su3AdvancedVideoPlugin = {
	getInfo : function() {
		return {
			longname : 'Siteupdate3 Advanced video',
			author : 'sitefactory Oy',
			authorurl : 'http://www.sitefactory.fi',
			infourl : 'http://www.sitefactory.fi',
			version : '1.1'
		};
	},

	initInstance : function(inst) {
		if (!tinyMCE.settings['flash_skip_plugin_css'])
			tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/plugins/su3advideo/css/content.css");
	},

	getControlHTML : function(cn) {
		switch (cn) {
			case "video":
				return tinyMCE.getButtonHTML(cn, 'lang_su3advideo_desc', '{$themeurl}/images/video.gif', 'mcesu3AdvancedVideo');
		}

		return "";
	},

	execCommand : function(editor_id, element, command, user_interface, value) {
		switch (command) {
			case "mcesu3AdvancedVideo":
				var template = new Array();

				//template['file']   = '../../plugins/su3_advimage/image.htm';

				var inst = tinyMCE.getInstanceById(editor_id);
				var url = tinyMCE.getParam("su3_homeurl");
				if(inst){

					var elm = inst.getFocusElement();
					if(elm.nodeName.toLowerCase() == "img" && tinyMCE.getAttrib(elm, 'class') == "mceItemFlash")

					var current_video = -1;

					// tässä luetaan kuvan scrstä id ja fid, jotta voidaan avata oikea kansio ja kuva valituksi dialogissa, JOS kuva on valittuna kun nappia painetaan
					var current_cfg = ""

					var query = tinyMCE.getAttrib(elm, 'attr');

					var vars = query.split("&");
					for (var i=0;i<vars.length;i++) {
						var pair = vars[i].split("=");
						if (pair[0] == "videoID") {
							current_video =  pair[1];

						}
						if (pair[0] == "cfgFile") {
							current_cfg = pair[1]

						}
					}

					template['file']   = url+'siteupdate/tinymce/su3_advvideodlg/-/video_id/'+current_video+"/selected_cfg/"+current_cfg;
				} else {
					template['file']   = url+'siteupdate/tinymce/su3_advvideodlg';
				}
				template['width']  = 480;
				template['height'] = 480;


				if (elm != null && tinyMCE.getAttrib(elm, 'class') != "mceItemFlash" && elm.nodeName.toLowerCase() == "img"){
					return true;
				}
				tinyMCE.openWindow(template, {editor_id : editor_id, inline : "yes"});

				return true;
				break;
			case "su3uploadImage":

			return true;
		}

		return false;
	},

	cleanup : function(type, content) {
		switch (type) {
			/*case "insert_to_editor_dom":
				var imgs = content.getElementsByTagName("img");
				for (var i=0; i<imgs.length; i++) {
					var onmouseover = tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i], 'onmouseover'));
					var onmouseout = tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i], 'onmouseout'));

					if ((src = this._getImageSrc(onmouseover)) != "") {
						if (tinyMCE.getParam('convert_urls'))
							src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], src);

						imgs[i].setAttribute('onmouseover', "this.src='" + src + "';");
					}

					if ((src = this._getImageSrc(onmouseout)) != "") {
						if (tinyMCE.getParam('convert_urls'))
							src = tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings['base_href'], src);

						imgs[i].setAttribute('onmouseout', "this.src='" + src + "';");
					}
				}
				break;*/
			case "insert_to_editor_dom":
				// Force relative/absolute
				if (tinyMCE.getParam('convert_urls')) {
					var imgs = content.getElementsByTagName("img");
					for (var i=0; i<imgs.length; i++) {
						if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") {
							var src = tinyMCE.getAttrib(imgs[i], "alt");

							if (tinyMCE.getParam('convert_urls'))
								src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);");

							imgs[i].setAttribute('alt', src);
							imgs[i].setAttribute('title', src);
						}
					}
				}
				break;
			/*case "get_from_editor_dom":
				var imgs = content.getElementsByTagName("img");
				for (var i=0; i<imgs.length; i++) {
					var onmouseover = tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i], 'onmouseover'));
					var onmouseout = tinyMCE.cleanupEventStr(tinyMCE.getAttrib(imgs[i], 'onmouseout'));

					if ((src = this._getImageSrc(onmouseover)) != "") {
						if (tinyMCE.getParam('convert_urls'))
							src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);");

						imgs[i].setAttribute('onmouseover', "this.src='" + src + "';");
					}

					if ((src = this._getImageSrc(onmouseout)) != "") {
						if (tinyMCE.getParam('convert_urls'))
							src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);");

						imgs[i].setAttribute('onmouseout', "this.src='" + src + "';");
					}
				}
				break;*/
			case "get_from_editor_dom":
				var imgs = content.getElementsByTagName("img");
				for (var i=0; i<imgs.length; i++) {
					if (tinyMCE.getAttrib(imgs[i], "class") == "mceItemFlash") {
						var src = tinyMCE.getAttrib(imgs[i], "alt");

						if (tinyMCE.getParam('convert_urls'))
							src = eval(tinyMCE.settings['urlconverter_callback'] + "(src, null, true);");

						imgs[i].setAttribute('alt', src);
						imgs[i].setAttribute('title', src);
					}
				}
				break;
			case "insert_to_editor":
				var startPos = 0;
				var embedList = new Array();

				// Fix the embed and object elements
				content = content.replace(new RegExp('<[ ]*embed','gi'),'<embed');
				content = content.replace(new RegExp('<[ ]*/embed[ ]*>','gi'),'</embed>');
				content = content.replace(new RegExp('<[ ]*object','gi'),'<object');
				content = content.replace(new RegExp('<[ ]*/object[ ]*>','gi'),'</object>');

				// Parse all embed tags
				while ((startPos = content.indexOf('<embed', startPos+1)) != -1) {
					var endPos = content.indexOf('>', startPos);
					var attribs = TinyMCE_su3AdvancedVideoPlugin._parseAttributes(content.substring(startPos + 6, endPos));
					embedList[embedList.length] = attribs;
				}

				// Parse all object tags and replace them with images from the embed data
				var index = 0;
				while ((startPos = content.indexOf('<object', startPos)) != -1) {
					if (index >= embedList.length)
						break;

					var attribs = embedList[index];

					// Find end of object
					endPos = content.indexOf('</object>', startPos);
					endPos += 9;
					var query = attribs['flashvars'];
					var current_video = -1;
					var url = "";
					// Insert image
					var vars = query.split("&");
					for (var i=0;i<vars.length;i++) {
						var pair = vars[i].split("=");
						if (pair[0] == "videoID") {
							current_video =  pair[1];
						}
						if (pair[0] == "url") {
							url = pair[1];
						}

					}
					var contentAfter = content.substring(endPos);
					content = content.substring(0, startPos);
					content += '<img width="' + attribs["width"] + '" height="' + attribs["height"] + '"';
					content += ' src="'+ url +'binary/image/thumbnailer/-/vid/'+current_video+'/width/' + attribs["width"] + '/height/' + attribs["height"] + '" title="' + attribs["src"] + '"';
					content += ' alt="' + attribs["src"] + '" class="mceItemFlash" attr="'+attribs['flashvars']+'" />' + content.substring(endPos);
					content += contentAfter;
					index++;

					startPos++;
				}

				// Parse all embed tags and replace them with images from the embed data
				var index = 0;
				while ((startPos = content.indexOf('<embed', startPos)) != -1) {
					if (index >= embedList.length)
						break;

					var attribs = embedList[index];

					// Find end of embed
					endPos = content.indexOf('>', startPos);
					endPos += 9;
					var attribs = TinyMCE_su3AdvancedVideoPlugin._parseAttributes(content.substring(startPos + 4, endPos));

					// Insert image
					var contentAfter = content.substring(endPos);
					content = content.substring(0, startPos);
					content += '<img width="' + attribs["width"] + '" height="' + attribs["height"] + '"';
					content += ' src="binary/image/thumbnailer/-/vid/236/width/200/height/200" title="' + attribs["src"] + '"';
					content += ' alt="' + attribs["src"] + '" class="mceItemFlash" attr="'+attribs['flashvars']+'" />' + content.substring(endPos);
					content += contentAfter;
					index++;

					startPos++;
				}

				break;
			case "get_from_editor":
				// Parse all img tags and replace them with object+embed
				var startPos = -1;
				while ((startPos = content.indexOf('<img', startPos+1)) != -1) {
					var endPos = content.indexOf('/>', startPos);
					var attribs = TinyMCE_su3AdvancedVideoPlugin._parseAttributes(content.substring(startPos + 4, endPos));

					// Is not flash, skip it
					if (attribs['class'] != "mceItemFlash")
						continue;


					endPos += 2;

					var attr = attribs['attr'];

					var embedHTML = '';
					var wmode = tinyMCE.getParam("flash_wmode", "");
					var quality = tinyMCE.getParam("flash_quality", "high");
					var menu = tinyMCE.getParam("flash_menu", "false");

					// Insert object + embed
					embedHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
					embedHTML += ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"';
					embedHTML += ' width="' + attribs["width"] + '" height="' + attribs["height"] + '">';
					embedHTML += '<param name="movie" value="' + attribs["title"] + '" />';
					embedHTML += '<param name="quality" value="' + quality + '" />';
					embedHTML += '<param name="menu" value="' + menu + '" />';
					embedHTML += '<param name="wmode" value="' + wmode + '" />';
					embedHTML += '<param name="salign" value="lt" />';
					embedHTML += '<param name="allowFullScreen" value="true" />';
					embedHTML += '<param name="FlashVars" value="' + attr + '" />';
					embedHTML += '<embed src="' + attribs["title"] + '" allowFullScreen="true" FlashVars="' + attr + '" wmode="' + wmode + '" salign="lt" quality="' + quality + '" menu="' + menu + '" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="' + attribs["width"] + '" height="' + attribs["height"] + '"></embed></object>';

					// Insert embed/object chunk
					chunkBefore = content.substring(0, startPos);
					chunkAfter = content.substring(endPos);
					content = chunkBefore + embedHTML + chunkAfter;
				}
				break;
		}

		return content;
	},

	handleNodeChange : function(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) {
		if (node == null)
			return;

		do {
			if (node.nodeName == "IMG" && tinyMCE.getAttrib(node, 'class') == 'mceItemFlash') {
				tinyMCE.switchClass(editor_id + '_video', 'mceButtonSelected');
				return true;
			}
		} while ((node = node.parentNode));

		tinyMCE.switchClass(editor_id + '_video', 'mceButtonNormal');

		return true;
	},

	/**
	 * Returns the image src from a scripted mouse over image str.
	 *
	 * @param {string} s String to get real src from.
	 * @return Image src from a scripted mouse over image str.
	 * @type string
	 */
	_getImageSrc : function(s) {
		var sr, p = -1;

		if (!s)
			return "";

		if ((p = s.indexOf('this.src=')) != -1) {
			sr = s.substring(p + 10);
			sr = sr.substring(0, sr.indexOf('\''));

			return sr;
		}

		return "";
	},

	_parseAttributes : function(attribute_string) {
		var attributeName = "";
		var attributeValue = "";
		var withInName;
		var withInValue;
		var attributes = new Array();
		var whiteSpaceRegExp = new RegExp('^[ \n\r\t]+', 'g');

		if (attribute_string == null || attribute_string.length < 2)
			return null;

		withInName = withInValue = false;

		for (var i=0; i<attribute_string.length; i++) {
			var chr = attribute_string.charAt(i);

			if ((chr == '"' || chr == "'") && !withInValue)
				withInValue = true;
			else if ((chr == '"' || chr == "'") && withInValue) {
				withInValue = false;

				var pos = attributeName.lastIndexOf(' ');
				if (pos != -1)
					attributeName = attributeName.substring(pos+1);
				attributes[attributeName.toLowerCase()] = attributeValue.substring(1);

				attributeName = "";
				attributeValue = "";
			} else if (!whiteSpaceRegExp.test(chr) && !withInName && !withInValue)
				withInName = true;

			if (chr == '=' && withInName)
				withInName = false;

			if (withInName)
				attributeName += chr;

			if (withInValue)
				attributeValue += chr;
		}
		return attributes;
	}
};

tinyMCE.addPlugin("su3advideo", TinyMCE_su3AdvancedVideoPlugin);
