window.addEvent('domready',function(){
    switchLang();
    searchForm();
    captureForms();
    sendForm();
    logout();
    externalLink();
    references();
    leftMenu();
    fontSize();
    handbook_pagination();
    friendlyPrint();
    addRollOver('.images', '_ov', true);
//    splash_screen();
  
});




function addRollOver(el, ov, dis) {
	
	$$(el + ' img',el + ' input[type=image]').each( function(itm, index) {
		 var loc = location.href;
		 var lnk = itm.getParent('a');
		 if(itm.getProperty('type') == 'image'){
			 lnk = itm;
		 }
		 if(lnk != null)
		 {			 
			var href = lnk.getProperty('href');
			var src = itm.getProperty('src').split('/');
			var ind = src.length - 1;
			var file = src.getLast().split('.');
	
			src[ind] = file[0] + ov + '.' + file[1];
			src = src.join('/');
			
			if (loc.contains(href) && !dis) {
				itm.setProperty('src', src); 
			} else {
				var ovImg = new Element('img', {
					'src' :src
				});
				itm.addEvents({
					'mouseover' : function() {
						rollOver(this, ov);
					},
					'mouseout' : function() {
						rollOver(this, ov);
					}
				});
			}
		 }
	});
}

function rollOver(obj, ov) {
	var path = obj.getProperty('src').split('/');
	var ind = path.length - 1;
	var file = path.getLast();

	file = file.split('.');

	if (file[0].indexOf(ov) > -1) {
		path[ind] = file[0].replace(ov, '') + '.' + file[1];
	} else {
		path[ind] = file[0] + ov + '.' + file[1];
	}
	path = path.join('/');
	obj.setProperty('src', path);

}


function handbook_pagination() {
	var base  = $(document.head).getElement('base').get('href');
	var pagination_tips = new Tips('.pag_tip',{
		'className':'pag_tips',
		'offset ':{
			x:'left',
			y:'top'
		}
	});
	$$('.pagination a').each(function(el){
		if(base+el.get('href') == location.href) {
			el.addClass('current');
		}
	});
}

function switchLang(){
	var base  = $(document.head).getElement('base').get('href');

    $$('a[rel=switchLang]').addEvent('click',function(e){
        e.stop();
        var url = this.get('href');
        var ajx = new Request({
            'method': 'get',
            'url': url,
            onComplete: function(rsp){
        		var rs = rsp.split('|');
        		if(rs[0] === 'true') {
        			location.href = base + rs[1];
        		}
            }
        }).send();
    });
}

function searchForm() {
	var k = $('keyword');
	k.addEvents({
		'focus': function() { 
			k.value = (k.value == _search ? '' : k.value); 
		},
		'blur': function()  { 
			k.value = (k.value == '' ? _search : k.value); 
		}
	});
}

function captureForms() {
    $$('form').addEvent('submit', function(e) {
        e.stop();
    });
}

function sendForm() {

    $$('input[type=image], input[type=submit]').each(function(el) {
    	addSubmitListener(el, el.hasClass('no-ajx'));
    });
}

function addSubmitListener(el, no_ajx) {
    el.addEvent('click', function(e) {
        e.stop();
        var f = this.getParent('form');
        if(no_ajx) {
    		return f.submit();
    	}
        var name = f.get('name');
        if (!name) {
            name = f.get('id');
        }
        var url = name.split('_');
        url = 'ajx/' + url[1] + '.ajx.php';

        if ($('actionMsg')) {
            $('actionMsg').destroy();
        }

        ajx_loading(f);

        f.set('send', {
            'url' : url,
            'method' : 'post',
            onComplete : function(rsp) {
                formAction(f, rsp);
            }
        });
        f.send();
    });
}

function formAction(el, rsp) {
    var act = rsp.split('|');
    var e = new Element('div', {
        'id' : 'actionMsg'
    });

    switch (act[0]) {
        case 'confirmation':
            e.set( {
                'html' : act[1],
                'class' : 'confirmationMgs'
            });
            e.inject(el, 'before');
            delete el.destroy();
            break;
        case 'warning':
            e.set( {
                'html' : act[1],
                'class' : 'warningMgs'
            });
            e.inject(el, 'before');
            break;
        case 'reload':
        	location.href = location.href;
        	break;
        case 'quiz':
        	e.set( {
                'html' : act[1]
            });
            e.inject(el, 'before');
            references();
            delete el.destroy();
        	break;
    }

    remove_ajx_loading();
}

function ajx_loading(el) {
    if ($('ajx_loading')) {
        return;
    }
    var target = el.getParent();
    var loading = new Element('div', {
        'id' : 'ajx_loading'
    });
    loading.set('opacity', 0.50);
    loading.inject(target, 'top');
}

function remove_ajx_loading() {
    if (!$('ajx_loading')) {
        return;
    }
    $('ajx_loading').destroy();
}

function logout() {
	$$('a[rel=logout]').addEvent('click',function(e){
		e.stop();
		var ajx = new Request({
            'method': 'get',
            'url': 'ajx/logout.ajx.php',
            onComplete: function(){
                location.href = location.href;
            }
        }).send();
	});
}

function externalLink(){
	$$('a[target=_blank]').addEvent('click',function(e){
		if(this.hasClass('no-notice')) {
			return true;
		}
		e.stop();
		var href = this.get('href');
		var coords = $('mainContainer').getCoordinates();
		var scroll = document.getScroll();
		var top = (scroll.y + 50);
		var left = (coords.width/2)-200;
		var wrapper = new Element('div',{
			'id':'external-lik-wrapper',
			styles:{
				'height':coords.height +'px'
			}
		}) ;
		var prompt = new Element('div',{
			'id':'external-link',
			styles:{
				'top':top +'px',
				'left':left+'px'
			}
		}) ;
		var ajx = new Request.HTML({
			'url': 'ajx/externalLink.ajx.php',
			update:prompt,
            onComplete: function(){
                $('closePopup').addEvent('click',function(){
                	$('external-lik-wrapper').destroy();
                	$('external-link').destroy();
                });
                $('openLink').addEvent('click',function(){
                	window.open(href);
                	$('external-lik-wrapper').destroy();
                	$('external-link').destroy();
                });
            }
		}).send();
		wrapper.inject('mainContainer','before');
		prompt.inject('mainContainer','before');
	});
}

function references() {
	var myTips = new Tips({'className':'refs'});
	$$('sup a').each(function(el){
		el.addEvent('click',function(e){
			e.stop();
		});
		var ref = el.get('href');
		ref = ref.split('#');
		ref = ref[ref.length -1];
		el.addClass('refs');
		var ajx = new Request({
			'url':'ajx/references.ajx.php',
			'method':'get',
			'data':{'ref':ref},
			onComplete:function(rsp){
				var rs = rsp.split('|');
				el.store('tip:title', rs[0]);
				el.store('tip:text', rs[1]);
				myTips.attach(el);
			}
		}).send();
	});
	
}

function leftMenu() {
	if(!$('leftMenu')) {
		return false;
	}
	var base  = $(document.head).getElement('base').get('href');
	var uri = new URI(location.href,{'base':base}) ;
	var href = uri.toRelative();
	var links = $('leftMenu').getElements('a');
	
	links.each(function(el){
		if(el.get('href') == href) {
			leftmenu_getParent( el );
		}
	});
}

function leftmenu_getParent(el){
    var li = el.getParent('li');
    el.addClass('current');
    if(li.getParent('li')) {
        li.getParent('ul').setStyle('display','block');
        var prev = li.getParent('ul').getPrevious('a');
        prev.addClass('current');
        leftmenu_getParent( prev );
    }
    
    if(li.getElement('ul')) {
        li.getElement('ul').setStyle('display','block');
    }
}

function fontSize() {
	var uri = new URI(location.href);
	
	var size = Cookie.read('fontsize') || 12;
	size = size.toInt();
	var body = document.getElement('body');
	body.setStyle('font-size',size+'px');
	$('font-size-up').addEvent('click',function(){
		size = size <= 16 ? size + 2 : size;
		Cookie.write('fontsize',size, {path:'/'});
		body.setStyle('font-size',size+'px');
	});
	
	$('font-size-down').addEvent('click',function(){
		size = size >= 12 ? size - 2 : size;
		Cookie.write('fontsize',size, {path:'/'});
		body.setStyle('font-size',size+'px');
	});
}

function friendlyPrint() {
	$$('a[rel=friendly-print]').addEvent('click',function(e){
		e.stop();
		var base  = $(document.head).getElement('base').get('href');
		var uri = base + this.get('href');
		var win = window.open(uri,'Print','status=0,toolbar=0,location=0,menubar=yes,resizable=0,scrollbars=1,width=850,height=600');
		win.focus();
	});
}

function splash_screen(){
	if(!$('splashContainer')){
		return false;
	}
	
	if(!Cookie.read('splash')){
		$('splashContainer').setStyle('display','block');
		Cookie.write('splash','true',{
			duration:0
		});
	}
	
	$$('.close').addEvent('click',function(e){
		delete $('splashContainer').destroy();
	});
}

