window.addEvent('load', function(){
	forceLogin();
	
	initMainMenu();	
	//
	initPhotoGallery();	
	//Blog Slider
	initBlogSlider();
	initAjaxLoadContent();
	initConsulterBtn();
	
});

function forceLogin(){
	if(flag_login){
		showHideDiv('loginForm' , 1);
	}
}

///////////////////////////////////////////////////////////////////////
//Blog Slider
///////////////////////////////////////////////////////////////////////
function initBlogSlider(){
	var aULTagContainer = $('blogSlider');
	if (!aULTagContainer){
		return;
	}	
		
	var aULTag = aULTagContainer.getElement('li.slideCover').getElement("ul");
	var arrLITags = aULTag.getElements("li");
	var WIDTH = arrLITags[0].getCoordinates().width;
		
	var prevButton = aULTagContainer.getElement('a.prev');
	var nextButton = aULTagContainer.getElement('a.next');
	if(arrLITags.length <= 1){
		prevButton.setStyle('visibility', 'hidden');
		nextButton.setStyle('visibility', 'hidden');
		return;
	}
	
	
	prevButton.addEvent("click", function(evt) {
		evt.stop();
		
		showImage(currentImage - 1);
	});
	
	
	nextButton.addEvent("click", function(evt) {
		evt.stop();
		
		showImage(currentImage + 1);
	});
	
	
	// slider effect
	var fxScroll = new Fx.Morph(aULTag, {
		duration: 500,
		transition: Fx.Transitions.linear,
		
		onComplete: function() {
			isMoving = false;
		}
	});
	
	var isMoving = false;
	var currentImage = 0;
	
	function showImage(index) {
		if (index < 0 || index >= arrLITags.length) {
			return;
		}

		if (isMoving) {
			return;
		}
		isMoving = true;
		
		currentImage = index;
		if (currentImage > 0) {
			prevButton.setStyles({
				opacity: 1,
				background: '',
				cursor: 'pointer'
			});
		} else {
			prevButton.setStyles({
				opacity: 0.5,
				background: '#ebe9ea',
				cursor: 'default'
			});
		}
		
		if (currentImage < arrLITags.length - 1) {
			nextButton.setStyles({
				opacity: 1,
				background: '',
				cursor: 'pointer'
			});
		} else {
			nextButton.setStyles({
				opacity: 0.5,
				background: '#e0dedf',
				cursor: 'default'
			});
		}
		
		fxScroll.start({
			"margin-left": -currentImage * WIDTH
		});
	}
	
	showImage(0);
}

//////////////////////////////////////////////
//Init Main Menu
//////////////////////////////////////////////
// var for select box
var mustHide = false;
function initMainMenu() {
	// validate conditions
	var arrLITags = $('lev').getElements('li.menu');
	if (arrLITags.length == 0) {
		return;
	}
	
	// add event listener for each main menu
	arrLITags.each(function(aLi, index) {
		var aDiv = aLi.getElement('a').getNext();
		if (aDiv) {
			aLi.getElement('a').aDiv = aDiv;
			var _closeSM = aDiv.getElement('a.closeSubMenu');
			if(_closeSM) _closeSM.addEvent('click', function(e){
				e.stop();				
				//aDiv.aLink.getElement("img").reset();
				aDiv.aLink.aDiv.setStyle("left", -1000);
			});
			aLi.getElement('a').addEvents({
				mouseenter: function(evt) {
					evt.stop();
					showSubMenu(this);
				},
				
				mouseleave: function(evt) {
					evt.stop();					
					var self = this;
					activeMenu = null;
					setTimeout(function() {
						hideSubMenu(self);
					}, 10);
				}
			});
			
			aDiv.aLink = aLi.getElement('a');
			aDiv.inject(document.body);
			if(index == 0 && Browser.Engine.trident5) {
				if(aDiv.getElement('li').getCoordinates().width > 170) {
					_width = 185;
				} else {
					_width =  aDiv.getElement('li').getCoordinates().width + 30;
				}
				aDiv.setStyle('width' , _width);
			}
			aDiv.addEvents({			
				mouseenter: function(evt) {
					evt.stop();
					showSubMenu(this.aLink);
				},
				
				mouseleave: function(evt) {
					evt.stop();
					
					var self = this;
					activeMenu = null;
					setTimeout(function() {
						if(mustHide) return;
						hideSubMenu(self.aLink);
					}, 50);
				},
				
				click: function(evt){
                    var tObj = evt.target;
					if(tObj.tagName != 'A'){                                            
                        if(tObj.type != 'submit')                        
						    evt.stop();
                    }
				}
			});
		}
	});
	
	var activeMenu = null;
	var timeoutId = null;
	
	function showSubMenu(aLinkTag) {
		activeMenu = aLinkTag;
		//activeMenu.getElement("img").setSelected();
		aLinkTag.getParent().addClass('active');		
		//alert(activeMenu.aDiv.getElement('li').getCoordinates().width +';'+ activeMenu.aDiv.getElement('ul').getCoordinates().width)
		if(Browser.Engine.trident4) {
			activeMenu.aDiv.setStyle("left", activeMenu.getCoordinates().left - 2);			
		} else {			
			activeMenu.aDiv.setStyles({
				"left": activeMenu.getCoordinates().left
			});
		}
		
	}

	function hideSubMenu(aLinkTag) {
		if (activeMenu == aLinkTag) {
			return;
		}
        if($$('.selScrollContent').length){
		    $$('.selScrollContent').each(function(item){
             item.setStyle('display', 'none');
              item.getNext().setStyle('display', 'none');
           });
        }    
            
		//aLinkTag.getElement("img").reset();
		aLinkTag.aDiv.setStyle("left", -1000);
		aLinkTag.getParent().removeClass('active');
	}
}

function initPhotoGallery() {
	// image width
	var WIDTH = 157;
	
	// validate conditions
	var aDivContainer = $('slideImgContainer');
	if (!aDivContainer) {
		return;
	}
	
	var aULTag = aDivContainer.getElement("ul");
	aULTag.setStyle("float", "none");
	
	var arrLITags = aULTag.getElements("li");	
	if (arrLITags.length < 5) {
		for (var i = 0; i < arrLITags.length; i++) {
			arrLITags[i].clone().inject(aULTag);
		}
	}
	arrLITags = aULTag.getElements("li");
	
	// add event for back button
	aDivContainer.getPrevious().addEvent('click', function(evt) {
		evt.stop();
		moveSlider(true);
	});
	
	// add event for next button
	aDivContainer.getNext().addEvent('click', function(evt) {
		evt.stop();
		moveSlider();
	});
	var nextNode;
	// slider effect
	var fxScroll = new Fx.Morph(aULTag, {
		duration: 500,
		transition: Fx.Transitions.linear,
		
		onComplete: function() {
			isMoving = false;
			if(nextNode.getElement("img").getNext())
				nextNode.getElement("img").getNext().setStyle('display', 'block');			
		}
	});
	
	// create zoom effect for all image
	aULTag.getElements("img").each(function(aImage) {
		aImage.fx = new Fx.Morph(aImage, {
			duration: 500,
			transition: Fx.Transitions.linear			
		});
		
		aImage.setStyle("margin-top", 80);
	});
	
	// calculate center position
	var paddingLeft = -Math.floor((arrLITags.length - 3) / 2) * WIDTH;
	if (arrLITags.length % 2 == 0) {
		paddingLeft -= WIDTH;
	}
	
	// this variable is used to make sure only one move at a time
	var isMoving = false;
	
	// move slider
	function moveSlider(toLeft) {
		// only one move at a time
		if (isMoving) {
			return;
		}
		isMoving = true;
		
		// determine moving distance
		var distance = WIDTH;
		
		// node to be applied effect
		var centerNode = arrLITags[Math.floor(arrLITags.length / 2)];
		//var nextNode;
		
		if (toLeft) {
			arrLITags[arrLITags.length - 1].inject(aULTag, "top");
			distance = -distance;
			nextNode = centerNode.getPrevious();
		} else {
			arrLITags[0].inject(aULTag);
			nextNode = centerNode.getNext();
		}
		
		// move slider
		fxScroll.set({
			"margin-left": paddingLeft + distance
		}).start({
			"margin-left": [paddingLeft + distance, paddingLeft]			
		});
		
		// make it smaller
		centerNode.getElement("img").fx.start({
			width: 122,
			height: 172,
			'margin-top': [0, 80],
			onComplete: function(){
				if(centerNode.getElement("img").getNext())
					centerNode.getElement("img").getNext().setStyle('display', 'none');
			}
		});
		
		// make it bigger
		nextNode.getElement("img").fx.start({
			width: 228,
			height: 319,
			'margin-top': [80, 0]					
		});
		
		// reset array
		arrLITags = aULTag.getElements("li");
	}
	
	// show center image
	moveSlider();
}

function showHideDiv(div, i){
	
var aDiv = $(div);
	window.removeEvents("scroll");
	
	if (i == 1) {
		if($('overLay'))
			$('overLay').setStyle('display', 'block');
			
		if (showHideDiv.lastPopup) {
			showHideDiv(showHideDiv.lastPopup, 0);
		}
		showHideDiv.lastPopup = div;
		
		if (aDiv.hasClass("hidden")) {
			aDiv.removeClass("hidden");
			aDiv.addClass("hidden1");
			return;
		}
		if(aDiv.id == 'friendLayer'){
			$('frmFriend').reset();
			$('frmFriend').getNext().setStyle('display', 'none');
			$('frmFriend').setStyle('display', 'block');			
		}
		var divCoordHeight = aDiv.getCoordinates().height;
		var divCoordWidth = aDiv.getCoordinates().width;
		var _divInside = aDiv.getElement('div');
		if(_divInside){
			divCoordHeight = _divInside.getCoordinates().height;
			divCoordWidth = _divInside.getCoordinates().width;
		}
		
		if(Browser.Engine.trident4){
			aDiv.setStyle('position', 'absolute');
			aDiv.setStyles({
				display: "block",
				top: (window.getCoordinates().height - divCoordHeight) / 2 + window.getScrollTop(),
				left: (window.getCoordinates().width - divCoordWidth) / 2
			});
			
			window.addEvent("scroll", function() {
				aDiv.setStyles({
					top: (window.getCoordinates().height - divCoordHeight) / 2 + window.getScrollTop()
				});
			});
		}
		else{
			aDiv.setStyle('position', 'fixed');
			aDiv.setStyles({
				display: "block",
				top: (window.getCoordinates().height - divCoordHeight) / 2,
				left: (window.getCoordinates().width - divCoordWidth) / 2
			});
			
			window.addEvent("scroll", function() {
				aDiv.setStyles({
					top: (window.getCoordinates().height - divCoordHeight) / 2
				});
			});
		}
	} else {		
		//close popup
		if(flag_login) {		
			var return_page = $('return_page');
			if(return_page){
				window.location = $('return_page').value;
			}
			return;
		}
		if(div != 'loginForm'){
			aDiv.setStyles({
				top: -1500
			});
		}
		
		if($('overLay')) {
			$('overLay').setStyle('display', 'none');
			showHideDiv.lastPopup = null;
		}
		
		
		if (aDiv.hasClass("hidden1")) {
			aDiv.removeClass("hidden1");
			aDiv.addClass("hidden");
			return;
		}
	}
}


function showHideDiv2(div, i){
	var aDiv = $(div);
	if(!aDiv){
		return;
	}
	window.removeEvents("scroll");	
	if (i == 1) {
		var newADiv = aDiv.inject($$('body')[0]);				
		showHideDiv2.lastPopup = newADiv;
		showHideDiv2.lastPopup.removeClass('hidden');
		var divCoordHeight = newADiv.getCoordinates().height;
		var divCoordWidth = newADiv.getCoordinates().width;
		var _divInside = newADiv.getElement('div');
		if(_divInside){
			divCoordHeight = _divInside.getCoordinates().height;
			divCoordWidth = _divInside.getCoordinates().width;
		}
		if(Browser.Engine.trident4){
			newADiv.setStyle('position', 'absolute');
			newADiv.setStyles({
				display: "block",
				top: (window.getCoordinates().height - divCoordHeight) / 2 + window.getScrollTop(),
				left: (window.getCoordinates().width - divCoordWidth) / 2
			});
			
			window.addEvent("scroll", function() {
				newADiv.setStyles({
					top: (window.getCoordinates().height - divCoordHeight) / 2 + window.getScrollTop()
				});
			});
		}
		else{
			newADiv.setStyle('position', 'fixed');
			newADiv.setStyles({
				display: "block",
				top: (window.getCoordinates().height - divCoordHeight) / 2,
				left: (window.getCoordinates().width - divCoordWidth) / 2
			});
			
			window.addEvent("scroll", function() {
				newADiv.setStyles({
					top: (window.getCoordinates().height - divCoordHeight) / 2
				});
			});
		}
		
	} else {		
		if(aDiv){		
			aDiv.setStyles({				
				'position': 'absolute',
				'top': -1500,
				'left': -1500
			});
		}
		/*
		if(showHideDiv2.lastPopup){
			showHideDiv2.lastPopup.addClass("hidden");
		}
		*/	
	}
}

function initConsulterBtn(){
	var consulterBtn =$('consulterBtn');
	if(!consulterBtn) return;
	consulterBtn.addEvent('click', function(e){
		new Event(e).stop();
		showHideDiv2('fileView' , 1);
	});
}

function initAjaxLoadContent(){
	
	var btnConsulterResets =  $$('a.btnConsulterReset');
	if(btnConsulterResets.length){
		btnConsulterResets.each(function(btnConsulterReset){
			btnConsulterReset.addEvent('click', function(e){
				e.stop();
				$('frmParam').getElement('input[name=paging]').set('value', 1);
				loadAjaxContent($('frmParam').action, btnConsulterReset.getParent('form'), $('itemResultContainer'));
			});
		});
	}
	
	var aLinks =  $$('a.btnConsulter');
	if(aLinks.length){
		aLinks.each(function(aLink){
			aLink.addEvent('click', function(e){
				e.stop();
				loadAjaxContent(aLink.getParent('form').action, aLink.getParent('form'), $('itemResultContainer'));
			});
		});
	}
	
	var pagings = $$('ul.paging');
	if(pagings.length){
		pagings[0].getElements('li').each(function(paging){
			paging.removeEvents('click').addEvent('click', function(e){
				e.stop();
				$('frmParam').getElement('input[name=paging]').set('value', this.getElement('a').className);
				loadAjaxContent($('frmParam').action, $('frmParam'), $('itemResultContainer'));
			});
		});
	}
	/*
	var sortDate = $('sortDate');
	if(sortDate){
		sortDate.addEvent('click', function(e){
			e.stop();
			if(sortDate.hasClass('date')){
				sortDate.removeClass('date').addClass('date2');	
				$('frmParam').getElement('input[name=sortType]').value = 'ASC';
			}
			else{
				sortDate.removeClass('date2').addClass('date');	
				$('frmParam').getElement('input[name=sortType]').value = 'DESC';
			}
			loadAjaxContent($('frmParam').action, $('frmParam'), $('itemResultContainer'));
		});
	}*/
	var itemLesResources = $('itemLesResources');
	if(itemLesResources){
		itemLesResources.getElements('a').each(function(aLink){
			aLink.addEvent('click', function(e){
				e.stop();
				loadAjaxContent2(this.href,  $('itemResultContainer'));
			});
		});
	}
	
}

function loadAjaxContent(url, postParams, updater){
	new Request.HTML({
		url: url,
		update: updater,
		onRequest: function(){
			
			new Element('div', {
				'class': 'loading',
				'html': '<div style="width: 100%; text-align: center; margin: 30px 0 0 0;">'+				
							'<img src="../images/loading.gif" border="0"/>' +
						'</div>'
			}).inject(updater.empty());
		},
		onComplete: function(){
			var pagings = $$('ul.paging');
			if(pagings.length){
				pagings[0].getElements('li').each(function(paging){
					paging.removeEvents('click').addEvent('click', function(e){
						e.stop();
						$('frmParam').getElement('input[name=paging]').set('value', this.getElement('a').className);
						loadAjaxContent($('frmParam').action, $('frmParam'), $('itemResultContainer'));
					});
				});
			}
		}
	}).post(postParams);	
}

function loadAjaxContent2(url, updater){
	new Request.HTML({
		update: updater,
		onRequest: function(){
			new Element('div', {
				'class': 'loading',
				'html': '<div style="width: 100%; text-align: center; margin: 30px 0 0 0;">'+				
							'<img src="../images/loading.gif" border="0"/>' +
						'</div>'
			}).inject(updater.empty());
		},
		onComplete: function(){
			var pagings = $$('ul.paging');
			if(pagings.length){
				pagings[0].getElements('li').each(function(paging){
					paging.removeEvents('click').addEvent('click', function(e){
						e.stop();
						$('frmParam').getElement('input[name=paging]').set('value', this.getElement('a').className);
						loadAjaxContent($('frmParam').action, $('frmParam'), $('itemResultContainer'));
					});
				});
			}
		}
	}).get(url);	
}

function checkAuthentication(url){	
	new Request.HTML({
		onComplete: function(){
			//alert(arguments[2]);
			if(arguments[2].toInt() == 0){
				showHideDiv('loginForm' , 1);
				var locHask = location.hash;
				if(!locHask){
					window.location = window.location + '#top';
				}				
				else{
					window.location = window.location;
				}
				$('autoDownload').value = url;
			}
			else{
				window.location.href = url;	
			}
		}
	}).get('/authentication');	
	return false;
}
