window.addEvent('domready', function(){
	if($('divMask')){
		$('divMask').setStyles({
			'width': window.getScrollSize().x,
			'height': window.getScrollSize().y
		});
	}
	
	mainMenuHover();
	checkFormSearch();
	titleMenuHover();
	sortAjax();
	pageAjax();
	
	customSelectBox();
	if($('hid_registration_popup')){
		if($('hid_registration_popup').value.trim() != ''){
			showLayout('popupRegistration', 'popupRegistrationContent', $('hid_registration_popup').value);
		}
	}
	
	if($('divMask')){
		setTimeout(function(){
			$('divMask').setStyle('display', 'none');
		},3000);
	}
});
function mainMenuHover(){
	var ulMenus = $$('ul.mainNav');
	if(!ulMenus.length)	return;
	
	var liMenus = ulMenus[0].getChildren('li');
	if(!liMenus.length)	return;
	
	liMenus.each(function(liItem, index){
		var divSubMenu = liItem.getElement('div.subNav');
		
		if(divSubMenu){
			divSubMenu.myFx = new Fx.Tween(divSubMenu,{
				property: 'opacity',
				duration: 500,
				link: 'cancel'
			});
			divSubMenu.myFx.start('0');
			liItem.removeEvents().addEvents({
				'mouseover': function(){
					clearTimeout(liItem.timer);
					liItem.getElement('a').addClass('selected');
					divSubMenu.setStyle('top', liItem.getCoordinates().top + liItem.getCoordinates().height + 1);
					divSubMenu.setStyle('left', $('header').getCoordinates().left);
					divSubMenu.myFx.start('1');
				},
				'mouseleave': function(){
					liItem.timer = setTimeout(function(){
						liItem.getElement('a').removeClass('selected');
						divSubMenu.myFx.start('0');
						divSubMenu.setStyle('top', '-9999px');					
					},200);
				}
			});
		}
	});
}

function checkFormSearch(){
	var demoFormData = [
	{
		name: 'keyWord',
		valid: 'required',	
		maxLength: 20,
		message: {
			en: _message['search.value']
		},
		init: _message['search.value']
	}];	
	
	if($('keyWord').value.trim() == ''){
		//$('keyWord').value = _message['search.value'];
		$('keyWord').addClass('typeColorGray');
	}
	if($('keyWord').value.trim() == _message['search.value']){
		$('keyWord').addClass('typeColorGray');
	}
	
	$('keyWord').addEvents({
		'focus': function(){
			/*if($('keyWord').value.trim() == _message['search.value']){
				$('keyWord').value = '';
			}*/
			$('keyWord').removeClass('typeColorGray');
		},
		'blur': function(){
			if($('keyWord').value.trim() == ''){
				//$('keyWord').value = _message['search.value'];
				$('keyWord').addClass('typeColorGray');
			}
		}
	});	
	
	new MooForm('frmSearch', demoFormData, {			
		onSubmit: function(form){			
			var value = form.keyWord.value;
			if (value.trim() != '') {				
				var action = form.action;				
				action = action.substring(0,action.lastIndexOf('/'));				
				action = action.replace(/keyword/, value.trim()) + '/';								
				form.action = action;				
			}
		}
	});	
}

function titleMenuHover(){
	var ulSubMenu = $$('ul.subExternal');
	if(!ulSubMenu.length)	return;
	ulSubMenu = ulSubMenu[0];
	
	var liMenu = ulSubMenu.getParent('li');
	if(!liMenu)	return;
	
	var myFx = new Fx.Tween(ulSubMenu,{
		link:'cancel'
	});
	ulSubMenu.setStyle('opacity', 0);
	liMenu.removeEvents().addEvents({
		'mouseover': function(){
			myFx.start('opacity', 1);
		},
		'mouseleave': function(){
			myFx.start('opacity', 0);
		}
	});
}

function sortAjax(){
	var divContent = $('div_update');	
	if(!divContent)	return;
	
	var ulSort = $$('ul.sortBy');	
	if(!ulSort.length)	return;
	ulSort = ulSort[0];
	
	var aSorts = ulSort.getElements('a');
	if(aSorts.length < 1)	return;
	
	var imgLoading = $$('.imgLoading');
	
	aSorts.each(function(aSort){
		if(aSort.getProperty('href') != 'javascript:void(0);'){
			aSort.addEvent('click', function(e){
				e.stop();			
				new Request.HTML({
					url: aSort.get('href'),
					method: 'get',
					update: divContent.value,				
					onRequest: function(){	
						imgLoading[0].setStyle('display', 'block');
					},
					onComplete: function(){
						imgLoading[0].setStyle('display', 'none');
						sortAjax();
						pageAjax();
						new mooScroller($$(".smScrollContent"));
					}
				}).send();
			});
		}
	});
}

function pageAjax(){
	var url = $('link_paging');
	if(!url)	return;
	var divContent = $('div_update');
	if(!divContent)	return;
	
	var ulPaging = $$('ul.pagging');
	if(!ulPaging.length)	return;
	ulPaging = ulPaging[0];
	
	var aPages = ulPaging.getElements('a');
	if(aPages.length < 1)	return;
	
	var imgLoading = $$('.imgLoading');
	
	aPages.each(function(aPage){	
		if(aPage.getProperty('href') != 'javascript:void(0);'){
			aPage.addEvent('click', function(e){
				e.stop();
				var page = aPage.get('text');
				if(aPage.get('href') != '#'){
					page = aPage.get('href');
				}
				
				
				new Request.HTML({
					url: url.value,
					method: 'get',
					data: {
						'page': page 
					},
					update: divContent.value,				
					onRequest: function(){	
						imgLoading[0].setStyle('display', 'block');
					},
					onComplete: function(){
						imgLoading[0].setStyle('display', 'none');
						sortAjax();
						pageAjax();
						if($$('a.subReplayComment').length > 0){
							showSubComment();
						}
						new mooScroller($$(".smScrollContent"));
					}
				}).send();
			});
		}
	});
}

function customSelectBox() {	
    var container = $('container');
    if (!container) return;
	
	var selectsAll = $$('select');
    if (selectsAll.length) {
        selectsAll.each(function(select) {
			if(!select.hasClass('normal-select')){
				var div = select.getNext('div.select-box');						
				if(!select.hasClass('accesSel') && !div){
					new selectBox({ elem: select,
						useATagImg: 2
					});
				}
			}
        });
    }	
}

var selectBox = new Class({
    Implements: [Options, Events],

    options: {
        useATagImg: 0,
        allowSplit: true, 						// depricate for .filter()
        altClass: 'select-box-alt',
        alternate: false,
        alternateOdd: false,
        attachResize: true,
        container: null,
        disableClass: 'disabled',
        elem: null,
        filter: null,
        fxOptions: {},
        groupClass: 'select-box-options-group',
        maxShow: null,
        minShow: 3,
        optionClass: 'select-box-opt',
        selectboxClass: 'select-box',
        selectClass: 'selected',
        selectmenuClass: 'select-box-options',
        separator: '--', 						// depricate for .filter()
        showStyles: false,
        size: 1,
        template: '<span>%s</span>',
        tmplt_regex: null,
        useFx: true,

        onHide: $empty(),
        onOver: $empty(),
        onSelect: $empty(),
        onShow: $empty()
    },
    //Modification
    isCrolling: false,
    //<--Modification
    container: null,
    element: null,
    focused: null,
    length: 0,
    selected: null,
    selectedIndex: 0,
    showing: false,
    textSearch: '',
    version: '0.5.5',

    initialize: function(_options) {
        this.boundShow = this.show.bind(this);
        this.boundKey_option = this.key_option.bind(this);
        this.boundHide = this.hide.bind(this);

        var opts = ($type(_options) != 'object' ? { 'elem': _options} : _options);
        if (!$defined(opts.elem)) return;

        this.setOptions(opts);

        if (this.options.filter) {
            this.filter = this.options.filter;
        }

        this.element = this.options.elem;
        this.elementCopy = this.element.clone().set({
            'id': this.element.get('id'),
            'name': this.element.get('name')
        });

        if (!$defined(this.options.container) || (this.container = $(this.options.container)) == null) {
            this.container = null;
        }

        this.optClass = 'li[class*=' + this.options.optionClass + ']';

        this.create_select();
        if (this.options.attachResize) { window.addEvent('resize', function() { if (this.showing) { this.show(); } } .bind(this)); }
		this.element.setStyles({
			'width': '1px',
			'border': '0 none',
			'opacity': '0.01',
			'position': 'absolute',
			'top': '-999px',
			'float': 'right'
		});		
    },

    destroy: function(_revert) {
        if (_revert) {
            if (this.selected && $defined(this.selected.retrieve('value'))) {
                $each(this.elementCopy.options, function(_elem) {
                    if (_elem.value == this.selected.retrieve('value')) { _elem.selected = true; }
                }, this);
            }

            this.elementCopy.replaces($(this.element.get('id')));
        }

        this.remove_events();
        this.elementSelect.destroy();
    },

    ieFocus: function() {
        this.isCrolling = true;
    },

    create_select: function() {
        var wh = this.element.getSize();
        this.eid = this.element.get('id');

        // create the select element
        this.elementSelect = new Element('div', {
            'class': this.options.selectboxClass,
            'styles': {
                'width': wh.x,
				'padding': 0
                //'height': wh.y
            }
        }).inject(this.element, 'after');

        // create display element for selectbox

        this.elementDisplay = new Element('a', {
            'href': 'javascript:void(0)'
        }).inject(this.elementSelect, 'top');

        if (this.elementCopy.get('tabindex') != 0) {
            this.elementDisplay.set('tabindex', this.elementCopy.get('tabindex'));
        }
        /*this.elementDisplay.setStyles({
        'height': (wh.y-5),
        'line-height': (wh.y-5)			
        });*/
        switch (this.options.useATagImg) {
            case 0:
                this.elementDisplay.setStyles({
                    'background-image': 'url(/images/bgd_input_01.gif)',
                    'background-position': '0 0',
                    'background-repeat': 'no-repeat',
                    'background-color': 'transparent',
                    'width': (wh.x - 30),
                    'font-size': '0.93em',
                    'color': '#444444'
                });

                this.elementSelect.setStyles({
                    'background-image': 'url(/images/btn_select_new.gif)',
                    'background-position': '100% 0',
                    'background-repeat': 'no-repeat',
                    'background-color': 'transparent',
                    'height': wh.y
                });
                break;
            case 1:
                this.elementDisplay.setStyles({
                    'background-image': 'url(../images/bgd_input.png)',
                    'background-position': '0 0',
                    'background-repeat': 'no-repeat',
                    'background-color': 'transparent',
                    'width': (wh.x - 15)
                });

                this.elementSelect.setStyles({
                    'background-image': 'url(../images/btn_select_new_01.png)',
                    'background-position': '100% 0',
                    'background-repeat': 'no-repeat',
                    'background-color': 'transparent',
                    'height': wh.y + 1
                });
                break;
            case 2:
                this.elementDisplay.setStyles({
                    'background-image': 'url(/canalinsep/images/ui_general.gif)',
                    'background-position': '0 -906px',
                    'background-repeat': 'no-repeat',
                    'background-color': 'transparent',
                    'width': (wh.x - 28)
                });
                this.elementSelect.setStyles({
                    'background-image': 'url(/canalinsep/images/ui_general.gif)',
                    'background-position': '100% -924px',
                    'background-repeat': 'no-repeat',
                    'background-color': 'transparent',
                    //'height': wh.y + 1
					'height': '18px'
                });
                break;
        }

        /*if(this.options.useATagImg){			
        this.elementDisplay.setStyles({
        'background-image': 'url(../images/bgd_input_emplacement.gif)',
        'background-position': '0 0',
        'background-repeat': 'no-repeat',
        'background-color': 'transparent',
        'width': (wh.x-15)
        });
			
			this.elementSelect.setStyles({				
        'background-image': 'url(../images/btn_select_new_01.png)',
        'background-position': '100% 0',
        'background-repeat': 'no-repeat',
        'background-color': 'transparent',
        'height': wh.y + 1
        });			
        }else{
        this.elementDisplay.setStyles({				
        'background-image': 'url(/images/bgd_input_01.gif)',
        'background-position': '0 0',
        'background-repeat': 'no-repeat',
        'background-color': 'transparent',
        'width': (wh.x-30),
        'font-size': '0.93em',
        'color': '#444444'
        });
			
			this.elementSelect.setStyles({				
        'background-image': 'url(/images/btn_select_new.gif)',
        'background-position': '100% 0',
        'background-repeat': 'no-repeat',
        'background-color': 'transparent',
        'height': wh.y
        });
        }*/

        this.add_events();

        // create the options element
        this.elementOptions = new Element('ul', {
            'styles': { 'width': wh.x },
            'opacity': (this.options.useFx ? 0 : 1),			
            'class': this.options.selectmenuClass,
			'z-index': 1002
        }).inject(document.body);

        if (Browser.Engine.trident) {
            this.boundIeFocus = this.ieFocus.bind(this);
            this.elementOptions.addEvent('mousedown', this.boundIeFocus);
        }

        // create the fx object if useFx is set
        this.fx = this.options.useFx ? new Fx.Tween(this.elementOptions, $merge({
            'duration': '200',
            'link': 'cancel'
        }, this.options.fxOptions)).set('opacity', 0) : null;
		
        // loop thru existing options and recreate
        $each(this.element.getChildren(), this.create_option.bind(this));

        // set alternating
        if (this.options.alternate) {
            this.elementOptions.getElements(this.optClass + ':' + (this.options.alternateOdd ? 'odd' : 'even')).addClass(this.options.altClass);
        }

        // set default selected option and dislpay value		
        (this.selected = this.elementOptions.getElement('li.' + this.options.selectClass)).removeClass(this.options.selectClass);
        this.selectedIndex = this.selected.retrieve('idx');
		
        //alert(this.selected.get('html'));
        this.elementDisplay.set({
            'text': this.selected.get('text'),
            'class': (this.options.showStyles ? this.selected.get('class') : '')
            //'style': (this.options.showStyles ? this.selected.get('style') : '')
        });

        // store option menu coords info
        this.elementOptions.store('coords', this.elementOptions.getCoordinates()).setStyles({ 'visibility': '', 'display': 'none' });

        // replace select element with hidden input by same id/name
		
        /*this.element = new Element('input', {
            'type': 'hidden',
            'value': this.element.get('value'),
            'id': this.element.get('id'),
            'name': this.element.get('name')
        }).replaces(this.element).set('id', this.eid);*/
    },

    create_option: function(_opt, _idx, _group) {
        // get option information
        var val = _opt.get('value'), selected = !!(_opt.selected);
        var text = (_opt.get('label') ? _opt.get('label') : (_opt.get('text') || '&nbsp;'));

        // determine class for option unselectable
        var opt_class = (_opt.get('tag') == 'optgroup' ? ' optgroup ' : ' ' + this.options.optionClass) + (selected && !_opt.disabled ? ' ' + this.options.selectClass : '') +
						(_opt.disabled ? ' ' + this.options.disableClass : '');

        // create li replacement for select option	
		var stringEvent = '';
		//alert(_opt.getProperty('onclick'));		
		if(_opt.getProperty('onclick')){			
			if(typeof(_opt.getProperty('onclick')) == "string"){
				stringEvent = _opt.getProperty('onclick');
			}else{
				stringEvent = "'" + _opt.getProperty('onclick') + "'";				
				stringEvent = stringEvent.replace(/^'function| onclick| anonymous|\(\)|{|}'$/gi,'');
			}			
		}
        var new_option = new Element('li', {
            'id': this.eid + '_opt' + _idx,
            'style': _opt.get('style'),
            'class': _opt.get('class') + opt_class, //_opt.get('onclick')			
			'html': '<a href="javascript:void(0);" onclick="'+stringEvent+'" title="' + text + '">'+this.filter(text, this.options.tmplt_regex, this.options.template)+'</a>'
        }).store('value', _opt.get('value'))
		  .store('idx', (_opt.get('tag') != 'optgroup' ? (++this.length) : ''))
		  .addEvents({
		      'mouseover': this.over.bind(this),
		      'mousedown': this.select.bind(this)
		  }).inject(($(_group) || this.elementOptions));

        new_option.store('coords', new_option.getCoordinates());

        if (_opt.get('tag') == 'optgroup') {
            var optgroup = new Element('ul', { 'class': this.options.groupClass }).inject(new_option);
            $each(_opt.getChildren(), function(_sopt, _sidx) {
                this.create_option(_sopt, (_idx + '' + _sidx), optgroup);
            }, this);
        }

        // THIS TO BE REPLACED WITH this.filter()
        // if option.text matches this.options.separator split and go left / right with text
        if (this.options.allowSplit && text.match(new RegExp(this.options.separator))) {
            text = text.split(this.options.separator);
            this.elementOptions.lastChild.set('html', '<span><span class="goleft">' + text[0].trim() + '</span><span class="goright">' + text[1].trim() + '</span><br style="clear:both" /></span>');
        }
    },

    filter: function(_str, _regx, _tmplt) {
        return _tmplt.replace(/\%s/i, _str);
    },

    inject: function(_option, _where) {

    },

    dispose: function(_elem) {

    },

    add_events: function() {
		var timer = null;
		
		
        this.elementSelect.addEvents({
            'click': this.boundShow,
            'keydown': this.boundKey_option//,
            //'blur': this.boundHide
        });
		
		var that = this;
		
        this.elementDisplay.addEvents({
            'keydown': this.boundKey_option//,
            //'blur': this.boundHide
			/*'blur': function(e){
				that.hide();
			}*/
        });
		
		$(document.body).addEvent('mouseup', function(e){
			if(!e.target){
				return;
			}			
			var tg = e.target;			
			if(tg.tagName && tg.tagName.toLowerCase() == 'div'){
				if(tg.className && tg.className == 'select-box'){
					return;
				}
			}else{
				if(tg.tagName && tg.tagName.toLowerCase() == 'a'){
					if(tg.getParent){
						var parentDiv = tg.getParent('div');
						if(parentDiv){					
							if(parentDiv.hasClass('select-box')){							
								return;
							}
						}
					}
				}
			}			
			that.hide();
		});
		
    },

    remove_events: function() {
        this.elementOptions.removeEvent(this.boundIeFocus);
        this.elementSelect.removeEvents({
            'click': this.boundShow,
            'keydown': this.boundKey_option,
            'blur': this.boundHide
        });
        this.elementDisplay.removeEvents({
            'keydown': this.boundKey_option,
            'blur': this.boundHide
        });		
    },

    key_option: function(e) {
        e = new Event(e);
        if (e.key != 'tab') {
            e.stop();
            switch (e.key) {
                case 'esc':
                    this.hide();
                    break;

                case 'enter':
                    this.select(this.selected);
                case 'tab':
                    this.hide();
                    break;

                case 'up': case 'down':
                    if (e.alt) { this.show(); }
                    this.select(e.key);
                    break;

                case 'shift': case 'control': case 'alt':
                    break;

                default:
                    this.search(e.key);
            }
        }
    },

    search: function(_key, _retrying) {
        this.textSearch += _key;
        var option_elems = this.get_options(), str_found = false, elem = false;
        // var option_elems = this.get_options('li[text^=' + this.textSearch +']'), str_found=false, elem = false;

        for (var i = 0; i < option_elems.length; i++) {
            var elem = option_elems[i];			
            if ((elem.get('text')).match(new RegExp('^' + this.textSearch, 'i'))){
                if (this.selected != elem) { this.select(elem); }
                str_found = true;
                break;
            }
        }

        if (str_found === false) {
            this.textSearch = '';
            if (!_retrying) { this.search(_key, true); }
        }
    },

    get_options: function(_selector) {
        return this.elementOptions.getElements((_selector || this.optClass));
    },

    // is there a better way to do this?
    determine: function(_elem) {
        var elem = ($type(_elem) == 'element' ? (_elem.get('tag') != 'li' ? _elem.getParent('li') : _elem) : this.get_options());

        if ($type(_elem) != 'element') {
            var fromIdx = ((this.focused && this.focused != this.selected) ? this.focused : this.selected).retrieve('idx');

            elem = elem.filter(function(_el) {
                return (!$(_el).hasClass(this.options.disableClass) &&
								((_elem == 'up' && $(_el).retrieve('idx') < fromIdx) ||
								 (_elem == 'down' && $(_el).retrieve('idx') > fromIdx)));
            }, this);

            elem = elem[0] ? (_elem == 'up' ? elem.reverse() : elem)[0] : elem;
        }

        return elem;
    },

    over: function(e) {
        e = new Event(e);
        var elem = ($(e.target).get('tag') != 'li' ? $(e.target).getParent('li') : $(e.target));

        if (!elem.hasClass(this.options.disableClass) && !elem.hasClass('unselectable')) {
            if ($type(this.focused) == 'element') { this.focused.removeClass(this.options.selectClass); }
            (this.focused = elem).addClass(this.options.selectClass);
            this.fireEvent('over');
        }
    },

    select: function(_elem) {		
		var elem = ($type(_elem) == 'event' ? new Event(_elem).target : _elem);
        elem = this.determine(elem);

        if (elem && !elem.hasClass(this.options.disableClass) && !elem.hasClass('unselectable')) {			
            if (this.focused) { this.focused.removeClass(this.options.selectClass); }
            if (this.showing === true) {
                (this.focused = this.selected = elem).addClass(this.options.selectClass);
                this.scroll();
            } else {
                this.selected = elem;
            }

            //this.element.set('value', this.selected.retrieve('value'));
			this.element.selectedIndex = this.selected.retrieve('idx') - 1; 
			if(this.element.onchange){
				this.element.onchange();
			}
            this.selectedIndex = this.selected.retrieve('idx');
		
            this.elementDisplay.set({
                //'text': this.selected.get('text'), hao
				'text': this.selected.getElement('span').get('text'),
                'class': (this.options.showStyles ? this.selected.get('class') : '')
            }).removeClass(this.options.selectClass).removeClass(this.options.altClass);

            this.fireEvent('select', this.selected);

            if (Browser.Engine.trident) {
                this.isCrolling = false;
                this.hide();
            }
        }
    },

    scroll: function() {
        var sElem = this.elementOptions.getCoordinates();
        var selElem = this.selected.getCoordinates();
        var elScrollTop = this.elementOptions.scrollTop;

        if ((elScrollTop + sElem.height) < (selElem.top - sElem.top + 5)) {
            this.elementOptions.scrollTop = (selElem.top - sElem.top - sElem.height + selElem.height);
        }
        else if ((selElem.top - sElem.top + selElem.height) < (elScrollTop + 5)) {
            this.elementOptions.scrollTop = (selElem.top - sElem.top);
        }
    },

    show: function() {
        var coords = this.elementOptions.retrieve('coords');
        var sElem = this.elementSelect.getCoordinates(), sElem_top = (sElem.top + sElem.height);

        if (this.container) {
            sElem_top -= this.container.getStyle('top');
            sElem.left -= this.container.getStyle('left');
        }

        var h = ((window.getSize().y + window.getScroll().y) - sElem_top);
        var height = (coords.height >= h ? 0 : 'auto'), showing = 0;

        if (coords.height >= h) {
            $each(this.get_options(), function(_elem) {
                var eH = _elem.retrieve('coords').height;
                if (height < h && (height + eH) < h) { height += eH; showing++; }
            }, this);

            if (showing < this.options.minShow) {
                height = (sElem.top < coords.height ? sElem.top - 10 : coords.height);
                sElem_top = sElem.top - height - 1;
            }
        }

        this.elementOptions.setStyles({
            'display': '',
            'height': height,
            'top': sElem_top,
            'left': sElem.left,
            'margin': 0
        });
        this.scroll();

        this.showing = true;
        this.focused = this.selected;
        this.focused.addClass(this.options.selectClass);
        this.fireEvent('show');

        if (this.options.useFx) { this.fx.start('opacity', 0, 1); }		
        // fixes chrome/safari focus bug
        this.elementDisplay.focus();
    },

    hide: function(e) {			
        if (this.isCrolling) {			
            this.isCrolling = false;
            this.elementDisplay.focus();
        }
        else if (this.showing) {
            //if (this.options.useFx) {
			var a = false;
			if (a) {
                this.fx.start('opacity', 1, 0).chain(function() {
                    this.elementOptions.scrollTop = 0;
                    this.elementOptions.setStyle('display', 'none');

                    if (this.focused) {
                        this.focused.removeClass(this.options.selectClass);
                    }
                    this.showing = this.focused = false;
                } .bind(this));
            } else {
				this.elementOptions.setStyle('opacity', '0');
                this.elementOptions.setStyle('display', 'none');

                if (this.focused) {
                    this.focused.removeClass(this.options.selectClass);
                }
                this.showing = this.focused = false;
            }

            this.fireEvent('hide');
        }

       this.textSearch = '';
    }
});