/**
 * file default.js
 *
 * contains javascript for Intertrust website
 *
 * @require MooTools version 1.2.1
 */


window.addEvents({
    'domready': function() {
        initExternalLinks();
        initSubservices();
        initSendaFriend();
        initFaq();
        mapRollover();
        initDropdowns();
        attachCalendars();
		initAccordionConditions();
		startPushbox();
    },
    'load': function() {
    
		insertJWplayer();
        fixHoogteSitemap();
        defaultInputText();
        Shadowbox.init({ players: ["img", "html", "iframe", "ashx"] })       
    }
});

/**
 * starts pushbox
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @since 1.0, 14 aug, 2009
 * @return void
 */

function startPushbox() {
	if (!$('pushbox')) return;
	var pbox = new Pushbox({
		'viewport': $('pushbox').getElement('div.viewport'),
		'slides': $('pushbox').getElement('ul.slides').getElements('li'),
		'navigation': $('pushbox').getElement('ul.pushbox_nav').getElements('li'),
		'transition': 'fade',
		'delay': 10
	});
}

/**
 * initSubservices
 *
 * puts Subservice details in an accordion
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
function initSubservices() {
	if($$('div.subservicedetail').length < 1 && $$('div.subservicedetail').length != $$('p.togglesubservice').length) return false;
	var accordion = new Accordion('p.togglesubservice a', 'div.subservicedetail', {
		onActive: function(toggler) {
			toggler.removeClass('expand');
			toggler.addClass('collapse');
			toggler.set('text', 'Hide details');
			toggler.blur();
		},
		onBackground: function(toggler) {
			toggler.removeClass('collapse');
			toggler.addClass('expand');
			toggler.set('text', 'More');
			toggler.blur();
		},
		alwaysHide: true,
		show: -1,
		duration: 500
	});
}


/**
 * initFaq
 *
 * puts faq answer details in an accordion
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
 
function initFaq() {
	if($$('div.faqdetail').length < 1 && $$('div.faqdetail').length != $$('p.toggleanswer').length) return false;
	var accordion = new Accordion('p.toggleanswer a', 'div.faqdetail', {
		onActive: function(toggler) {
			toggler.removeClass('expand');
			toggler.addClass('collapse');
			toggler.set('text', 'Hide the answer');
			toggler.blur();
		},
		onBackground: function(toggler) {
			toggler.removeClass('collapse');
			toggler.addClass('expand');
			toggler.set('text', 'Show the answer');
			toggler.blur();
		},
		alwaysHide: true,
		show: -1,
		duration: 500
	});
}


/**
* mapRollover
*
* set rollovers global map
*
* @author Mirjam <mirjam{AT}efocus.nl>
* @return void
*/

function mapRollover() {

    if (!$('rollovers')) return;
    
    var continents = $('rollovers').getElements('area');

    continents.each(function(continent) {

        var thisRollOver = continent.getParent('div').getElementById(continent.get('id') + '_rollover');

        continent.addEvents({
            'mouseenter': function() {

                hideMapRollovers(); 
                
                thisRollOver.addClass('active');
                this.getParent('div').getElement('img').src = '../siteimg/bg_worldmap_' + this.get('id') + '.png';
                /*thisRollOver.getElement('span.close').addEvent('click', function(){
                    hideMapRollovers();
                });*/

            }
        });

    });
    document.getElement('div.worldmapcontainer').addEvent('mouseleave', hideMapRollovers);
       
}

/**
* hideMapRollovers
*
* hide all rollovers global map
*
* @author Mirjam <mirjam{AT}efocus.nl>
* @return void
*/

function hideMapRollovers() {
    
    
    var continents = $('rollovers').getElements('area');

    continents.each(function(continent) {

        var thisRollOver = continent.getParent('div').getElementById(continent.get('id') + '_rollover');
        thisRollOver.removeClass('active');
        
    });
    
    $$('div.worldmapcontainer')[0].getElement('img').src = '/siteimg/bg_worldmap.png';
    
}


/**
 * fixHoogteSitemap
 *
 * Zet de hoogte van de sitemap blokken even hoog.
 *
 * @author Jasper Leferink <jasper.leferink{AT}efocus.nl>
 * @editor Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */

function fixHoogteSitemap() {
	if (!document.getElement('.sitemap')) return;

	var intMaxHeight = 0;
	var arrSitemapListItems = document.getElement('.sitemap').getChildren('li');

	arrSitemapListItems.each(function(elSitemapListItem, i) {
		if (elSitemapListItem.getHeight() > intMaxHeight) {
			intMaxHeight = elSitemapListItem.getHeight();
		}
		if (!((i + 1) % 3)) {
			arrSitemapListItems[i-2].setStyle('height', intMaxHeight);
			arrSitemapListItems[i-1].setStyle('height', intMaxHeight);
			arrSitemapListItems[i].setStyle('height', intMaxHeight);
			intMaxHeight = 0;
		}
	});
}


/**
 * initSendaFriend
 *
 * initializes Send a friend form popup functionality
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
 
function initSendaFriend() {
	if(!$('sendafriend') || !$('sendafriendlink')) return false;
	
	var safHeight = $('sendafriend').getElement('div.popup').getSize().y + $('sendafriend').getElement('h3.top').getSize().y + 10;
	var safWidth = $('sendafriend').getElement('div.popup').getSize().x;

	$('sendafriend').setStyles({
		'height': 0,
		'width': 0,
		'top': $('sendafriendlink').getPosition(document.getElement('div.header_bottompane')).y - $('sendafriendlink').getSize().y,
		'left': $('sendafriendlink').getPosition(document.getElement('div.header_bottompane')).x + $('sendafriendlink').getSize().x
	});

	var openSendaFriend = function() {

	    var effect = new Fx.Morph($('sendafriend'));
	    
	    $('sendafriendlink').blur();
	    effect.start({
	        'height': safHeight,
	        'width': safWidth
	    }).chain(function() {setSendHeight()} );
	}
	
	var closeSendaFriend = function() {
		$('sendafriend').morph({
			'height': 0,
			'width': 0
		});
	}
	
	$('sendafriendlink').addEvent('click', openSendaFriend);
	$('sendafriendclose').addEvent('click', closeSendaFriend);

	initAntibot();
}


/**
 * initDropdowns
 * initiates the dropdown lists
 *
 * @author Rocco Janse <rocco[at]efocus.nl>
 * @return void
 */

function initDropdowns() {

    var dropdowns = $$('ul.dropdown');
    if (dropdowns.length == 0) return;

    dropdowns.each(function(dropdown) {
        dropdown.addEvents({
            'click': function() {
                dropdown.toggleClass('open');
            },
            'mouseleave': function() {
                dropdown.removeClass('open');
            }
        });
    });
}

/**
 * GetEnter
 * Gets the key "enter" on the input
 *
 * @author Jeroen Datema <jeroen.datema[at]efocus.nl>
 * @return void
 */
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;
}

/**
 * RedirectZoek
 *
 * @author Jeroen Datema <jeroen.datema[at]efocus.nl>
 * @return void
 */
function RedirectZoek(url, zoekstring) {
    window.location = url + "?q=" + encodeURIComponentNew(zoekstring);
    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;
}

/**
 * initExternalLinks
 * Opens external links valid in a new window without the target attribute.
 *
 * @author CSD (clientsidedevelopers[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'));
        });
    });
}

/**
 * initAntibot
 * replacement for capchta's
 *
 * @author: Klaas Dieleman, <klaas{at}efocus.nl>
 */
 
function initAntibot() {
	var inputs = $$('div.popup input.text');
	inputs.each(function(input) {
	    input.addEvent('keyup', function() {
	        $('sendafriend').getElement('input.antibotsecurity').set('value', 'antibotValid');
	    });
	});
}

/**
* defaultInputText
*
* toggles default text in text inputfields
*
* @author Klaas Dieleman <klaas{AT}efocus.nl>
* @return void
*/

function defaultInputText() {
    var inputfields = $$('.default');

    inputfields.each(function(item) {
        item.defaultText = item.value;

        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');
                }
            }
        });
    });
}


function setSendHeight() {
    if (!$('sendafriend') || !$('sendafriendlink')) return false;
    var safHeight = $('sendafriend').getElement('div.popup').getSize().y + $('sendafriend').getElement('h3.top').getSize().y + $('sendafriend').getElement('div.error').getSize().y + 10;
    $('sendafriend').setStyles({
        height: safHeight
    });
}


/**
 * Finds all datefields and attaches a calendar
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @return void
 */
 function attachCalendars() {
 	
	$$('input.datefield').each( function(el) {
		if ( $chk(el.getProperty('id')) ) {
			var id = el.getProperty('id');
			
			// the reference to the object
			var reference = new Object();
			reference[id] = 'd-m-Y';

			// options
			var options = new Object();
			options.classes = ['calendar'];
			options.tweak = {x: -170, y: 15};
			options.readOnly = true;
			
			/*// only attach a calendar if one is not yet attached
			var nextSibling = $(id).getNext();*/
			
			//if (!$chk(nextSibling) || nextSibling.getProperty('class') != 'calendar') {
				myCal = new Calendar(reference, options);
			//}
		}
	});
}



/**
 * initAccordionConditions
 *
 * puts Specifications list in an accordion
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 * @editor Phi Son Do <phison.do{AT}efocus.nl>
 * 
 * @return void
 */

function initAccordionConditions() {
	if(!document.getElement('ol.conditions')) return false;

	var arrConditionListItems = $$('ol.conditions>li');
		
	arrConditionListItems.each(function(elConditionListItem) {		
		elConditionListItem.addClass('closed')		
		elConditionListItem.getElement('h3').addEvent('click', function() {			
			this.addClass('open');						
			if (elConditionListItem.hasClass('closed')) {
				arrConditionListItems.addClass('closed');
				elConditionListItem.removeClass('closed');
			} else {
				elConditionListItem.addClass('closed');
			}			
		});
		
		if (Browser.Engine.trident && Browser.Engine.version == 4) {
		} else {			
			var ConditionsAccordionInner = new Accordion(elConditionListItem.getElements('h4'), elConditionListItem.getElements('div.outer_panel'), {
				onActive: function(toggler, element) {
					toggler.getParent().addClass('active');
				},
				onBackground: function(toggler, element) {
					toggler.getParent().removeClass('active');
				},
				alwaysHide: true,
				show: -1
			});		
		}		
	});
	
	if (Browser.Engine.trident && Browser.Engine.version == 4) {
	
		var mainItems = $$('ol.conditions h4');
			mainItems.each(function(item) {				
				item.addEvent('click', function (){					
					if (item.getParent('li').getElement('div.outer_panel').getStyle('display') == 'block') {
						item.getParent('li').getElement('div.outer_panel').setStyle('display', 'none');
					} else {
						item.getParent('li').getElement('div.outer_panel').setStyle('display', 'block');
					}					
				});				
			});		
	}

}

function RemoveAndSetTableStyles() {
    var landtabel = document.getElement("table");
    if (landtabel != null) {
        landtabel.removeProperty("style");
        landtabel.border = "1";
        landtabel.className = "landtabel";

        var rows = landtabel.getElementsByTagName("tr");

        for (i = 0; i < rows.length; i++) {

            var cells = rows[i].getElementsByTagName("td");
            //alert(cells.length);
            cells[0].className = "landtabel_cell";
        }
    }
    
}

/**
* insertJWplayer
*
* replaces hyperlinks to flv media (in the Sitecore medialibrary) with instance of JWplayer,
* adopting the source videofile plus the width and height of the placeholder image inside the hyperlink
*
* @author Klaas Dieleman <klaas{AT}efocus.nl>
* 
*/

function insertJWplayer() {

    var requiredFlashVersion = 9;
    var jwlinks = new Array;

//    document.getElements('a').each(function(item) {

//        var str = item.getProperty('href');
//        document.write(str);
//        var pos = str.indexOf("~/media/video/");
//        if (pos >= 0) {
//            jwlinks.include(item);
//        }
//    });

    document.getElements('a').each(function(item) {
   
        if (item.getProperty('href') && item.getElement('img'))
 
        //        var str = item.getProperty('href');
        //        document.write(str);

        var pos = item.getProperty('href').indexOf("~/media/Video/");
    if (pos >= 0) {
            jwlinks.include(item);
        }
    });

    if ($$('div.f33_accordion').length > 0 && Browser.Engine.webkit == false) {
        $$('div.slides div.slidevideo').setStyle('display', 'block');
        $$('div.slides div.slidevideo').setStyle('position', 'absolute');
        $$('div.slides div.slidevideo').setStyle('left', -99999);
    }

    constructMovieObject = function(item) {

        var jwFile = item.getProperty('href');
        jwContainer = new Element('span');
        jwContainer.inject(item, 'after');
        if (Browser.Plugins.Flash.version >= requiredFlashVersion) {

            var s1 = new SWFObject("/flash/player.swf", "player", item.getElement('img').getStyle('width'), item.getElement('img').getStyle('height'), item.getElement('img').getStyle('border'), requiredFlashVersion);
            s1.addParam("allowfullscreen", "true");
            s1.addParam("allowscriptaccess", "always");
            s1.addParam("wmode", "transparent");
            s1.addVariable("file", jwFile);
            s1.addVariable("type", "video");
            s1.write(jwContainer);
            item.destroy();
        }
    };

    jwlinks.each(function(item) {
        constructMovieObject(item);
    });

    if ($$('div.f33_accordion').length > 0) {
        $$('div.slides div.slidevideo').removeProperty('style');
    }

}

