function TinyMCE_media_initInstance(inst) {
	tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/plugins/media/media.css");
}

function TinyMCE_media_getControlHTML(control_name) {
    switch (control_name) {
        case "media":
            return '<img id="{$editor_id}_media" src="{$pluginurl}/images/media.gif" title="插入/编辑 媒体与 Flash 电影" width="20" height="20" class="mceButtonNormal" onmouseover="tinyMCE.switchClass(this,\'mceButtonOver\');" onmouseout="tinyMCE.restoreClass(this);" onmousedown="tinyMCE.restoreAndSwitchClass(this,\'mceButtonDown\');" onclick="tinyMCE.execInstanceCommand(\'{$editor_id}\',\'mceMedia\');">';
    }

    return "";
}

function TinyMCE_media_execCommand(editor_id, element, command, user_interface, value) {
	function getAttrib(elm, name) {
		return elm.getAttribute(name) ? elm.getAttribute(name) : "";
	}

    // Handle commands
    switch (command) {
        case "mceMedia":
			var name = "", mediafile = "", mediawidth = "", mediaheight = "", mediaautostart = false, action = "insert";
            var template = new Array();
			var inst = tinyMCE.getInstanceById(editor_id);
			var focusElm = inst.getFocusElement();

            template['file']   = '../../plugins/media/media.htm'; // Relative to theme
            template['width']  = 400;
            template['height'] = 220;

			// Is selection a image
            if (focusElm != null && focusElm.nodeName.toLowerCase() == "img") {
				name = getAttrib(focusElm, 'name');

				if (name != 'mce_plugin_media') // Not a Media
					return true;

				// Get rest of Media items
				mediafile = getAttrib(focusElm, 'title');
				mediawidth = getAttrib(focusElm, 'width');
				mediaheight = getAttrib(focusElm, 'height');
				mediaautostart = getAttrib(focusElm, 'autostart');
				action = "update";
            }

            tinyMCE.openWindow(template, {editor_id : editor_id, mediafile : mediafile, mediawidth : mediawidth, mediaheight : mediaheight, mediaautostart: mediaautostart, action : action});
		return true;
   }

   // Pass to next handler in chain
   return false;
}

function TinyMCE_media_cleanup(type, content) {
	switch (type) {
		case "insert_to_editor":
			var startPos = 0;

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

			// Parse all embed tags
			while ((startPos = content.indexOf('<embed', startPos)) != -1) {
				var endPos = content.indexOf('>', startPos);
				var attribs = TinyMCE.parseAttributes(content.substring(startPos + 6, endPos));

				if(typeof(attribs["width"])=="undefined")attribs["width"]=320;
				if(typeof(attribs["height"])=="undefined")attribs["height"]=240;
				if(typeof(attribs["autostart"])=="undefined")attribs["autostart"]="true";

				endPos ++;

				// Insert image
				var contentAfter = content.substring(endPos);
				content = content.substring(0, startPos);
				content += '<img name="mce_plugin_media" width="' + attribs["width"] + '" height="' + attribs["height"] + '"';
				content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + attribs["src"] + '"';
				content += ' alt="' + attribs["src"] + '" autostart="' + attribs["autostart"];
				if(attribs["src"].substr(attribs["src"].length - 4).toLowerCase() == '.swf')
					content += '" class="mce_plugin_flash">';
				else content += '" class="mce_plugin_media">';
				content += contentAfter;

				startPos++;
			}

			var startPos = 0;

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

			// Parse all embed tags
			while ((startPos = content.indexOf('<iframe', startPos)) != -1) {
				var endPos = content.indexOf('>', startPos);
				var attribs = TinyMCE.parseAttributes(content.substring(startPos + 7, endPos));

				if(typeof(attribs["width"])=="undefined")attribs["width"]=320;
				if(typeof(attribs["height"])=="undefined")attribs["height"]=240;

				endPos ++;

				// Insert image
				var contentAfter = content.substring(endPos);
				content = content.substring(0, startPos);
				if(attribs["src"].substr(attribs["src"].length - 4).toLowerCase() == '.swf')
				{
					content += '<img name="mce_plugin_media" width="' + attribs["width"] + '" height="' + attribs["height"] + '"';
					content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + attribs["src"] + '"';
					content += ' alt="' + attribs["src"] + '" class="mce_plugin_flash">';
				}
				content += contentAfter;

				startPos++;
			}

			break;

		case "get_from_editor":
			// Parse all img tags and replace them with embed
			var startPos = 0;
			content = content.replace(new RegExp('<[ ]*img','gi'),'<img');
			while ((startPos = content.indexOf('<img', startPos)) != -1) {
				var endPos = content.indexOf('>', startPos);
				var attribs = TinyMCE.parseAttributes(content.substring(startPos + 4, endPos));

				// Is not media, skip it
				if (attribs['name'] != "mce_plugin_media")
				{
					startPos = endPos;
					continue;
				}

				if(typeof(attribs["width"])=="undefined")attribs["width"]=320;
				if(typeof(attribs["height"])=="undefined")attribs["height"]=240;
				if(typeof(attribs["autostart"])=="undefined")attribs["autostart"]="true";

				endPos ++;

				// Insert embed chunk
				chunkBefore = content.substring(0, startPos);
				chunkAfter = content.substring(endPos);
				content = chunkBefore + '<embed src="' + attribs["title"] + '" autostart="' + attribs["autostart"] + '" width="' + attribs["width"] + '" height="' + attribs["height"] + '"></embed>' + chunkAfter;

				startPos ++;
			}

			break;
	}

	// Pass through to next handler in chain
	return content;
}

function TinyMCE_media_handleNodeChange(editor_id, node, undo_index, undo_levels, visual_aid, any_selection) {
	function getAttrib(elm, name) {
		return elm.getAttribute(name) ? elm.getAttribute(name) : "";
	}

	tinyMCE.switchClassSticky(editor_id + '_media', 'mceButtonNormal');

	if (node == null)
		return;

	do {
		if (node.nodeName.toLowerCase() == "img" && getAttrib(node, 'name').indexOf('mce_plugin_media') == 0)
			tinyMCE.switchClassSticky(editor_id + '_media', 'mceButtonSelected');
	} while ((node = node.parentNode));

	return true;
}
