window.addEvent('domready', function() {
    FoldLanguages();
    InitListFilter();
    initFAQcordion();
    initWorldmap();
    initLocationMap();
    initStoryCarrousel();
    initOrganogramAnchors();
});

window.addEvent('load', function() {
    initCategoryMenu();
    initWorldmapContinents();
    loadAlignContinentList();
});

function GetEnter(url, e, zoekstring) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13) {
        window.location = url + "?q=" + encodeURIComponentNew(zoekstring);
        return false;
    }
    else
        return true;
}

function SetLanguage(code) {
    // set time, it's in milliseconds
    var today = new Date();
    var expires = 28 * 1000 * 60 * 60 * 24;
    var expires_date = new Date(today.getTime() + expires);
    var domainparts = window.location.hostname.split('.');
    var domain = '.' + domainparts[domainparts.length - 2] + '.' + domainparts[domainparts.length - 1];

    document.cookie = "FrieslandCampinaLanguage" + "=" + code +
        ";expires=" + expires_date.toGMTString() +
        ";domain=" + domain +
        ";path=/";
}

function RedirectZoek(url, zoekstring) {
    window.location = url + "?q=" + encodeURIComponentNew(zoekstring);
    return false;
}

/**
 * FoldLanguages
 *
 * collapses/expands other languages in language selection
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function FoldLanguages() {
	if (!$$('dl.language dd a')[0]) return;	
	$$('dl.language dd a')[0].addEvent('click', function() {
		this.getParent().getParent().toggleClass('lang_open');
		this.blur();
	});
}


// ------------------------------------------------ BEGIN List Filter Functions

function InitListFilter() {
    // there can/should be only one tagfilter on the page and its id is always 'tagfilter'
    var filterdiv = $('tagfilter');
    if (filterdiv == null) return;

    // set filter checkboxes based on querystringparam 'tagfilter'
    // the tagfiltervalue is a list of tagvalues seperated by '|'
    var tagfiltervalue = '|' + getQsParam('tagfilter') + '|';
    var checkboxes = filterdiv.getElementsByTagName('input');
    for (var i=0; i<checkboxes.length; i++) {
        if (checkboxes[i].type != 'checkbox') continue;
        if (checkboxes[i].value == 'All') {
            checkboxes[i].checked = tagfiltervalue.length == 2;
        }
        else {
            checkboxes[i].checked = tagfiltervalue.toLowerCase().indexOf('|' + checkboxes[i].value.toLowerCase() + '|') >= 0;
        }
    }
}

// return url, optionally with querystringpart and anchorpart
function getUrl(url, withQs, withAnchor) {
    var splits1 = url.split('#');
    var splits2 = splits1[0].split('?');

    var urlwithoutqs = splits2[0];
    var urlwithqs = splits2[1] ? splits2[0] + '?' + splits2[1] : splits2[0];
    var urlwithanchor = splits1[1] ? urlwithqs + '#' + splits1[1] : urlwithqs;

    if (!withQs && !withAnchor) return urlwithoutqs;
    else if (!withAnchor) return urlwithqs;
    else return urlwithanchor;
}

// parse querystring to assoc array
function parseQuerystring(url) {
    var arr = {};
    var que = url;
    if (que.indexOf('?') >= 0)
        que = que.substring(que.indexOf('?') + 1);
    else que = "";

    if (que != "") {
        que = que.split("&");

        for (var i = 0; i < que.length; i++) {
            var inter = que[i].split("=");
            var inter2 = inter[1];
            var inter3 = inter[0];
            que[i] = inter2;
            arr[inter3] = inter2;
        }
    }
    return arr;
}

// read param from current url and return value
function getQsParam(param) {
    var querystring = parseQuerystring(location.href);
    return querystring[param] ? unescape(querystring[param]) : '';
}

function listfilterReset() {
    var url = getUrl(location.href, true, false);
    url = removeQsParam(url, 'tagfilter');
    url = removeQsParam(url, 'pagnr');
    location.href = url;
}

function listfilterUpdate(tag) {
    var tagfiltervalues = getQsParam('tagfilter');
    var url = getUrl(location.href, true, false);
    if (tagfiltervalues == '') {
        url = setQsParam(url, 'tagfilter', tag);
    }
    else {
        tagfiltervalues = tagfiltervalues.split('|');
        if (InArray(tagfiltervalues, tag)) {
            var tagfiltervalues2 = [];
            for (var i = 0; i < tagfiltervalues.length; i++)
                if (tagfiltervalues[i] != tag) tagfiltervalues2.push(tagfiltervalues[i]);
            if(tagfiltervalues2.length == 0)
                url = removeQsParam(url, 'tagfilter');
            else
                url = setQsParam(url, 'tagfilter', tagfiltervalues2.join('|'));
        }
        else {
            tagfiltervalues.push(tag);
            url = setQsParam(url, 'tagfilter', tagfiltervalues.join('|'));
        }
    }
    url = removeQsParam(url, 'pagnr');
    location.href = url;
}

function InArray(arr, scalar) {
    for (var i = 0; i < arr.length; i++)
        if (arr[i] == scalar) return true;
    return false;
}

function removeQsParam(url, param) {
    // remove param from url and return result

    var querystring = parseQuerystring(url);
    delete (querystring[param]);

    var vars = [];
    for (var i in querystring) vars.push(i + '=' + querystring[i]);
    url = getUrl(url, false, false);
    if (vars.length > 0) url += '?' + vars.join('&');

    return url;
}

function setQsParam(url, param, value) {
    // update or add param to url and return result

    var querystring = parseQuerystring(url);
    querystring[param] = value;

    var vars = [];
    for (var i in querystring) vars.push(i + '=' + querystring[i]);
    url = getUrl(url, false, false);
    if (vars.length > 0) url += '?' + vars.join('&');

    return url;
}

// ------------------------------------------------ END List Filter Functions

/**
* listPeriodChange
*
* changes list period without disturbing other querystring parameters, but reset pagnr
*
* @author Barend van der Hout <barend{AT}efocus.nl>
* @return false
*/
function listPeriodChange(qsvar, value) {
    var url = getUrl(location.href, true, false);
    url = removeQsParam(url, 'pagnr');
    if (value) url = setQsParam(url, qsvar, ''+value);
    else url = removeQsParam(url, qsvar);
    location.href = url;
    return false;
}

/**
* showContenttab
*
* switches the current displayed tab
*
* @author Barend van der Hout <barend{AT}efocus.nl>
* @return false
*/
function showContenttab(tabnumber) {
    // reset all tabs
    for (var i = 1; i <= 7; i++)
        if ($('contenttab' + i)) $('contenttab' + i).className = 'contenttab';
    // activate desired tab
    $('contenttab' + tabnumber).className = 'contenttab_active';
    // stop page refresh
    return false;
}


/**
 * initFAQcordion
 *
 * initializes accordion in FAQ list
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function initFAQcordion() {
	var FAQcordion = new Accordion($$('div.f22_faq dt'), $$('div.f22_faq dd'), {
		show: -1,
		alwaysHide: true,
		onActive: function(toggler, element) {
			toggler.addClass('open');
			element.addClass('open');
		},
		onBackground: function(toggler, element) {
			toggler.removeClass('open');
			element.removeClass('open');
		}
	});
	
	var anchor = document.location.href.split("#")[1] + "-answer";
	FAQcordion.display($(anchor));
}


/**
 * initWorldmap
 *
 * initializes mouseovers in World map
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function initWorldmap() {
	if(!$('globalmap')) return false;
	
	var continents = new Array;
	continents[0] = $('europe_map');
	continents[1] = $('northamerica_map');
	continents[2] = $('asia_map');
	continents[3] = $('southamerica_map');
	continents[4] = $('australia_map');
	continents[5] = $('africa_map');
	
	continents[0].image = 'map_europe.png';
	continents[1].image = 'map_northamerica.png';
	continents[2].image = 'map_asia.png';
	continents[3].image = 'map_southamerica.png';
	continents[4].image = 'map_australia.png';
	continents[5].image = 'map_africa.png';
	
	var globalimage = $('global_image').getProperty('src');
	var urlprefix = '';
	for (n = 0; n < globalimage.split('/').length - 1; n ++) {
		urlprefix += globalimage.split('/')[n];
		urlprefix += '/';
	}
	
	continents.each(function(continent, index) {
		continent.addEvents({
			'mouseenter': function() {
				$('global_image').setProperty('src', urlprefix + this.image);
				$$('div.f50_globalmap ul.tabs a')[index].addClass('hover');
			},
			'mouseleave': function() {
				$('global_image').setProperty('src', globalimage);
				$$('div.f50_globalmap ul.tabs a')[index].removeClass('hover');
			}
		})
		
		$$('div.f50_globalmap ul.tabs a')[index].addEvents({
			'mouseenter': function() {
				$('global_image').setProperty('src', urlprefix + continents[index].image);
			},
			'mouseleave': function() {
				$('global_image').setProperty('src', globalimage);
			}
		})
	});
}


/**
* inserts a simple Google Map with a custom icon (F90)
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/
function initLocationMap() {
	var elMap = $('location_map');
	if (!$defined(elMap)) return false;
	
	// get icon within holder
	var elIcon = elMap.getElement('img.icon_location');
	if (elIcon) {
		var strIconSrc = elIcon.getAttribute('src');
		var intIconWidth = elIcon.getWidth();
		var intIconHeight = elIcon.getHeight();
	}

	// get coordinates within holder
	var strCoordinates = elMap.getElement('.location_coordinates').get('text');

	if (GBrowserIsCompatible()) {
		// initalize map
		var map = new GMap2(elMap);

		// define marker icon
		if (elIcon) {
			var icon = new GIcon();
			icon.image = strIconSrc;
			icon.iconSize = new GSize(intIconWidth, intIconHeight);
			icon.iconAnchor = new GPoint((intIconWidth / 2), intIconHeight);
			icon.infoWindowAnchor = new GPoint(0, 0);
		}

		// generate a marker
		if (!$empty(strCoordinates)) {
			var arrCoordinates = strCoordinates.split(',');
			var point = new GLatLng(arrCoordinates[0].toFloat(), arrCoordinates[1].toFloat());
			var marker = (icon) ? new GMarker(point, icon) : new GMarker(point);
			map.addOverlay(marker);
			map.setCenter(point, 9);
		}
	}
}


/**
 * resizeDiv
 * resizes a div to given height using an animation
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @param integer height height in pixels to resize to
 * @param string id of the target element
 * @return void
 */
 
function resizeDiv(height, id) {
    if ($(id)) {
        animateMe(height, id);
    }
    $(id).blur();
}

/**
 * resizeSwf
 * resizes a swf to given height using an animation if not IE
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @param integer height height in pixels to resize to
 * @param string id of the target element
 * @return void
 */
 
function resizeSwf(height, id) {
    if ($(id)) {
        if(Browser.Engine.trident) {
            // IE cannot animate SWF objects
            initMe(height, id);
        } else {
            animateMe(height, id);
        }
    }
    $(id).blur();
}

/**
 * initMe
 * initializes SWF Object height
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @param integer height height in pixels to resize to
 * @param string id of the target element
 * @return void
 */
 
function initMe(height, id) {
	document.getElementById(id).height = height;
}

/**
 * animateMe
 * handles resizing with a tween (animation)
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @param integer height height in pixels to resize to
 * @param string id of the target element
 * @return void
 */

function animateMe(height, id) {
    var elementFx = new Fx.Tween($(id));
    elementFx.start('height', height);
}

/**
 * @author Jeroen Datema <jeroendatema@efocus.nl>
**/
function change_class(obj, strClass) {
    obj.className = strClass;
} 

/**
 * initCategoryMenu
 * handles wiki category menu rollovers
 *
 * @author Rocco Janse, <rocco@efocus.nl>
 * @return void
 */
 
 function initCategoryMenu() {
    var menu = $('catmenu');
    if (!menu) return;
    
    var items = menu.getElements('li');
    
    items.each(function(item) {
        item.addEvents({
            'mouseover': function() {
                item.addClass('selected');
            },
            'mouseout': function() {
                item.removeClass('selected');
            },
            'click': function() {
                window.location = item.getElement('a').get('href');
            }
        });
    });
 }

/**
 * Enlarges the thumbnails of the gallery into the viewport.
 *
 * @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */
function initFarmGallery() {
 	var elFarmGallery = $(document).getElement('.farm_gallery');
 	if (!elFarmGallery) return false;

	if (!elFarmGallery.getElement('.viewport')) return false;
 	var elViewportImage = elFarmGallery.getElement('.viewport').getElement('img');
 	
 	if (!elFarmGallery.getElement('.farm_gallery_thumbs')) return false;
 	var arrGalleryThumbLinks = elFarmGallery.getElement('.farm_gallery_thumbs').getElements('a');

 	arrGalleryThumbLinks.each(function(elGalleryThumbLink) {
 		elGalleryThumbLink.addEvent('click', function(event) {
 			event.stop();
 			this.blur();
 			elViewportImage.setProperty('src', elGalleryThumbLink.get('href'));
 			elViewportImage.setProperty('alt', elGalleryThumbLink.get('title'));
 		});
 	});
}

/**
 * Loads a Google Map showing a single Open Day location.
 *
 * @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */
function initOpenDayDetailMap() {
 	var elMap = $('farm_map');
 	if (!elMap) return false;

 	var elCoordinates = elMap.getElement('.coordinates');

 	// initalize map
 	var map = new GMap2(elMap);
 	map.setCenter(new GLatLng(0, 0), 0);
 	map.addControl(new GSmallMapControl());
 	//map.addControl(new GMapTypeControl());

 	// add markers as events
 	if (elCoordinates) {
 		var arrCoordinates = elCoordinates.get('text').split(',');
 		var point = new GLatLng(arrCoordinates[0].toFloat(), arrCoordinates[1].toFloat());
 		var marker = new GMarker(point);
 		map.addOverlay(marker);
 	}

 	// center map
 	map.setCenter(point, 12);
}

 /**
* @author Jeroen Datema <jeroendatema@efocus.nl>
* Pas op: deze functie wordt ook na elke ajax-update uitgevoerd. 
**/
function initF11_Flash() {

    var cd = new Date;
    for(var i=1; i<=3; i++) {
        var position = i.toString();
        if (!$('fact' + position + '_content')) continue;
        // de linkto is optioneel
        var linkto = $('fact' + position + '_linkto') ? $('fact' + position + '_linkto').innerHTML : '';
        var fact = new Swiff('/include/FrieslandCampina/swf/fc_milkfact.swf?ignore='+cd.getTime(), {
            id: 'milkfact' + position,
            container: 'fact' + position,
            width: 198,
            height: 50,
            params: { wmode: 'transparent' },
            vars: {
                milkfact: $('fact'+position+'_content').innerHTML,
                linkto: linkto,
                soid: 'milkfact' + position,
                contid: 'fact' + position
            }
        });
    }
}

/** 
 * functie encodeURIComponentNew() doet escape() maar dan netjes unicode 
 */
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;
}


/**
 * makes related teaser stories browseable
 *
 * @author Klaas Dieleman <klaas[at]efocus.nl>
 * @return void
 */
function initStoryCarrousel() {
	if(!document.getElement('div.storycarrousel')) return false;
	
	var car = document.getElement('div.storycarrousel ul.stories');
	var prev = document.getElement('div.related_teaser_story p.tabbrowse span.prev');
	var next = document.getElement('div.related_teaser_story p.tabbrowse span.next');
	var slideWidth = car.getElement('li').getSize().x;
	var curSlide = 0;
	
	next.addEvent('click', function() {
		if(next.hasClass('inactive')) return false
		
		car.tween('margin-left', -(curSlide * slideWidth + slideWidth));
		curSlide++;
		
		if(curSlide > 0) prev.removeClass('inactive');
		if(curSlide >= car.getElements('li').length - 1) next.addClass('inactive');
	});
	
	prev.addEvent('click', function() {
		if(prev.hasClass('inactive')) return false
		
		car.tween('margin-left', -(curSlide * slideWidth - slideWidth));
		curSlide--;
		
		if(curSlide == 0) prev.addClass('inactive');
		if(curSlide < car.getElements('li').length - 1) next.removeClass('inactive');
	});
}


/**
 * shows continents on a worldmap using an image map
 *
 * @author Ralph Meeuws <ralph.meeuws[at]efocus.nl>
 * @return void
 */
function initWorldmapContinents() {
	if (!$('worldmap_continents')) return false;

	var elWorldmap = $(document).getElement('.worldmap');
	var strWorldmapImgSrc = elWorldmap.get('src');
	var strWorldmapImgSrcPath = strWorldmapImgSrc.split('.')[0];
	var strWorldmapImgSrcExt = strWorldmapImgSrc.split('.')[1];

	hideContinents = function() {
		elWorldmap.setProperty('src', strWorldmapImgSrc);
	}

	showContinent = function(intContinentIndex) {
		elWorldmap.setProperty('src', strWorldmapImgSrcPath + (intContinentIndex + 1) + '.' + strWorldmapImgSrcExt);
	}

	var arrWorldmapContinents = $('worldmap_continents').getElements('area');
	if (arrWorldmapContinents.length != 0) {
		arrWorldmapContinents.each(function(elWorldmapContinent, index) {
			elWorldmapContinent.addEvents({
				'mouseenter': function() {
					showContinent(index);
				},
				'mouseleave': function() {
					hideContinents();
				}
			});
		});
	}

	var arrTabsContinents = $(document).getElement('.worldmap_holder').getElement('.location_top_links').getElements('li');
	if (arrTabsContinents.length != 0) {
		arrTabsContinents.each(function(elTabsContinent, index) {
			elTabsContinent.addEvents({
				'mouseenter': function() {
					showContinent(index);
				},
				'mouseleave': function() {
					hideContinents();
				}
			});
		});
	}
	
	var arrListContinents = $(document).getElement('.continent_countries').getChildren('li');
	if (arrListContinents.length != 0) {
		arrListContinents.each(function(elListContinent, index) {
			elListContinent.addEvents({
				'mouseenter': function() {
					showContinent(index);
				},
				'mouseleave': function() {
					hideContinents();
				}
			});
		});
	}
}

/**
 * adds #content anchors to links in Organogram
 *
 * @author Klaas Dieleman <klaas[at]efocus.nl>
 * @return void
 */
function initOrganogramAnchors() {
	$$('ul.organogram a').each(function(item){
		item.set('href', item.get('href') + '#content');
	});
}


/**
* Measures the height of the heads and aligns the content beneath them.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @since 1.0, 21 may 2010
* @return void
*/

function loadAlignContinentList() {
	var arrContinentCountries = $$('ul.continent_countries > li');
	if (arrContinentCountries.length == 0) return false;

	var elBreak = new Element('br');

	arrContinentCountries.each(function(elContinentCountry) {
		var elHeadAnchor = elContinentCountry.getElement('h3 a');
		
		if (Math.ceil(elHeadAnchor.getStyle('line-height').toFloat()) == elHeadAnchor.getHeight() - elHeadAnchor.getStyle('padding-bottom').toInt()) {
			elBreak.clone().inject(elContinentCountry.getElement('h3'), 'after');
		}
	});
}