
//show an image
function get_image(img, alt, extra){
    if (arguments.length == 2){
            extra = "";
    }else if (arguments.length == 1){
            alt = extra = "";
    }

    var img_html = "<img src='"+images_path+"/"+img+"' border='0' title='"+alt+"' align='left' "+extra+">";
    return img_html;
}

function custom_apperance(module_name){
    if (module_name == "expressions_module"){
        var custom_button = document.getElementById("expression_button");
        if (custom_button){
            var tmp = expressions_module.obj.getState();
            if (tmp == "on")
                setvisible(custom_button, false);
            else if (tmp == "off")
                setvisible(custom_button, true);
        }
    }
}

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function getStyleSheetList() {
  var i, a;
  var arr = new Array();
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title"))
        arr.push(a.getAttribute("title"));
  }
    return arr;
}

function getActiveStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
  }
  return null;
}

function getPreferredStyleSheet() {
  var i, a;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel") && a.getAttribute("rel").indexOf("style") != -1
       && a.getAttribute("rel").indexOf("alt") == -1
       && a.getAttribute("title")
       ) return a.getAttribute("title");
  }
  return null;
}

//page
function getPageNavigation(prefix, postfix, closetag, curr, limit, total){
    var size = 10;
    var html = "";
    var start = curr - (size/2)*limit;
    if (start < 0) start = 0;
    var counter = parseInt(start/limit)+1;
    var end = counter + size;
    
    html += prefix + (0) + postfix + '|<' + closetag + ' ';
    if (start != 0)
        html += prefix + (curr-limit) + postfix + '<<' + closetag + ' | ';
    for(i=start; i<total && counter < end; i+=limit){
        if (i>=curr && i< curr+limit)
            html += "<span class='more_hits'>" + counter + "</span> | ";
        else
            html += prefix + i + postfix + counter + closetag + ' | ';
        counter++;
    }
    if (counter >= end)
        html += prefix + (curr+limit) + postfix + '>>' + closetag;
    html += ' ' + prefix + (Math.floor((total-1)/limit)*limit) + postfix + '>|' + closetag;
    
    return html;
}


//swap images
function MM_findObj(n, d) { //v4.01
	var p,i,x;
	if(!d) d=document;
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) x=d.all[n];
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n);
	return x;
}
function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments;
	document.MM_sr=new Array;
	for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x;
	if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr;
	for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
	var d=document;
	if(d.images){
	if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
	for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}


//cookie handling functions
function getCookieVal (offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1)
        endstr = document.cookie.length;
    return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}  

function SetCookie (name, value) {
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    if (expires == null){
        var nDays = 100;
        expires = new Date();
        expires.setTime(expires.getTime() + 3600000*24*nDays);
    }
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
}

function DeleteCookie(name){
    var yesterday = new Date();
    yesterday.setTime ( yesterday.getTime() - 1 );
    SetCookie(name, 0, yesterday);
}

function get_boolean_value(str){
    if (str == "false")
        return false;
    return true;
}


function get_preferences(variable_name, default_value){
    var tmp = GetCookie(variable_name);
    if (tmp != null){
        if (tmp == "false")
            return false;
        else if (tmp == "true")
            return true;
        else
            return tmp;
    }
    return default_value;
}

function set_preferences(variable_name, value){
    SetCookie(variable_name, value);
}

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
      if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return strReturn;
}


//log function
function log_info(level, title, str){
    if (level == 0){
        //fatal error, warn the user
        alert(title + " " + str);
    }
    if (debug && level <= debug_level){
        //alert("level: " + level + " " + title + " " + str);
   		var historyDiv = document.getElementById('History');
        if (historyDiv) {
            var time = new Date();
            var time_str = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds() + ":" + time.getMilliseconds();
            historyDiv.appendChild(document.createTextNode(time_str + " (level: " + level + ") " + title + " " + str));
            historyDiv.appendChild(document.createElement('BR'));
            historyDiv.appendChild(document.createElement('BR'));

            historyDiv.scrollTop += 50;
        }
    }
}

function show_error(node){
    if (node != null){
        var text = node.nodeValue;
        log_info (1, "error:", "'"+text+"'");
    }
}



// module and column positioning/creations
function load_modules_infos(obj, value_arr){
    if (value_arr.length == 0)
        return;
    obj.length = 0;
    var module_name, module_size, module_state, col_number, other;
    for(var j=0; j<value_arr.length; j++){
        var cookieValues = value_arr[j].split(';');
        other = ""; module_size=0;
        for(var i=0;i<cookieValues.length; i++){
            if(cookieValues[i].length == 0) continue;
            if(cookieValues[i].indexOf(':')>0){
                module_attr = cookieValues[i].split(':');
                module_name = module_attr[0];
                module_state = module_attr[1];
                col_number = j+1;
                if (module_attr[2] && module_attr[2]>2)
                    module_size = module_attr[2];
                if (module_attr[3])
                    other = module_attr[3];
            }else{
                module_name = cookieValues[i];
                module_size = 0;
                module_state = 'on';
                col_number = 1;
            }
    
            obj.push( new Array(module_name, module_state, col_number, module_size, other));
        }
    }
}

function get_module_infos(obj, module_name, extra_info){
    for(var i=0;i<obj.length; i++){
        if(obj[i][0] == module_name){
            if (extra_info)
                return obj[i][4] ? obj[i][4] : "";
            else
                return (new Array(obj[i][1], obj[i][2], obj[i][3]));
        }
    }
    return (new Array());
}

function removeChildrenFromNode(node){
   if(node == undefined ||
        node == null){
    return;
   }

   if (node.childNodes.length == 0)
    return;
	while (node.hasChildNodes())
	{
	  node.removeChild(node.firstChild);
	}
}

function make_config(config_item){

    //var c1 = document.getElementById("parent"); 
    load_modules_infos(module_info, config_item.columns);
    if (column_number != config_item.columns.length)
        change_col_number(config_item.columns.length);
    column_number = config_item.columns.length;
    create_columns(config_item, module_info);
}

function change_col_number(num){
     if (num == 1){
        document.getElementById("column_2").style.display = "none";
        document.getElementById("column_3").style.display = "none";
        
        document.getElementById("column_td_1").style.width = "100%";
        document.getElementById("column_td_2").style.width = "0";
        document.getElementById("column_td_3").style.width = "0";
        
        document.getElementById("column_1").style.width  = "100%";
        document.getElementById("column_2").style.width  = "0%";
        document.getElementById("column_3").style.width  = "0%";
        
/*        var c3 = get_positions(document.getElementById("column_2"));
        c3 += get_positions(document.getElementById("column_3"));
        var c3_arr = c3.split(";");
        var item;
        for(i=0; i<c3_arr.length-1;i++){
            item = c3_arr[i].split(":");
            var curr_obj = eval(item[0]+".module");
            removeItem(curr_obj);
            document.getElementById("column_1").appendChild(curr_obj);
        }
  */

     }else if (num == 2){
        document.getElementById("column_2").style.display = "block";
        document.getElementById("column_3").style.display = "none";
        
        document.getElementById("column_td_1").style.width = "50%";
        document.getElementById("column_td_2").style.width = "50%";
        document.getElementById("column_td_3").style.width = "0%";
        document.getElementById("column_1").style.width = "100%";
        document.getElementById("column_2").style.width = "100%";
        document.getElementById("column_3").style.width = "0%";
        

     }else if (num == 3){
        document.getElementById("column_2").style.display = "block";
        document.getElementById("column_3").style.display = "block";

        document.getElementById("column_td_1").style.width = "33%";
        document.getElementById("column_td_2").style.width = "33%";
        document.getElementById("column_td_3").style.width = "33%";
        document.getElementById("column_1").style.width  = "100%";
        document.getElementById("column_2").style.width  = "100%";
        document.getElementById("column_3").style.width  = "100%";

    }

}

function create_columns(conf, obj){
    //create columns
    for(var j=1; j<=conf.columns.length; j++){
        var container = document.getElementById("column_"+j);
        removeChildrenFromNode(container);
        if (conf.col_width.length >= j && conf.col_width[j-1] != "")
            container.style.width = conf.col_width[j-1] + "px";
        else
            container.style.width = "100%";

        draw_modules(container, j, obj);
    }
}

function draw_modules(container, col_index, obj){
    //var col_width = get_preferences("col"+col_index+"_width", "");
    for(var i=0; i<obj.length; i++){
        try{
            if (obj[i][2] == col_index) { //&& (obj[i][1] != 'off'))
                var my_module;
                eval("my_module = " + obj[i][0] + ";");
                my_module.obj.setProperties(obj[i][3], obj[i][1]);
                container.appendChild(my_module.module);
                //eval(obj[i][0]+".obj.setProperties("+obj[i][3]+", '"+obj[i][1]+"')");
                //container.appendChild(eval(obj[i][0]+".module"));
        }
        }catch(err){
        }
    }
    //CreateDragContainer(document.getElementById('column_'+col_index));
}


function restore_defaults(){
    //delete cookies
    DeleteCookie("col1");
    DeleteCookie("col2");
    DeleteCookie("col3");
    DeleteCookie("column_number");
    DeleteCookie("col1_width");
    DeleteCookie("col2_width");
    DeleteCookie("col3_width");
    DeleteCookie("dictionary_order");
    DeleteCookie("active_css");
    DeleteCookie("active_config");
    DeleteCookie("entries_mode");
    DeleteCookie("font_size");
    //window.location.reload();
    settings_module.change_config(original_active_config);
}



function get_positions(container){
    var value="";
    for(var j=0; j<container.childNodes.length; j++){
        if(container.childNodes[j].nodeName=='#text') continue;
        //alert(container.childNodes[j].value);
        with(container.childNodes[j]){
            if (id !="-1" && id != "38"){
                value += id;
                value += eval(id + ".obj.getProperties()");
                //alert(id.size);
                //if (j<container.childNodes.length-1)
                value += ";";
                custom_apperance(id);
            }
        }
    }
    return value;
}

function save_positions(what){
    var arr = new Array();
    var arr_width = new Array();
    if (what === undefined){
        var c1 = document.getElementById("column_1"); 
        
        var v1 = get_positions(c1);
        if (v1 != ""){
            arr.push(v1);
        }
        SetCookie("col1", v1);
        var c2 = document.getElementById("column_2"); 
        var v2 = get_positions(c2);
        if (v2 != ""){
            arr.push(v2);
        }
        SetCookie("col2", v2);
        var c3 = document.getElementById("column_3"); 
        var v3 = get_positions(c3);
        if (v3 != ""){
            arr.push(v3);
        }
        SetCookie("col3", v3);
    }else if (what == 'column_width'){
        var c = document.getElementById("column_1"); 
        SetCookie("col1_width", c.offsetWidth);
        arr_width.push(c.offsetWidth);
        c = document.getElementById("column_2"); 
        SetCookie("col2_width", c.offsetWidth);
        arr_width.push(c.offsetWidth);
        c = document.getElementById("column_3"); 
        SetCookie("col3_width", c.offsetWidth);
        arr_width.push(c.offsetWidth);
    }
    settings_module.update_config(arr, arr_width);
}



function open_loading(){
  var obj = document.getElementById("loading");
  obj.innerHTML = get_image('loading.gif', '') + ' ' + get_text('loading...');
  obj.style.visibility = "visible";
}

function close_loading(){
  //var obj = getJObject("loading");
  var obj = document.getElementById("loading");
  obj.style.visibility = "hidden";
}

function getSelected(select_obj){
//    if (select_obj.selectedIndex)
        return select_obj.options[select_obj.selectedIndex].value;
    //ie8
    /*for(var oNum = 0; oNum != select_obj.options.length; oNum++) {
        if(select_obj.options[oNum].selected) return select_obj.options[oNum].value;
    }*/
}

function getJObject(variable_name){
  if (document.getElementById)
    {
    return document.getElementById(variable_name);
    }
  else if (document.all)
    {
    return document.all[variable_name];
    }
}




function get_user_settings(){

    var tmp = GetCookie("ui_lang");
    if (tmp != null)    ui_lang = tmp;
    tmp = getURLParam("lang");
    tmp = tmp.replace("#", "");
    if (tmp != "")    ui_lang = tmp;
    var user_config = new Array();
    var column_1 = get_preferences("col1", "");
    if (column_1 != "")
        user_config.push(column_1);
    var column_2 = get_preferences("col2", "");
    if (column_2 != "")
        user_config.push(column_2);
    var column_3 = get_preferences("col3", "");
    if (column_3 != "")
        user_config.push(column_3);
    if (user_config.length != 0){
        //version check...
        var arr = user_config[0].split(";");
        if (arr.length > 0){
            var arr2 = arr[0].split(":");
            if (arr2.length == 4){
                restore_defaults();
                return;
            }
        }
        
        var user = new configuration();
        user.name = "user";
        user.columns = user_config.slice(0);
        var c1_width = get_preferences("col1_width", '');
        var c2_width = get_preferences("col2_width", '');
        var c3_width = get_preferences("col3_width", '');
        user.col_width = new Array(c1_width, c2_width, c3_width);
        configs.push(user);
    }
    font_size = get_preferences('font_size', font_size);
    active_config = get_preferences('active_config', active_config);
}

function get_config_index(name){
    for(var i=0; i<configs.length; i++){
        if (configs[i].name == name){
            return i;
        }
    }
    return 0; //error
}

function update_user_config(arr, arr_w){
    var i = get_config_index("user");
    if (arr.length != 0)
        configs[i].columns = arr.slice(0);
    if (arr_w.length != 0)
        configs[i].col_width = arr_w.slice(0);
}

//helper function to drag and drop
function findPosX(obj) {
	var curleft = 0;
	if (obj && obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	} else if (obj && obj.x) curleft += obj.x;
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj && obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	} else if (obj && obj.y) curtop += obj.y;
	return curtop;
}


var moduleGhost = document.createElement("div");
moduleGhost.id = "moduleGhost";

function removeItem(element){
  element.parentNode.removeChild(element);
}

function getGhostPos(arr, y) {
	var ln = arr.length;
    var h = 0;
	for (var z=0; z<ln; z++) {
		if (arr[z]==moduleGhost) return z;
/*        h += arr[z].clientHeight;
        if (y < h)
            return z;
*/	}
}

function getModuleArr(column) {
    var arr = [];
    var ln = column.childNodes.length;
    for (var z=0; z<ln; z++) {
      if (column.childNodes[z].className != "frame"
            && column.childNodes[z] != moduleGhost) {
            continue;
        };
        
        if ((!column.childNodes[z].isDragging)
            || (column.childNodes[z] == moduleGhost))  { 
            arr.push(column.childNodes[z]);
        }
    }
    return arr;
}

  function watch_event(obj, event, func){
    if (obj.addEventListener)
      obj.addEventListener(event, func, false); //true or false?
    else{
      obj.attachEvent('on' + event, func);
      }
  }

  function unwatch_event(obj, event, func){
    if (obj.removeEventListener)
      obj.removeEventListener(event, func, false); //true or false?
    else
      obj.detachEvent('on' + event, func);
  }

//base class of all modules
var Module = function(title, setup_info, content, id, style) {

  var divTitle;
  var divSettings;
  var divEdit;
  var divHide;
  var divClose;
  var divContent;
  var divModule;
  var divFrame;
  var editInit = null;
  var editInitialized = false;
  var initialY;
  var initialHeight;
  var m_size;
  var m_title_text;
  var m_default_title_text;
  var m_module_name;
  var m_mainbox; 
  var m_state="on";
  
  
  function closeditModule(){
    divEdit.title = get_text('edit');
    divEdit.className = "box_settings";
    unwatch_event(divEdit, 'mousedown', closeditModule);
    watch_event(divEdit, 'mousedown', editModule);
    divSettings.style.display = "none";
    return false;
  }
  
  function editModule(){
    if ((editInit != null) && !editInitialized){
        editInit();
        editInitialized = true;
    }

    divSettings.style.display = "block";
    divEdit.className = "box_settings_pushed";
    divEdit.title = get_text('close edit');
    unwatch_event(divEdit, 'mousedown', editModule);
    watch_event(divEdit, 'mousedown', closeditModule);
    return false;
  }

  function closeModule(){//!!!

    var save = true;
    if (closeModule.arguments.length > 0)
        save = closeModule.arguments[0];

    //confim dialog causes a bug in ie: reload the page...
    var close = true;//confirm(get_text('Do you really want to close this window?'));
    if (close){
        m_state = "off";
        divFrame.style.display = "none";
        //update cookie and module_info
        settings_module.updateModuleState(m_module_name, false);
        if (save){
            //store it in cookie, too
            save_positions();
        }
    }

    return false;
  }

  //show content, inverse of hideModule
  function showModule(){
    divFrame.style.display = "block";
    divHide.className = "box_minimize";
    divHide.title = get_text('hide');
    unwatch_event(divHide, 'mousedown', showModule);
    watch_event(divHide, 'mousedown', hideModule);
    divContent.style.display = "block";
    if (m_size != 0){
      //divContent.style.overflow = "auto";
      divContent.style.height = m_size+"px";
    }
    m_state = "on";
    return false;
  }
  

  //hide content, inverse of showModule
  function hideModule(){
    if (m_size != 0){
      divContent.style.height = "0px";
      //divContent.style.overflow = "";
    }
    if (m_state == "off")
        divFrame.style.display = "block";
    divContent.style.display = "none";
    divHide.className = "box_maximize";
    divHide.title = get_text('show');
    unwatch_event(divHide, 'mousedown', hideModule);
    watch_event(divHide, 'mousedown', showModule);
    m_state = "hide";
    return false;
  }

  this.hide = function(){
    return hideModule();
  }

  this.open = function(){
    divFrame.style.display = "block";
    m_state = "on";
  }

  this.close = function(){
    divFrame.style.display = "none";
    m_state = "off";
  }

  this.getState = function(){
    return m_state;
  }

  //get the properties of box
  this.getProperties = function(){
    var str = ":";
    //FIXME: ha a modulok delete new-val fognak eltunni, visszajonni, akkor itt at kell fogalmazni az if-et
    
    //state
    str += m_state;
    //size
    str += ":" + m_size;
    return str;
  }

  this.setProperties = function(content_size, state){
      if (content_size != 0){
        m_size = content_size;
        divContent.style.height = content_size+"px";
        }
    if (state == "hide" && m_state != "hide")
        hideModule();
    else if (state == "off" && m_state != "off")
        closeModule(false);
    else if (state == "on" && m_state != "on")
        showModule();
    
    if (settings_module)
        settings_module.updateModuleState(m_module_name, (state != "off" ? true : false));
        


  }


  function text_selection(target, enable){
    // Stop selection while dragging
    if (!enable){
        target.ondrag = function () { return false; };
        target.onselectstart = function () { return false; };
        if (typeof target.style.MozUserSelect!="undefined") //Firefox route
            target.style.MozUserSelect="none";
        //better idea: http://www.dynamicdrive.com/dynamicindex9/noselect.htm
    }else{
        target.ondrag = null;
        target.onselectstart = null;
        if (typeof target.style.MozUserSelect!="undefined") 
            target.style.MozUserSelect="";
    }
  }
  
  function start_boxresize(e){
    watch_event(document, 'mousemove', boxresize);
    watch_event(document, 'mouseup', finish_boxresize);

	if (initialY == -1){
        initialY = e.clientY;
        initialHeight = divContent.offsetHeight; //parseInt(divContent.style.height); //offsetHeight; 
    }

    // Stop selection while dragging
    text_selection(document.body, false);
  }

  function boxresize(e){
    var diff_y = e.clientY - initialY;
    if (diff_y != 0){
      var new_height = initialHeight + diff_y;
	    divContent.style.height= new_height + "px";
			m_size = new_height; //into cookie...
    }
    return false;  
  }

  function finish_boxresize(){
    unwatch_event(document, 'mousemove', boxresize);
    unwatch_event(document, 'mouseup', finish_boxresize);
    initialY = -1;
	save_positions(); //fixme: lehetne olcsobban is menteni: id alapjan csak ennek a magassagat
    //document.body.style.cursor = 'auto';
    
    // Restore selection
    text_selection(document.body, true);
  }

  function start_resize_column_right(e){
    var col_id = divFrame.parentNode.id;
    var col_number = parseInt(col_id.replace(/[^0-9]/g,''));
    if (col_number == column_number)
        return false; //last col's right side
    start_resize_column(e, col_number);
  }
  function start_resize_column_left(e){
    var col_id = divFrame.parentNode.id;
    var col_number = parseInt(col_id.replace(/[^0-9]/g,''));;
    if (col_number == 1)
        return false; //1st col's left side

    start_resize_column(e, col_number-1);
  }


  function start_resize_column(e, col_number){
    if (initialX == -1){
        initialX = e.clientX;
        //var col_id = divFrame.parentNode.id;
        //curr_resize_col = divFrame.parentNode;
        var col_obj = document.getElementById("column_" + col_number);
        initialWidth = col_obj.offsetWidth;;//ParseInt(curr_resize_col.style.width);//
        curr_resize_col_number = col_number;
    }
    watch_event(document, 'mousemove', resize_column);
    watch_event(document, 'mouseup', finish_column_resize);

    // Stop selection while dragging
    text_selection(document.body, false);
  }
  
  function resize_column(e){
    e=Drag.fixE(e); //because of ie error... :)

    var diff_x = e.clientX - initialX;
    if (diff_x != 0){
        var new_width = initialWidth + diff_x;
        if (new_width < min_col_width )
            return false;
//	    curr_resize_col.style.width = new_width + "px"; //style.width 
        //trick: resize all columns... :)
        var col_width = new Array();
        
        for(var j=1; j<=column_number; j++){
            col_width.push(document.getElementById("column_"+j).offsetWidth);
            log_info(4, "before", j + " " + col_width[j-1]);
        }
        
        var curr = curr_resize_col_number;        
        if (max_width == 0){
                max_width = col_width[curr-1] + col_width[curr];
        }
/*        if (max_width < col_width[curr-1] + col_width[curr])
            return false; //ie...
*/
        var rel = max_width - new_width;
        if (rel < min_col_width )
            return false;
        if (col_width[curr-1] == new_width) //ie calls it more times...
            return false;
        col_width[curr-1] = new_width;
        col_width[curr] = rel;
        for(var i=1; i<=column_number; i++){
            document.getElementById("column_"+i).style.width = col_width[i-1] + "px";
            log_info(4, "after", i + " " + col_width[i-1]);
        }
    }
    return false;  
  }

  function finish_column_resize(){
    unwatch_event(document, 'mousemove', resize_column);
    unwatch_event(document, 'mouseup', finish_column_resize);
	save_positions('column_width');
    initialX = -1;
    curr_resize_col = null;
    max_width = 0;
    // Restore selection
    text_selection(document.body, true);
  }


  this.isMainModule = function(){
    return m_mainbox;
  }
  
  this.setEditInit = function (func){ editInit = func;}    

  this.create = function (title, setup_info, content, id, style){
    
    var col_index = 1;
    var close_state = false;
    var close_option = true;
    var size = 0;
    var module_infos_cookie = get_module_infos(module_info, id, false);
    if (module_infos_cookie.length != 0){
        col_index = module_infos_cookie[1];
        if (module_infos_cookie[0] == "off")
            close_state = true;
        if (module_infos_cookie[2])
            size = module_infos_cookie[2];
        }
		//fixme: itt lehetne oszlopba tenni is akar

    m_module_name = id;
    m_state = "on";
    boxclass = style;
    m_mainbox = false;
    if (style == "main"){
        m_mainbox = true;
        close_option = false;
    }
    if (id == "settings_module")
        close_option = false;

    divModule = document.createElement("div");
    
    divTitle = document.createElement("div");
    divTitle.innerHTML = title;
    divTitle.className = boxclass + "box_title title_window";
    divTitle.setAttribute("id", "title_"+id); //kell ez?
    
    m_title_text = title;
    m_default_title_text = title;

    divEdit = document.createElement("div");
		if (setup_info != ""){
            divEdit.className = "box_settings";
            divEdit.title = get_text('edit');
			watch_event(divEdit, 'mousedown', editModule);
		}
    divHide = document.createElement("div");
    divHide.className = "box_minimize";
    divHide.title = get_text('hide');
    watch_event(divHide, 'mousedown', hideModule);

    divClose = document.createElement("div");
    if (close_option){
        divClose.className = "box_close";
        divClose.title = get_text('close');
        watch_event(divClose, 'mousedown', closeModule);
    }

    divSettings = document.createElement("div");
	if (setup_info != ""){
        divSettings.innerHTML = setup_info;
        divSettings.className = "settings";
        divSettings.style.display = "none";
	}


    divContent = document.createElement("div");//span
    divContent.className = "content";
    divContent.setAttribute("id", title);
    if (content == "")
        content = "&nbsp;";
    divContent.innerHTML = content;
    m_size = size;
    if (size != 0){
      divContent.style.height = size+"px";
      //divContent.style.overflow = "auto";
    }

    initialY = -1;

    divFrame = document.createElement("div");
    divFrame.className = "frame";
    if (close_state){
        divFrame.style.display = "none";
        m_state = "off";
    }


    var divButtons = document.createElement("div");
    divButtons.className = "buttons";
    
    
    divModule.appendChild(divClose);
    divModule.appendChild(divHide);
    divModule.appendChild(divEdit);
    
    
    var table1 = document.createElement("table");
    table1.className = "top table_window";
    var row = document.createElement("tr");
    var cell1 = document.createElement("td");
    cell1.className = boxclass + "box_nw";
    var cell2 = document.createElement("td");
    cell2.className = boxclass + "box_n";
/*
    cell2.appendChild(divClose);
    cell2.appendChild(divHide);
    cell2.appendChild(divEdit);
*/    
    cell2.appendChild(divTitle);
    var cell3 = document.createElement("td");
    cell3.className = boxclass + "box_ne";
    row.appendChild(cell1);
    row.appendChild(cell2);
    row.appendChild(cell3);
    var tbody = document.createElement("tbody"); //ie... thanks: http://www.codingforums.com/showthread.php?t=17321
    tbody.appendChild(row);
    table1.appendChild(tbody);
    
    var table2 = document.createElement("table");
    table2.className = "mid table_window";

    //settings row
/*    var table_settings = document.createElement("table");
    table_settings.className = "mid table_window";
    var row2_settings = document.createElement("tr");
    var cell2_settings = document.createElement("td");
    var tbody2_settings = document.createElement("tbody"); //ie...     
    cell2_settings.colSpan="3";
    cell2_settings.className = "settings";
    cell2_settings.appendChild(divSettings);
    row2_settings.appendChild(cell2_settings);
    tbody2_settings.appendChild(row2_settings); 
    table_settings.appendChild(tbody2_settings);
*/
    //content row
    var row2 = document.createElement("tr");
    var cell2_1 = document.createElement("td");
    cell2_1.className = "box_w";
    watch_event(cell2_1, 'mousedown', start_resize_column_left);
    var cell2_2 = document.createElement("td");
    cell2_2.className = "box_content";
    
    cell2_2.appendChild(divSettings);
    cell2_2.appendChild(divContent);

    var cell2_3 = document.createElement("td");
    cell2_3.className = "box_e";
    watch_event(cell2_3, 'mousedown', start_resize_column_right);
   
    row2.appendChild(cell2_1);
    row2.appendChild(cell2_2);
    row2.appendChild(cell2_3);
    var tbody2 = document.createElement("tbody"); //ie... 
    tbody2.appendChild(row2);
    table2.appendChild(tbody2);
    
    
    
    var table3 = document.createElement("table");
    table3.className = "bot table_window";
    var row3 = document.createElement("tr");
    var cell3_1 = document.createElement("td");
    cell3_1.className = "box_sw";
    var cell3_2 = document.createElement("td");
    cell3_2.className = "box_s";
    watch_event(cell3_2, 'mousedown', start_boxresize);
    var span = document.createElement("span");
    span.className = "bottomspan";
    cell3_2.appendChild(span);
    var cell3_3 = document.createElement("td");
    cell3_3.className = "box_se";
    row3.appendChild(cell3_1);
    row3.appendChild(cell3_2);
    row3.appendChild(cell3_3);
    var tbody3 = document.createElement("tbody"); //ie... 
    tbody3.appendChild(row3);
    table3.appendChild(tbody3);

    divModule.className = "dialog";
    
    divModule.appendChild(table1);
    //divModule.appendChild(table_settings);
    divModule.appendChild(table2);
    divModule.appendChild(table3);
    
    divFrame.appendChild(divModule);
    divFrame.setAttribute("id", id); //kell ez?
    
    this.content = divContent;
    this.settings = divSettings;
    this.module = divFrame;//divModule;
    this.title = divTitle;
    
	Drag.init(divTitle, divFrame);//divModule);//divFrame);//

    divFrame.onDragStart = function(x,y,mousex, mousey) {
        var left = findPosX(this);
        var top = findPosY(this);
        var w = this.offsetWidth;
        this.style.width = (w-3)+"px";  //size of module border!!!
        this.style.left = (left-5)+"px";
        this.style.top = (top-5)+"px";
        /*			var op = 75;
        this.style.opacity = op/100;
        this.style.filter = 'alpha(opacity=' + op + ')';
        */
        this.style.zIndex = 1000;
        
        moduleGhost.style.display = "block";
        moduleGhost.style.width = this.offsetWidth+"px"; // prevent resizing column... :)
        this.parentNode.insertBefore(moduleGhost, this);
        this.style.position = "absolute";
        this.isDragging = true;
        //App.draggingItem = true;
        moduleGhost.col=this.parentNode;
        
        this.col1X = findPosX(document.getElementById('column_1'));
        this.col2X = findPosX(document.getElementById('column_2'));
        this.col3X = findPosX(document.getElementById('column_3'));
        moduleGhost.style.height = this.offsetHeight+"px";
	}

    divFrame.onDrag = function(x,y, mousex, mousey) {
        moduleGhost.style.width = ""; //width sould be automatic ( prevent resizing column...)
        /*	var op = 90;
            this.style.opacity = op/100;
            this.style.filter = 'alpha(opacity=' + op + ')';
            */
        var col;
        if ((x+this.offsetWidth/2)>=this.col1X) col=document.getElementById('column_1') ;//App.columnsObj.col1;
        if (this.col2X != 0 && (x+this.offsetWidth/2)>=this.col2X) col=document.getElementById('column_2');
        if (this.col3X != 0 && (x+this.offsetWidth/2)>=this.col3X) col=document.getElementById('column_3');

        if (!moduleGhost.parentNode && moduleGhost.col) { // if it has been removed by tab-drag
            moduleGhost.col.appendChild(moduleGhost);
        }

        if (moduleGhost.col!=col) {
            removeItem(moduleGhost);
            moduleGhost.col = col;
            col.appendChild(moduleGhost);
        }
        var elems = getModuleArr(col);
        var myPos = getGhostPos(elems, y);
        

        //implement main boxes behavior in spec way
        var k = 0;
        var prev_y = y;
        var ghost=false;
        while(k< elems.length){
            if (elems[k] == moduleGhost){
                ghost = true;
                k++;
            }else if (eval(elems[k].id + ".obj.isMainModule()"))
                k++;
            else
                break;
        }
        if (ghost)
            k--;
        
        var mainbox = eval(this.id + ".obj.isMainModule()");
        if (mainbox){
            //only top of after another main
            if (k > 0 && y>findPosY(elems[k-1]))
                y = findPosY(elems[k]);
            else
                y = 0;
        }else if (k > 0 && y<=findPosY(elems[k-1]))
            //only after top
            y = findPosY(elems[k]);
        //if (y != prev_y)
          //  myPos = getGhostPos(elems, y);
          //if (y == 0)
            //myPos = 1;//getGhostPos(elems, y);
        //log_info(1, "DRAG", prev_y + " " + y + " " + myPos);
        //main boxes
        
        if (myPos!=0 && y<=findPosY(elems[myPos-1])) {
            removeItem(moduleGhost);
            col.insertBefore(moduleGhost, elems[myPos-1]);
        }
        if (myPos!=(elems.length-1) && y>=findPosY(elems[myPos+1])) {
            if (elems[myPos+2]) {
                col.insertBefore(moduleGhost, elems[myPos+2]);
            } else {
                col.appendChild(moduleGhost);
            }
        }
	}

    divFrame.onDragEnd = function(x,y,el) {
        /*var op = 100;
        this.style.opacity = op/100;
        this.style.filter = 'alpha(opacity=' + op + ')';
        */

        
        var col = moduleGhost.col;
        if (!moduleGhost.parentNode) {
            moduleGhost.col.appendChild(moduleGhost);
        }

        this.style.position = "static";
        this.style.width = "auto";
        this.style.display = "block";
        this.style.zIndex = 0;

        this.isDragging = false;

        col.insertBefore(this, moduleGhost);
        removeItem(moduleGhost);
        save_positions();
	}
  }

  if (Module.arguments.length < 5)
    style = "";
  this.create(title, setup_info, content, id, style);
    
    function getElement(obj, tagname, name){  
        var x = obj.getElementsByTagName(tagname);
        for(var i=0; i< x.length; i++){
            if ((x[i].name == name) || (x[i].id == name))
                return x[i];
        }
    }

    this.getSettingsItem = function (tag, name){
        return getElement(divSettings, tag, name);
    }

    this.getContentItem = function (tag, name){ //fixme use this many times...
        return getElement(divContent, tag, name);
    }

    function max_title_length(){
        //return 100; //dont have to calculate: .title_window has 'overflow:hidden'
        
        if (divTitle.offsetWidth == 0)
            return 33;
        var font_pixel = 12;
        if (font_size != "")
            font_pixel = parseInt(font_size);
        var max = parseInt(divTitle.offsetWidth/font_pixel)+11;
        
        return max;
    }

    this.loadingState = function (str){
        var long_title = false;
        var max_length = max_title_length();
        
        
        if (str == undefined)
            str = m_title_text + " " + get_text("loading...");
        if (str.length > max_length){
            str = str.substr(0, max_length) + "...";
            long_title = true;
        }
        divTitle.innerHTML = get_image('loading.gif', '') +  " " + str;
/*        if (long_title)
            divTitle.className="box_title_long";
        else
            divTitle.className="box_title";
*/
        divModule.style.cursor = "wait";
    }
    
    
    this.restore_caption = function (str){
        var long_title = false;
        if (str == undefined)
            divTitle.innerHTML = m_title_text;
        else{
            var str_plain = str.replace(/<img src=([^>]+)>/g,"");
            divTitle.setAttribute("title", str_plain); // tooltip to field
            var str_length_after_img = str.replace(/.*<img src=([^>]+)>/g,"").length;
            var max_length = max_title_length();
            var min = str.length-str_length_after_img;
            if (str_plain.length > max_length){
                var cut = str_plain.length - max_length;
                if (cut > str_length_after_img)
                    cut = min;
                else
                    cut = str.length-cut;
                str = str.substr(0, cut) + "...";
                long_title = true;
            }
            divTitle.innerHTML = str;            
        }
  /*      if (long_title)
            divTitle.className="box_title_long";
        else
            divTitle.className="box_title";
*/        divModule.style.cursor = "default";
    }
    
    this.getTitle = function(){
        return m_title_text;
    }

    this.SetContent = function (callback){
      var t = callback();
      divContent.innerHTML = t;
    }
    
    this.ClearContent = function (){
      divContent.innerHTML = "";
      this.restore_caption(m_default_title_text);
    }

    this.getModuleName = function(){
        return m_module_name;
    }


    function SetFunc2Event_base(element, event, tag, name, callback){
      var obj = getElement(element, tag, name);
      eval("obj."+event+" = callback;");
      //obj.setAttribute(event, callback);
    }
  
    this.settings.SetFunc2Event = function (event, tag, name, callback){
      SetFunc2Event_base(divSettings, event, tag, name, callback);
    }
    this.content.SetFunc2Event = function (event, tag, name, callback){
      SetFunc2Event_base(divContent, event, tag, name, callback);
    }

}

