/**
 * @author Mateusz Cyburt
 */     
 
var Main = new Class({
		initialize: function(){
	}, // initialize

    domReady: function() {
		newsScroller.activate(8000);
		this.menuMoved = 0;
		this.insertFlash();
		this.activateForms();
		//this.activateInputs();
		this.activateRemind();
		this.switchFonts();
		if ( !Browser.Engine.trident4 ) this.activateAccordion();
		else this.activateAccordionIe6();
		this.activateTree();
		this.insertGmaps();
		this.activateBackBtn();
		var fix4ie = new Fix4ie();
	}, // domReady
    
    insertFlash: function(){
		elements = $$('div.flash');
		if (elements.length > 0) {
	    	elements.each(function(obj){
            	var size = obj.getSize();
            	var id = obj.get('id');
            	var SwiffObj = new Swiff('html/flash/' + id + '.swf', { id: "flash" + $random(1,99),container: id, width: size.x, height: size.y, 
										 params: {wmode: 'transparent', bgcolor: '#' + obj.getStyle('background-color')} });
            	obj.setStyle('background-image', 'none');
	    	});
		}
    }, // insertFlash
        
	checkTitles: function(form) {
		form.getElements('input').each(function(obj){
			if (obj.value == obj.title) obj.value = '';
		});
		form.getElements('textarea').each(function(obj){
			if (obj.value == obj.title) obj.value = '';
		});
	}, // checkTitles
	
	activateInputs: function() {
		$$('input').each(function(obj){
			obj.value = obj.title;
			obj.onclick = function() { if (obj.value == obj.title) { obj.value = '';} };
			obj.onblur = function()  { if (obj.value == '') { obj.value = obj.title;} };
		});

		$$('textarea').each(function(obj){
			obj.onclick = function() { if (obj.innerHTML == obj.title){obj.innerHTML = '';} };
			obj.onblur = function()  { if (obj.innerHTML == ''){obj.innerHTML = obj.title;} };
		});

		$$('form').each(function(obj){
			obj.onsubmit = function() { main.checkTitles(this); };
		});
	}, // activateInputs
		
	activateForms: function() {
		if ($('login_form')) $('login_form_btn').onclick = function(){ main.checkTitles(this.getParent()); main.tryLogin(); return false; };
		if ($('logout')) $('logout').onclick = function(){ main.logout(); return false; };
	}, // activateForms

	tryLogin: function() {
		if ($('login_form_login').value != '' && $('login_form_password').value != '') {
			var req = new Request({
				url: 'ajax/login', 
				method: 'post',
				data: {'login_form_username' : $('login_form_login').value,
					   'login_form_password' : $('login_form_password').value},
				onRequest: function() { 
						   $('login_form_btn').disabled = 'disabled';
						   $('ajax-loader-login').setStyle('display', 'block'); },  
				onComplete: function(response) { 
						   $('ajax-loader-login').setStyle('display', 'none');
						   $('login_form_btn').disabled = '';
						   if (response != 0) window.location.reload();
						   else {
							   $('login_form_login').addClass('error');
							   $('login_form_password').addClass('error');
						   }
						   //$('login_status').innerHTML = response;
						   }  
			});
			req.send();
	
		} else {
			if ($('login_form_login').value == '') $('login_form_login').addClass('error'); 
			if ($('login_form_password').value == '') $('login_form_password').addClass('error');
		}
	}, // tryLogin
	
	logout: function() {
		if ($('logout')) {
			var req = new Request({
				url: 'ajax/logout', 
				method: 'get',
				onRequest: function() { 
						   $('logout').disabled = 'disabled';
						   $('ajax-loader-logout').setStyle('display', 'block'); },  
				onComplete: function(response) { 
						   $('ajax-loader-logout').setStyle('display', 'none');
						   $('logout').disabled = '';
						   window.location.reload();
						   }
			});
			req.send();
			
		}
	}, // logout
	
	switchFonts: function() {
		var color = 'b';
		if ($('top_menu').hasClass('debt-recovery') || $('top_menu').hasClass('recuperacion-de-deudas')) { var color = 'r'; }
		if ($('top_menu').hasClass('make-payment') || $('top_menu').hasClass('hacer-un-pago'))  { var color = 'g'; }
		
		$$('ul#top_menu li ul li a').each(function(obj){
			obj.innerHTML = '<span><img src="html/php/top-submenu.php?c='+color+'&amp;txt='+obj.title+'" alt="'+obj.title+'" /></span>';
			// ie6 fuck
			if ( Browser.Engine.trident4 ) {
				var img_width = obj.getElement('span').getElement('img').getStyle('width').toInt();
				obj.getElement('span').setStyle('width', img_width + 'px');
				obj.getParent().setStyle('width', img_width + 10 + 'px');
			}			
		});
		$$('ul#mini_sections li ul li a').each(function(obj){
			obj.innerHTML = '<span style="background-image: url(\'html/php/menu-txt.php?txt='+obj.innerHTML+'\')"></span>';
		});
		if ($('news_list')) {
			var elems = $$('ul#news_list li a');
			elems.each(function(obj){
				obj.innerHTML = '<img src="html/php/text-gfx.php?txt='+obj.innerHTML+'" alt="'+obj.innerHTML+'" />';
			});
		}
		if ($('h1_myriad')) {
			var element = $('h1_myriad');
			element.innerHTML = '<span style="background-image: url(\'html/php/text-gfx.php?txt='+element.innerHTML+'\')"></span>';
			}
	},
	
	activateAccordion: function() {
		var display_element = 0;
		if ($('debt_recovery_toggler').hasClass('active')) display_element = 1;
		if ($('make_payment_toggler').hasClass('active')) display_element = 2;
		var acordion = new Accordion('.accordion_toggler', '.accordion_element', {
			 display: display_element,
			 opacity: true, 
			 duration: 100, 
			 wait: false, 
             height: true, 
             alwaysHide: true,
             onComplete: function(){
             	if ($('call_center_element').getStyle('visibility') == 'hidden') debt_recovery_margin = '-5px';
             	else debt_recovery_margin = 0;
             	if ($('debt_recovery_element').getStyle('visibility') == 'hidden') make_payment_margin = '-5px';
             	else make_payment_margin = 0;

             	$('debt_recovery_toggler').setStyle('margin-top', debt_recovery_margin);
             	$('make_payment_toggler').setStyle('margin-top', make_payment_margin);
			 }
           });
	},
	
   activateAccordionIe6: function() {
		$('call-centre_toggler').onclick = function(){
			var style = $('call_center_element').getStyle('display');
			if (style == 'block') $('call_center_element').setStyle('display', 'none');
			else $('call_center_element').setStyle('display', 'block');
			$('debt_recovery_element').setStyle('display', 'none');
			$('make_payment_element').setStyle('display', 'none');
		};
		$('debt_recovery_toggler').onclick = function(){
			var style = $('debt_recovery_element').getStyle('display');
			if (style == 'block') $('debt_recovery_element').setStyle('display', 'none');
			else $('debt_recovery_element').setStyle('display', 'block');
			$('call_center_element').setStyle('display', 'none');
			$('make_payment_element').setStyle('display', 'none');
		};
		$('make_payment_toggler').onclick = function(){
			var style = $('make_payment_element').getStyle('display');
			if (style == 'block') $('make_payment_element').setStyle('display', 'none');
			else $('make_payment_element').setStyle('display', 'block');
			$('debt_recovery_element').setStyle('display', 'none');
			$('call_center_element').setStyle('display', 'none');
		};
   },
	
   insertGmaps: function() {
	  if ($('gmap_01') && GBrowserIsCompatible() ) {
		  var map = new GMap2(document.getElementById("gmap_01"));

		  	map.setCenter(new GLatLng(51.896404,-8.442274), 13);
		  	map.addControl(new GSmallMapControl());
		    
		  	var point = new GLatLng(51.896404,-8.442274); 
		  	map.addOverlay(new GMarker(point));
		}
	  if ($('gmap_02') && GBrowserIsCompatible() ) {
		  var map = new GMap2(document.getElementById("gmap_02"));

		  	map.setCenter(new GLatLng(41.212051,-75.900664), 13);
		  	map.addControl(new GSmallMapControl());
		    
		  	var point = new GLatLng(41.212051,-75.900664); 
		  	map.addOverlay(new GMarker(point));
		}
	  if ($('gmap_03') && GBrowserIsCompatible() ) {
		  var map = new GMap2(document.getElementById("gmap_03"));

		  	map.setCenter(new GLatLng(36.537123,-4.624171), 13);
		  	map.addControl(new GSmallMapControl());
		    
		  	var point = new GLatLng(36.537123,-4.624171); 
		  	map.addOverlay(new GMarker(point));
		}
	},
	
	remindPassword: function() {
		if ($('newpass_form_login').value != '' && $('newpass_form_password').value != '') {
			var req = new Request({
				url: 'ajax/request-password', 
				method: 'post',
				data: {'newpass_form_login' : $('newpass_form_login').value,
					   'newpass_form_password' : $('newpass_form_password').value},
				onRequest: function() { 
						   $('newpass_form_btn').disabled = 'disabled';
						   $('ajax-loader-remind').setStyle('display', 'block'); },  
				onComplete: function(response) { 
						   $('ajax-loader-remind').setStyle('display', 'none');
						   $('newpass_form_btn').disabled = '';
						   //window.location.reload();
						   //if (response != 0) window.location.reload();
						   if (response == 0) {
							   $('newpass_form_login').addClass('error');
							   $('newpass_form_password').addClass('error');
						   } else {
							   alert(response);
						   }
				}
			});
			req.send();
		} else {
			if ($('newpass_form_login').value == '') $('newpass_form_login').addClass('error'); 
			if ($('newpass_form_password').value == '') $('newpass_form_password').addClass('error');
		}
	},
	
	activateRemind: function() {
		if ($('new_pass_btn')) {
			if (Browser.Engine.trident4) {
				$('new_pass_btn').onclick = function() { $('newpass_form').setStyle('display', 'block');return false; };
			} else {
				$('new_pass_btn').onclick = function() { return false; };
				var acordion = new Accordion('#new_pass_btn', '#newpass_form', {
					 opacity: true, 
					 duration: 100, 
					 wait: false, 
		             height: true, 
		             alwaysHide: true,
		             display: 1});
			}
			$('newpass_form_btn').onclick = function() { main.remindPassword(); return false; }
		}
	}, // activateRemind
	
	getDirListing: function(node) {
		var myRequest = new Request({
			url: 'ajax/get-dir',
			method: 'post',
			async: true,
			data: {'directory': node.data.title },
			onComplete: function(response) { 
					new_ul = new Element('ul');
					new_ul.innerHTML=response;
					node.clear();
					main.tree.adopt(new_ul,node);
					new_ul.dispose();
				}
			});
		node.clear();
		node.insert(node.control.loader);
		myRequest.send();
	}, // getDirListing
	
	activateTree: function() {
		if ($('tree_listing')) {
			tree = new MooTreeControl({
				div: 'tree_view',
				mode: 'files',
				grid: true,
				onSelect: function(node, state) { if (node.data.rel == 'file') window.location = node.data.title;},
				onExpand: function(node, state) { if (state == true) main.getDirListing(node); }
				},
				{ text: $('tree_listing').title,
				  open: true
				});
			tree.adopt('tree_listing');
			main.tree = tree;
		}
	},
	
	activateBackBtn: function() {
		$$('a.back_btn').each(function(obj){
			obj.onclick = function() { history.back(); return false; }
		});
	},

	showMail: function(user, dmain, contry, attr) {
		var start = "<a href=\"mailto:" + user + "@" + dmain + "." + contry + "\"" + attr + "title=\"" + user + "@" + dmain + "." + contry + "\">";
		var end = "</a>";
		document.write(start + user + "@" + dmain + "." + contry + end);
		return false;
	} // showMail
}); // Main

var NewsScroller = new Class({
	
	activate: function(timeout){
		this.container = $('news_list_short');
		
		if (this.container) this.initScroller(timeout);
	}, // activate
	
	initScroller: function(timeout){
		this.threadTimeout = timeout;
		var li_elem = this.container.getElement('li');
		this.scrollLen = li_elem.getStyle('width').toInt() + li_elem.getStyle('padding-right').toInt();
		var elems_count = this.container.getChildren().length;
		this.container.setStyle('width', this.scrollLen * elems_count);
		this.boxWidth =  elems_count * this.scrollLen;
		this.boxHeight = li_elem.getStyle('height').toInt();
		this.scrollMax = this.boxWidth - this.scrollLen;  

		this.container_clone = this.container.clone();
		this.container_clone.set('id', 'news_list_short_clone');
		this.container_clone.setStyle('margin-left', this.boxWidth);
		this.container_clone.setStyle('margin-top', -this.boxHeight);
		this.container_clone.inject($('news_box'), 'bottom');
		
		this.fx  = new Fx.Tween(this.container, { duration: 'normal',onComplete: function(obj){ newsScroller.scrollBack(obj); }});
		this.fx2 = new Fx.Tween(this.container_clone, { duration: 'normal',onComplete: function(obj){ newsScroller.scrollBack(obj); }});
		
		if (elems_count > 2) this.startThread();
		
		this.container.onmouseover = function(){ newsScroller.killThread(); };
		this.container.onmouseout = function() { newsScroller.startThread(); };
	}, // initScroller
	
	killThread: function() {
		clearInterval(this.threadId);
	}, // killThread
	
	startThread: function() {
		this.threadId = setInterval("newsScroller.scrollIt()",this.threadTimeout);
	}, // restartThread

	scrollIt: function(){
		var pos_x = this.container.getStyle('margin-left').toInt();
		x = pos_x - this.scrollLen;
		var pos_x_clone = this.container_clone.getStyle('margin-left').toInt();
		x_clone = pos_x_clone - this.scrollLen;

		this.fx.start('margin-left', x);
		this.fx2.start('margin-left', x_clone);
	},

	scrollBack:function(obj) {
		if (obj.getStyle('margin-left').toInt() < -(this.scrollMax+2)) {
			obj.setStyle('margin-left', this.boxWidth + 1);
		}
	} // scrollBack
	


}); // NewsScroller

var Fix4ie = new Class({
	initialize: function(){
		if ( Browser.Engine.trident ) {
			this.fixInputFocus();
			this.fixSpanClick();
		}
	
		if ( Browser.Engine.trident4 ) {
			this.fixHovers();
		}
	}, // initialize

	fixInputFocus: function() {
    	var elems = $$('input');  
        elems.each(function(obj) {
            obj.onclick = function() { if (obj.value == obj.title) { obj.value = ''; };this.addClass('focus'); };
            obj.onblur = function()  { if (obj.value == '') { obj.value = obj.title; };this.removeClass('focus'); };
        });
    }, // fixInputFocus

    fixHovers: function() {
    	var elems = $$('input,button,li');  
        elems.each(function(obj) {
            obj.onmouseover = function() {
            	var new_class = this.get('class');
            	if (new_class != '') this.addClass('hover_' + new_class);
            	else this.addClass('hover');
            };
            obj.onmouseout = function()  {
            	var class_name = this.get('class');

            	if (this.hasClass('hover')) this.removeClass('hover');
            	else {
            		class_array = class_name.split(' ');
            		class_array.each(function(element){
            			if (element.match('hover_')) obj.removeClass(element);
            		});
            	}
            };
        });
    }, // fixHovers
    
    fixSpanClick: function() {
    	$$('ul#top_menu li ul li a span img').each(function(obj){
    		obj.onclick = function() { window.location = this.getParent().getParent().href; };
    	});
    }

}); // fix4ie6

var main = new Main();
var newsScroller = new NewsScroller();

window.addEvent('domready', function(){ main.domReady(); });

