


var WebSiteMain = new Class({
	
	languageId: null,
	templateId: null,
	currentSection: null,
	
	allContainerElement: null,
	
	contentElement: null,
	containerElement: null,
	containerInitHeight: null,

	initialize: function() {
		window.addEvent('domready', this.onDOMReady.bind(this));
		window.addEvent('resize', this.onResize.bind(this));
		window.addEvent('scroll', this.onResize.bind(this));
		
		if(!window.console || !window.console.log) {
			window.console = {};
			window.console.log = function(str) { window.webSiteMain.writeToConsole(str); }
			window.console.debug = function(str) { window.webSiteMain.writeToConsole(str); }
		}
	},
	
	writeToConsole: function(str) { /*$('consol').set('html', $('consol').get('html') + "<br />\n" + str); */},
	
	
	onDOMReady: function() { 
		
		var htmlParams = $('allContainer').get('class').split(' ');
		htmlParams.each(function(param) {
			param = param.split('-');
			switch(param[0]) {
				case 'template': this.templateId = parseInt(param[1]); break;
				case 'lang': this.languageId = parseInt(param[1]); break;
			}
		}, this);
		
		this.allContainerElement = $('allContainer');
		//console.debug(this.allContainerElement);
		this.containerElement = $('contentContainer');
		this.contentElement = $('content');
		
		this.menu = new WebSiteMenu(this.languageId);
		
		
		switch(this.templateId) {
			case 1:
			case 2: 
			case 4: this.currentSection = new ProjectsSection(this.contentElement, this.templateId); break;
			case 5: this.currentSection = new ClientsSection(this.contentElement, this.templateId); break;
			case 6: this.currentSection = new LoginSection(this.contentElement, this.templateId); break;
		}
		
		
		// if the section innter content changes height, the bruto height should be re-calculated
		if(this.currentSection) this.currentSection.addEvent('resize', this.updateContentHeight.bind(this));
		
		// calculate the initial height of the content
		this.updateContentHeight();
	},
	
	
	updateContentHeight: function() {
		$('allContainer').addClass('autoHeight');
		this.containerElement.addClass('autoHeight');
		
		this.containerInitHeight = this.containerElement.getSize().y;
		/*console.log('---- Current Content height: ' + this.containerInitHeight);
		console.log('---- Current Window height: ' + window.getSize().y);
		console.log('---- Current Window Scroll height: ' + window.getScrollSize().y);
		console.log('---- Current Window scroll: ' + window.getScroll().y);*/
		
		$('allContainer').setStyle('height', this.containerInitHeight);
		$('allContainer').removeClass('autoHeight');
		this.containerElement.removeClass('autoHeight');
		
		this.onResize();
	},
	
	onResize: function() {
		if(this.allContainerElement) { // element for some reason sometimes is not defined!!!
			var newHeight = parseInt(window.getScroll().y) + parseInt(window.getSize().y);
			//console.log('new height: ' + newHeight);
			if(newHeight > this.containerInitHeight) {
				if(!this.allContainerElement.hasClass('autoHeight')) this.allContainerElement.addClass('autoHeight');
			} else {
				if(this.allContainerElement.hasClass('autoHeight')) this.allContainerElement.removeClass('autoHeight');
			}
			this.containerElement.setStyle('height', newHeight);
		}
	}
	
	
	
	
	
	
});

var webSiteMain = new WebSiteMain();




  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 /////////////    WEB SITE MENU      ////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var WebSiteMenu = new Class({

	Extends: Swiff,
	
	languageId: null,
	menuLinks: [],
	selectedMenuId: null,
	
	initialize: function(langId) {
		this.languageId = langId;
		
		$$('a.menuLink').each(function(item) {
			var id = item.id.substr(5);
			this.menuLinks[id] = item.href;
			if(item.getParent('li').hasClass('selected')) this.selectedMenuId = id;
		}.bind(this));
		
		var menuVersion = $('headerFlash').get('class').split('-')[1];
		
		if(Browser.Plugins.Flash.version >= 9) {
			this.parent('/_content/deep-white-top-' + menuVersion + '_' + this.languageId + '.swf', {
			    id: 'headerFlashObj',
			    container: 'headerFlash',
			    width: '100%',
			    height: '100%',
			    params: {
			        wmode: 'opaque',
			        /*bgcolor: '#FFFFFF',*/
					/*salign: 'TL',
					aling: 'L',*/
					scale: 'noscale'
			    },
			    vars: {
			        selectedMenuNum: this.selectedMenuId
			    }
			    /*callBacks: {
			        load: myOnloadFunc
			    }*/
			});
		} else {
			$('headerMenu').setStyle('visibility', 'visible');
		}
	},
	
	
	// called from flash
	navigate: function(menuId) {
		//console.debug(menuId);
		window.location = this.menuLinks[menuId];
	}
	
	
});




  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 /////////////    PROJECTS SECTION    ///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var ProjectsSection = new Class({
	
	Implements: Events,
	
	templateId: null,
	
	contentElement: null,
	contentWidth: null,
	
	itemWidth: 250,
	itemMargin: 24,
	
	initialize: function(cEl, templateId) {
		
		this.templateId = templateId;
		this.contentElement = cEl;
		this.contentWidth = parseInt(cEl.getSize().x);
		
		// init galleries
		this.images_init();
		
		// init "read more" and "close links"
		this.openClose_init();
		
		this.textBlock_init();
	},
	
	images_init: function() {
		this.milkbox = new SuperMilkbox({ topPosition: 20 });
		
		if(this.templateId != 4) // for peoples list do not allow bigger sized images
			this.contentElement.getElements('.images .image').addEvent('click', this.images_onClick.bindWithEvent(this));
	},
	images_onClick: function(event) {
		event.stop();
		
		var hrefList = [];
		//$(event.target).getParent('.images').getElements('a').each(function(el) { hrefList.push([el.get('href')]); });
		//Slimbox.open(hrefList, 0);
		
		var gallName = $(event.target).getParent('.images').getElement('a').getProperty('rel').substr(8);
		this.milkbox.showGallery({ gallery: gallName });
	},
	
	
	
	openClose_init: function() {
		this.openClose_listScrollFx = new Fx.Scroll(this.contentElement.getParent(), {
			'duration': 500,
			'transition': Fx.Transitions.Sine.easeInOut
		});
		this.openClose_bodyScrollFx = new Fx.Scroll($(document.body), {
			'duration': 500,
			'transition': Fx.Transitions.Sine.easeInOut
		});
		
		this.contentElement
			.getElements('a.readMoreLink')
			.addEvent('click', this.readMore_onMoreClick.bindWithEvent(this));
			
		this.contentElement
			.getElements('div.intro')
			.addEvent('mouseenter', this.openClose_onMouseOver.bindWithEvent(this))
			.addEvent('mouseleave', this.openClose_onMouseOut.bindWithEvent(this))
			.addEvent('click', this.openClose_onClick.bindWithEvent(this))
			
		this.contentElement
			.getElements('div.intro a')
			.addEvent('mouseenter', this.openClose_onLinkMouseOver.bindWithEvent(this))
			.addEvent('mouseleave', this.openClose_onLinkMouseOut.bindWithEvent(this))
			
		this.contentElement
			.getElements('a.readLessLink')
			.addEvent('click', this.readMore_onLessClick.bindWithEvent(this));
	},
	
	openClose_onMouseOver: function(event) {
		var target = $(event.target);
		if(target.get('tag') != 'div' || !target.hasClass('intro')) target = target.getParent('div.intro');
		target.addClass('hover');
	},
	openClose_onMouseOut: function(event) {
		var target = $(event.target);
		if(target.get('tag') != 'div' || !target.hasClass('intro')) target = target.getParent('div.intro');
		target.removeClass('hover');
	},
	openClose_onClick: function(event) {
		var target = $(event.target);
		if(target.get('tag') != 'div' || !target.hasClass('intro')) target = target.getParent('div.intro');
		if(target.hasClass('hover')) {
			this.readMore_onMoreClick(event);
		}
	},
	
	openClose_onLinkMouseOver: function(event) {
		var target = $(event.target).getParent('div.intro');
		target.removeClass('hover');
	},
	openClose_onLinkMouseOut: function(event) {
		var target = $(event.target).getParent('div.intro');
		target.addClass('hover');
	},
	
	
	
	readMore_onMoreClick: function(event) {
		event.stop();
		var target = $(event.target);
		this.readMore_open(target.getParent('.project'));
	},
	readMore_onLessClick: function(event) {
		event.stop();
		var target = $(event.target);
		this.readMore_close(target.getParent('.project'));
	},
	readMore_open: function(project) {
		if(!project.hasClass('projectOpened') && project.getElement('a.readMoreLink')) {
			project.addClass('projectOpened');
			this.adjustContentWidth(this.itemWidth + this.itemMargin);
			this.fireEvent('resize');
			project.tween('width', this.itemWidth * 2 + this.itemMargin);
			this.openClose_listScrollFx.start(project.getPosition(this.contentElement).x - this.contentElement.getStyle('paddingLeft').toInt(), 0);
		}
	},
	readMore_close: function(project) {
		project.tween('width', this.itemWidth)
			   .get('tween')
			   .chain(this.readMore_closeDone.bind(this, [ project ]));
		this.openClose_bodyScrollFx.start(null, 0);
		this.openClose_listScrollFx.start(project.getPosition(this.contentElement).x - this.contentElement.getParent().getSize().x / 2 + 125, 0);
	},
	readMore_closeDone: function(project) {
		project.removeClass('projectOpened');
		this.adjustContentWidth(-this.itemWidth - this.itemMargin);
		this.fireEvent('resize');
	},
	
	
	
	textBlock_init: function() {
		this.textBlock = $('textBlock');
		if(this.textBlock) {
			this.textBlock.getElements('a.textReadMoreLink').addEvent('click', this.textBlock_onReadMoreClick.bindWithEvent(this));
			//this.textBlock.getElements('.textReadMore').reveal();
			this.textBlock.getElements('.textRemainder')
						  .set('reveal', { onComplete: this.textBlock_onReadMoreComplete.bind(this) })
						  .dissolve();
			
		}
	},
	
	textBlock_onReadMoreClick: function(event) {
		event.stop();
		var link = $(event.target).getParent('.textReadMore');
		var remainder = link.getParent('.textIntro').getNext('.textRemainder');
		this.textBlock.getElements('.textRemainder').each(function(el) {
			if(el == remainder) {
				el.reveal();
			} else {
				el.dissolve();
			}
		});
		this.textBlock.getElements('.textReadMore').each(function(el) {
			if(el == link) {
				el.setStyle('display', 'none');
				//el.dissolve();
			} else {
			//	el.reveal();
				el.setStyle('display', 'inline');
			}
		})
		
	},
	
	textBlock_onReadMoreComplete: function() {
		this.fireEvent('resize');
	},
	
	
	
	
	
	adjustContentWidth: function(widthAdjustment) {
		//console.log('DW: adding ' + widthAdjustment + ' to the width');
		this.contentWidth += widthAdjustment;
		this.updateContentWidth();
	},
	
	updateContentWidth: function() {
		this.contentElement.setStyle('width', (parseInt(this.contentWidth) + this.itemMargin) + 'px');
		//console.log('DW: content element width: ' + this.contentElement.getSize().x);
	}
	
	
	
	
	
	
	
});



  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 /////////////    CLIENTS SECTION    ////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var ClientsSection = new Class({
	
	Implements: Events,
	
	templateId: null,
	
	contentElement: null,
	contentWidth: null,
	
	initialize: function(cEl, templateId) {
		
		this.templateId = templateId;
		this.contentElement = cEl;
		this.contentWidth = parseInt(cEl.getSize().x);
		
		// hovers
		this.contentElement
			.getElements('.client em')
			.addEvent('mouseover', this.client_onMouseOver.bindWithEvent(this))
			.addEvent('mouseleave', this.client_onMouseOut.bindWithEvent(this));
	},
	
	client_onMouseOver: function(event) {
		event.stop();
		var target = $(event.target);
		if(target.get('tag') != 'em' && target.getParent().get('tag') == 'em') target = target.getParent();
		if(target.get('tag') == 'em') {
			target.set('tween', {duration: 100}).fade('in');
		}
	},
	client_onMouseOut: function(event) {
		event.stop();
		var target = $(event.target);
		console.debug('out', target);
		if(target.get('tag') != 'em') target = target.getParent('em');
		target.set('tween', {duration: 500}).fade('out').get('tween').chain(function() { target.setStyle('visibility', 'visible') });
	}
	

	
});





  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 /////////////    LOGIN SECTION    //////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var LoginSection = new Class({
	
	Implements: Events,
	
	templateId: null,
	
	contentElement: null,
	form: null,
	
	initialize: function(cEl, templateId) {
		
		this.templateId = templateId;
		this.contentElement = cEl;
		this.form = $('clientsLoginForm');
		this.form.addEvent('submit', this.onFormSubmit.bindWithEvent(this));
		
		new OverText($('clientUserName'), { poll: true });
		new OverText($('clientPassword'), { poll: true });
	},
	
	onFormSubmit: function(event) {
		event.stop();
		this.submitData();
	},
	
	submitData: function() {
		this.form.getElements('input').set('disabled', 'disabled');
		$('clientsLogin').removeClass('unlocked');
		var clientName = $('clientUserName').get('value');
		var clientPass = $('clientPassword').get('value');
		new Request({
			url: '/client-auth/',
			noCache: true,
			method: 'post',
			onComplete: this.submitDataComplete.bind(this)
		}).send($H({ 'client_data': MD5(clientName) + MD5(clientPass) }).toQueryString());
	},
	
	submitDataComplete: function(data) {
		this.form.getElements('input').set('disabled', '');
		if(data.substr(0, 5) == 'error') {
			alert(data.substr(8));
		} else {
			$('clientsLogin').addClass('unlocked');
			window.location = data;
		}
	}

	
});





  ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
 /////////////    SUPER MILK BOX     ////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var SuperMilkbox = new Class({
	
	Extends: Milkbox,
	
	initialize: function(options) {
		this.parent(options);
		
	},
	
	
	// override loadImage
	// the original loadImage creates an IMG element
	// here we create a DIV element with a background
	// and add a click event to proceed to the next image
	
	
	loadImage:function(file) {
		var imageAsset = new Asset.image(file, { onload:function(img){
			if(!this.loadedImages.contains(file)){ this.loadedImages.push(file); };//see next/prev events
			
			//console.debug(img, img.get('width'));
			
			this.currentFile = new Element('DIV', {
				'class': 'image',
				'styles': {
					'background-image': 'url(' + img.get('src') + ')',
					'width': img.get('width') + 'px',
					'height': img.get('height') + 'px'
				},
				'width': img.get('width'),		// also add properties width and height, for
				'height': img.get('height'),	// compatibility with Milkbox superclass
				'events': {
					'click': this.next_prev_aux.bindWithEvent(this,'next')
				}
			});
			//console.debug(this.currentFile);
			
			
			this.loadAux(this.currentFile);
		}.bindWithEvent(this)});
	},
	
	
	// override loadSwf
	// to check the URL for "?" and add the right side of it as flashVars
	
	loadSwf:function(swf){
		var href = swf.retrieve('href').split('?');
		var flashVars = {};
		if(href[1]) flashVars = String(href[1]).parseQueryString();
		

		var swfObj = new Swiff(href[0], {
			width: swf.retrieve('width').toInt(),
			height: swf.retrieve('height').toInt(),
			params: { 
				wMode:'opaque', 
				swLiveConnect:'false',
				FlashVars: href[1] //Hash.toQueryString(flashVars)
			}/*
			vars: flashVars*/
		});
		
		this.currentFile = swfObj;
		this.loadAux(swf);
	},
	
	
	// override prepareHTML
	// place navigation behind canvas
	
	prepareHTML:function(){		
		
		//console.debug('SuperMilkBox: create elements');
		
		this.overlay = new Element('div', { 'id':'mbOverlay','styles':{ 'opacity':0,'visibility':'visible','height':0,'overflow':'hidden' }}).inject($(document.body));
		
		this.center = new Element('div', {'id':'mbCenter', 'styles':{
			'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2),'opacity':0 
		}}).inject($(document.body));
		
		
		// navigation (before canvas element to put it behind it
		this.navigation = new Element('div',{'id':'mbNavigation'}).setStyle('visibility','hidden').inject($(document.body));
		this.next = new Element('a',{'id':'mbNextLink', href:"#"});
		this.prev = new Element('a',{'id':'mbPrevLink', href:"#"});
		this.playpause = new Element('a',{'id':'mbPlayPause'});
		this.navigation.adopt(this.next, this.prev, this.playpause, new Element('div',{'class':'clear'}), this.count);
		
		this.close = new Element('a',{'id':'mbCloseLink', href:"#"}).inject(this.center);
		
		// image/video container
		this.canvas = new Element('div', {'id':'mbCanvas'}).inject(this.center);
		
		
		// bottom
		this.bottom = new Element('div',{'id':'mbBottom'}).inject(this.center).setStyle('visibility','hidden');
		this.description = new Element('div',{'id':'mbDescription'}).setStyle('visibility','hidden');
		this.count = new Element('span',{'id':'mbCount'});
		this.bottom.adopt(this.description, this.count, new Element('div',{'class':'clear'}));

		$$(this.next, this.prev, this.count, this.playpause).setStyle('display','none');
	}
	
	
});



