/*
 * Meb-core.js 0.2
 * */
var Y = YAHOO;
Y.namespace("MEB"); 
var MEB = Y.MEB;

MEB.om={};
MEB.addToOm=function(obj) //,update
{
	var k=obj.classname+'.'+obj.id;
	if (!MEB.om[k])
		MEB.om[k]=obj;
	else //if (update)
		MEB.om[k].fromObj(obj);
	return MEB.om[k];
}
MEB.json=[];
MEB.jsonT=0;
MEB.zIndex=100000;
MEB.lang=new Object();
MEB.loader=new Y.util.YUILoader({base:'http://www.myeverybodys.net/js/yui/2.7/'});  
MEB.onUnload=new Y.util.CustomEvent ('onUnload',null,true,Y.util.CustomEvent.FLAT);

Y.util.Event.addListener(window,'beforeunload',function(){MEB.onUnload.fire()});


MEB.NO_COOKIES=Y.env.ua.webkit;

MEB.loader.addModule({   
	name:'meb-core-jsjac',   
	type:'js',   
	fullpath:MEB.JS_BASE+'meb-core.jsjac.js'  
}); 
MEB.loader.addModule({   
	name:'meb-core-sm',
	type:'js',
	fullpath:MEB.JS_BASE+'meb-core.sm.js'  
}); 

/*
 * STATIC FUNCTIONS
 */
MEB.parseJson=function(str)
{
	try
	{
		return eval('('+str+')');
	}
	catch(e)
	{
		return false;
	}
}

MEB.preloadImages=function()
{
	var i=new Image();
	for(var i=0; i<arguments.length; i++)
		i.src=arguments[i]; 
}
MEB.getTimezone=function()
{
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));

	return (jan1 - jan2) / (1000 * 60 * 60);
}
MEB.date=function(id,time,fdata,fwd,shorts)
{
	var s='',d=new Date(),ty=d.getFullYear(),tm=d.getMonth(),td=d.getDate();
	d.setTime(time*1000);
	var y=d.getFullYear(),m=d.getMonth(),day=d.getDate();
		
	if (shorts)
	{	
		if (y==ty && m==tm && day==td)
		{
			if (shorts)
			{
				switch (shorts)
				{
					case('1'):
						return null;
					break;
					default:
						s=MEB.lang.time.today+shorts;
						if (id)
							document.getElementById(id).innerHTML+=s;
						return s;
					break;
				}
			}
		}
	}
	if (fwd)
		s=MEB.lang.time[fwd][d.getDay()]+' ';
	
	if(!fdata)
	{
		switch (MEB.lang.time.DATE_TYPE)
		{
			case(1):
				s+=(m+1)+'-'+day+'-'+y;
			break;
			case('2'):
				s+=day+'-'+(m+1)+'-'+y;
			break;
		}
	}
	else
	{
		switch (MEB.lang.time.DATE_TYPE)
		{
			case('1'):
				s+=MEB.lang.time[fdata][m]+" "+day;
				if (!shorts || y!=ty)
					s+=' '+y;
			break;
			case('2'):
				s+=day+' '+MEB.lang.time[fdata][m];
				if (!shorts || y!=ty)
					s+=" "+y;
			break;
		}
	}
	if (shorts && shorts!='1')
		s+=shorts;
	if (id)
		document.getElementById(id).innerHTML+=s;
	return s;
}

MEB.hour=function(id,time)
{
	var d=new Date();
	d.setTime(time*1000);
	
	var m=d.getMinutes().toString(),s;
	if (m.length<2)
		m='0'+m;
	s=d.getHours()+':'+m;
	if (id)
		document.getElementById(id).innerHTML+=s; 
	return s;
}
MEB.timeAgo=function(id,time,timeDiff,fwd,shorts)
{
	var d=new Date(),s='';
	if (timeDiff>86400)
		return MEB.date(id,time,'months',fwd,shorts)+MEB.hour(id,time);
	
	d.setTime(timeDiff*1000);
	
	var m=d.getMinutes(),h=d.getHours()-MEB.getTimezone(),sec=d.getSeconds();
	if (h>0)
		s+=h+' ';
	if (m>0)
	{
		if (h>0)
			s+=(h>1?MEB.lang.time.hours:MEB.lang.time.hour)+' '+MEB.lang.time.and+' ';
		s+=m+' ';
	}
	if (!h && sec)
	{
		if (m)
			s+=(m>1?MEB.lang.time.mins:MEB.lang.time.min)+' '+MEB.lang.time.and+' ';
		s+=sec+' '+(sec>1?MEB.lang.time.seconds_ago:MEB.lang.time.second_ago);
	}
	else
	{
		if (m>0)
			s+=(m>1?MEB.lang.time.mins_ago:MEB.lang.time.min_ago);
		else if (h>0)
			s+=(h>1?MEB.lang.time.hours_ago:MEB.lang.time.hour_ago);
		else
			s='0 '+MEB.lang.time.seconds_ago;
	}
		
	if (id)
		document.getElementById(id).innerHTML=s; 
	return s;
}
/*
MEB.hashToObj=function(query) 
{
  var data={},pair;
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
	  pair = vars[i].split("=");
      data[pair[0]]=pair[1];
  }
  return data;
}
MEB.objToHash=function(obj)
{
	
	var h='',i=0;
	for (var key in obj)
	{
		if (i++)
			h+='&';
		if (Y.lang.isObject(obj[key]) && !Y.lang.isString(obj[key]) )
			h+=MEB.objToHash(obj[key]);
		else
			h+=key+'='+(obj[key]?encodeURIComponent(obj[key]):'');
	}
	return h;
}
*/
MEB.replaceLinks=function(str,target)
{
	var v = new RegExp("([A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+)","g"); 
	return str.replace(v, '<a href="$1" target="'+(!target?'_blank':target)+'">$1</a>');
}
MEB.isValidEmail=function(email)
{ 
    var RegExp = /^((([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+(\.([a-z]|[0-9]|!|#|$|%|&|'|\*|\+|\-|\/|=|\?|\^|_|`|\{|\||\}|~)+)*)@((((([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.))*([a-z]|[0-9])([a-z]|[0-9]|\-){0,61}([a-z]|[0-9])\.)[\w]{2,4}|(((([0-9]){1,3}\.){3}([0-9]){1,3}))|(\[((([0-9]){1,3}\.){3}([0-9]){1,3})\])))$/ 
    if(RegExp.test(email))
        return true; 
    else
        return false; 
}
MEB.htmlentities=function(string, quote_style) {
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = MEB.get_html_tt('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}
MEB.get_html_tt=function(table, quote_style) {
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        if (useQuoteStyle != 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle == 'ENT_QUOTES') {
            entities['39'] = '&#039;';
        }
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
        if (useQuoteStyle != 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle == 'ENT_QUOTES') {
            entities['39'] = '&#039;';
        }
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}
MEB.str_repeat=function(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }
MEB.sprintf=function () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? MEB.str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}
MEB.number_format=function(number, decimals, dec_point, thousands_sep) 
{
    var n = number, prec = decimals;
 
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
 
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

MEB.ucfirst=function(str) 
{
    return str.charAt(0).toUpperCase()+ str.substr(1);
}
MEB.disableSelection=function(target)
{
	if (typeof target.onselectstart!="undefined") 		//IE route    
		target.onselectstart=function(){return false};
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route    
		target.style.MozUserSelect="none";
}
MEB.enableSelection=function(target)
{
	if (typeof target.onselectstart!="undefined") 		//IE route    
		target.onselectstart=null;
	else if (typeof target.style.MozUserSelect!="undefined") //Firefox route    
		target.style.MozUserSelect="inherit";
}
MEB.onDisplayed=function(obj,handler)
{
	var t=Y.lang.later(1000,window,function(){ if (obj.style.display!='none') {t.cancel();handler.fn.call(handler.scope);} },null,true);
}
/*
 * MEB CORE COMPONENTS
 */
MEB.Connect=function(method, url, callback, data, loading)
{
	this._callback = callback;
	if (loading)
		this._target = loading.t;
	this._method=method;
	
	if(this._target)
	{
		this._loadingObj = new MEB.Loading(this._target,loading.p);
		this._loadingObj.show();
	}
	if (this._method)
		this._t=Y.util.Connect.asyncRequest(method, url, { success: this._success, failure: this._error, scope:this} , 'check='+MEB.CHECK+'&'+data);
	else
	{
		this._jsonT=MEB.jsonT;
		this._t=Y.util.Get.script(url+'?check='+MEB.CHECK+'&jsonT='+MEB.jsonT+'&'+data, { onSuccess: this._jsonSuccess,onFailure:this._error,onTimeout:this._error,scope:this,autopurge:false,timeout:5000});
		MEB.jsonT++;
	}
	//alert(this._t+' '+url);
}
MEB.Connect.sync=function(url,data)
{
	var AJAX;
	if (window.XMLHttpRequest) 
	{                  
		AJAX=new XMLHttpRequest();                
	} 
	else 
	{                                      
		AJAX=new ActiveXObject("Microsoft.XMLHTTP");  
	}  
	if (AJAX) 
	{    
		AJAX.open("POST", url, false); 
		AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
		AJAX.send('check='+MEB.CHECK+'&'+data);
		return AJAX.responseXML;                                           
	} 
	else 
	{     
		return false;  
	}   
}
MEB.Connect.prototype={
	handleError:function(err,txt)
	{
	 	if (this._callback && this._callback.error)
			if (this._callback.error.apply(this._callback.scope, [err,txt,this._callback.obj]))
				err=0;
				
	 	MEB.Connect.handleError(err,txt);
	},
	abort:function()
	{
		this._abort=true;
		if(this._loadingObj)
		{
			this._loadingObj.destroy();
			delete this._loadingObj; 
			this._loadingObj=null;
		}
		if (this._method)
			Y.util.Connect.abort(this._t);
		else
			Y.util.Get.abort(this._t);
	},
	_jsonSuccess: function()
	{
		if (this._abort)
			return;
		if(this._loadingObj)
		{
			this._loadingObj.destroy();
			delete this._loadingObj;
			this._loadingObj=null;
		}
		var err=0,txt=null;
		if (MEB.json[this._jsonT]!==undefined) 
		{
			if (Y.lang.isObject(MEB.json[this._jsonT]) && MEB.json[this._jsonT].err)
			{
				err=MEB.json[this._jsonT].err;
				txt=MEB.json[this._jsonT].text;
			}
			else
			{
				
				if (this._callback && this._callback.ok)
					this._callback.ok.apply(this._callback.scope, [MEB.json[this._jsonT],this._callback.obj]);
			}
		}
		else
			err=1;
		if (err)
			this.handleError(err,txt);
	},
	_success: function(o)
	{
		if (this._abort)
			return; 
		if(this._loadingObj)
		{
			this._loadingObj.destroy();
			delete this._loadingObj; 
			this._loadingObj=null;
		}
		var err=0,txt=null;
		//alert(o.responseText);  
		if (o && o.responseXML) 
		{
			var root=o.responseXML.documentElement;
			if (Y.lang.isObject(root))
			{
				if (root.nodeName!='error')
				{
					if (this._callback && this._callback.ok)
						this._callback.ok.apply(this._callback.scope, [o.responseXML.documentElement,this._callback.obj]);
				}
				else
				{
					err=parseInt(root.getAttribute('n'));
					txt=root.firstChild?root.firstChild.nodeValue:null;
				}
			}
			else
				err=1;
		}
		else
			err=1;
		
		if (err)
			this.handleError(err,txt);
	},
	
	_error: function(response)
	{
		if (this._abort || cl.unloaded)
			return;
		if(this._loadingObj)
		{
			this._loadingObj.destroy();
			delete this._loadingObj; 
			this._loadingObj=null;
		}
		new MEB.ErrorPopup({body:MEB.lang.errors[2]});
		if (this._callback && this._callback.error)
			this._callback.error.apply(this._callback.scope, [2,null,this._callback.obj]);
	}
}

MEB.Loading=function(target,position,text)
{
	if (target.tagName)
		var d=target.ownerDocument?target.ownerDocument:document;
	else
		var d=target.getDocument();
	var Y=d.parentWindow?d.parentWindow.Y:d.defaultView.Y;
	this._htmlObj = d.createElement('div');
	this._htmlObj.className = "meb-loading";
	this._pos=position;
	Y.util.Dom.setStyle(this._htmlObj,'display','none');
	this._htmlObj.innerHTML = '<img align="absmiddle" src="'+MEB.LOADING_IMG_URL+'" border="0" /> '+(text?text:'');
	
	if (this._pos=='inside')
		target.appendChild(this._htmlObj);
	else
	{
		if (Y.lang.isObject(target))
		{
		    var region;
		    if(target.tagName)
			    region = Y.util.Dom.getRegion(target);
		    else
			    region = target.getRegion();
	    	
		    switch(this._pos)
		    {
		    	case 'inside':
		    	break;
		    	case 't':
				    Y.util.Dom.setStyle(this._htmlObj,'top', region.top - 24 +'px');
				    Y.util.Dom.setStyle(this._htmlObj,'left',region.left+(region.right - region.left)/2 - 12 +'px');
				    break;
			    case 'r':
				    Y.util.Dom.setStyle(this._htmlObj,'top', region.top+(region.bottom - region.top)/2 - 12 +'px');
				    Y.util.Dom.setStyle(this._htmlObj,'left',region.right +'px');
				    break;
			    case 'b':
				    Y.util.Dom.setStyle(this._htmlObj,'top', region.bottom +'px');
				    Y.util.Dom.setStyle(this._htmlObj,'left',region.left+(region.right - region.left)/2 - 12 +'px');
				    break;
			    case 'l':
				    Y.util.Dom.setStyle(this._htmlObj,'top', region.top+(region.bottom - region.top)/2 - 12 +'px');
				    Y.util.Dom.setStyle(this._htmlObj,'left',region.left - 24 +'px');
				    break;
			    case 'c':
			    default:
				    Y.util.Dom.setStyle(this._htmlObj,'top', region.top+(region.bottom - region.top)/2 - 12 +'px');
				    Y.util.Dom.setStyle(this._htmlObj,'left',region.left+(region.right - region.left)/2 - 12 +'px');
				    break;
		    }
	    }
	    else if (target)
	        this._htmlObj.className+= " "+target;
	    else
	    {
	        var vw=Y.util.Dom.getViewportWidth();
			var vh=Y.util.Dom.getViewportHeight();
			var l=Y.util.Dom.getDocumentScrollLeft()+vw/2,t=Y.util.Dom.getDocumentScrollTop()+vh/2;
	        Y.util.Dom.setStyle(this._htmlObj,'top',t+'px');
		    Y.util.Dom.setStyle(this._htmlObj,'left',l +'px');
	    }
		d.body.appendChild(this._htmlObj);
	}
}

MEB.Loading.prototype={
	visible:false,
	destroy: function(){
		this._htmlObj.parentNode.removeChild(this._htmlObj);
	},
	show:function()
	{
		this.visible=true;
	    Y.util.Dom.setStyle(this._htmlObj,'z-index',MEB.zIndex++);
	    Y.util.Dom.setStyle(this._htmlObj,'display','block');
	},
	hide:function()
	{
		this.visible=false;
	    Y.util.Dom.setStyle(this._htmlObj,'display','none');
	}
}

MEB.MouseEnterLeave=function(evt, landmark)
{
	var eventType = evt.type;
	
	this.inside = false;
	this.left = false;
	this.entered = false;
	
	if(eventType == "mouseout")
	{
		this.toElement = evt.relatedTarget || evt.toElement;
		this.fromElement = evt.target || evt.srcElement;
	}
	else if(eventType == "mouseover")
	{
		this.toElement = evt.target || evt.srcElement;
		this.fromElement = evt.relatedTarget || evt.fromElement;
	}
	else throw (new Error("Event type \""+eventType+"\" is irrelevant"));	//irrelevant event type
	
	//target is unknown
	//this seems to happen on the mouseover event when the mouse is already inside the element when the page loads and
	// the mouse is moved: fromElement is undefined
	if(!this.toElement || !this.fromElement) 
		return false;
	
	//determine whether from-element is inside or outside of landmark (i.e., does tmpFrom == the landmark or the document?)
	var tmpFrom = this.fromElement;
	try
	{
		while(tmpFrom.nodeType == 1)	//while tmpFrom is an element node
		{
			if(tmpFrom == landmark) break;
			tmpFrom = tmpFrom.parentNode;
		}
	}
	catch(err)
	{
		return false;	
	}
	//determine whether to-element is inside or outside of landmark (i.e., does tmpTo == the landmark or the document?)
	var tmpTo = this.toElement;
	try
	{
		while(tmpTo.nodeType == 1)	//while tmpTo is an element node
		{
			if(tmpTo == landmark) break;
			tmpTo = tmpTo.parentNode;
		}
	}
	catch(err)
	{
		return false;	
	}
	if(tmpFrom == landmark && tmpTo == landmark) this.inside = true;	//mouse is inside landmark; didn't enter or leave
	else if(tmpFrom == landmark && tmpTo != landmark)	//mouse left landmark
	{
		this.left = true;
		this.inside = (eventType == "mouseout");	//mouseout: currently inside landmark, but leaving now
														//mouseover: currently outside of landmark; just left
	}
	else if(tmpFrom != landmark && tmpTo == landmark)	//mouse entered landmark
	{
		this.entered = true;
		this.inside = (eventType == "mouseover");	//mouseover: currently inside landmark; just entered
														//mouseout: currently outside of landmark, but entering now
	}
}
MEB.DataHandler=function(id,data,table)
{
	this.onDel=new Y.util.CustomEvent ('onDel',this,true,Y.util.CustomEvent.FLAT);
	this.onUpdate=new Y.util.CustomEvent ('onUpdate',this,true,Y.util.CustomEvent.FLAT);
	
	this.id=id;
	this.table=table;
	
	if (data)
		this.data=cl.addToDm(this,data);
	else
		this.data=cl.addToDm(this,{});
}
MEB.DataHandler.prototype={
	delData:function(sync)
	{
		cl.delData(this,sync);
	},
	setData:function(d,sync)
	{
		cl.setData(this,d,sync);
	},
	updateData:function(d)
	{
		cl.addToDm(this,d,true);
	},
	dataUpdated:function(what){ this.onUpdate.fire(); },
	dataDeleted:function(){ this.onDel.fire(); },
	fromObj:function(obj){},
	fromXml:function(el)
	{
		this.id=el.getAttribute('id');
		var data={};
		for(var j=0;j<el.childNodes.length;j++)
		{
			data[el.childNodes[j].tagName]=el.childNodes[j].firstChild.nodeValue;
		}
		this.data=cl.addToDm(this,data);
	}
}
/*
 * IMAGE MANAGER
 */
MEB.InitImagePopup=function()
{
	var image =  Y.util.Dom.getElementsByClassName('image-popup-link',null,document);	
	for(var i=0;i<image.length;i++){
		Y.util.Event.addListener(image[i],'click',this._showImagePopup,image[i],this);
	}
}
MEB.InitImagePopup.prototype={
	_showImagePopup:function(e,arg)
	{
		var rel = arg.getAttribute("rel");
		var data = rel.split(';');
		new MEB.ImagePopup({image: data[0], title: data[1]});
	}
}
/*
*Inizializzazione tips
*/
MEB.InitTips=function()
{
	var elements = Y.util.Dom.getElementsByClassName('tip-title',null,document);	
	for(var i=0;i<elements.length;i++)
	{
		if(elements[i].getAttribute("title"))
		{
			new MEB.Tooltip({target: elements[i],type:'tip',content:elements[i].getAttribute("title"), align: (elements[i].getAttribute("rel")?elements[i].getAttribute("rel"):'t')});
			elements[i].removeAttribute('title');
		}
	}
}
/*
 * MEB CLIENT
 */
MEB.CoreClient=function()
{
	this.dm={};
	//init
    this.onInitSm=new Y.util.CustomEvent ('onInitSm',null,true);
	
	//popups
	this._popups={};
	this._popupsList=[];
	//hider
	this._hiderLevels=[];
	
	//tooltips
	this._tooltips=new Array();
	this._tooltipsCodes=new Array();
}
MEB.CoreClient.prototype={
	sm:null,
	
	initSm:function()
	{
	    if (!this.sm)
	    {
	        MEB.loader.require('meb-core-sm');
		    MEB.loader.insert({onSuccess: function() { var c=this;this.sm=soundManager=new SoundManager();this.sm.url=MEB.MODULES_BASE; this.sm.onload=function(){c._smOk=true;c.onInitSm.fire();};},scope:this});
		}
		if (this._smOk)
		    return true;
	},
	/*
	 * FIXED LOADING
	 */
	initLoading:function(t,p)
	{
	    this._loading=new MEB.Loading(t,p);
	    this._cLoading=0;
	},
	loading:function()
	{
	    this._cLoading++;
	    this._loading.show();
	},
	loadingEnds:function()
	{
	    this._cLoading--;
	    if (this._cLoading<=0)
	    {
	        this._cLoading=0;
	        this._loading.hide();
	    }
	},
	/*
	 * DATA MANAGER
	 */
	syncData:function()	{},
	_updateData:function(from,to)
	{
		var up={_c:0},tmp;
		for (var x in from)
		{
			if (Y.lang.isObject(from[x]))
			{
				if (!to[x])
					to[x]={};
				tmp=this._updateData(from[x],to[x]);
				if (tmp._c)
				{
					up[x]=tmp;
					up._c++;
				}
			}
			else
			{
				if (from[x]!=to[x])
				{
					to[x]=from[x];
					up[x]=true;
					up._c++;
				}
			}
		}
		return up;
	},
	setData:function(obj,d,sync)
	{
		var k=obj.table+'.'+obj.id,c={};
		
		for (var x in d)
		{
			c[x]=true;
			this.dm[k].d[x]=d[x];
		}
		this.dataUpdated(obj,c);
		if (sync)
			this.syncData([{table:obj.table,id:obj.id,d:d}],sync);
	},
	dataUpdated:function(obj,newData,sync)
	{
		var k=obj.table+'.'+obj.id;
		//var r=new Array();
		for (var i=0;i<this.dm[k].o.length;i++)
		{
			try
			{
				this.dm[k].o[i].dataUpdated(newData);
			}
			catch(e)
			{
				
			}
		}
		if (sync)
		{
			var d={};
			for (var x in newData)
			{
				d[x]=this.dm[k].d[x];
			}
			this.syncData([{table:obj.table,id:obj.id,d:d}],sync);
		}
	},
	addToDm:function(obj,data,updateOnly)
	{
		var k=obj.table+'.'+obj.id;
		if (!this.dm[k])
		{
			if (!updateOnly)
				this.dm[k]={o:[obj],d:data};
			else
				return;
		}
		else
		{
			var up=this._updateData(data,this.dm[k].d);
			if (up._c)
				this.dataUpdated(obj,up);
			if (!updateOnly)
				this.dm[k].o.push(obj);
		}
		return this.dm[k].d;
	},
	getData:function(obj)
	{
		return this.dm[obj.table+'.'+obj.id]?this.dm[obj.table+'.'+obj.id].d:null;
	},
	delData:function(obj,sync)
	{
		var k=obj.table+'.'+obj.id;
		if (!this.dm[k])
			return;
		for (var i=0;i<this.dm[k].o.length;i++)
		{
			try
			{
				this.dm[k].o[i].dataDeleted();
			}
			catch(e)
			{
				
			}
		}
		delete this.dm[k];
		if (sync)
			this.syncData([{table:obj.table,id:obj.id}],sync);
	},
	/*
	 * TAB INDEX
	 */
	tabIndexRemove:function()
	{
		if (this._tabIndexRemoved>0)
		{
			this._tabIndexRemoved++;
			return;
		}
		else
			this._tabIndexRemoved=1;
		
		var el=document.getElementsByTagName('input'),i;
		for (i=0;i<el.length;i++)
		{
			el[i].oldTabIndex=el[i].tabIndex;
			el[i].tabIndex='-1';
		}
		el=document.getElementsByTagName('textarea');
		for (i=0;i<el.length;i++)
		{
			el[i].oldTabIndex=el[i].tabIndex;
			el[i].tabIndex='-1';
		}
		el=document.getElementsByTagName('button');
		for (i=0;i<el.length;i++)
		{
			el[i].oldTabIndex=el[i].tabIndex;
			el[i].tabIndex='-1';
		}
	},
	tabIndexRestore:function()
	{
		if (this._tabIndexRemoved>1)
		{
			this._tabIndexRemoved--;
			return;
		}
		else
			this._tabIndexRemoved=0;
		
		var el=document.getElementsByTagName('input'),i;
		for (i=0;i<el.length;i++)
		{
			el[i].tabIndex=el[i].oldTabIndex;
		}
		el=document.getElementsByTagName('textarea');
		for (i=0;i<el.length;i++)
		{
			el[i].tabIndex=el[i].oldTabIndex;
			
		}
		el=document.getElementsByTagName('button');
		for (i=0;i<el.length;i++)
		{
			el[i].tabIndex=el[i].oldTabIndex;
		}
	},
	/*
	 * HIDER
	 */
	resizeHider:function()
	{
		if (!this._hider)
			return;
		var w=Y.util.Dom.getViewportWidth(),h=Y.util.Dom.getViewportHeight();
		this._hider.style.width=w+'px';
		this._hider.style.height=h+'px';
	},
	showHider:function()
	{
		if (!this._hider)
		{
			this._hider=document.createElement('DIV')
			this._hider.id="meb-hider";
			Y.util.Event.addListener(window,'resize',this.resizeHider,null,this);
			document.body.appendChild(this._hider);
		}
			
		this._hider.style.zIndex=MEB.zIndex++;
		
		this._hiderLevels.push(this._hider.style.zIndex);
		this.resizeHider();
		
		return this._hiderLevels.length-1;
	},
	hideHider:function(i)
	{
		this._hiderLevels[i]=false;
		var hide=false,j;
		for (j=this._hiderLevels.length-1;j>=0;j--)
		{
			if (this._hiderLevels[j]>0)
			{
				hide=true;
				break;
			}
		}
		
		if (hide)
			this._hider.style.zIndex=this._hiderLevels[j];
		else
		{
			Y.util.Event.removeListener(window,'resize',this.resizeHider);
			this._hider.parentNode.removeChild(this._hider);
			this._hider=null;
		}
		
		
	},
	/*
	 * POPUP
	 */
	 getPopup:function(id)
	 {
		return this._popups[id];
	 },
	 popupOpened:function(obj)
	 {
		if (obj.id)
		{
			if (this._popups[obj.id])
				this._popups[obj.id].close();
			this._popups[obj.id]=obj;
		}
		obj.hider=this.showHider();
		obj.index=this._popupsList.length;
		this._popupsList.push(obj);
		obj.zIndex=MEB.zIndex++;
		this.tabIndexRemove();
	 },
	 popupClosed:function(obj)
	 {
		 this.hideHider(obj.hider);
		
		 this._popupsList.splice(obj.index,1);
		 if (obj.id)
			delete this._popups[obj.id];
		 this.tabIndexRestore();
		 delete obj;
	 },
	 /*
	  * TOOLTIP
	  * */
	tooltipAdd:function(tooltip)
	{
		if (tooltip.code && this._tooltipsCodes[tooltip.code]!=null)
			this._tooltipsCodes[tooltip.code].close();
		
		var i=this._tooltips.length;
		this._tooltipsCodes[tooltip.code]=this._tooltips[i]=tooltip;
		return {i:i,zIndex: MEB.zIndex++};
	},
	tooltipRemove:function(index)
	{
		try
		{
			if (this._tooltips[index] && this._tooltips[index].code)
				this._tooltipsCodes[this._tooltips[index].code]=null;
		}
		catch(e)
		{
			
		}
		this._tooltips[index]=null;
	},
	tooltipCloseAll:function()
	{
		for (var i=0;i<this._tooltips.length;i++)
		{
			try
			{
				if (this._tooltips[i])
					this._tooltips[i].close();
			}
			catch(e)
			{
				this._tooltips[i]=null;
			}
		}
	},
	tooltipCloseByType:function(type)
	{
		//var r=[];
		for (var i=0;i<this._tooltips.length;i++)
		{
			try
			{
				if (this._tooltips[i] && this._tooltips[i].getType()==type && this._tooltips[i].isAutoclose())
					this._tooltips[i].close();
			}
			catch(e)
			{
				this._tooltips[i]=null;
			}
		}
		/*
		for (var i=0;i<r.length;i++)
		{
			this.tooltipRemove(r[i]);
		}
		*/
	}
}