/**
 * default.js JavaScript for Chapel Parket website
 *
 * @copyright eFocus
 * @require MooTools 1.2.5 core (http:/www.mootools.net)
 */
window.addEvents({
	'domready': function() {
		defaultInputText();
		initExternalLinks();
		removeMarginTeasers();
		
		if(document.getElement('div.routeplanner')) new RoutePlanner();
		
		if ($('pushbox')) {
			new EfxNavSlideShow({
				arrSlides: $$('div.pushbox li.slide'),
				elNav: $('pushbox').getElement('.pushbox_nav'),
				intInterval: 5000
			});
		}
		
		$$('div.carrousel a.patternswitch').each(function(elLink) {
			elLink.addEvent('click', function() { handlePatternSwap(elLink) });
		});
		
		$$('div.carrousel').each(function(elCarrousel) {
			// attach mouseover showing of larger image functionality
			if(!elCarrousel.hasClass('carrousel_large')) {
				elCarrousel.getElements('li:not(.nopatterns)').each(function(elThumbnail){ attachImagePopup(elThumbnail) });
			}
			
			// attach Carrousel functionality, AFTER attaching imagepopup
			var intSlidesToShow = 5;
			if(elCarrousel.hasClass('carrousel_large')) intSlidesToShow = 1;
			elCarrousel.carrousel = new Carrousel({
				'slidesContainer'	: elCarrousel.getElement('ul'),
				'linkNext'			: elCarrousel.getElement('a.btn_next'),
				'linkPrevious'		: elCarrousel.getElement('a.btn_prev'),
				'slidesToShift'		: 1,
				'slidesToShow'		: intSlidesToShow
			});
			
		});
		
		$$('dl.language span.active').addEvent('click', function() { $$('dl.language').toggleClass('lang_open') });
		
		
		if ($$('div.teaser-home div.teaser').length > 0) {		
			makeEqualHeight($$('div.teaser-home div.teaser'), 3);
		}
		
    }
});

/**
 * toggles default text in text inputfields
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function defaultInputText() {
	var inputfields = $$('.defaultText');
	
	inputfields.each(function(item) {
		item.defaultText = item.value;
		item.addClass('default');
		
		item.addEvents({
			'focus': function() {
				if (item.value == item.defaultText) item.value = '';
				item.removeClass('default');
			},
			'blur': function() {
				if (item.value == '') {
					item.value = item.defaultText;
					item.addClass('default');
				}
			}
		});
	});
}

/**
 * Opens external links valid in a new window without the target attribute.
 * 
 * @author Mirjam Verloop, <mirjam.verloop@efocus.nl>
 * @author Klaas Dieleman, <klaas[AT]efocus.nl>
 * @version 1.1, 14 oct, 2010
 * @requires MooTools 1.2.4 Core, <http://www.mootools.net>
 * @return void
 */
function initExternalLinks() {
	var allExternalLinks = $$('a[href^="http://"]', 'a.external');
	var thisDomain = window.location.host;
	
	allExternalLinks.each(function(thisLink) {
		
		if (!thisLink.get('href').contains(thisDomain) && thisLink.hasClass("linkBlocker") == false) {
			thisLink.addEvent('click', function(event) {
				event.stop();
				window.open(this.get('href'));
			});
		}
				
	});
}

/**
 * Every third teaser has a margin-right 10px
 * 
 * @author Phi Son Do, <phison.do@efocus.nl>
 * @version 1.0, 12 feb, 2010
 * @requires MooTools 1.2.4 Core, <http://www.mootools.net>
 * @requires <a href="http://www.efocus.nl/" class="external">eFocus</a>
 * @return void
 */
function removeMarginTeasers(){
	var elHomeTeaser = $$('div.teaser-home');
	if(elHomeTeaser){
		arrHomeThirdTeasers = elHomeTeaser.getElements('ul li:nth-child(3n+3)');
		arrHomeThirdTeasers.each(function(elHomeThirdTeaser){			
			elHomeThirdTeaser.getElement('div.teaser').setStyle('margin-right', 10);
		});
	}
}

/**
 * gets and replaces new patterns-list trough AJAX-call from a certain Wood Type
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @param Element: Woodtype-link which is clicked, its rel-attribute is sent with the JSON-request
 * @return void
 */
var strListItemNoPattern = '';

function handlePatternSwap(elLink) {
	elLink.getParent('li').getSiblings().removeClass('active');
	elLink.getParent('li').addClass('active');
	
	var arrIdentifiers = elLink.get('rel').split(',');
	var elProductLevelCurrent = elLink.getParent('.product_level');
	
	var postVariables = new Object();
	if (elProductLevelCurrent.get('id') == 'patterns') {
		postVariables.action = 'woodtypes';
		postVariables.languageUid = arrIdentifiers[0];
		postVariables.productLineUid = arrIdentifiers[1];
		postVariables.patternUid = arrIdentifiers[2];
	} else if (elProductLevelCurrent.get('id') == 'woodtypes') {
		postVariables.action = 'implementation';
		postVariables.patternProductlineWoodtypeUid = arrIdentifiers[0];
	}
	
	new Request.JSON({
		url: "/typo3conf/ext/chapelparket/intro_productlines/class.ajax_productlines.php",
		onComplete: function(arrResp){
			if (arrResp) {
				if (elProductLevelCurrent.getNext()) {
					var elProductLevelNext = elProductLevelCurrent.getNext();
					var elProductLevelNextSecond = elProductLevelNext.getNext();
					var elCarrousel = elProductLevelNext.getElement('.carrousel');
					var elCarrouselList = elCarrousel.getElement('ul');
					if (arrResp.length > 0) {
					//if (elProductLevelCurrent.get('id') == 'patterns') {
						var strList = buildProductList(arrResp, elProductLevelCurrent);
						if (strListItemNoPattern == '') strListItemNoPattern = elProductLevelNextSecond.getElement('.viewport ul').get('html');
						elProductLevelNextSecond.getElement('.viewport ul').set('html', strListItemNoPattern);
						elProductLevelNextSecond.removeClass('hidden');
						elProductLevelNextSecond.getNext().addClass('hidden');
					} else if (arrResp.length == undefined) {
					//} else if (elProductLevelCurrent.get('id') == 'woodtypes') {
						var strList = buildProductList(arrResp.implementations, elProductLevelCurrent);
						elProductLevelNextSecond.removeClass('hidden');
						$('specifications').getElements('dd')[0].set('html', arrResp.specification.typeboards);
						$('specifications').getElements('dd')[1].set('html', arrResp.specification.width);
						$('specifications').getElements('dd')[2].set('html', arrResp.specification.length);
						$('specifications').getElements('dd')[3].set('html', arrResp.specification.finishes);
					}
					
					elCarrouselList.set('html', strList);
					
					if (elProductLevelCurrent.get('id') != 'implementations') {
						elCarrouselList.getElements('a').each(function(elCarrouselLink) {
							elCarrouselLink.addEvent('click', function() {
								handlePatternSwap(elCarrouselLink);
							});
						});
					}
					
					// image popups need to be attached again to newly added listitems
					if(!elCarrousel.hasClass('carrousel_large')) {
						elCarrousel.getElements('li:not(.nopatterns)').each(function(elThumbnail){ attachImagePopup(elThumbnail) });
					}
					
					// carrousel needs to be initialized again because number of listitems might be different
					elCarrousel.carrousel.initialize();
				}
			}
		}
	}).post(postVariables);
}

/**
 * renders string of html listitems with producttypes from JSON-response
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @param Array: JSON-response consisting of producttype-objects
 * @return String: string of html listitems
 */
function buildProductList(arrResp, elProductLevelCurrent) {
	var blnLink = (elProductLevelCurrent.get('id') == 'woodtypes') ? false : true;
	var strList = '';
	
	for(var i = 0 ; i < arrResp.length ; i++) {
		strList += '<li>';
		strList += '<h4>';
		if (blnLink) strList += '<a class="patternswitch" rel="' + arrResp[i].patternProductlineWoodtypeUid + '">';
		strList += '<img src="' + arrResp[i].imgurl + '" alt="' + arrResp[i].number + ' | ' + arrResp[i].name + '" />';
		strList += '<span class="number">' + arrResp[i].number + ' | </span>';
		strList += '<span class="name">' + arrResp[i].name + '</span>';
		if (blnLink) strList += '</a>';
		strList += '</h4>';
		strList += '</li>';
	}
	
	return strList;
}

/**
 * attaches mouse-events to image thumbnail, to show or hide large image popup
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @param Element: html listitem which contains the image thumbnail
 */
function attachImagePopup(elThumbnail) {
	
	// we are using a short delay here to fix mouseenter/mouseleave transition problems
	elThumbnail.addEvents({
		'mouseenter'	: function() {
			$clear(elThumbnail.timeout);
			showImagePopup(elThumbnail);
		},
		'mouseleave'	: function() { 
			elThumbnail.timeout = hideImagePopup.delay(50, elThumbnail, elThumbnail);
		}
	});
}

/**
 * renders and shows large image popup
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @param Element: html listitem which contains the image thumbnail
 */
function showImagePopup(elThumbnail) {
	if(elThumbnail.elImagePopupContainer) return false
	
	elThumbnail.addClass('hover');
		
	elThumbnail.elImagePopupContainer = new Element('div', {'class' : 'imagepopup'});
	elThumbnail.getElement('img').clone().inject(elThumbnail.elImagePopupContainer);
	elThumbnail.getElements('span').clone().inject(elThumbnail.elImagePopupContainer);
	
	var intYpos = window.getScrollSize().y - elThumbnail.getPosition().y - 40;
	
	elThumbnail.elImagePopupContainer.setStyles({
		'position'	: 'absolute',
		'z-index'	: 999,
		'left'		: elThumbnail.getPosition($$('div.pagewrapper').getLast()).x + 60,
		'bottom'	: intYpos,
		'overflow'	: 'hidden'
	});
	
	elThumbnail.elImagePopupContainer.addEvents({
		'mouseenter' : function() { $clear(elThumbnail.timeout) },
		'mouseleave' : function() { elThumbnail.timeout = hideImagePopup.delay(50, elThumbnail, elThumbnail) }
	});
	
	elThumbnail.elImagePopupContainer.fade('hide');
	elThumbnail.elImagePopupContainer.set('tween', {duration: 200});
	elThumbnail.elImagePopupContainer.inject($$('div.pagewrapper').getLast());
	elThumbnail.elImagePopupContainer.fade('in');
	
}

/**
 * hides and destroys large image popup
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @param Element: html listitem which contains the image thumbnail
 */
function hideImagePopup(elThumbnail) {
	if(elThumbnail.elImagePopupContainer) {
		elThumbnail.elImagePopupContainer.fade('out').get('tween').chain(function() {
			elThumbnail.removeClass('hover');
			elThumbnail.elImagePopupContainer.destroy();
			elThumbnail.elImagePopupContainer = null;
		});
	}
}

/**
* equals the height of the elements in an array
*
* @author Mirjam
* @since 1.0, dec 2010
* @param array - elements to equalize
* @param integer - optional amount of columns per row
*/

function makeEqualHeight(arrElements, intColumns) {
	
	var intMaxheight = 0;
	var arrCurrentRow = new Array();
	
	arrElements.each(function(item, index) {
		
		item.setStyle('height', 'auto');
		var intHeight = item.getSize().y;
		if (intHeight > intMaxheight) {
			intMaxheight = intHeight;
		}
		arrCurrentRow.push(item);
		
		
		if((index+1)%intColumns == 0) {
			arrCurrentRow.each(function(el) {
				el.setStyle('height', intMaxheight);
			});
			intMaxheight = 0;
			arrCurrentRow = [];
		}
		
	});
	
	arrCurrentRow.each(function(el) {
		el.setStyle('height', intMaxheight);
	});
	
}


