/**
 * @author Remco
 */
$(window).addEvent('domready', ynkify );
var myAccordion;
    initReadMore();
    initArticleImages();
function ynkify()
{
	buildSubnavImages();
	buildNavAccordeon();
	onResize();
	window.addEvent('resize', onResize );
	
	$('content').set( 'morph', { duration: 1000, transition: Fx.Transitions.Sine.easeOut } );
	
	if ( window.location.hash.length >= 2 )
	{
	    $('content').store( 'path', window.location.hash.substr(1) );
	    loadContent();
	} else {
	    loadMathFlash();
	}
	
	initFAQ();
}

function buildSubnavImages()
{
	var navElements = $('navigation').getElements ( 'ul ul a' );	
			
	var subCounter = 1;
	var itemHeight = 17;
	var itemWidth  = 172;
	
	$each ( navElements, function( item ){
		
		/*item.getElement('span').setStyle('display', 'none' );
		item.setStyle( 'background-image', 'url(assets/img/subnav/subnav_s'+item.getProperty('rel')+'.png)' );
		
		if ( item.hasClass ( 'active') ) item.setStyle ( 'background-position', '-' + itemWidth + 'px 0');*/
		
		subCounter++;
	} );
}

function buildLogoImages()
{	
	$$('.logocontainer .logo').addEvents ( {
			'mouseover': hideLogo,
			'mouseout': showLogo } );
}

function showLogo(){
	$(this).getElement ( 'img' ).setStyle ( 'display', 'block' );
	$(this).getElement ( 'span' ).setStyle ( 'display', 'none' );
}

function hideLogo(){
	$(this).getElement ( 'img' ).setStyle ( 'display', 'none' );
	$(this).getElement ( 'span' ).setStyle ( 'display', 'block' );
}

function onResize()
{
    var extractor = $('header').getStyle('height').toInt();
    var borders = 4;
	var height = $(window).getSize().y - extractor;
	height = Math.max( height, 600 - extractor );
	$('content').setStyle('height', height - borders );
	
	if ( Browser.Engine.trident ) {
    	$('content').addEvent('scroll', function() {
    	    $(this).setStyle('display', 'none');
    	    $(this).setStyle('display', 'block');
    	} );
	}
	
	$('navigation').setStyle('height', height - borders );
	$('container').setStyles({
	   'top': '0px',
	   'margin-top' : 0,
	   'height' : ($(window).getSize().y - borders) +'px'
	});
}

function buildNavAccordeon()
{
    var togglers = [];
    $$('.toggle>li a').each(function( item )
    {
        if ( item.getParent().getElement('ul') )
        {
            togglers.push( item );
            item.addEvent('click', function(){
                return false;
            });
        }
    });
    myAccordion = new Accordion( togglers, $$('.toggle li ul'), {
        start : true
    });
    $$('.toggle>li a').each( function( item ) {
        item.addEvent('click', getContents );
    });
	
}

function getContents()
{
    var c = $(this).getProperty('href');
    if ( c != null )
    {
        c = c.split('index.php')[1];
        if ( c.length >= 2 )
        {
            navigateTo( c );
        }
        var myScr = new Fx.Scroll($('content')).start(0,0);
    }
    
    $$('.toggle>li a').removeClass('active');
    $(this).addClass('active');
    
    return false;
}

var contentHolder = '';

function navigateTo( _url )
{
    $('content').store( 'path', _url );
    $('content').morph( {
        opacity: -1,
        onComplete: loadContent
    } );
}

function loadContent()
{
    var myHTMLRequest = new Request.HTML( { onComplete : onContentSwitch } );
    myHTMLRequest.get( 'index.php/ajax'+$('content').retrieve( 'path' ) );
    window.location.hash = $('content').retrieve( 'path' );
}

function onContentSwitch( responseTree, responseElements, responseHTML, responseJavaScript )
{
    contentHolder = responseHTML;
    $('content').set('html', contentHolder );
    $('content').morph( {
        opacity: 1
    });
    buildLogoImages();
    //initMathCredit();
    loadMathFlash();
    initContactForm();
    /*if (    window.location.hash.indexOf('veelgestelde_vragen') >= 0 ||
            window.location.href.indexOf('faq') >= 0 )
    {*/
        initFAQ();
    //}
    initReadMore();
    initArticleImages();
    pageTracker._trackPageview( window.location.hash.substr( 1 ) );
}

function initArticleImages()
{
    $$('.article_image').addEvent( 'load', function(){
        if ( $(this).width > 250 ) {
            $(this).setStyle( 'width', '250px' );
        }
    } );
    $$('.article_image').each( function( item ){
        if ( $(item).width > 250 ) {
            $(item).setStyle( 'width', '250px' );
        }
    } );
}

function initContactForm()
{
    $$('#contact_form').addEvent( 'submit',function( e ) {
        new Event(e).stop();
        
        var error = false;
        var sendStr = '';
        
        var requiredFields = new Array( 'initials', 'surname', 'phonenumber' );
        $$('#contact_form input').each(function(item) {
            
            for (var i in requiredFields )
            {
                var val = item.getProperty('value');
                if ( val.indexOf(' ') >= 0 )
                    val = val.split(' ').join('');
                if ( requiredFields[i] == item.getProperty('name') )
                {
                    if ( val == '' )
                    {
                        error = true;
                        item.setStyle('border', '1px #f00 solid');
                    } else {
                        item.setStyle('border', 'none');
                    }
                }
            }
            if ( item.getProperty('name') == 'gender' ) {
                sendStr += ( item.getProperty('checked') == true ) ? 'gender='+item.getProperty('value')+'&' : '' ;
            } else {
                sendStr += item.getProperty('name') +'='+item.getProperty('value')+'&';
            }
        });
        sendStr += $('question').getProperty('name') +'='+$('question').getProperty('value');
        if ( !error )
        {
            if ( document.location.href.indexOf('index.php') >= 0 ) {
                var _url = document.location.href.split('index.php')[0] + 'index.php';
            } else {
                var _url = document.location.href.split('#')[0]+'index.php';
            }
            var myRequest = new Request({method: 'post', url: _url+'/ajax/contact_data/handle'});
            
            myRequest.addEvent('request', function() {
                $$('#contact_form .submit_contact').morph({ 'background-color': '#0f0' });
                $$('#contact_form .submit_contact').setProperty( 'value', 'Verstuurd');
                $$('#contact_form .submit_contact').setProperty( 'disabled', 'disabled');
                $$('#contact_form .submit_contact').removeEvents('submit');
                $$('#contact_form .submit_contact').addEvent('submit', function(e){ new Event(e).stop(); });
                $$('#contact_form fieldset').morph({ 'height': '0px', 'opacity' : 0 });
                var myScr = new Fx.Scroll($('content')).start(0,0);
                $$('#contact_form').adopt( new Element( 'p', {
                        'html' : 'Bedankt voor uw reactie. We gaan er zo snel mogelijk mee aan de slag.',
                        'class' : 'notice'
                    }));
            });
            myRequest.addEvent('failure', function() {
                $$('#contact_form .submit_contact').morph({ 'background-color': '#f00' });
                $$('#contact_form .submit_contact').setProperty( 'value', 'Mislukt');
            });
            
            myRequest.send(sendStr.substr(0,sendStr.length -1));
        }


    });
}

function loadMathFlash( load )
{
    if ( $('mrynk_flash') )
    {
        swfobject.embedSWF("./assets/swf/rekenmodule_maximaal.swf", "mrynk_flash", "622", "400", "8.0.0", "expressInstall.swf", {}, {wmode : 'transparent'});
    }
}

function initFAQ()
{
    $$('#content div.collapseable div.content_item_header').setStyle( 'cursor', 'pointer' );
    $$('#content div.collapseable div.content_item_header').store( 'closed', true );
    var togglers = $$('#content div.collapseable div.content_item_header');
    var contents = $$('#content div.collapseable div.content_item_content');
    if (    window.location.hash.indexOf('veelgestelde_vragen') >= 0 ||
            window.location.href.indexOf('faq') >= 0 )
    {
        togglers.shift();
        contents.shift();
    }
    
    togglers.setStyle('padding-left', '20px');
    togglers.setStyle('background', "#fff url('assets/img/list-closed.png') top right no-repeat");
    $$('#content div.collapseable div.content_item_header').addEvent( 'click', function() {
        if ( $(this).retrieve('closed') == true )
        {
            togglers.setStyle('background', "#fff url('assets/img/list-closed.png') top right no-repeat");
            $(this).setStyle('background', "#fff url('assets/img/list-open.png') top right no-repeat");
        } else {
            $(this).setStyle('background', "#fff url('assets/img/list-closed.png') top right no-repeat");
        }
        $(this).store( 'closed', !$(this).retrieve('closed') );
    } );
    
    myAccordion = new Accordion( togglers, contents, {
        start : true,
        alwaysHide: true
    });
}

function initReadMore()
{
    $$('#content div.content_item_content.readmore').each(function( item ) {
        $$('#content div.content_item').setStyle('position','relative');
        item.setStyle( 'height', '200px' );
        item.setStyle( 'overflow', 'hidden' );
        if ( item.getScrollSize().y >= 210 )
        {
            var newElm = new Element('a', {
                'href':'',
                'html':'Lees meer',
                'class':'read_more',
                'styles': {
                    'position':'absolute',
                    'font-size':'70%',
                    'font-weight':'bolder',
                    'display':'block',
                    'width':'55%',
                    'background-color':'#E3E4E5',
                    'top':'209px',
                    'padding-bottom':'6px',
                    'padding-top':'6px',
                    'z-index': 5
                    },
                'events' : {
                    'click' : function() {
                        $(this).setStyle('display', 'none');
                        item.set('morph', {duration: 500});
                        item.morph({
                            'height' : item.getScrollSize().y
                        });
                        return false;
                    }
                }
            });
            item.adopt( newElm );
        }
    });
}
