var tinyMCE_GZ = {
	settings : {
		themes : '',
		plugins : '',
		languages : '',
		disk_cache : true,
		page_name : 'tiny_mce_gzip.aspx',
		debug : false,
		suffix : ''
	},

	init : function(s, cb, sc) {
		var t = this, n, i, nl = document.getElementsByTagName('script');

		for (n in s)
			t.settings[n] = s[n];

		s = t.settings;

		for (i=0; i<nl.length; i++) {
			n = nl[i];

			if (n.src && n.src.indexOf('tiny_mce') != -1)
				t.baseURL = n.src.substring(0, n.src.lastIndexOf('/'));
		}

		if (!t.coreLoaded)
			t.loadScripts(1, s.themes, s.plugins, s.languages, cb, sc);
	},

	loadScripts : function(co, th, pl, la, cb, sc) {
		var t = this, x, w = window, q, c = 0, ti, s = t.settings;

		function get(s) {
			x = 0;

			try {
				x = new ActiveXObject(s);
			} catch (s) {
			}

			return x;
		};

		// Build query string
		q = 'suffic=_src&js=true&diskcache=' + (s.disk_cache ? 'true' : 'false') + '&core=' + (co ? 'true' : 'false') + '&suffix=' + escape(s.suffix) + '&themes=' + escape(th) + '&plugins=' + escape(pl) + '&languages=' + escape(la);

		if (co)
			t.coreLoaded = 1;

		// Send request
		x = w.XMLHttpRequest ? new XMLHttpRequest() : get('Msxml2.XMLHTTP') || get('Microsoft.XMLHTTP');
		x.overrideMimeType && x.overrideMimeType('text/javascript');
		x.open('GET', t.baseURL + '/' + s.page_name + '?' + q, !!cb);
		x.setRequestHeader('Content-Type', 'text/javascript');
		x.send('');

		// Handle asyncronous loading
		if (cb) {
			// Wait for response
			ti = w.setInterval(function() {
				if (x.readyState == 4 || c++ > 10000) {
					w.clearInterval(ti);

					if (c < 10000 && x.status == 200) {
						t.loaded = 1;
						t.eval(x.responseText);
						tinymce.dom.Event.domLoaded = true;
						cb.call(sc || t, x);
					}

					ti = x = null;
				}
			}, 10);
		} else
			t.eval(x.responseText);
	},

	start : function() {
		var t = this, each = tinymce.each, s = t.settings, ln = s.languages.split(',');

		tinymce.suffix = s.suffix;

		function load(u) {
			tinymce.ScriptLoader.markDone(tinyMCE.baseURI.toAbsolute(u));
		};

		// Add core languages
		each(ln, function(c) {
			if (c)
				load('langs/' + c + '.js');
		});

		// Add themes with languages
		each(s.themes.split(','), function(n) {
			if (n) {
				load('themes/' + n + '/editor_template' + s.suffix + '.js');

				each (ln, function(c) {
					if (c)
						load('themes/' + n + '/langs/' + c + '.js');
				});
			}
		});

		// Add plugins with languages
		each(s.plugins.split(','), function(n) {
			if (n) {
				load('plugins/' + n + '/editor_plugin' + s.suffix + '.js');

				each(ln, function(c) {
					if (c)
						load('plugins/' + n + '/langs/' + c + '.js');
				});
			}
		});
	},

	end : function() {
	},

	eval : function(co) {
		var w = window;

		// Evaluate script
		if (!w.execScript) {
			if (/Gecko/.test(navigator.userAgent))
				eval(co, w); // Firefox 3.0
			else
				eval.call(w, co);
		} else
			w.execScript(co); // IE
	}
};

/**
 * iFokus RTE configration handling...
 */
var iFokusRTE = {

  initialize: function(id, custom_options) {
    if (navigator.platform && (navigator.platform.indexOf('iPhone') != -1 || navigator.platform.indexOf('iPod') != -1)) {
        return;
    }

    try {
        var options = Object.extend({
            mode: 'exact',
            elements: id,
  		    language: "sv",
            content_css: "/Styles/TinyEditor.css.aspx",
  		    theme: "advanced",
  		    browsers: "msie,gecko,opera,safari",
  		    theme_advanced_path_location: "",
  		    theme_advanced_buttons1: "",
  		    theme_advanced_buttons2: "",
  		    theme_advanced_buttons3: "",
  		    theme_advanced_toolbar_location: "top",
  		    theme_advanced_toolbar_align: "left",
  		    paste_unindented_list_class: "unindentedList",
  		    paste_create_paragraphs: true,
  		    paste_use_dialog: false,
  		    paste_auto_cleanup_on_paste: true,
  		    paste_convert_middot_lists: true,
  		    entity_encoding: 'raw',
  		    relative_urls: false,
  		    remove_script_host: false,
  		    convert_urls : false,
  		    tab_focus: ':prev,:next'
        }, custom_options);
        
        tinyMCE_GZ.init({
            themes: options.theme,
            languages: options.language,
            plugins: options.plugins 
        }, function() {
            tinyMCE.init(options);
        });
    } catch (e) { alert("Error Tiny:174\n\n" + e) }
  },
  
  extendedValidElements: function() {
    var source = {
        a: "a[name|href|target|title|onclick]",
        img: "img[class|style|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name]",
        hr: "hr[class|width|size|noshade]",
        span: "span[class|align|style]",
        h1: "h1,h2,h3",
        table: "table[class|cellpadding|cellspacing|border=0|width|style],tr,td[valign|align|style|class]"
    }
    return $A(arguments).map(function(arg) { return source[arg] }).join(",");
  },
  
  toolbar: function() {
    return $A(arguments).join(",separator,");
  },
  
  basicToolbar: function(survey) {
    return iFokusRTE.toolbar(
        "bold,italic,underline", 
        "justifyleft,justifycenter",
        "bullist,numlist,ifokuslink,unlink",
        "copy,paste,undo",
        (survey ? "emotions,survey" : "emotions")
    );
  },
  
  plugins: function() {
    var extra = "";
    if (arguments.length > 0) {
        extra = "," + $A(arguments).join(",");
    }
    return "safari,contextmenu,paste,emotions,inlinepopups,fullscreen,keys,ifokuslink" + extra;
  },
  
  /**
   *
   * Configurations...
   *
   */
  initRTE: function(element) {
    element.removeClassName('rte');

    if (element.hasClassName('comment')) {
      iFokusRTE.initComment(element.id);
    } else if (element.hasClassName('post')) {
      iFokusRTE.initPost(element.id);
    } else if (element.hasClassName('article')) {
      iFokusRTE.initArticle(element.id);
    }
  },
  
  initComment: function(id) {
  	iFokusRTE.initialize(id, {
  		plugins: iFokusRTE.plugins(),
  		theme_advanced_buttons1: iFokusRTE.basicToolbar(false),
  		extended_valid_elements: iFokusRTE.extendedValidElements('a', 'img', 'hr', 'span')
  	});
  },
   
  initPost: function(id) {
  	iFokusRTE.initialize(id, {
  		plugins: iFokusRTE.plugins('survey'),
  		theme_advanced_buttons1: iFokusRTE.basicToolbar(true),
  		extended_valid_elements: iFokusRTE.extendedValidElements('a', 'img', 'hr', 'span')
  	});
  },
  
  initArticle: function(id) {
    iFokusRTE.initialize(id, {
        plugins: iFokusRTE.plugins('ifokusimage,survey'),
        theme_advanced_buttons1: iFokusRTE.toolbar(
            "cut,copy,paste,pastetext",
            "undo,redo,separator,ifokusimage,ifokuslink,unlink",
            "fullscreen,code,survey"
        ),
        theme_advanced_buttons2: iFokusRTE.toolbar( 
            "formatselect,bold,italic,underline",
            "justifyleft,justifycenter,justifyright",
            "bullist,numlist,outdent,indent",
            "emotions"
        ),
        theme_advanced_blockformats : "p,h2,h3,pre,code,blockquote",
        ifokusimage_maxwidth: 385,
        ifokusimage_maxheight: 400,
        ifokusimage_autofloat: true,
        extended_valid_elements: iFokusRTE.extendedValidElements('a', 'img', 'hr', 'span', 'table', 'h1')
    });
  }  
}

document.observe('dom:loaded', function() {
    $$('textarea.rte').each(function(element) {
        iFokusRTE.initRTE(element);
    });
}, false);

function showProperties(obj) {
    alert(getProperties(obj));
}

function getProperties(obj) {
    l = [];
    for (k in obj) {
        if (k > 'p') {
            l.push(k);
        }
    }
    return l.sort().join("\n");
}
