/**
 * Hallo Welt! MediaWiki Distribution
 * @copyright Copyright 2007 by Hallo Welt! Medienwerkstatt GmbH
 * @author Markus Glaser
 * @abstract This file is a common library for Hallo Welt! extensions.
 *
 * $LastChangedDate: 2009-07-14 12:00:44 +0200 (Di, 14 Jul 2009) $
 * $LastChangedBy: mglaser $
 * $Rev: 894 $
 * $Id: hw_framework.js 894 2009-07-14 10:00:44Z mglaser $
 */

/* Changelog
 * v1.8.5
 * - added support for selection in non editor mode
 */

var i18n_msg = false;
var timeout_personal;
var personalmenu = true;
var hw_file_data = new Object;
var hw_link_data = new Object;
var hw_image_data = new Object;
var hw_category_data = new Object;
var hw_file_data = new Object;
var scroll_pos = false;
var selected_text = false;
var orig_text = false;
var start_pos = false;

function hw_save_scrollpos()
{
    if ((typeof(tinyMCEmode)!="undefined") && tinyMCEmode ) return;

    if (document.selection  && document.selection.createRange) { // IE/Opera
        //save window scroll position
        if (document.documentElement && document.documentElement.scrollTop)
                scroll_pos = document.documentElement.scrollTop
        else if (document.body)
                scroll_pos = document.body.scrollTop;
    } else {
        textbox = document.getElementById('wpTextbox1');
        scroll_pos = textbox.scrollTop;
    }
}

function hw_restore_scrollpos()
{
    if ((typeof(tinyMCEmode)!="undefined") && tinyMCEmode ) return;
    if (document.selection  && document.selection.createRange) { // IE/Opera
                if (document.documentElement && document.documentElement.scrollTop)
			document.documentElement.scrollTop = scroll_pos
		else if (document.body)
			document.body.scrollTop = scroll_pos;
    } else {
        textbox = document.getElementById('wpTextbox1');
        textbox.scrollTop = scroll_pos;
    }
}

function hw_save_selection()
{
   if ((typeof(tinyMCEmode)!="undefined") && tinyMCEmode ) return;
   if (selected_text!==false)
   {
       //if (document.selection  && document.selection.createRange) document.selection.removeAllRanges();
       return selected_text;
   }
   textbox = document.getElementById('wpTextbox1');
   textbox.focus();
   if (document.selection  && document.selection.createRange) {
        range = document.selection.createRange();
        selected_text = range.text;
        temp_text = textbox.value;
        range.text = "hw_selection";
        //start = textbox.value.indexOf("hw_selection");
        orig_text = textbox.value.replace(/\r\n/g, "\n");
        start_pos = orig_text.indexOf("hw_selection");
        textbox.value = temp_text;
   } else {
        start_pos = textbox.selectionStart;
        var endPos = textbox.selectionEnd;
        selected_text = textbox.value.substring(start_pos, endPos);
        temp_text = textbox.value;
        textbox.value = textbox.value.substring(0, start_pos)
                + "hw_selection"
                + textbox.value.substring(endPos, textbox.value.length);
        orig_text = textbox.value;
        textbox.value = temp_text;
   }
   return selected_text;
}

function hw_restore_selection(text)
{
    if ((typeof(tinyMCEmode)!="undefined") && tinyMCEmode ) return;
    textbox = document.getElementById('wpTextbox1');
    textbox.focus();
    if (text == undefined) text = selected_text;
    textbox.value = orig_text.replace("hw_selection", text);
    selected_text = false;

    if (start_pos)
    {
      pos = start_pos + text.length;
      if (document.selection  && document.selection.createRange) {
        range = textbox.createTextRange();
        range.move('character', pos);
        range.select();
      } else {
         textbox.setSelectionRange(pos, pos);
      }
 }

}

function hw_show_personal(show, mode) {
	if (!personalmenu) return;
	if (show)
	{
		document.getElementById('p-personal-menu').style.display = 'block';
		if (mode=='init') timeout_personal = setTimeout('hw_show_personal(false)', 1000);
	}
	else
	{
		document.getElementById('p-personal-menu').style.display = 'none';
		clearTimeout(timeout_personal);
	}
}

var timeout_more;
var moremenu = true;
function ca_more_toggle(show, mode) {
	if (!moremenu) return;
	if (show)
	{
		morebox_style = document.getElementById('ca-more-box').style;
		morebox_style.display = 'block';
//		morebox_style.top=(mouse_y+10)+"px";
//		morebox_style.left=(mouse_x+15)+"px";

		if (mode=='init') timeout_more = setTimeout('ca_more_toggle(false)', 1000);
		else if (timeout_more) clearTimeout(timeout_more);
	}
	else
	{
		document.getElementById('ca-more-box').style.display = 'none';
		if (timeout_more) clearTimeout(timeout_more);
	}
}

function check_pagename(pagename)
{
	forbidden = new Array('[', ']', '{', '}', '&', '?', '<', '>', '\\', ',');
	valid = true;
	if (pagename=="")
    {
        i18n.load("js");
		hw_alert(["ERR",i18n.js.hw_notitle]);
        return false;
    }
	for (i=0; i<forbidden.length; i++)
		if (pagename.indexOf(forbidden[i])!=-1)
		{
			valid=false;
			
			i18n.load("js");
			hw_alert(["ERR",i18n.js.hw_charnotallowed_pre+forbidden[i]+i18n.js.hw_charnotallowed_post]);
//			hw_alert(i18n_msg[0]["hw_charnotallowed_pre"]+forbidden[i]+i18n_msg[0]["hw_charnotallowed_post"], 'ok');
			return false;
		}
	return true;
}

var mouse_x=0;
var mouse_y=0;

if (navigator.appName == "Netscape")
{
	document.captureEvents(Event.MOUSEMOVE);
}

document.onmousemove = mousexy;

function mousexy(e) {
	if (navigator.appName == "Netscape")
	{
		mouse_x = e.pageX;
		mouse_y = e.pageY;
	}
	else
	{
		var obj = (window.document.compatMode && window.document.compatMode == "CSS1Compat") ?
         				window.document.documentElement : window.document.body || null;

		mouse_x = window.event.clientX + obj.scrollLeft;
		mouse_y = window.event.clientY + obj.scrollTop;
	}
}

var page_height = false;
var page_width = false;

function get_page_size()
{
	if (window.innerHeight && window.scrollMaxY)
	{
		page_width = document.body.scrollWidth;
		page_height = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight)  // all but Explorer Mac
	{
		page_width = document.body.scrollWidth;
		page_height = document.body.scrollHeight;
	} else if (	document.documentElement &&
				document.documentElement.scrollHeight > document.documentElement.offsetHeight) // Explorer 6 strict mode
	{
		page_width = document.documentElement.scrollWidth;
		page_height = document.documentElement.scrollHeight;
	}
	else // Explorer Mac...would also work in Mozilla and Safari
	{
		page_width = document.body.offsetWidth;
		page_height = document.body.offsetHeight;
	}
}

var LoadOnDemand = function() {}
LoadOnDemand.prototype = {
	callback : false,
	errcount : 0,

	load : function(module, callback, i18n) {
        loadExt();

	    if(this.modules[module] == 'loaded') {
			window[callback]();
			return;
		}
		if(this.callback) {
			alert("Just one module can load at the same time.\nPlease wait a few seconds.");
			return;
		}
		this.callback = callback;
		if(i18n) {
		    /* here, no wgScriptPath is needed. Reason is not clear */
			this.getFile('/hallowelt/'+module+'/i18n/'+module+'.i18n.'+wgUserLanguage+'.js');
		}
		for(i in this.modules[module]) {
			if(typeof(this.modules[module][i]) == 'function')
				continue;
			this.getFileWithCallback(this.modules[module][i]);
		}
		this.modules[module] = 'loaded';
	},

	getFile : function(path) {
		Ext.Ajax.request({
			url: wgScriptPath+path,
			success: function(r) {
				eval(r.responseText);
			}
		});
	},

	getFileWithCallback : function(path) {
		Ext.Ajax.request({
			url: wgScriptPath+path,
			success: function(r) {
				eval(r.responseText);
				lod.doCallback();
			}
		});
	},

	doCallback : function() {
		try {
			callback = this.callback;
			window[callback]();
		}
		catch(e) {
			if(this.errcount == 1000) {
				alert("An error occurred loading "+this.callback+"().\nAction aborted!");
				this.callback = false;
				this.errcount = 0;
			}
			else {
				this.errcount++;
				window.setTimeout("lod.doCallback()", 10);
			}
			return;
		}
		this.callback = false;
	}
}

var lod = new LoadOnDemand();


var i18nMngr = function() {}
i18nMngr.prototype = {
	load: function(module) {
		if (!this[module]) {
            //Prevent caching with Math.random in order to be able to cope with language change.
			hw_load_js(wgScriptPath+'/hallowelt/'+module+'/i18n/'+module+'.i18n.'+wgUserLanguage+'.js'+'?'+Math.random());
		}
	}
};

var i18n = new i18nMngr();

var loadExt = function() {
	if (!Ext.Ajax) {
	    hw_load_js(wgScriptPath+'/hallowelt/js/ext/ext-all.js');
		// Overwrite Ext's default BLANK_IMAGE_URL. Requires that Ext be loaded beforehand.
	    Ext.BLANK_IMAGE_URL = wgScriptPath+'/hallowelt/js/ext/resources/images/default/s.gif';
	}
}

var localizeExt = function() {
	hw_load_js(wgScriptPath+'/hallowelt/js/ext/build/locale/ext-lang-'+wgUserLanguage+'.js');
}


var hw_ajax;

function hw_createRequestObject() {
//    var browser = navigator.appName;
//    if(browser == "Microsoft Internet Explorer"){
//        ro = new ActiveXObject("Microsoft.XMLHTTP");
//    }else{
//        ro = new XMLHttpRequest();
//    }
	  if (hw_ajax) {
	  	return;
	  }
      if (window.XMLHttpRequest)
	  {
		  hw_ajax = new XMLHttpRequest();
	  }
      else if (window.ActiveXObject)
	  {
		  hw_ajax = new ActiveXObject("Microsoft.XMLHTTP");
	  }
}

function hw_requestTest()
{
	//alert(wgScriptPath);
	hw_createRequestObject();

	hw_ajax.open('get', wgScriptPath+'/hallowelt/lib/hw_ajax.php?ajax_test');
    hw_ajax.onreadystatechange = function()
	{
    	//alert('irgendwas');

		if(hw_ajax.readyState == 4)
		{
        	var response = hw_ajax.responseText;
//			window.status = response;
		}
	}
	hw_ajax.send(null);
}

function hw_requestWithAnswer(url)
{
    hw_createRequestObject();
    mouseWait(true);
	hw_ajax.open('get', url);
    hw_ajax.onreadystatechange = function()
	{
	    if(hw_ajax.readyState == 4)
		{
        	mouseWait(false);
            var response = hw_ajax.responseText;
			hw_alert(response, 'ok');
		}
	}
    document.getElementById('')
	hw_ajax.send(null);
}

// return value must consist of two parts divided by a semicolon: a) 'yes' or 'no' for reload, b) the message
function hw_requestWithAnswerAndReload(url)
{
	hw_createRequestObject();
    hw_ajax.open('get', url);
    mouseWait(true);
    hw_ajax.onreadystatechange = function()
	{
	    if(hw_ajax.readyState == 4)
		{
        	mouseWait(false);
            var response = hw_ajax.responseText;
			var res = eval(response);
			if((typeof(res) == 'object' && res[0] == 'SUC')) {
				hw_alert(response, 'reload');
			}
			else {
				hw_alert(response, 'ok');
			}
		}
	}
	hw_ajax.send(null);
}

function mouseWait(on)
{
    setTimeout("mouseWaitTM("+on+")", 1);
}

function mouseWaitTM(on)
{
    if (on) document.body.style.cursor = "wait";
    else document.body.style.cursor = "default";
}

function hw_message (text)
{
	hw_alert(text);
}

function hw_update_select_csv (sel_id, opts)
{
	opts = opts.split(';');
	hw_update_select(sel_id, opts);
}

function hw_update_select(sel_id, opts)
{
	sel = document.getElementById(sel_id);
	if (sel.options.length > 0)
		for (i=sel.options.length; i>=0; i--) sel.remove(i);
	for (i=0; i<opts.length-1; i++)
	{
		opt = document.createElement("OPTION");
		if (opts[i].indexOf('@@') != -1)
		{
			t = opts[i].split('@@');
			opt.value=t[0];
			opt.text=t[1];
		}
		else
		{
			opt.value=opts[i];
			opt.text=opts[i];
		}
		try { sel.add(opt, null); }
		catch(e) { sel.add(opt); } // IE
	}
}

function hw_load_js(url)
{
	hw_createRequestObject();

	//alert(url);
    hw_ajax.open('get', url, false);
	hw_ajax.send(null);
	var response = hw_ajax.responseText;
	return eval(response);
}

function hw_load_css(url)
{
	 // IE
  	if(document.createStyleSheet) document.createStyleSheet(url);
    // Mozilla, Netscape, Opera
  	else
	{
    	var objStyle = document.createElement("style");
    	var objText = document.createTextNode("@import url("+url+") screen;");
    	objStyle.appendChild(objText);
    	document.getElementsByTagName("head")[0].appendChild(objStyle);
  	}
}

function hw_inc_js(filename) {
	var body = document.getElementsByTagName('head').item(0);
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	body.appendChild(script);
}

function hw_inc_css(filename) {
	var body = document.getElementsByTagName('head').item(0);
	style = document.createElement('link');
	style.rel = 'stylesheet';
	style.type = 'text/css';
	style.href = filename;
	body.appendChild(style);
}

if (Ext.Ajax) {
	Ext.BLANK_IMAGE_URL = wgScriptPath+'/hallowelt/js/ext/resources/images/default/s.gif';
}

/* ------------ Message.js ----------- */

var hw_message_borderwidth = 76;
var win = false;
//var alert_mode;

function toggleMessage(url, title, width, height, callback) {
	if (!url)
	{
		if (win) win.close();
		return;
	}

	loadExt();
	i18n.load("js");

	if(!win) {
		win = new Ext.Window({
			renderTo:'hw_messagebox',
			layout:'fit',
			width:width,
			title:title,
			bodyStyle:'z-index:9999;',
			plain: true
			});
		win.load({url: url, callback:callback, text:i18n.js.loading});
		win.on('close', function() { win = false; });
	}
	win.show();
};

hw_alert = function(text, alert_mode) {
	var res;
	loadExt();

	res = eval(text);
	toggleMessage();
	if(typeof(res) == 'object') {
		text = res[1];
	}

	i18n.load("js");
	Ext.Msg.alert(i18n.js.alert, text, function() {
		if(typeof(res) == 'object' && res[0] == 'SUC') {
			if(alert_mode == 'ok' || alert_mode == '') {
				//toggleMessage();
			}
			else if(alert_mode == 'reload') {
				window.location.reload( false );
			}
		}
		else if(alert_mode == 'reload') {
			window.location.reload( false );
		}
	});
}

/* ---------- Tooltip.js ---------- */
var timeout_tt;
var hw_tooltip = true;
function hw_show_tooltip(show, mode, title, content, ref, params) {
	if (!hw_tooltip) return;
	if (params) eval('('+params+')');
	if (!ref)
	{
		tt_x = mouse_x+15;
		tt_y = mouse_y+10;

	}
	else
	{
		pos = findPos(ref);
		tt_x = pos[0]+10;
		tt_y = pos[1]+ref.offsetHeight+10;
	}
	if (show)
	{
		tooltip_style = document.getElementById('hw_tooltip').style;
		tooltip_style.display = 'block';
		if (timeout_tt) clearTimeout(timeout_tt);
		if (mode=='init')
		{
			if (title) document.getElementById('hw_tooltip_title').innerHTML = title;
			if (content) document.getElementById('hw_tooltip_body').innerHTML = content;
			tooltip_style.top=tt_y+"px";
			tooltip_style.left=tt_x+"px";
		}
		else if (mode=='timeout') timeout_tt = setTimeout('hw_show_tooltip(false)', 200);
//		else if (timeout_tt) clearTimeout(timeout_tt);
	}
	else
	{
		document.getElementById('hw_tooltip').style.display = 'none';
		if (timeout_tt) clearTimeout(timeout_tt);
	}
}

//thanks to http://www.quirksmode.org
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

