/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('mediamanager', tinyMCE.getParam('lang_list'));

var TinyMCE_MediaManagerPlugin = {
	getInfo : function() {
		return {
			longname : 'JCE MediaManager',
			author : 'Ryan Demmer',
			authorurl : 'http://www.cellardoor.za.net/jce',
			infourl : '',
			version : '1.0.0'
		};
	},

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

    getControlHTML : function(cn) {
		switch (cn) {
			case "mediamanager":
				return tinyMCE.getButtonHTML(cn, 'lang_mediamanager_desc', '{$pluginurl}/images/mediamanager.gif', 'mceMediaManager');
		}

		return "";
	},
	execCommand : function(editor_id, element, command, user_interface, value) {
		// Handle commands
		switch (command) {
			case "mceMediaManager":
   	            var mm_id = "", mm_title = "", mm_alt = "", mm_width = "", mm_height = "", mm_align = "", mm_vspace = "", mm_hspace = "", action = "insert";
				var template = new Array();
				var inst = tinyMCE.getInstanceById(editor_id);
				var focusElm = inst.getFocusElement();

				template['file']   = tinyMCE.getParam('site')+'/index2.php?option=com_jce&no_html=1&task=plugin&plugin=mediamanager&file=manager.php';
                template['width']  = 560;
			    template['height'] = 560;
			    
			    // Is selection a image
				if (focusElm != null && focusElm.nodeName.toLowerCase() == "img") {
					mm_id = tinyMCE.getAttrib(focusElm, 'id');

					if (mm_id.indexOf('mce_media_') != 0) // Not a Media File
						return true;

					// Get rest of Flash items
					mm_alt = tinyMCE.getAttrib(focusElm, 'alt');
					mm_title = tinyMCE.getAttrib(focusElm, 'title');
				    mm_width = tinyMCE.getAttrib(focusElm, 'width');
				    mm_height = tinyMCE.getAttrib(focusElm, 'height');
                    mm_align = tinyMCE.getAttrib(focusElm, 'align');
                    mm_hspace = tinyMCE.getAttrib(focusElm, 'hspace');
                    mm_vspace = tinyMCE.getAttrib(focusElm, 'vspace');
					action = "update";
				}
                tinyMCE.openWindow(template, {editor_id : editor_id, inline : "yes", mm_id : mm_id, mm_alt : mm_alt, mm_title : mm_title, mm_width : mm_width, mm_height : mm_height, mm_align : mm_align, mm_hspace : mm_hspace, mm_vspace : mm_vspace, action : action});
            return true;
      }
      // Pass to next handler in chain
	   return false;
    },
    cleanup : function(type, content) {
        switch (type) {
		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_MediaManagerPlugin._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;

                    //Converts URLs back to absolute - Ryan Demmer 08/05/2005 (ryandemmer@gmail.com)
                    var hostURL = tinyMCE.settings['document_base_url'];
                    if ((attribs['src'].indexOf(hostURL, attribs['src']+1) != -1) || (attribs['src'].indexOf('http://', attribs['src']+1) != -1) || (attribs['src'].indexOf('https://', attribs['src']+1) != -1)){
                        attribs['src'] = attribs['src'];
                    }else{
                      attribs['src'] = hostURL+attribs['src'];
                    }

                    var ext = TinyMCE_MediaManagerPlugin._getExtension(attribs['src']);
                    //Flash
                    if(ext == 'swf' || ext == 'flv'){
                        var fileStr = attribs["src"]+'|'+attribs["quality"]+'|'+attribs["menu"]+'|'+attribs["bgcolor"]+'|'+attribs["play"]+'|'+attribs["scale"]+'|'+attribs["wmode"]+'|'+attribs["AllowScriptAccess"]+'|'+attribs["loop"];
                        var className = "mceItemFlash";
                        var objName = "mce_media_swf";
                    }
                    //Quicktime
                    if(ext == 'mov' || ext == 'mp4'){
                        var fileStr = attribs["src"]+'|'+attribs["bgcolor"]+'|'+attribs["controller"]+'|'+attribs["autoplay"];
                        var className = "mceItemMov";
                        var objName = "mce_media_mov";
                    }
                    //Windows Media Video
                    if(ext == 'asf' || ext == 'asx' || ext == 'mpeg' || ext == 'mpg' || ext == 'avi' || ext == 'wmv'){
                        var fileStr = attribs["src"]+'|'+attribs["showcontrols"]+'|'+attribs["autostart"]+'|'+attribs["showstatusbar"];
                        var className = "mceItemMedia";
                        var objName = "mce_media_wmv";
                    }

                    // Insert image
    				var contentAfter = content.substring(endPos);
    				content = content.substring(0, startPos);
    				content += '<img id="' + objName + '" width="' + attribs["width"] + '" height="' + attribs["height"] + '" align="' + attribs["align"] + '"';
    				content += ' src="' + (tinyMCE.getParam("theme_href") + '/images/spacer.gif') + '" title="' + fileStr + '"';
    				content += ' alt="' + fileStr + '" vspace="' + attribs['vspace'] + '" hspace="' + attribs['hspace'] + '" class="'+className+'" />';
                    content += 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_MediaManagerPlugin._parseAttributes(content.substring(startPos + 4, endPos));

                    attribsName = new Array( 'mce_media_swf', 'mce_media_mov', 'mce_media_wmv' );

                    if(!TinyMCE_MediaManagerPlugin._inArray(attribs['id'], attribsName))
                        continue;

        			endPos += 2;

                    var embedHTML = '';

                    //Set defaults
                    attribs['vspace'] = (attribs['vspace'] == 'undefined') ?  '5' : attribs['vspace'];
                    attribs['hspace'] = (attribs['hspace'] == 'undefined') ? '5' : attribs['hspace'];
                    attribs['align'] = (attribs['align'] == 'undefined') ? '' : attribs['align'];
                    attribs['width'] = (attribs['width'] == 'undefined') ? '100' : attribs['width'];
                    attribs['height'] = (attribs['height'] == 'undefined') ? '100' : attribs['height'];
                    //Flash
                    if (attribs['id'] == "mce_media_swf") {

                        var fileStr = attribs["title"].split('|');
                        swf_src = fileStr[0];
                        swf_quality = (fileStr[1] == 'undefined') ? 'high' : fileStr[1];
                        swf_menu = (fileStr[2] == 'undefined') ? 'false' : fileStr[2];
                        swf_bgcolor = (fileStr[3] == 'undefined') ? '' : fileStr[3];
                        swf_play = (fileStr[4] == 'undefined') ? 'true' : fileStr[4];
                        swf_scale = (fileStr[5] == 'undefined') ? '' : fileStr[5];
                        swf_wmode = (fileStr[6] == 'undefined') ? 'opaque' : fileStr[6];
                        swf_script = (fileStr[7] == 'undefined') ? 'sameDomain' : fileStr[7];
                        swf_loop = (fileStr[8] == 'undefined') ? 'false' : fileStr[8];

        				// 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"] + '" align="' + attribs["align"] + '" vspace="' + attribs["vspace"] + '" hspace="' + attribs["hspace"] + '">';
        				embedHTML += '<param name="movie" value="' + swf_src + '" />';
        				embedHTML += '<param name="src" value="' + swf_src + '" />';
        				embedHTML += '<param name="play" value="' + swf_play + '" />';
        				embedHTML += '<param name="wmode" value="' + swf_wmode + '" />';
        				embedHTML += '<param name="scale" value="' + swf_scale + '" />';
        				embedHTML += '<param name="quality" value="' + swf_quality + '" />';
        				embedHTML += '<param name="menu" value="' + swf_menu + '" />';
        				embedHTML += '<param name="bgcolor" value="' + swf_bgcolor + '" />';
        				embedHTML += '<param name="AllowScriptAccess" value="' + swf_script + '" />';
        				embedHTML += '<param name="loop" value="' + swf_loop + '" />';
        				embedHTML += '<embed src="' + swf_src + '" scale="' + swf_scale + '"';
                        embedHTML += ' wmode="' + swf_wmode + '" play="' + swf_play + '" quality="' + swf_quality + '"';
                        embedHTML += ' menu="' + swf_menu + '" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"';
                        embedHTML += ' width="' + attribs["width"] + '" height="' + attribs["height"] + '" align="' + attribs["align"] + '" bgcolor="' + swf_bgcolor + '"';
                        embedHTML += ' AllowScriptAccess="' + swf_script + '" loop="' + swf_loop + '" hspace="' + attribs["hspace"] + '" vspace="' + attribs["vspace"] + '"></embed></object>';
                    }
                    //Quicktime
                    if (attribs['id'] == "mce_media_mov") {

                        var fileStr = attribs["title"].split('|');
                        swf_src = fileStr[0];
                        swf_bgcolor = (fileStr[1] == 'undefined') ? '' : fileStr[1];
                        swf_menu = (fileStr[2] == 'undefined') ? 'true' : fileStr[2];
                        swf_play = (fileStr[3] == 'undefined') ? 'true' : fileStr[3];

                        embedHTML += '<object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b" width="' + attribs["width"] + '" height="' + attribs["height"] + '" align="' + attribs["align"] + '" vspace="' + attribs["vspace"] + '" hspace="' + attribs["hspace"] + '" codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0">'
        				embedHTML += '<param name="controller" value="' + swf_menu + '">';
        				embedHTML += '<param name="type" value="video/quicktime">';
        				embedHTML += '<param name="autoplay" value="' + swf_play + '">';
        				embedHTML += '<param name="target" value="myself">';
        				embedHTML += '<param name="src" value="' + swf_src + '">';
        				embedHTML += '<param name="pluginspage" value="http://www.apple.com/quicktime/download/index.html">';
        				embedHTML += '<embed width="' + attribs["width"] + '" height="' + attribs["height"] + '" controller="' + swf_menu + '"';
                        embedHTML += ' target="myself" src="' + swf_src + '" type="video/quicktime" bgcolor="' + swf_bgcolor + '" align="' + attribs["align"] + '"';
                        embedHTML += ' pluginspage="http://www.apple.com/quicktime/download/index.html" autoplay="' + swf_play + '" hspace="' + attribs["hspace"] + '" vspace="' + attribs["vspace"] + '">';
                        embedHTML += '</embed></object>';
                    }
                    //Windows Media
                    if (attribs['id'] == "mce_media_wmv") {

                        var fileStr = attribs["title"].split('|');
                        swf_src = fileStr[0];
                        swf_menu = (fileStr[1] == 'undefined') ? 'true' : fileStr[1];
                        swf_play = (fileStr[2] == 'undefined') ? 'true' : fileStr[2];
                        swf_status = (fileStr[3] == 'undefined') ? 'false' : fileStr[3];

                        embedHTML += '<object id="mediaPlayer" classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" width="' + attribs["width"] + '" height="' + attribs["height"] + '" align="' + attribs["align"] + '" vspace="' + attribs["vspace"] + '" hspace="' + attribs["hspace"] + '" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" STANDBY="Loading Microsoft Windows Media Player components...">'
        				embedHTML += '<param name="showControls" value="' + swf_menu + '">';
        				embedHTML += '<param name="type" value="application/x-mplayer2">';
        				embedHTML += '<param name="autoStart" value="' + swf_play + '">';
        				embedHTML += '<param name="fileName" value="' + swf_src + '">';
        				embedHTML += '<param name="animationAtStart" value="true">';
        				embedHTML += '<param name="showStatusBar" value="' + swf_status + '"';
        				embedHTML += '<param name="clickToPlay" value="false">';
        				embedHTML += '<param name="transparentAtStart" value="true">';
        				embedHTML += '<embed width="' + attribs["width"] + '" height="' + attribs["height"] + '" showcontrols="' + swf_menu + '" showDisplay="false"';
                        embedHTML += ' src="' + swf_src + '" type="application/x-mplayer2" align="' + attribs["align"] + '"';
                        embedHTML += ' pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/" showstatusbar="' + swf_status + '" showdisplay="False" autostart="' + swf_play + '" hspace="' + attribs["hspace"] + '" vspace="' + attribs["vspace"] + '">';
                        embedHTML += '</embed></object>';
                    }
                    // Insert embed/object chunk
    				chunkBefore = content.substring(0, startPos);
    				chunkAfter = content.substring(endPos);
    				content = chunkBefore + embedHTML + chunkAfter;
    			}
    			break;
    	}
    	// Pass through to next handler in chain
    	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, 'id').indexOf('mce_media_swf') == 0 || tinyMCE.getAttrib(node, 'id').indexOf('mce_media_mov') == 0 || tinyMCE.getAttrib(node, 'id').indexOf('mce_media_wmv') == 0)){
				tinyMCE.switchClass(editor_id + '_mediamanager', 'mceButtonSelected');
				return true;
			}
		} while ((node = node.parentNode));

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

		return true;
	},
	// Private plugin internal functions
	_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;
	},
	// Returns true or false based on whether the specified string is found
    // in the array. This is based on the PHP function of the same name.
    // Written by Beau Lebens <beau@dentedreality.com.au>
    _inArray : function(stringToSearch, arrayToSearch) {
   	    for (s = 0; s < arrayToSearch.length; s++) {
  		    thisEntry = arrayToSearch[s].toString();
  		    if (thisEntry == stringToSearch) {
                return true;
      		}
       	}
       	return false;
    },
    _getExtension : function(name) {
        var regexp = /\/|\\/;
        var parts = name.split(regexp);
        var filename = parts[parts.length-1].split(".");
        if (filename.length <= 1) {
            return(-1);
        }
        var ext = filename[filename.length-1].toLowerCase();
        return ext;
    }
};

tinyMCE.addPlugin("mediamanager", TinyMCE_MediaManagerPlugin);
