

Element.implement({
	getIndex: function(type) {
        type = (type) ? type : '';
        return $$(type).indexOf(this);
    },

	exists: function() {
        return (this.getIndex() >= 0);
    },

	getClassStoredValue: function(varName) {
		var c = this.get('class').split(' ');
		for(var i = 0; i < c.length; i++) {
			if(c[i].substr(0, c[i].indexOf('-')) == varName) {
				return c[i].substr(c[i].indexOf('-') + 1);
			}
		}
		return null;
	},
	
	setClassStoredValue: function(varName, varValue) {
		var c = this.get('class').split(' ');
		var curValue = this.getClassStoredValue(varName);
		if(curValue) {
			this.removeClass(varName + '-' + curValue);
		}
		this.addClass(varName + '-' + varValue);
	}
});



var WebSiteMain = new Class({

	templateId: null,
	sectionPath: '/',
	
	allContainerElement: null,

	initialize: function() {
		window.addEvent('domready', this.onDOMReady.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 body = $$('body')[0];
		this.templateId = parseInt(body.getClassStoredValue('template'));
		this.rootPath = body.getClassStoredValue('root');
		this.sectionPath = body.getClassStoredValue('section');
		
		this.allContainerElement = $('allContainer');
		this.menu = new WebSiteMenu();
	
		// fill the empty container rows with "-"...
		this.fillEmptyRows();
		
		// projects...
		if(this.templateId == 15 || this.templateId == 16) { // main page or projects section
			this.projectsSection_init();
		} else if(this.templateId == 18) {
			this.contactsSection_init();
		}

		// input fields in the contact section...
		$$('.overText').each(function(item) {
			new OverText(item, { 'poll': true, 'positionOptions': { 'offset': { x: 8, y: 1}} });
		});
	},
	
	
	// for each element that needs filling with dashes, measure difference between the actual height and CSS set height and
	// fill the remainder with the appropriate amount of lines of "-"
	fillEmptyRows: function() {
		$$('.dashAutoFill').each(function(el) {
			this.fillEmptyRowsForElement(el);
		}, this);
	},
	fillEmptyRowsForElement: function(el) {
		var numTotalRows = el.getClassStoredValue('numRows');
		var lineHeight = parseInt(el.getStyle('line-height'));
		var testEl = new Element('div', { 'class': 'textQuartTest', 'styles': {  }, 'html': el.get('html') }).inject(this.allContainerElement);
		var testElHeight = testEl.getSize().y;
		testEl.destroy();
		
		var numRowsToAdd = (lineHeight * numTotalRows - testElHeight) / lineHeight;
		var str = '';
		for(var i = 0; i < numRowsToAdd; i++) str += '<p class="f">-</p>';
		el.set('html', el.get('html') + str);
	},
	
	repairFooter: function() {
		$('footerPadding').setStyle('display', 'none');
		$('footer').setStyle('display', 'none');
		this.repairFooterDone.delay(100, this);
	},
	repairFooterDone: function() {
		$('footerPadding').setStyle('display', 'block');
		$('footer').setStyle('display', 'block');
	},
	
	
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	
	projectsSection_init: function() {
		var bprojectsList_init = true;
		
		this.projectMainArea_init();
		
		if(bprojectsList_init)
			this.projectsList_init();
	},
	
	
	
	
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	
	// inits the main area, loading the project flash, managing the image navigation etc.
	// call this whenever loading a project page
	projectMainArea_init: function() {
		this.projectMainArea = $('mainArea');
		if(this.projectMainArea) {
			this.projectId = this.projectMainArea.getClassStoredValue('pId');
			this.projectUrlComponent = this.projectMainArea.getClassStoredValue('pUrlComp');
			this.projectMediaContainer = $('mainMediaContainer');
			if(this.projectMediaContainer && swfobject.hasFlashPlayerVersion("9")) {
				// redirect is done if we appear in place which is not direct link to the project or
				// to one of the project media categories (and not the first one)
				var doRedirect = parseInt(this.projectMediaContainer.getClassStoredValue('doRedirect'));
				if(doRedirect) {
					this.allContainerElement.empty();
					window.location.replace(this.sectionPath + this.projectUrlComponent + '/');
					bprojectsList_init = false;
				
				} else {
					
					// media menu 1 2 3 ... 
					this.mediaMenu = $('imagesMenu').setOpacity(0);
					var links = this.mediaMenu.getElements('a');
					var hrefList = links.get('rev');
					var typesList = links.get('rel');
					links.addEvent('click', this.projectMainArea_onImageLinkClick.bindWithEvent(this));
					
					// THE flash
					var flashvars = {
						"media_paths": hrefList.join('|||'),
						"media_types": typesList.join('|||'),
						"current_index": parseInt(this.projectMediaContainer.getClassStoredValue('mediaId')) - 1
					};
					var params = {
						"menu": "false",
						"scale": "noscale",
						"salign": "tl",
						"wmode": "window",
						"swliveconnect": "true",
						"allowfullscreen": "true",
						"allownetworking":  "all",
						"allowscriptaccess": "always"
					};
					var attributes = { id: "KathiMain" };
					swfobject.embedSWF(this.rootPath + "c/KathiMain.swf", "mainMediaContainer", "100%", "100%", "9.0.0", this.rootPath + "c/expressInstall.swf", flashvars, params, attributes);

					/*swfobject.addLoadEvent(function() {
						var fl = swfobject.getObjectById("KathiMain");
						if(fl && fl.focus) { try { fl.focus(); } catch(e) { } }
					});*/
					
				}
			}
		}
	},
	
	projectMainArea_onImageLinkClick: function(event) {
		event.stop();
		
		var a = $(event.target);
		var idx = -1;
		this.mediaMenu.getElements('a').some(function(item, i) {
			idx = i;
			return item == a;
		});
		
		this.projectMainArea_imageMenuHilight(idx);
		
		var fl = swfobject.getObjectById("KathiMain");;
		try {
			fl.openMedia(idx);
		} catch(e) {
			
		}
	},
	
	// called from flash via ExternalInterface when the flash is fully initialised
	projectMainArea_flashReady: function() {
		if(this.mediaMenu.getElements('a').length > 1) 
			this.mediaMenu.fade('in');
		else {
			var p = this.mediaMenu.getParent();
			this.mediaMenu.destroy();
			this.fillEmptyRowsForElement(p);
		}
	},

	// called from flash via ExternalInterface when a new media item is being loaded
	projectMainArea_imageMenuHilight: function(idx) {
		this.mediaMenu.getElements('a').removeClass('selected');
		var a = this.mediaMenu.getElements('a')[idx];
		if(a) {
			a.addClass('selected');
			this.fillEmptyRowsForElement($('projectMediaCaption').set('text', a.get('title')));
		}
	},
	
	
	
	
	
	
	
	
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	
	
	projectsList_init: function() {
		this.projecItemFxIn = new Array();
		this.projecItemFxOut = new Array();
		this.projectItemYDiff = new Array();
		this.projectsList = $$('.projectItem');
		this.yearsForType = { 'free' : new Array('year_all'), 'comm': new Array('year_all') };
		this.projecItemFirstVisible = null;
		this.projectsList.each(function(item) {
			
			var pY = item.getClassStoredValue('pYear');
			var pId = item.getClassStoredValue('pId');
			
			this.yearsForType[item.hasClass('pProjectFree') ? 'free' : 'comm'].push(pY);
			
			if(!this.projecItemFirstVisible) this.projecItemFirstVisible = item;
			
			item.store('pYear', pY)
				.store('pId', pId)
				.addEvent('mouseenter', this.projectsList_onItemOver.bindWithEvent(this))
				.addEvent('mouseleave', this.projectsList_onItemOut.bindWithEvent(this))
				.addEvent('click', this.projectsList_onItemClick.bindWithEvent(this));
		}, this);
		
		this.projectsList_initFilters();
	},
	
	projectsList_getFirstVisible: function() {
		return this.projecItemFirstVisible;
	},

	projectsList_initFilters: function() {
		this.projectsList_typeFilter = 'free';
		this.projectsList_yearFilter = 'year_all';
		$$('.selectedFilter').each(function(el) {
			fType = el.get('rel');
			if(fType == 'free' || fType == 'comm') {
				this.projectsList_typeFilter = fType;
			} else {
				this.projectsList_yearFilter = fType;
			}
		}, this)
		$$('.projectsFilter').addEvent('click', this.projectsList_onFilterClick.bindWithEvent(this));

		this.projectsList_updateFilters();
		this.projectsList_filter(true);
	},
	
	// shows/hides the year filters according to whether those years are represented in the filtered list
	projectsList_updateFilters: function() {
		if(this.projectsList_yearFilter != 'year_all') {
			if(this.yearsForType[this.projectsList_typeFilter].indexOf(this.projectsList_yearFilter) < 0) {
				this.projectsList_yearFilter = 'year_all';
				$$('.projectsYearFilter').removeClass('selectedFilter');
				$('projectsFilterAllYears').addClass('selectedFilter');
			}
		}
		
		$$('.projectsYearFilter').each(function(el) {
			el.setStyle('display', this.yearsForType[this.projectsList_typeFilter].indexOf(el.get('rel')) >= 0 ? 'inline' : 'none');
		}, this);
	},
	
	projectsList_onFilterClick: function(event) {
		event.stop();
		var a = $(event.target);
		var fType = a.get('rel');
		if(fType == 'free' || fType == 'comm') {
			this.projectsList_typeFilter = fType;
			$$('.projectsTypeFilter').removeClass('selectedFilter');
			a.addClass('selectedFilter');
		} else {
			this.projectsList_yearFilter = fType;
			$$('.projectsYearFilter').removeClass('selectedFilter');
			a.addClass('selectedFilter');
		}
		this.projectsList_updateFilters();
		this.projectsList_filter(false);
	},
	
	// show/hide the projects list according to type and year
	projectsList_filter: function(isInitialFiltering) {
		//console.debug('filter ' , this.projectsList_typeFilter, ' ', this.projectsList_yearFilter);
		if(!isInitialFiltering) {
			if($('mainArea')) {
				$('mainArea').destroy();
				$('mainProjectInfo').destroy();
				//$('mainAreaColumn1').destroy();
				$('mainAreaColumn2').destroy();
				$('mainAreaColumn3').destroy();
				$('mainAreaColumn4').destroy();
			}
			//$('mainAreaContainer').dissolve();
			$$('.selectedProject').removeClass('selectedProject');
		}
		
		this.projecItemFirstVisible = null;
		this.projectsList.each(function(item) {
			var canShow = this.projectsList_typeFilter == 'free' ? item.hasClass('pProjectFree') : item.hasClass('pProjectComm');
			if(canShow && this.projectsList_yearFilter != 'year_all') {
				canShow &= item.retrieve('pYear') == this.projectsList_yearFilter;
			}
			
			if(canShow) {
				item.addClass('filteredIn').setStyle('display', 'block').fade('hide').fade('in');
				if(!this.projecItemFirstVisible) this.projecItemFirstVisible = item;
			} else {
				item.removeClass('filteredIn').setStyle('display', 'none');
			}
		}, this);
		
		this.repairFooter();
		
		if(!isInitialFiltering)
			this.projectsList_notifyServerAboutFilter();
	},
	
	projectsList_notifyServerAboutFilter: function() {
		//console.debug('notify');
		new Request({
			url: '.',
			data: 'cmd=filter_notify&t=' + this.projectsList_typeFilter + '&y=' + this.projectsList_yearFilter,
			method: 'get'
		}).send();
	},
	

	
	
	
	// hovering and clicking on projects
	
	projectsList_itemSetHoverDiff: function(item, itemId) {
		if(this.projectItemYDiff[itemId] == undefined) {
			var pId = itemId ? itemId : item.getClassStoredValue('pId');
			var outer = item.getElement('.outer');
			var inner = item.getElement('.inner');
			this.projectItemYDiff[pId] = outer.getSize().y - inner.getSize().y;
			if(this.projectItemYDiff[pId] > 0) this.projectItemYDiff[pId] = 0;
			
			this.projecItemFxIn[pId] = new Fx.Tween(inner, { duration: 600, transition: Fx.Transitions.Quint.easeOut });
			this.projecItemFxOut[pId] = new Fx.Tween(inner, { duration: 800, transition: Fx.Transitions.Quint.easeOut });
		}
	},
	
	projectsList_getItemAsParentOf: function(target) {
		if(!target.hasClass('projectItem')) target = target.getParent('.projectItem');
		return target;
	},
	projectsList_onItemOver: function(event) {
		var target = this.projectsList_getItemAsParentOf($(event.target));
		var pId = target.getClassStoredValue('pId');
		this.projectsList_itemSetHoverDiff(target, pId);
		target.addClass('hoveredProject');
		if(this.projectItemYDiff[pId]) {
			this.projecItemFxOut[pId].cancel();
			this.projecItemFxIn[pId].start('top', this.projectItemYDiff[pId]);//.chain(this.load_Render.bind(this));
		}
	},
	projectsList_onItemOut: function(event) {
		var target = this.projectsList_getItemAsParentOf($(event.target));
		var pId = target.getClassStoredValue('pId');
		target.removeClass('hoveredProject');
		if(this.projectItemYDiff[pId]) {
			this.projecItemFxIn[pId].cancel();
			this.projecItemFxOut[pId].start('top', 0);//.chain(this.load_Render.bind(this));
		}
	},
	projectsList_onItemClick: function(event) {
		var target = this.projectsList_getItemAsParentOf($(event.target));
		var pLink = target.getElement('a.projectLink');
		window.location = pLink.get('href');
	},
	
	
	
	
	
	
	
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 
	// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // 

	
	contactsSection_init: function() {
		this.contactsForm = $('contactsForm');

		var fieldsContainer2 = $('contactsFields2');
		fieldsContainer2.addClass('dashAutoFill').addClass('numRows-16');
		new Element('input', { 'type': 'hidden', 'name': 'cmd', 'value': 'contact_form' }).inject(fieldsContainer2);
		new Element('textarea', { 'name': 'contact_text', 'id': 'contactsText', 'class': 'contactsInput' }).inject(fieldsContainer2);
		new Element('p', { 'class' : 'f' }).adopt(new Element('input', { 'type': 'submit', 'id': 'contactsSubmit', 'name': 'contacts_submit', 'value': 'send', 'class': 'contactsInput ltWhiteInput' })).inject($('contactsFields2'));
		new Element('p', { 'class' : 'f' }).adopt(new Element('input', { 'type': 'reset', 'id': 'contactsClear', 'name': 'contacts_reset', 'value': 'clear', 'class': 'contactsInput ltWhiteInput' })).inject($('contactsFields2'));
		this.fillEmptyRowsForElement(fieldsContainer2);
		
		
		this.contactsForm.addEvent('submit', this.contactsSection_onSubmit.bindWithEvent(this));
	},
	contactsSection_validate: function() {
		var emailRegEx = /^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-.]+\.)+[A-Za-z]{2,4}$/;
		var name = $('contactsName').get('value').trim();
		var email = $('contactsEmail').get('value').trim();
		var subject = $('contactsSubject').get('value').trim();
		var text = $('contactsText').get('value').trim();
		if(name && email && subject && text) {
			if(emailRegEx.test(email)) {
				return true;
			} else {
				alert('Please verify your email address!');
				$('contactsEmail').focus();
			}
		} else {
			alert('Please fill all fields!');
			if(!text) $('contactsText').focus();
			if(!subject) $('contactsSubject').focus();
			if(!email) $('contactsEmail').focus();
			if(!name) $('contactsName').focus();
		}
		
		return false;
	},
	contactsSection_onSubmit: function(event) {
		event.stop();
		
		if(this.contactsSection_validate()) {
			new Request({
				url: '.',
				data: this.contactsForm,
				method: 'post',
				onComplete: this.contactsSection_onSubmitComplete.bind(this)
			}).send();
			$('contactsForm').getElements('.contactsInput').set('disabled', true);
		}
	},
	contactsSection_onSubmitComplete: function(response) {
		//console.debug(response);
		var fieldsContainer2 = $('contactsFields2');
		//var t = $('contactsText').dispose();
		fieldsContainer2.getElements('p.f').destroy();
		new Element('p').set('html', 'Your message has been sent!').inject(fieldsContainer2);
		this.fillEmptyRowsForElement(fieldsContainer2);
	}
	
	
});

var webSiteMain = new WebSiteMain();




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

var WebSiteMenu = new Class({


	
	initialize: function() {
		
		
	}
	
	
});




