var SI_ERROR = 'error';
var SI_NORMAL = 'normal';         
      
function getScrollTop() {
  if ( document.documentElement.scrollTop )
    return document.documentElement.scrollTop;

  return document.body.scrollTop;
}

function get_radio_value (radio_array)
{
 var i;
 for (i = 0; i < radio_array . length; ++ i)
  if (radio_array [i] . checked)
   return radio_array [i] . value;
 return null; 
}

function show_info(text, type, delay)
{   
   if (!$defined(text) || text.trim() == '') return;
   if (!$defined($('hintdiv'))) {
    var hintdiv = new Element('div', {    
      'id': 'hintdiv',
      'class': 'hintdiv',
      'styles': {
        'display': 'block',                
        'z-index': '100'
       }}
     );     
     hintdiv.injectTop(document.body);       
     $('hintdiv').setStyle('top', getScrollTop()+'px');
     
     window.addEvent('scroll', function() {              
       $('hintdiv').setStyle('top', getScrollTop()+'px');
     });
     
   }                        

    var type = (type == null) ? SI_NORMAL : type;
    var delay = (delay == null) ? 2000 : delay;            
    
    var classnm = 'hintdiv_'+type;
    var hint = new Element('div', {            
        'class': classnm
    }).injectInside($('hintdiv')).setHTML(text);
    
    /*var myEffect = hint.effect('opacity', {duration: 3000});
    myEffect.start(1,0.7);*/
                           
    (function(){                     
      var slider = new Fx.Slide(hint, {duration: delay/2});
      slider.slideOut().          
      chain(function(){hint.setStyle('display', 'none')}).      
      chain(function(){hint.remove();})      
     }).delay(delay);        
}

           
         

/**
 * text selection&cursor functions
 */
function getSelectionStart(o){
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd('character', o.value.length);
        if (r.text == '') 
            return o.value.length;
        return o.value.lastIndexOf(r.text);
    }
    else 
        return o.selectionStart;
}

function getSelectionEnd(o){
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveStart('character', -o.value.length);
        return r.text.length;
    }
    else 
        return o.selectionEnd;
}

function setSelectionRange(o, selectionStart, selectionEnd){
    if (o.createTextRange) {
        var range = o.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
    else 
        if (o.setSelectionRange) {
            o.focus();
            o.setSelectionRange(selectionStart, selectionEnd);
        }
}

/**
 * misc functions
 */
function copyToClipboard(s){    
    if (window.clipboardData) {
        window.clipboardData.setData("Text", s);
    }
    else 
        if (window.netscape) {
        /*netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
         var clip = Components.classes['@mozilla.org/widget/clipboard;1']
         .createInstance(Components.interfaces.nsIClipboard);
         if (!clip) return;
         var trans = Components.classes['@mozilla.org/widget/transferable;1']
         .createInstance(Components.interfaces.nsITransferable);
         if (!trans) return;
         trans.addDataFlavor('text/unicode');
         var str = new Object();
         var len = new Object();
         var str = Components.classes["@mozilla.org/supports-string;1"]
         .createInstance(Components.interfaces.nsISupportsString);
         var copytext=s;
         str.data=copytext;
         trans.setTransferData("text/unicode",str,copytext.length*2);
         var clipid=Components.interfaces.nsIClipboard;
         if (!clip) return false;
         clip.setData(trans,null,clipid.kGlobalClipboard);*/
        }
    return false;
}

function validate(name, type){
    el = $(name);
    errorel = $(name + '_error');
    var error = '';
    var requestdone = false;
    result = new Json.Remote('/rt_validate/', {
        method: 'post',
        autoCancel: true,
        onComplete: function(resp){
            error = resp.error;
            errorel.setHTML(resp.error);
            requestdone = true;
        },
        onFailure: function(){
            error = '';
            errorel.empty();
            requestdone = true;
        }
    }).send({
        value: el.value,
        type: type
    });
    while (!requestdone) {
    };
    return error;
}

function notifydiv(el, newoptions){
    if ($type(el) != 'element') {
        el = $(el);
    }
    if (!$defined(el)) 
        return false;
    var options = {
        'background-color': '#F0F0F0'
    };
    var oldoptions = {
        'background-color': '#FFFFFF'
    };
    el_transparent = false;
    if ($defined(el.getStyle('background-color')) && el.getStyle('background-color') != 'transparent') {
        oldoptions['background-color'] = el.getStyle('background-color');
    }
    else 
        el_transparent = true;
    if ($defined(newoptions)) 
        var options = $merge(options, newoptions);
    el.setStyles(oldoptions);
    new Fx.Styles(el, {
        duration: 200,
        onComplete: function(){
            new Fx.Styles(el, {
                duration: 1000,
                onComplete: function(){
                    el.setStyle('background-color', '');
                }
            }).start(oldoptions);
        }
    }).start(options);
}

/**
 * popup functions
 */
 
var mboxvar = 0;
function popbox(type, method, width, height, data, sch){
    var url = '/query/' + type + '/' + method;    
    if ($defined(data)) {
    	url+='?' + data;
    }
    if (!$defined(width)) width = 400;
    if (!$defined(height)) height = 250;
    if (!$defined(sch)) sch = 0;
    
	var a = new Element('a', 
	    {'href': '#',
	     'id': 'multibox',           
	     'rel': 'height:'+height+',width:'+width+',ajax:true,url:'+url}).injectInside(document.body);  
    a.addClass('multibox');
         
    mboxvar = new MultiBox('multibox', {'sch': sch});
    mboxvar.open(a);       
    
    a.remove();  
}


function closebox(){
    if (mboxvar) mboxvar.close();
}

/**
 * ajax form functions
 */
function setformerror(name, text, options){
    if (!$defined(options)) 
        var options = {};
    el = ($defined(options.formid) ? $$('#' + options.formid + ' #' + name)[0] : $(name));
    if ($defined(el)) {
        er_name = $defined(options.error_element) ? options.error_element : name + '-error';
        el2 = $(er_name);
        if ($defined(el2) && text == '') {
            el2.empty();
            return true;
        }
        if (!$defined(el2)) 
            el2 = new Element('div', {
                'class': 'form-error',
                id: er_name
            }).injectAfter(el);
        el2.setHTML(text);
        return true;
    }
    else 
        return false;
}

function clearformerror(name, options){
    return setformerror(name, '', options);
}

function clearformerrors(formid, newoptions){
    var options = {
        error_place: '%element%-error',
        error_places: {}
    }
    if ($defined(newoptions)) 
        options = $merge(options, newoptions);
    var er_place = $($defined(options.error_places[formid]) ? options.error_places[formid] : options.error_place.replace('%element%', formid));
    if ($defined(er_place)) 
        er_place.empty();
    $$('#' + formid + ' input', '#' + formid + ' radio', '#' + formid + ' checkbox', '#' + formid + ' select', '#' + formid + ' textarea').each(function(el){
        er_place = $($defined(options.error_places[el.name]) ? options.error_places[el.name] : options.error_place.replace('%element%', el.name));
        if ($defined(er_place)) {
            //alert(options.error_place);
            //alert(options.error_places[el.name])?options.error_places[el.name]:options.error_place.replace('%element%', el.name);
            //alert(er_place.getText());
            er_place.empty();
        }
    });
}

var formsinfofx = {};

function setforminfo(formid, info, infoplace){
    if (!$defined(infoplace)) 
        infoplace = formid + '-info';
    el = $(infoplace);
    if (!$defined(info) || info == '') {
        if ($defined(el)) {
            el.setStyle('display', 'none');
            el.empty();
        }
        return true;
    }
    if (!$defined(el)) 
        el = new Element('div', {
            'class': 'form-info',
            id: infoplace,
            style: 'display: none;'
        }).injectBefore(formid);
    el.setStyle('display', 'block');
    if (!$defined(formsinfofx[infoplace])) 
        formsinfofx[infoplace] = new Fx.Slide(infoplace);
    formsinfofx[infoplace].stop();
    formsinfofx[infoplace].hide();
    el.setHTML(info);
    formsinfofx[infoplace].slideIn();
    hideinfoplace.delay(3000, false, {
        infoplace: infoplace
    });
    return true;
}

function hideinfoplace(args){
    if ($defined(formsinfofx[args.infoplace])) {
        formsinfofx[args.infoplace].stop();
        formsinfofx[args.infoplace].slideOut();
    }
    //new Fx.Slide(args.infoplace, {duration: 500}).slideOut();
}

function setformerrors(formid, errors, options){
    if (!$defined(options)) 
        var options = {};
    if ($defined(errors)) {
        $each(errors, function(text, name){
            if (name == '%form%' || name == formid) {
                setformerror(formid, text, {
                    error_element: ($defined(options.error_places[formid]) ? options.error_places[formid] : options.error_place.replace('%element%', formid))
                });
            }
            else {
                setformerror(name, text, {
                    formid: formid,
                    error_element: ($defined(options.error_places[name]) ? options.error_places[name] : options.error_place.replace('%element%', name))
                });
            }
        });
    }
    else {
        setformerror(formid, 'Произошла ошибка обработки формы', {
            error_element: ($defined(options.error_places[formid]) ? options.error_places[formid] : options.error_place.replace('%element%', formid))
        });
    }
}

function setformvalue(formid, name, value){
    el = $$('#' + formid + ' #' + name)[0];
    if ($defined(el)) {
        switch (el.getTag()) {
            case 'textarea':
            case 'input':
                el.value = value;
                break;
            //case 'select': el.selectedIndex = value; break;
            //case 'radio':
            //case 'checkbox': el.checked = (value==el.value); break;
            default:
                return false;
        }
        return true;
    }
    return false;
}

function setformvalues(formid, values){
    if ($defined(values)) {
        $each(values, function(item, index){
            setformvalue(formid, index, item);
        });
    }
}

function submitform(formid, type, newoptions){
    var options = {
        error_place: '%element%-error',
        submit_place: '%form%-submit-place',
        submit_loading_place: '%form%-submit-loading',
        form_info: '%form%-info',
        error_places: {}
    }
    if ($defined(newoptions)) 
        options = $merge(options, newoptions);
    options.submit_place = options.submit_place.replace('%form%', formid);
    options.submit_loading_place = options.submit_loading_place.replace('%form%', formid);
    options.form_info = options.form_info.replace('%form%', formid);
    var aform = $(formid);
    var el = $$('#' + formid + ' input[name=to]')[0];
    var to = el.value;
    var act = '/query/' + type;
    if ($defined(to) && to) {
        act += '/' + to;
    }
    aform.action = act;
    var submitplace = $(options.submit_place);
    /*var submitloadingplace = $(options.submit_loading_place);
    if (!$defined(submitloadingplace)) {
        submitloadingplace = new Element('div', {
            'class': 'ajax-loading-simple',
            id: options.submit_loading_place
        }).injectAfter($defined(submitplace) ? submitplace : aform);
    }
    submitloadingplace.setStyle('display', 'block');*/
    /*if ($defined(submitplace)) {
        submitplace.setStyle('display', 'none');
    }*/
    disable(submitplace);
    clearformerrors(formid, options);
    
    aform.send({
        autoCancel: true,
        onComplete: function(){           
            if ($defined(this.response.text) && this.response.text != '') {
                var res = Json.evaluate(this.response.text);
            }
            else {
                var res = {};
            }            
            var next = true;
            if ($defined(options.onComplete)) {
                next = options.onComplete(res, options);
            }
            if (next) {
                if ($defined(res.status) && res.status == 'ok') {
                    if ($defined(options.onSuccess)) {
                        next = options.onSuccess(res, options);
                    }
                    if (next) {
                    	show_info(res.info);
                        //setforminfo(formid, res.info, options.form_info);
                        setformvalues(formid, res.values);
                        /*submitloadingplace.setStyle('display', 'none');
                        submitplace.setStyle('display', 'block');*/
                        disable(submitplace, false);
                        if ($defined(options.postSuccess)) {
                            options.postSuccess(res, options);
                        }
                    }
                }
                else {
                    if ($defined(options.onError)) {
                        next = options.onError(res, options);
                    }
                    if (next) {
                        setformerrors(formid, res.errors, options);
                        setforminfo(formid, res.info, options.form_info);
                        setformvalues(formid, res.values);
                        /*if ($defined(submitloadingplace)) 
                            submitloadingplace.setStyle('display', 'none');
                        if ($defined(submitplace)) 
                            submitplace.setStyle('display', 'block');*/
                        disable(submitplace, false);
                        if ($defined(options.postError)) {
                            options.postError(res, options);
                        }
                    }
                }
                if ($defined(options.postComplete)) {
                    options.postComplete(res, options);
                }
            }
        }
    });
}

//

var loadedscripts = {};

function loadscript(sname){
    if (!$defined(loadedscripts[sname])) {
        var e = new Element('script');
        e.src = '/js/' + sname;
        e.type = "text/javascript";
        e.injectInside($$('head')[0]);
        loadedscripts[sname] = true;
        return true;
    }
}

function query(type, query_name, newoptions){
    var options = {
        method: 'post',
        autoCancel: true,
        evalScripts: true,
        onFailure: function(){    
            if ($defined(this.options.postFailed)) {
                this.options.postFailed(this);
            }
        },
        data: {'ajax': true},
        onComplete: function(){
            if ($defined(this.options.postComplete)) {
                if ($defined(this.response.text) && this.response.text != '') {
                    var resp = Json.evaluate(this.response.text);
                }
                else {
                    var resp = {};
                }
                if ($defined(resp.popupinfo)) show_info(resp.popupinfo);
                this.options.postComplete(resp, this);
            }
        }
    }
    if ($defined(newoptions)) {
		options = $merge(options, newoptions);
	}
    var queryurl = '/query/' + type;
    if ($defined(query_name) && query_name && query_name != '') 
        queryurl += '/' + query_name;
    new Ajax(queryurl, options).request();
}

function edit_element(id, type, query_name, options){
    var el = $(id);
    var inputType = $defined(options) && $defined(options.inputType) && options.inputType == 'text' ? 'text' : 'textarea';
//    var elt = el;
//    if ($defined(options.targetElement)) elt = $(options.targetElement);

    if ($defined(el)) {
        var opt = {
            onComplete: function(obj){
                var newContent = obj.element.innerHTML;
                var oldContent = obj.self.originalText;
                if (newContent != oldContent || false) {
                    var data = {
                        'text': newContent
                    };
                    if ($defined(options) && $defined(options.data)) 
                        data = $merge(data, options.data);
                    query(type, query_name, {
                        'data': data,
                        postComplete: function(resp){
                            if (resp.status == 'ok') {
                                el.setHTML(resp.text);
                                if ($defined(resp.info)) show_info(resp.info, null, 500);
                                /*if (!($defined(options)) || ($defined(options.notify) && options.notify)) 
                                    notifydiv(id);*/
                                if ($defined(options) && $defined(options.onSuccess)) {
                                    options.onSuccess(id, options, newContent, oldContent);
                                }
                            }
                            else {
                                obj.element.setHTML(oldContent);
                                if ($defined(options) && $defined(options.onFailure)) {
                                    options.onFailure(id, options);
                                }                                
                            }
                        }
                    });
                } else {
                	if ($defined(options) && $defined(options.onFailure)) {                    
                    	options.onFailure(id, options);
                    }                
                }
            },
            onCancel: function (obj) {
            	if ($defined(options) && $defined(options.onCancel)) {
                	options.onCancel(id, options);
                }            	
            }
        };
        if ($defined(options.options)) 
            opt = $merge(opt, options.options);
        el.inlineEdit(opt);
    }
}

function set_ajaxloading(elname, active) {
	if (!$defined(active)) active = true;
	//if (!$type(elname))
	var el = $(elname);
	if (!$defined(el)) return false;
	var ajname = elname + '-ajaxloding';
	var ajel = $(ajname);
	if (active) {
		el.addClass('ajax-loading-container');
		if (!$defined(ajel)) {
			ajel = new Element('div', {
				'class': 'ajax-loading',
				'id': ajname,
				'display': 'none'
			});
		}
		var zindex = el.getStyle('z-index');
		if (!$defined(zindex) || !zindex || isNaN(zindex)) zindex = 10;
		else zindex++;
        var coords = $(el).getCoordinates();
        ajel.setStyles({
			'z-index': zindex,
			'width': coords.width,
			'height': coords.height,
			'left': coords.left,
			'top': coords.top,
			'position': 'absolute'
		});
		ajel.injectAfter(el);
		ajel.setStyle('display', '');
	} else {
		if ($defined(ajel)) {
			ajel.empty();
			ajel.remove();
			//ajel.setStyle('display', 'none');
		}
		el.removeClass('ajax-loading-container');
	}
}

function disable(elname, active) {
	if (!$defined(active)) active = true;
	//if (!$type(elname))
	var el = $(elname);
	if (!$defined(el)) return false;
	var dname = elname + '-disabled';
	var del = $(dname);
	if (active) {
		if (!$defined(del)) {
			del = new Element('div', {
				'class': 'disabled',
				'id': dname
			});
			del.injectInside(el);
		}
		var zindex = el.getStyle('z-index');
		if (!$defined(zindex) || !zindex || isNaN(zindex)) zindex = 10;
		else zindex++;
        var coords = el.getCoordinates();
		del.setStyles({
			'display': '',
			'z-index': zindex,
			'height': coords.height,
			'width': coords.width
		});
		el.addClass('disabled-container');
	} else {
		if ($defined(del)) {
			del.setStyle('display', 'none');
		}
		el.removeClass('disabled-container');
	}
}

function inputOnBlur(name, text) {
	var el = $(name);
	if ($defined(el)) {
		if (!$defined(text)) text = el.title;
		if (el.value.trim() == '') {
			el.value = text;
		}
	}
}

function inputOnFocus(name, text) {
	var el = $(name);
	if ($defined(el)) {
		if (!$defined(text)) text = el.title;
		if (el.value.trim() == text) {
			el.value = '';
		}
	}
}

function undefValue(name) {
    var el = $(name);
    if ($defined(el)) {
        st = el.getProperty('emptyv');
        return (el.value == st)?"":el.value;        
    }      
    return false;
}

function clearDefValue(name) {
    var el = $(name);
    if ($defined(el)) {
        el.value = undefValue(el.value);        
    }          
}

function attachHint(name, text) {
    var el = $(name);       
    if ($defined(el)) {       
       el.setProperty('emptyv', text);
       el.addEvent('blur', function(){inputOnBlur(this, this.getProperty('emptyv'));} );
       el.addEvent('focus', function(){inputOnFocus(this, this.getProperty('emptyv'));} );
       el.value=text;
       el.addClass("emptyfield");
    }
}



/* 
   page navigator
                     */
       
// выполняет все скрипты из html и возвращает их в ресалте       
function eval_scripts(resp)
{
    var scripts=[];
    var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
    while ((script = regexp.exec(resp))) scripts.push(script[1]);
    scripts = scripts.join('\n');                    
    if (scripts) (window.execScript) ? window.execScript(scripts) : window.eval(scripts);
    return scripts;
}

var fetchHash = [];
function nav_move(delta, div, newpage)
{     
   _vnav[div]['page'] = parseInt(_vnav[div]['page']) + delta;      
   var params = new Object();            
   for (key in _vnav[div]) {
      if (key == "json") continue;
      if (typeof(_vnav[div][key])=="function") continue;
      params[key] = _vnav[div][key];                  
   }      
    
    set_ajaxloading(div, true);     
    query(_vnav[div]["obj"], _vnav[div]["to"], {
            data: params,
            onComplete: function(){                    
                    var resp = this.response.text;                    
                    //var scripts = eval_scripts(resp);                    
                    // чтоб не передавать отдельно, читаем для какого div-а прочитали скрипт из ключа переменной _vnav:                                        
                    /*  div = /_vnav\["([^"]+)"]/gi.exec(scripts); 
                    if (!$defined(div)) alert(scripts);
                    div = div[1];                    */
                                                            
                    $(div).setHTML(resp);
                    set_ajaxloading(div, false);
                    /*if (fetchHash.length == 0) {
                    	setInterval(nav_move_hash, 1000);
                    }*/
                    fetchHash[div] = _vnav[div]['page'];
                    window.location.hash = div + '|' + _vnav[div]['page'];                    
                    
            } 
    });              
  
}

function nav_move_hash() {
	var arr = window.location.hash.split('|');
    if (arr.length == 0) return false;
	var name = arr[0].substr(1);
	if (fetchHash[name]!=arr[1]) {
		fetchHash[name] = arr[1];
		nav_move(fetchHash[name] - _vnav[name]['page'], name);
	}
}

function autoresizetextarea(txtbox, limitmin, limitmax)
{
    var cols = txtbox.cols ;
    var content = txtbox.value ;
    var lineCount = 0 ;
    var lastEOL = -1 ;   
    if (!$defined(limitmin)) var limitmin = 20;
    if (!$defined(limitmax)) var limitmax = 50; 
    do {
        var begin = lastEOL+1 ;
        lastEOL = content.indexOf("\n",lastEOL+1) ;
        var line = "" ;
        if(lastEOL != -1) {
            line = content.substring(begin,lastEOL) ;
        } else {
            line = content.substring(begin,content.length) ;
        }
        //var rows_in_line = Math.floor(line.length/cols)+1 ;
        lineCount += 1;//rows_in_line
    } while (lastEOL != -1) ;
    lineCount = lineCount < limitmin?limitmin:(lineCount > limitmax?limitmax:lineCount);
    txtbox.rows = lineCount ;
     
}

function checkbox_click(name) {
	var el = $(name);
	if ($defined(el)) el.setProperty('checked', el.checked?'':'on');
	return true;
}


function Set_Cookie( name, value, expires, path, domain, secure )
{
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    if ( expires )
    {
    expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for ( i = 0; i < a_all_cookies.length; i++ )
    {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split( '=' );


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if ( cookie_name == check_name )
        {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if ( a_temp_cookie.length > 1 )
            {
                cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if ( !b_cookie_found )
    {
        return null;
    }
}  

function Delete_Cookie( name, path, domain ) {
    if ( Get_Cookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/*
function copyIntoClipboard(text) {
    var flashId = 'flashId-HKxmj5';

    var clipboardSWF = '/swf/clipboard.swf';

    if(!document.getElementById(flashId)) {
       var div = document.createElement('div');
       div.id = flashId;
       document.body.appendChild(div);
    }
    document.getElementById(flashId).innerHTML = '';
    var content = '<embed src="' +
            clipboardSWF +
            '" FlashVars="clipboard=' + encodeURIComponent(text) +
            '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashId).innerHTML = content;
}        */

/* ie bug, unload all objects */
function fcRemoveObjects() {
    if (!document.all) return false; // not required in FF
    var arr = document.all.tags("object");
    if (arr && arr.length) {
    for (var i=arr.length-1; 0<=i; i--) {
    arr[i].removeNode(true);
    }
    }
}

    
    

/**************************************************************

	Script		: MultiBox
	Version		: 1.3.1
	Authors		: Samuel Birch
	Desc		: Supports jpg, gif, png, flash, flv, mov, wmv, mp3, html, iframe
	Licence		: Open Source MIT Licence

**************************************************************/
var MultiBox = new Class({
	
	getOptions: function(){
		return {
			initialWidth: 250,
			initialHeight: 250,
			container: document.body,
			useOverlay: true,
			contentColor: '#FF',
			showNumbers: false,
			showControls: false,
			//showThumbnails: false,
			//autoPlay: false,
			waitDuration: 300,
			descClassName: false,
			descMinWidth: 400,
			descMaxWidth: 600,
			movieWidth: 400,
			movieHeight: 300,
			offset: {x:0, y:0},
			fixedTop: false,
			path: 'files/',
			onOpen: Class.empty,
			onClose: Class.empty,
			openFromLink: true,
			relativeToWindow: true
		};
	},

	initialize: function(className, options){
            
    
		this.setOptions(this.getOptions(), options);
		
		this.openClosePos = {};
		this.timer = 0;
		this.contentToLoad = {};
		this.index = 0;
		this.opened = false;
		this.contentObj = {};
		this.containerDefaults = {};
		if(this.options.useOverlay){
			this.overlay = new Overlay({container: this.options.container, onClick:this.close.bind(this)});
		}
		this.content = $$('.'+className);
		if(this.options.descClassName){
			this.descriptions = $$('.'+this.options.descClassName);
			this.descriptions.each(function(el){
				el.setStyle('display', 'none');
			});
		}
		         
        if (this.options.sch == 1) {
           addlt = "_L";
        } else { 
           addlt = "";
        }
                
        this.container = new Element('div').addClass('MultiBoxContainer').injectInside(this.options.container);
        this.container_top1 = new Element('div').addClass('MultiBoxTL'+addlt).injectInside(this.container);        
        this.container_top2 = new Element('div').addClass('MultiBoxTC'+addlt).injectInside(this.container);        
        this.container_top3 = new Element('div').addClass('MultiBoxTR'+addlt).injectInside(this.container);                
		this.iframe = new Element('iframe').setProperties({
			'id': 'multiBoxIframe',
			'name': 'mulitBoxIframe',
			'src': 'javascript:void(0);',
			'frameborder': 1,
			'scrolling': 'no'
		}).setStyles({
			'position': 'absolute',
			'top': -20,
			'left': -20,
			'width': '115%',
			'height': '115%',
			'filter': 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)',
			'opacity': 0
		}).injectInside(this.container);        
        this.container_bot1 = new Element('div').addClass('MultiBoxBL'+addlt).injectInside(this.container);        
        this.container_bot2 = new Element('div').addClass('MultiBoxBC'+addlt).injectInside(this.container);        
        this.container_bot3 = new Element('div').addClass('MultiBoxBR'+addlt).injectInside(this.container);                
        
        
		this.box = new Element('div').addClass('MultiBoxContent'+addlt).injectInside(this.container);
        		
		this.closeButton = new Element('div').addClass('MultiBoxClose').injectInside(this.container).addEvent('click', this.close.bind(this));
		
		this.controlsContainer = new Element('div').addClass('MultiBoxControlsContainer').injectInside(this.container);
		this.controls = new Element('div').addClass('MultiBoxControls').injectInside(this.controlsContainer);
		
		this.previousButton = new Element('div').addClass('MultiBoxPrevious').injectInside(this.controls).addEvent('click', this.previous.bind(this));
		this.nextButton = new Element('div').addClass('MultiBoxNext').injectInside(this.controls).addEvent('click', this.next.bind(this));
		
		this.title = new Element('div').addClass('MultiBoxTitle').injectInside(this.controls);
		this.number = new Element('div').addClass('MultiBoxNumber').injectInside(this.controls);
		this.description = new Element('div').addClass('MultiBoxDescription').injectInside(this.controls);	
		
		if(this.content.length == 1){
			this.title.setStyles({
				'margin-left': 0
			});
			this.description.setStyles({
				'margin-left': 0
			});
			this.previousButton.setStyle('display', 'none');
			this.nextButton.setStyle('display', 'none');
			this.number.setStyle('display', 'none');
		}
		
		new Element('div').setStyle('clear', 'both').injectInside(this.controls);
		
		this.content.each(function(el,i){
			el.index = i;
			el.addEvent('click', function(e){
				new Event(e).stop();
				this.open(el);
			}.bind(this));
			if(el.href.indexOf('#') > -1){
				el.content = $(el.href.substr(el.href.indexOf('#')+1));
				if(el.content){el.content.setStyle('display','none');}
			}
		}, this);
		
		//this.containerEffects = new Fx.Styles(this.container, {duration: 400, transition: Fx.Transitions.sineInOut});
		//this.controlEffects = new Fx.Styles(this.controlsContainer, {duration: 300, transition: Fx.Transitions.sineInOut});
		
		this.reset();
	},
	
	setContentType: function(link){
		var str = link.href.substr(link.href.lastIndexOf('.')+1).toLowerCase();
		var contentOptions = {};
		if($chk(link.rel)){
			var optArr = link.rel.split(',');
			optArr.each(function(el){
				var ta = el.split(':');
				contentOptions[ta[0]] = ta[1];
			});
		}
		
		if(contentOptions.type != undefined){
			str = contentOptions.type;
		}
		
		this.contentObj = {};
		this.contentObj.url = link.href;
//added by KT
		if(contentOptions.url){
		  this.contentObj.url = contentOptions.url;
		}
//
		this.contentObj.xH = 0;
		        
		if(contentOptions.width){
			this.contentObj.width = contentOptions.width;
		}else{
			this.contentObj.width = this.options.movieWidth;
		}
		if(contentOptions.height){
			this.contentObj.height = contentOptions.height;	
		}else{
			this.contentObj.height = this.options.movieHeight;
		}
		if(contentOptions.panel){
			this.panelPosition = contentOptions.panel;
		}else{
			this.panelPosition = this.options.panel;
		}
		
		
		switch(str){
			case 'jpg':
			case 'gif':
			case 'png':
				this.type = 'image';
				break;
			case 'swf':
				this.type = 'flash';
				break;
			case 'flv':
				this.type = 'flashVideo';
				this.contentObj.xH = 70;
				break;
			case 'mov':
				this.type = 'quicktime';
				break;
			case 'wmv':
				this.type = 'windowsMedia';
				break;
			case 'rv':
			case 'rm':
			case 'rmvb':
				this.type = 'real';
				break;
			case 'mp3':
				this.type = 'flashMp3';
				this.contentObj.width = 320;
				this.contentObj.height = 70;
				break;
			case 'element':
				this.type = 'htmlelement';
				this.elementContent = link.content;
				this.elementContent.setStyles({
					display: 'block',
					opacity: 0
				})
	
				if(this.elementContent.getStyle('width') != 'auto'){
					this.contentObj.width = this.elementContent.getStyle('width');
				}
				
				this.contentObj.height = this.elementContent.getSize().size.y;
				this.elementContent.setStyles({
					display: 'none',
					opacity: 1
				})
				break;
				
			default:
				
				this.type = 'iframe';
				if(contentOptions.ajax){
					this.type = 'ajax';
				}
				break;
		}
	},
	
	reset: function(){
		this.container.setStyles({
			'opacity': 0,
			'display': 'none'
		});
		this.controlsContainer.setStyles({
			'height': 0
		});
		this.removeContent();
		this.previousButton.removeClass('MultiBoxButtonDisabled');
		this.nextButton.removeClass('MultiBoxButtonDisabled');
		this.opened = false;
	},
	
	getOpenClosePos: function(el){
		if (this.options.openFromLink) {
			if (el.getFirst()) {
				var w = el.getFirst().getCoordinates().width - (this.container.getStyle('border').toInt() * 2);
				if (w < 0) {
					w = 0
				}
				var h = el.getFirst().getCoordinates().height - (this.container.getStyle('border').toInt() * 2);
				if (h < 0) {
					h = 0
				}
				this.openClosePos = {
					width: w,
					height: h,
					top: el.getFirst().getCoordinates().top,
					left: el.getFirst().getCoordinates().left
				};
			}
			else {
				var w = el.getCoordinates().width - (this.container.getStyle('border').toInt() * 2);
				if (w < 0) {
					w = 0
				}
				var h = el.getCoordinates().height - (this.container.getStyle('border').toInt() * 2);
				if (h < 0) {
					h = 0
				}
				this.openClosePos = {
					width: w,
					height: h,
					top: el.getCoordinates().top,
					left: el.getCoordinates().left
				};
			}
		}else{
			if(this.options.fixedTop){
				var top = this.options.fixedTop;
			}else{
				var top = ((window.getHeight()/2)-(this.options.initialHeight/2)-this.container.getStyle('border').toInt())+this.options.offset.y;
			}
			this.openClosePos = {
				width: this.options.initialWidth,
				height: this.options.initialHeight,
				top: top,
				left: ((window.getWidth()/2)-(this.options.initialWidth/2)-this.container.getStyle('border').toInt())+this.options.offset.x
			};
		}
		return this.openClosePos;
	},
	
	open: function(el){
	
		this.options.onOpen();
	
		this.index = this.content.indexOf(el);
		
		this.openId = el.getProperty('id');
		
		if(!this.opened){
			this.opened = true;
			
			if(this.options.useOverlay){
				this.overlay.show();
			}            
			this.container.setStyles(this.getOpenClosePos(el));
			/*this.container.setStyles({
				opacity: 0.5,
				display: 'block'
			});*/			
			if(this.options.fixedTop){
				var top = this.options.fixedTop;
			}else{
				var top = ((window.getHeight()/2)-(this.options.initialHeight/2)-this.container.getStyle('border').toInt())+this.options.offset.y;
			}
			this.container.setStyles({
                width: this.options.initialWidth,
                height: this.options.initialHeight,               
                /*            
                width: this.options.width,
                height: 200,//this.options.initialHeight,            */
				top: top,
				left: ((window.getWidth()/2)-(this.options.initialWidth/2)-this.container.getStyle('border').toInt())+this.options.offset.x,
				opacity: 1,
				display: 'block'
			});
			/*this.containerEffects.start({
				width: this.options.initialWidth,
				height: this.options.initialHeight,
				top: top,
				left: ((window.getWidth()/2)-(this.options.initialWidth/2)-this.container.getStyle('border').toInt())+this.options.offset.x,
				opacity: [0.5, 1],
				duration: 100
			});*/
			
			
			this.load(this.index);
		
		}else{
			if (this.options.showControls) {
				this.hideControls();
			}
			this.getOpenClosePos(this.content[this.index]);
			this.timer = this.hideContent.bind(this).delay(100);
			this.timer = this.load.pass(this.index, this).delay(100);
			
		}
		
	},
	
	getContent: function(index){
		this.setContentType(this.content[index]);
		var desc = {};
		if(this.options.descClassName){
		this.descriptions.each(function(el,i){
			if(el.hasClass(this.openId)){
				desc = el.clone();
			}
		},this);
		}
		//var title = this.content[index].title;
		this.contentToLoad = {
			title: this.content[index].title || '&nbsp;',
			//desc: $(this.options.descClassName+this.content[index].id).clone(),
			desc: desc,
			number: index+1
		};
	},
	
	close: function(){
		if(this.options.useOverlay){
			this.overlay.hide();
		}
		if (this.options.showControls) {
			this.hideControls();
		}        

		this.hideContent();
		//this.reset();
		//this.containerEffects.stop();
		this.zoomOut();//.bind(this).delay(0);
		this.options.onClose();
	},
	
	zoomOut: function(){
		/*this.containerEffects.start({
			width: this.openClosePos.width,
			height: this.openClosePos.height,
			top: this.openClosePos.top,
			left: this.openClosePos.left,
			opacity: 0
		});*/
		this.reset();//.bind(this).delay(100);
	},
	
	load: function(index){
		this.box.addClass('MultiBoxLoading');
		this.getContent(index);
		if(this.type == 'image'){
			var xH = this.contentObj.xH;
			this.contentObj = new Asset.image(this.content[index].href, {onload: this.resize.bind(this)});
			this.contentObj.xH = xH;
			/*this.contentObj = new Image();
			this.contentObj.onload = this.resize.bind(this);
			this.contentObj.src = this.content[index].href;*/
		}else{
			this.resize();
		}
	},
	
	resize: function(){
		if (this.options.fixedTop) {
			var top = this.options.fixedTop;
		}
		else {
			var top = ((window.getHeight() / 2) - ((Number(this.contentObj.height) + this.contentObj.xH) / 2) - this.container.getStyle('border').toInt() + window.getScrollTop()) + this.options.offset.y;
		}
		var left = ((window.getWidth() / 2) - (this.contentObj.width / 2) - this.container.getStyle('border').toInt()) + this.options.offset.x;
		if (top < 0) {
			top = 0
		}
		if (left < 0) {
			left = 0
		}
		
		
		/*this.containerEffects.stop();
		this.containerEffects.start({
			width: this.contentObj.width,
			height: Number(this.contentObj.height) + this.contentObj.xH,
			top: top,
			left: left,
			opacity: 1,
			duration: 100
		});*/        
		this.container.setStyles({
			width: Number(this.contentObj.width),
			height: Number(this.contentObj.height) + this.contentObj.xH,
			top: top,
			left: left,
			opacity: 1,
			duration: 100
		});
		//this.timer = this.showContent.bind(this).delay(500);
		this.showContent();
	},
	
	showContent: function(){
		this.box.removeClass('MultiBoxLoading');
		this.removeContent();
		
		this.contentContainer = new Element('div').setProperties({id: 'MultiBoxContentContainer'}).setStyles({opacity: 0, width: this.contentObj.width+'px', height: (Number(this.contentObj.height)+this.contentObj.xH)+'px'}).injectInside(this.box);
		
		if(this.type == 'image'){
			this.contentObj.injectInside(this.contentContainer);
			
		}else if(this.type == 'iframe'){
			new Element('iframe').setProperties({
				id: 'iFrame'+new Date().getTime(), 
				width: this.contentObj.width,
				height: this.contentObj.height,
				src: this.contentObj.url,
				frameborder: 0,
				scrolling: 'auto'
			}).injectInside(this.contentContainer);
			
		}else if(this.type == 'htmlelement'){
			this.elementContent.clone().setStyle('display','block').injectInside(this.contentContainer);
			
		}else if(this.type == 'ajax'){
			new Ajax(this.contentObj.url, {
				method: 'get',
				update: 'MultiBoxContentContainer',
				evalScripts: true,
				autoCancel: true
			}).request();
			
		}else{
			var obj = this.createEmbedObject().injectInside(this.contentContainer);
			if(this.str != ''){
				$('MultiBoxMediaObject').innerHTML = this.str;
			}
		}
		
		/*this.contentEffects = new Fx.Styles(this.contentContainer, {duration: 200, transition: Fx.Transitions.linear});
		this.contentEffects.start({
			opacity: 1
		});*/
		this.contentContainer.setStyle('opacity', 1);
		
		this.title.setHTML(this.contentToLoad.title);
		this.number.setHTML(this.contentToLoad.number+' of '+this.content.length);
		if (this.options.descClassName) {
			if (this.description.getFirst()) {
				this.description.getFirst().remove();
			}
			this.contentToLoad.desc.injectInside(this.description).setStyles({
				display: 'block'
			});
		}
		//this.removeContent.bind(this).delay(500);
		if (this.options.showControls) {
			this.timer = this.showControls.bind(this).delay(800);
		}
		//this.resize();
	},
	
	hideContent: function(){
		this.box.addClass('MultiBoxLoading');
		/*this.contentEffects.start({
			opacity: 0
		});*/
		//this.removeContent.bind(this).delay(100);
		this.removeContent();
	},
	
	removeContent: function(){
		if($('MultiBoxMediaObject')){
			$('MultiBoxMediaObject').empty();
			$('MultiBoxMediaObject').remove();
		}
		if($('MultiBoxContentContainer')){
			//$('MultiBoxContentContainer').empty();
			$('MultiBoxContentContainer').remove();	
		}
	},
	
	showControls: function(){
		this.clicked = false;
		
		if(this.container.getStyle('height') != 'auto'){
			this.containerDefaults.height = this.container.getStyle('height')
			this.containerDefaults.backgroundColor = this.options.contentColor;
		}
		
		this.container.setStyles({
			//'backgroundColor': this.controls.getStyle('backgroundColor'),
			'height': 'auto'
		});
		
		if(this.contentToLoad.number == 1){
			this.previousButton.addClass('MultiBoxPreviousDisabled');
		}else{
			this.previousButton.removeClass('MultiBoxPreviousDisabled');
		}
		if(this.contentToLoad.number == this.content.length){
			this.nextButton.addClass('MultiBoxNextDisabled');
		}else{
			this.nextButton.removeClass('MultiBoxNextDisabled');
		}
		
		this.controlEffects.start({'height': this.controls.getStyle('height')});

	},
	
	hideControls: function(num){
		this.controlEffects.start({'height': 0}).chain(function(){
			this.container.setStyles(this.containerDefaults);
		}.bind(this));
	},
	
	showThumbnails: function(){
		
	},
	
	next: function(){
		if(this.index < this.content.length-1){
			this.index++;
			this.openId = this.content[this.index].getProperty('id');
			if (this.options.showControls) {
				this.hideControls();
			}
			this.getOpenClosePos(this.content[this.index]);
			//this.getContent(this.index);
			this.timer = this.hideContent.bind(this).delay(500);
			this.timer = this.load.pass(this.index, this).delay(1100);
		}
	},
	
	previous: function(){
		if(this.index > 0){
			this.index--;
			this.openId = this.content[this.index].getProperty('id');
			if (this.options.showControls) {
				this.hideControls();
			}
			this.getOpenClosePos(this.content[this.index]);
			//this.getContent(this.index);
			this.timer = this.hideContent.bind(this).delay(500);
			this.timer = this.load.pass(this.index, this).delay(1000);
		}
	},
	
	createEmbedObject: function(){
		if(this.type == 'flash'){
			var url = this.contentObj.url;
			
			var obj = new Element('div').setProperties({id: 'MultiBoxMediaObject'});
			this.str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" '
			this.str += 'width="'+this.contentObj.width+'" ';
			this.str += 'height="'+this.contentObj.height+'" ';
			this.str += 'title="MultiBoxMedia">';
  			this.str += '<param name="movie" value="'+url+'" />'
  			this.str += '<param name="quality" value="high" />';
  			this.str += '<embed src="'+url+'" ';
  			this.str += 'quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" ';
  			this.str += 'width="'+this.contentObj.width+'" ';
  			this.str += 'height="'+this.contentObj.height+'"></embed>';
			this.str += '</object>';
			
		}
		
		if(this.type == 'flashVideo'){
			//var url = this.contentObj.url.substring(0, this.contentObj.url.lastIndexOf('.'));
			var url = this.contentObj.url;
			
			var obj = new Element('div').setProperties({id: 'MultiBoxMediaObject'});
			this.str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" '
			this.str += 'width="'+this.contentObj.width+'" ';
			this.str += 'height="'+(Number(this.contentObj.height)+this.contentObj.xH)+'" ';
			this.str += 'title="MultiBoxMedia">';
  			this.str += '<param name="movie" value="'+this.options.path+'flvplayer.swf" />'
  			this.str += '<param name="quality" value="high" />';
  			this.str += '<param name="salign" value="TL" />';
  			this.str += '<param name="scale" value="noScale" />';
  			this.str += '<param name="FlashVars" value="path='+url+'" />';
  			this.str += '<embed src="'+this.options.path+'flvplayer.swf" ';
  			this.str += 'quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" ';
  			this.str += 'width="'+this.contentObj.width+'" ';
  			this.str += 'height="'+(Number(this.contentObj.height)+this.contentObj.xH)+'"';
  			this.str += 'salign="TL" ';
  			this.str += 'scale="noScale" ';
  			this.str += 'FlashVars="path='+url+'"';
  			this.str += '></embed>';
			this.str += '</object>';
			
		}
		
		if(this.type == 'flashMp3'){
			var url = this.contentObj.url;
			
			var obj = new Element('div').setProperties({id: 'MultiBoxMediaObject'});
			this.str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" '
			this.str += 'width="'+this.contentObj.width+'" ';
			this.str += 'height="'+this.contentObj.height+'" ';
			this.str += 'title="MultiBoxMedia">';
  			this.str += '<param name="movie" value="'+this.options.path+'mp3player.swf" />'
  			this.str += '<param name="quality" value="high" />';
  			this.str += '<param name="salign" value="TL" />';
  			this.str += '<param name="scale" value="noScale" />';
  			this.str += '<param name="FlashVars" value="path='+url+'" />';
  			this.str += '<embed src="'+this.options.path+'mp3player.swf" ';
  			this.str += 'quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" ';
  			this.str += 'width="'+this.contentObj.width+'" ';
  			this.str += 'height="'+this.contentObj.height+'"';
  			this.str += 'salign="TL" ';
  			this.str += 'scale="noScale" ';
  			this.str += 'FlashVars="path='+url+'"';
  			this.str += '></embed>';
			this.str += '</object>';
		}
		
		if(this.type == 'quicktime'){
			var obj = new Element('div').setProperties({id: 'MultiBoxMediaObject'});
			this.str = '<object  type="video/quicktime" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"';
			this.str += ' width="'+this.contentObj.width+'" height="'+this.contentObj.height+'">';
			this.str += '<param name="src" value="'+this.contentObj.url+'" />';
			this.str += '<param name="autoplay" value="true" />';
			this.str += '<param name="controller" value="true" />';
			this.str += '<param name="enablejavascript" value="true" />';
			this.str += '<embed src="'+this.contentObj.url+'" autoplay="true" pluginspage="http://www.apple.com/quicktime/download/" width="'+this.contentObj.width+'" height="'+this.contentObj.height+'"></embed>';
			this.str += '<object/>';
			
		}
		
		if(this.type == 'windowsMedia'){
			var obj = new Element('div').setProperties({id: 'MultiBoxMediaObject'});
			this.str = '<object  type="application/x-oleobject" classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112"';
			this.str += ' width="'+this.contentObj.width+'" height="'+this.contentObj.height+'">';
			this.str += '<param name="filename" value="'+this.contentObj.url+'" />';
			this.str += '<param name="Showcontrols" value="true" />';
			this.str += '<param name="autoStart" value="true" />';
			this.str += '<embed type="application/x-mplayer2" src="'+this.contentObj.url+'" Showcontrols="true" autoStart="true" width="'+this.contentObj.width+'" height="'+this.contentObj.height+'"></embed>';
			this.str += '<object/>';
			
		}
		
		if(this.type == 'real'){
			var obj = new Element('div').setProperties({id: 'MultiBoxMediaObject'});
			this.str = '<object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA"';
			this.str += ' width="'+this.contentObj.width+'" height="'+this.contentObj.height+'">';
			this.str += '<param name="src" value="'+this.contentObj.url+'" />';
			this.str += '<param name="controls" value="ImageWindow" />';
			this.str += '<param name="autostart" value="true" />';
			this.str += '<embed src="'+this.contentObj.url+'" controls="ImageWindow" autostart="true" width="'+this.contentObj.width+'" height="'+this.contentObj.height+'"></embed>';
			this.str += '<object/>';
			
		}
		
		return obj;
	}
	
});
MultiBox.implement(new Options);
MultiBox.implement(new Events);

/**************************************************************

	Script		: Overlay
	Version		: 1.2
	Authors		: Samuel birch
	Desc		: Covers the window with a semi-transparent layer.
	Licence		: Open Source MIT Licence

**************************************************************/

var Overlay = new Class({
	
	getOptions: function(){
		return {
			colour: '#000',
			opacity: 0.7,
			zIndex: 89,
			container: document.body,
			onClick: Class.empty
		};
	},

	initialize: function(options){
		this.setOptions(this.getOptions(), options);
		
		this.options.container = $(this.options.container);
		
		this.container = new Element('div').setProperty('id', 'OverlayContainer').setStyles({
			position: 'absolute',
			left: '0px',
			top: '0px',
			width: '100%',
			zIndex: this.options.zIndex
		}).injectInside(this.options.container);
		
		this.iframe = new Element('iframe').setProperties({
			'id': 'OverlayIframe',
			'name': 'OverlayIframe',
			'src': 'javascript:void(0);',
			'frameborder': 0,
			'scrolling': 'no'
		}).setStyles({
			'position': 'absolute',
			'top': 0,
			'left': 0,
			'width': '100%',
			'height': '100%',
			'filter': 'progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)',
			'opacity': 0,
			'zIndex': 1
		}).injectInside(this.container);
		
		this.overlay = new Element('div').setProperty('id', 'Overlay').setStyles({
			position: 'absolute',
			left: '0px',
			top: '0px',
			width: '100%',
			height: '100%',
			zIndex: 2,
			backgroundColor: this.options.colour
		}).injectInside(this.container);
		
		this.container.addEvent('click', function(){
			this.options.onClick();
		}.bind(this));
		
		this.container.setStyle('opacity', 0);
		//this.fade = new Fx.Style(this.container, 'opacity', {duration: 100}).set(0);
		this.position();
		
		window.addEvent('resize', this.position.bind(this));
	},
	
	position: function(){ 
		if(this.options.container == document.body){ 
			var h = window.getScrollHeight()+'px'; 
			this.container.setStyles({top: '0px', height: h}); 
		}else{ 
			var myCoords = this.options.container.getCoordinates(); 
			this.container.setStyles({
				top: myCoords.top+'px', 
				height: myCoords.height+'px', 
				left: myCoords.left+'px', 
				width: myCoords.width+'px'
			}); 
		} 
	},
	
	show: function(){
		this.container.setStyle('opacity', this.options.opacity);
		//this.fade.start(0,this.options.opacity);
	},
	
	hide: function(){
		this.container.setStyle('opacity', 0);
		//this.fade.start(this.options.opacity,0);
	}
	
});
Overlay.implement(new Options);

/*************************************************************/

var LightMenu = new Class({
	options: {
		offsetX: 0,
		offsetY: 0,
		
		timeBeforeShow: 100,
		timeBeforeHide: 100,
		
		onHide: function() {},
		onShow: function() {},
		
		position: 'top-left' //top-right, bottom-left, bottom-right,
	},
	
	hidden: true,
	cursorOverMenu: false,
	cursorOverCont: false,
	
	containerDiv: null,
	menuDiv: null,
	
	cursorOver: function () {
		return this.cursorOverMenu || this.cursorOverCont;
	},
	
	onContMouseOver: function(obj)
	{
		this.cursorOverCont = true;
		if (this.isHidden() && this.cursorOver()) {
			this.triggerShowMenu();
		}	
	},
	
	onContMouseOut: function(obj)
	{
		this.cursorOverCont = false;
		if (this.isVisible() && !this.cursorOver()) {
			this.triggerHideMenu(obj);
		}	
	},
	
	onMenuMouseOver: function(obj)
	{
		this.cursorOverMenu = true;
		//this.options.menuOver = true;
	},
	
	onMenuMouseOut: function(obj)
	{
		this.cursorOverMenu = false;
		if (this.isVisible() && !this.cursorOver()) {
			this.triggerHideMenu();
		}
	},
	
	initialize: function(contId, menuId, options) {
		this.containerDiv = $(contId);
		this.menuDiv = $(menuId);
        if (!this.containerDiv || !this.menuDiv)  return;
		this.containerDiv.addEvent('mouseover', this.onContMouseOver.bind(this));
		this.containerDiv.addEvent('mouseout', this.onContMouseOut.bind(this));
		this.menuDiv.addEvent('mouseover', this.onMenuMouseOver.bind(this));
		this.menuDiv.addEvent('mouseout', this.onMenuMouseOut.bind(this));
		if ($defined(options)) this.setoptions(options);
	},
	
	setoptions: function(options) {
		
		this.options = $merge(this.options, options);
	},	

	isHidden: function()
	{
		return this.hidden;
	},
	
	isVisible: function()
	{
		return !this.hidden;
	},
	
	triggerHideMenu: function()
	{
		//this.hideMenu();
		this.hideMenu.delay(this.options.timeBeforeHide, this);			
	},
	
	hideMenu: function()
	{
		if (this.isVisible() && !this.cursorOver())	{
			if (this.menuDiv.setStyle)	this.menuDiv.setStyle('display', "none");
			this.fireEvent('onHide', [this.containerDiv]);
			this.hidden = true;
		}
	},

	triggerShowMenu: function()
	{
		//this.showMenu();
		this.showMenu.delay(this.options.timeBeforeShow, this);
	},
	
	showMenu: function()
	{
		if (this.isHidden() && this.cursorOver())
		{
			var coords = this.containerDiv.getCoordinates();
			var left = coords.left;
			var top = coords.top;
			switch (this.options.position) {
				case 'top-right':
				case 'bottom-right':
					left+= coords.width;
			}
			switch (this.options.position) {
				case 'bottom-left':
				case 'bottom-right':
					top+= coords.height;
			}
			if (this.menuDiv.setStyles) {
//			        this.menuDiv.injectTop(document.body);
				this.menuDiv.setStyles({
					'position': 'absolute',
					'top': top+this.options.offsetY,
					'left': left + this.options.offsetX,
					'z-index': '500',
					'display': 'inline'
				});
			}			
			this.fireEvent('onShow', [this.options.containerDiv]);
			this.hidden = false;
		}
	}
});

LightMenu.implement(new Events);
LightMenu.implement(new Options);


