/**
 *  $Id$
 *
 *    
 */

/* Import plugin specific language pack */
tinyMCE.importPluginLanguagePack('mmedia');

var TinyMCE_MMediaPlugin = {
  getInfo : function() {
    return {
      longname : 'mmedia',
      author : 'Rhys McGuckin',
      authorurl : '',
      infourl : 'http://drupal.org/project/media',
      version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
    };
  },

  initInstance : function(inst) {
    if ((inst.hasPlugin('flash') || inst.hasPlugin('media')) && !tinyMCE.mediaWarn) {
      alert('Flash/Media plugin should not be used with mmedia plugin.');
      tinyMCE.mediaWarn = true;
    }
  },

  getControlHTML : function(cn) {
    switch (cn) {
      case "mmedia":
        return tinyMCE.getButtonHTML(cn, 'lang_mmedia_desc', '{$pluginurl}/images/mmedia.gif', 'mceMedia');
    }

    return "";
  },

  execCommand : function(editor_id, element, command, user_interface, value) {
    // Handle commands
    switch (command) {
      case "mceMedia":
        var details = new Array();
        var inst = tinyMCE.getInstanceById(editor_id);
        var focusElm = inst.getFocusElement();
        
        var base_url = tinyMCE.baseURL;
        base_url = base_url.substring(0, base_url.indexOf('modules'));
        
        details['file'] = base_url + 'index.php?q=media/embed&popup=1&target=tinymce';
        details['width'] = 640;
        details['height'] = 480;
        details['html'] = false;
        
        var focusElm = inst.getFocusElement();
        if (focusElm != null && focusElm.nodeName.toLowerCase() == 'img') {
          var name = tinyMCE.getAttrib(focusElm, 'class');
          if (name.indexOf('mceItemMMedia') != -1) {
            var attribs = tinyMCE.getAttrib(focusElm, 'alt');
            var id = attribs.split('|');
            details['file'] += '&id=' + id[0] + '&tag=' + id[1];
          }
        }                
        
        tinyMCE.openWindow(details, {
            editor_id : editor_id,
            inline : "yes",
            scrollbars : "yes"
        });

        return true;
     }

     // Pass to next handler in chain
     return false;
  },
  
  cleanup : function(type, content) {
    switch (type) {
      case 'insert_to_editor':
        // convert tag [media:(id):(settings)] to <img>
        var startPos = 0;
        var index = 0;
        while ((startPos = content.indexOf('[media:', startPos)) != -1) {
          // get the entire tag
          var endPos = content.indexOf(']', startPos);
          
          // get the tag
          var tag = content.substring(startPos+7, endPos);

          // get the id, and the settings.
          var settings = '';
          var idPos = tag.indexOf(':');
          var width = 0;
          var height = 0;
          
          if (idPos != -1) {
            // we can get settings and readjust the ID
            settings = tag.substring(idPos+1);
            tag = tag.substring(0, idPos);
            
            // extract width and height from settings
            width = settings.match(/width="\d+"/);
            height = settings.match(/height="\d+"/);
          }
          
          // now that we have the correct settings, let's make it into something we can use.
          // convert to URI valid details.
          tag = encodeURIComponent(tag);
          settings = encodeURIComponent(settings);

          // go past the end        
          endPos++;
          
          // Insert wysiwyg image, which takes the ID and the settings and generates an image.
          var contentAfter = content.substring(endPos);
          content = content.substring(0, startPos);
          content += '<img src="' + Drupal.mediaEmbedUrl('media/embed/view', 'id=' + tag + '&settings=' + settings);
          content += '" alt="'+tag+'|'+ settings + '"';
          // use width and height to adjust image to specifications, it won't look perfect, but it's close.
          if (width != null) {
            content += ' ' + width;
          }
          if (height != null) {
            content += ' ' + height;
          }
          content += ' class="mceItemMMedia" />';
          content += contentAfter;
          
          // start from here the new checking through the content.
          startPos++;
        }
        break;
      case 'insert_to_editor_dom':
        break;
      case 'setup_content_dom':
        break;
      case 'submit_content_dom':
        break;
      case 'submit_content':
        break;
      case 'get_from_editor_dom':
        break;
      case 'get_from_editor':
        // convert <img> to tag...
        // Parse all image placeholders and replace them with drupalimage filter tags
        var startPos = -1;
        while ((startPos = content.indexOf('<img', startPos+1)) != -1) {
          var endPos = content.indexOf('/>', startPos);
          endPos += 2;
          
          // get attributes
          var attribs = TinyMCE_MMediaPlugin._parseHTMLAttributes(content.substring(startPos + 4, endPos));
          
          // Is not drupalimage, skip it
          if (attribs['class'] != "mceItemMMedia") {
            continue;
          }
          
          // Insert drupalimage filter code
          //  At this point all attribute values should have any pipes | or closing square brackets ]
          //  escaped with backslashes.  When this filter code is parsed, it will look for the closing 
          //  bracket to find the end and the pipe symbol to explode the rest of the attributes.  However,
          //  since we just parsed from HTML tag, HTML entities should be unescaped at this time.
          var height = attribs["height"];
          var width = attribs["width"];
          var alt = attribs["alt"];
          
          attribs = alt.split('|');
          var id = attribs[0];
          var settings = decodeURIComponent(attribs[1]);
  
          attribs = TinyMCE_MMediaPlugin._parseHTMLAttributes(settings);

          // readjust settings with changes in TinyMCE.          
          if (height != null && attribs['height'] != height) {
            attribs['height'] = height;
          }
          if (width != null && attribs['width'] != width) {
            attribs['width'] = width;
          }

          // update the content
          var contentBefore = content.substring(0, startPos);
          var contentAfter = content.substring(endPos);

          content = contentBefore;
          content += '[media:' + id;
          var attrib = '';
          for (var i in attribs) {
            attrib += i + '="' + attribs[i] + '";';
          }
          if (attrib) {
            content += ':' + attrib;
          }
          content += ']';
          content += contentAfter;
         }
        break;
      default:
        alert(type);
        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, 'class').indexOf('mceItemMMedia') == 0) {
        tinyMCE.switchClass(editor_id + '_mmedia', 'mceButtonSelected');
        return true;
      }
    } while ((node = node.parentNode));

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

    return true;
  }  ,

  // taken from drupalimage, modified to get proper values for object count
  _parseHTMLAttributes : function(attribute_string) {
    var attributes = new Array();
    var innerMatches = new Array();
    var regExp = '([a-zA-Z0-9]+)[\s]*=[\s]*"([^"](?:\\.|[^\\"]*)*)"';
  
    var outerRegExp = new RegExp(regExp, "g"); // doesn't work without global (g)
    var outerMatches = attribute_string.match(outerRegExp);
    var innerRegExp = new RegExp(regExp); // doesn't work with global (g)
    for (var i = 0; i < outerMatches.length; i++ ) {
      innerMatches = innerRegExp.exec(outerMatches[i]);
      attributes[innerMatches[1]] = innerMatches[2];
    }
    return attributes;
  },
};

tinyMCE.addPlugin("mmedia", TinyMCE_MMediaPlugin);
