/** @package eScript */

window.addEvents({
	'domready': function() {
		initExternalLinks();
		testFontFace();
		initSwiffBackground();
		initMessageOverlay();
		initCenterElements();
		startCarrousel();
		initFaqMiniAccordion();
		initFaqCategories();
		initSearchForm();
		initAllergyBrandsList();
	},
	'load': function() {
		initHomeBrandsList();
		initBrandsList();
		initHomepage();
	}
});


/**
* initExternalLinks
* 
* Opens external links valid in a new window without the target attribute.
* 
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @uses <a href="http://www.efocus.nl/" class="external">eFocus</a>
*/
function initExternalLinks() {
	var arrExternalLinks = $$('a.external');
	if (arrExternalLinks.length == 0) return;

	arrExternalLinks.each(function(elExternalLink) {
		elExternalLink.addEvent('click', function(event) {
			event.stop();
			window.open(this.get('href'));
		});
	});
}


/**
* testFontFace
*
* Test if the small Calibri font is available, and otherwise will increase the general font-size.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function testFontFace() {
	var detective = new Detector();
	
	if (!detective.test('Calibri')) {
		$(document).getElement('body').setStyle('font-size', '91%');
		if ($(document).getElement('.main_nav')) $(document).getElement('.main_nav').setStyles({ 'font-weight': 'normal', 'letter-spacing': '0'});
	}
}


/**
* initSwiffBackground
*
* sets background animation swiff
*
* @author Mirjam <mirjam{AT}efocus.nl>
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/

function initSwiffBackground() {
	if (!$('bgwrapper')) return false;

	var parent = $('bgwrapper').getParent('form');
	if (!parent) return;
	
	var fltVideoHeightPercent = 72.7;

	var bool = '';
	if ($('home_brands_list')) {
	    bool = 'true';
	} else {
	    bool = 'false';
	}

	var flashvars = {
		
		'xmlpath':'/flash.xml',
		'whatswf':'/flash/project.swf',
		'imgpath':'/flash/',
		'streamer':'rtmp://streaming2.dedicated.nines.nl/efocus/',
		'bubbles': bool
	};

	var params = {
		'allowfullscreen': 'true',
		'allowscriptaccess': 'always',
		'bgcolor': '#FFFFFF',
		'wmode': 'transparent'
	};

	var attributes = {
		'id': 'bgwrapper_flash'
	};

	swfobject.embedSWF("/flash/preloader.swf", 'flashwrapper', "100%", "619", "9.0.0", "", flashvars, params, attributes);
}


/**
* initMessageOverlay
*
* Shows and hides the message overlay bubble.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @author Rocco Janse <rocco{AT}efocus.nl>
* @return void
*/
function initMessageOverlay() {

	var elHomeVisualHolder = $(document.body).getElement('.home_visual_holder');
	var elBubbleOverlay = $(document.body).getElement('div.bubble_overlay');
	if (!elBubbleOverlay) return;
	
	var elBubbleOverlayClose = elBubbleOverlay.getElement('a.bubble_overlay_close');
	if (!elBubbleOverlayClose) return;

	if (elHomeVisualHolder) {
		var elHomeBrandsList = elHomeVisualHolder.getElement('.home_brands_list');
	}

	elBubbleOverlayClose.addEvent('click', function() {
		elBubbleOverlay.hide();
		if (elHomeBrandsList) elHomeBrandsList.removeClass('semi_transparent');
	});

	showBubbleOverlay = function() {

		// only show if cookie is not set 
		if (Cookie.read('overlay') != 'shown') {
			var overlaycookie = Cookie.write('overlay', 'shown');
			elBubbleOverlay.show();
			if (elHomeBrandsList) elHomeBrandsList.addClass('semi_transparent');
		} 
	}
	showBubbleOverlay();
}



/**
* initCenterElements
*
* Horizontally centers elements by comparing it to its parent element.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initCenterElements() {
	var arrCenters = $$('.center');
	if (arrCenters.length == 0) return;

	arrCenters.each(function(elCenter) {
		var intParentWidth = elCenter.getParent().getWidth() - (elCenter.getParent().getStyle('padding-left').toInt() + elCenter.getParent().getStyle('padding-right').toInt());
		elCenter.setStyle('margin-left', (intParentWidth - elCenter.getWidth()) / 2);
	});
}



/**
* initDidYouKnowCarrousel
*
* Creates a carrousel from the Did You Know items.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initDidYouKnowCarrousel() {
	if (!$(document).getElement('.did_you_know_carrousel')) return;
	
	var elDidYouKnowCarrousel = $(document).getElement('.did_you_know_carrousel');
	
	var objSlideShow = new EfxNavSlideShow({
	    arrSlides: elDidYouKnowCarrousel.getElement('.carrousel_slides').getChildren('li'),
		elNav: elDidYouKnowCarrousel.getElement('.carrousel_nav'),
		intInterval: 12000,
		strOutEffectProperty: 'left',
		intOutEffectStartValue: 0,
		intOutEffectEndValue: -252,
		strInEffectProperty: 'left',
		intInEffectStartValue: 252,
		intInEffectEndValue: 0
	});
}



/**
* initFaqMiniAccordion
*
* Adds an accordion effect to the miniversion of the FAQ.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initFaqMiniAccordion() {
	var arrFaqMinis = $$('.faq_mini');
	if (arrFaqMinis.length == 0) return;

	arrFaqMinis.each(function(elFaqMini) {
		var objFaqMini = new Accordion(elFaqMini.getElements('h3.faq_question'), elFaqMini.getElements('div.faq_answer_panel'), {
			
		});
	});
}


/**
* initFaqCategories
* puts FAQ categories in an accordion and enables toggling of answers
*
* @author Klaas Dieleman <klaas[AT]efocus.nl>
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initFaqCategories() {
	var arrFaqCats = $$('ul.faq li');
	if (arrFaqCats.length > 1) {

		var faqAccordion = new Accordion(arrFaqCats.getElements('h3.faq_category'), arrFaqCats.getElements('div.faq_questions_panel'), {
			onActive: function(toggler) {
				toggler.getParent().addClass('open');
			},
			onBackground: function(toggler) {
				toggler.getParent().removeClass('open');
			},
			alwaysHide: true,
			show: 0
		});
		$$('div.faq_questions_panel')[0].setStyle('height', $$('div.faq_questions_panel')[0].getSize().y);

	}

	if ($$('ul.faq dt').length == $$('ul.faq dd').length) {
		$$('ul.faq dt').each(function(item, index) {
			item.addEvent('click', function() {
				var oldHeight = item.getParent().getSize().y;

				$$('ul.faq dt').removeClass('open');
				$$('ul.faq dd').removeClass('open');

				$$('ul.faq dt')[index].addClass('open');
				$$('ul.faq dd')[index].addClass('open');

				var newHeight = item.getParent().getSize().y;
				item.getParent('div.faq_questions_panel').setStyle('height', (item.getParent('div.faq_questions_panel').getSize().y + (newHeight - oldHeight)));
			});
		});
	}
	
	if ($(document).getElement('.faq_show_all_answers')) {
		$(document).getElement('.faq_show_all_answers').addEvent('click', function(event) {
			event.stop();
			arrFaqCats.each(function(elFaqCat) {
				elFaqCat.addClass('open');
				elFaqCat.getElement('.faq_questions_panel').setStyles({
					'height': 'auto',
					'visibility': 'visible',
					'opacity': '1'
				});
				elFaqCat.getElements('dt').addClass('open');
				elFaqCat.getElements('dd').addClass('open');
			});
		});
	}
}



/**
* initHomepage
* In order to use the buttons within the Swiff on the homepage some wrappers need to be repositioned.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initHomepage() {
	if (!$(document.body).getElement('.home')) return false;

	if ($('bgwrapper_flash')) {
		$(document.body).getElement('div.pagewrapper').hide();
		$(document.body).getElement('div.footerwrapper').setStyle('position', 'absolute');
	} else {
		$(document.body).getElement('div.footerwrapper').setStyle('top', 'auto');
	}
}



/**
* initHomeBrandsList
* Adds classes to certain list items of the home brands list to divide.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initHomeBrandsList() {
	if (!$(document.body).getElement('.home_brands_list')) return false;
	$(document.body).getElement('.home_brands_list').setStyle('visibility', 'hidden');
	
	if (!Browser.Plugins.Flash || Browser.Plugins.Flash.version < 9) {
		$(document.body).getElement('.home_brands_list').setStyle('display', 'block');
		
		var arrHomeBrandsListItems = $(document).getElements('.home_brands_list li');
		
		arrHomeBrandsListItems[5].addClass('row1_end');
		arrHomeBrandsListItems[6].addClass('row2_start');
		
		$(document).getElement('.page_shadow_left').setStyle('top', 350);
		$(document).getElement('.page_shadow_right').setStyle('top', 350);
	} else {
		$(document).getElement('.home_visual_holder').setStyle('height', 325);
		$(document).getElement('.home_brands_list').setStyle('display', 'none');
		
		$(document).getElement('.page_shadow_left').setStyle('top', 325);
		$(document).getElement('.page_shadow_right').setStyle('top', 325);
    }
    
    $(document).getElement('.home_brands_list').setStyle('display', 'block');   
}



/**
* initBrandsList
* Adds an equal height per three list items, plus adds a class on each right-aligned list item of the brandlist (T4 F8).
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initBrandsList() {
	if (!$(document.body).getElement('.brands_list')) return;
	$(document.body).getElement('.brands_list').setStyle('visibility', 'hidden');
	
	var arrBrandsListItems = $(document).getElements('.brands_list li');
	var intBrandsListItemsPerRow = 3;
	var intBrandsListItemMaxHeight = 0;

	arrBrandsListItems.each(function(elBrandsListItem, index) {
		if (elBrandsListItem.getHeight() > intBrandsListItemMaxHeight) intBrandsListItemMaxHeight = elBrandsListItem.getHeight();

		if (index % intBrandsListItemsPerRow == intBrandsListItemsPerRow - 1) {
			elBrandsListItem.addClass('brands_list_item_right');
			var intBrandsListItemMaxHeightOnly = intBrandsListItemMaxHeight - (elBrandsListItem.getStyle('padding-top').toInt() + elBrandsListItem.getStyle('padding-bottom').toInt());
			for (var i = 0; i < intBrandsListItemsPerRow; i++) {
				arrBrandsListItems[index - i].setStyle('height', intBrandsListItemMaxHeightOnly);
			}
			intBrandsListItemMaxHeight = 0;
		} else if (index == arrBrandsListItems.length - 1) {
			for (var i = index; i < arrBrandsListItems.length; i++) {
				arrBrandsListItems[i].setStyle('height', intBrandsListItemMaxHeightOnly);
			}
		}
	});
	$(document.body).getElement('.brands_list').setStyle('visibility', 'visible');
}



/**
* initAllergyBrandsList
* Adds an equal height per four list items, plus adds a class on each right-aligned list item of the allergy brandlist (T6 F16).
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initAllergyBrandsList() {
	if (!$(document.body).getElement('.allergy_brands_list')) return;
	$(document.body).getElement('.allergy_brands_list').setStyle('visibility', 'hidden');

	var arrBrandsListItems = $(document).getElement('.allergy_brands_list').getChildren('li');
	var intBrandsListItemsPerRow = 4;
	var intBrandsListItemMaxHeight = 0;

	arrBrandsListItems.each(function(elBrandsListItem, index) {
		if (elBrandsListItem.getHeight() > intBrandsListItemMaxHeight) intBrandsListItemMaxHeight = elBrandsListItem.getHeight();
		
		if (index % intBrandsListItemsPerRow == intBrandsListItemsPerRow - 1) {
			elBrandsListItem.addClass('allergy_brands_list_item_right');
			var intBrandsListItemMaxHeightOnly = intBrandsListItemMaxHeight - elBrandsListItem.getStyle('padding-top').toInt();
			for (var i = 0; i < intBrandsListItemsPerRow; i++) {
				arrBrandsListItems[index - i].setStyle('height', intBrandsListItemMaxHeightOnly);
			}
			intBrandsListItemMaxHeight = 0;
		} else if (index == arrBrandsListItems.length - 1) {
			var intBrandsListItemMaxHeightOnly = intBrandsListItemMaxHeight - elBrandsListItem.getStyle('padding-top').toInt();
			for (var i = 0; i < (arrBrandsListItems.length % intBrandsListItemsPerRow); i++) {
				arrBrandsListItems[index - i].setStyle('height', intBrandsListItemMaxHeightOnly);
			}
		}
	});
	$(document.body).getElement('.allergy_brands_list').setStyle('visibility', 'visible');
}



/**
* GetEnter
* Gets the key "enter" on the input
*
* @author Jeroen Datema <jeroen.datema[at]efocus.nl>
* @return void
*/

function GetEnter(url, e, queryString) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        var connector = url.toString().indexOf("?") >= 0 ? "&" : "?";
        var newLocation = url + connector + "q=" + encodeURIComponentNew(queryString);
        window.location = newLocation;
        return false;
    }
    else
        return true;
}

function GetEnterWithQS(url, e, zoekstring, queryString) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        var newLocation = url + "?q=" + encodeURIComponentNew(zoekstring);
        if (queryString != '' && queryString != undefined && queryString.toString().indexOf('?') < 0) {
            newLocation = queryString + "?q=" + encodeURIComponentNew(zoekstring);
        }
        window.location = newLocation;
        return false;
    }
    else
        return true;
}

/**
* RedirectZoek
*
* @author Jeroen Datema <jeroen.datema[at]efocus.nl>
* @return void
*/

function RedirectSearch(url, zoekstring) {
    window.location = url + "?q=" + encodeURIComponentNew(zoekstring);
    return false;
}

function RedirectSearchWithQS(url, zoekstring, queryString) {
    var newLocation = url + "?q=" + encodeURIComponentNew(zoekstring);
    if (queryString != '' && queryString != undefined) {
        newLocation = queryString + "?q=" + encodeURIComponentNew(zoekstring);
    }
    window.location = newLocation;
    return false;
}

/** 
* functie encodeURIComponentNew() doet escape() maar dan netjes unicode 
*
* @author Barend <barend[at]efocus.nl>
*/

var hexchars = "0123456789ABCDEF";
var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
function encodeURIComponentNew(s) {
    var s = utf8(s);
    var c;
    var enc = "";
    for (var i = 0; i < s.length; i++) {
        if (okURIchars.indexOf(s.charAt(i)) == -1)
            enc += "%" + toHex(s.charCodeAt(i));
        else
            enc += s.charAt(i);
    }
    return enc;
}

function toHex(n) {
    return hexchars.charAt(n >> 4) + hexchars.charAt(n & 0xF);
}

function utf8(wide) {
    var c, s;
    var enc = "";
    var i = 0;
    while (i < wide.length) {
        c = wide.charCodeAt(i++);
        // handle UTF-16 surrogates
        if (c >= 0xDC00 && c < 0xE000) continue;
        if (c >= 0xD800 && c < 0xDC00) {
            if (i >= wide.length) continue;
            s = wide.charCodeAt(i++);
            if (s < 0xDC00 || c >= 0xDE00) continue;
            c = ((c - 0xD800) << 10) + (s - 0xDC00) + 0x10000;
        }
        // output value
        if (c < 0x80) enc += String.fromCharCode(c);
        else if (c < 0x800) enc += String.fromCharCode(0xC0 + (c >> 6), 0x80 + (c & 0x3F));
        else if (c < 0x10000) enc += String.fromCharCode(0xE0 + (c >> 12), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
        else enc += String.fromCharCode(0xF0 + (c >> 18), 0x80 + (c >> 12 & 0x3F), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    }
    return enc;
}


/**
* initializes search form; handles enter keyup event and click events
*
* @author Rocco Janse <rocco@efocus.nl>
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @since 1.1, 30 nov, 2009
* @return void(0)
*/
function initSearchForm() {
	var forms = $$('fieldset.header_search').combine($$('fieldset.f15_searchresults'));
	if (forms.length == 0) return;

	var buildUrl = function(form) {
		var input = form.getElement('input.search_field');

		var url = form.getElement('input.search_url').get('value');
		url += encodeURIComponent(input.get('value'));
		return (url);
	};

	forms.each(function(form) {

		var input = form.getElement('input.search_field');
		var button = form.getElement('.search_button');

		input.addEvents({
			'keyup': function(e) {
				if (e.key == 'enter' && input.get('value') != '') {
					e.stop();
					window.location = buildUrl(form);
				}
			}
		});
		button.addEvents({
			'click': function(e) {
				if (input.get('value') != '') {
					e.stop();
					window.location = buildUrl(form);
				}
			},
			'keyup': function(e) {
				if (e.key == 'enter' && input.get('value') != '') {
					e.stop();
					window.location = buildUrl(form);
				}
			}
		});
	});
}


/**
 * starts carrousel functionality
 *
 * @author Rocco Janse <rocco{at}efocus.nl>
 * @since 1.0, 27 sept, 2009
 * @return void
 */

function startCarrousel() {
	
	var cselcontainer = $(document.body).getElement('div.carrousel_viewport');
	if (!cselcontainer) return;
	var slidescontainer = cselcontainer.getElement('ul.carrousel_slides');
	if (!slidescontainer) return;

	var link_next = $(document.body).getElement('a.next');
	var link_prev = $(document.body).getElement('a.prev');
	if (!link_next || !link_prev) return;

	var csel = new Carrousel({
		'viewport': cselcontainer,
		'slidesContainer': slidescontainer,
		'linkNext': link_next,
		'linkPrevious': link_prev,
		'slidesToShift': 1,
		'slidesToShow': 1	
	});
}