(function($) {
    $(document).ready(function() {
		$.fn.loadAjax = function(url, data, callback) {
            return $(this).empty().addClass('loading').load(url, data, callback);
        }

        // Add menu to main navigation
        $('#main-nav').simpleMenu({
            menuSelector: 'div.menu',
			hoverClass: 'current'
        });

        // Footer input labels should be inside their inputs and disappear when they are clicked.
        $('#footer label').each(function() {
            var $label = $(this),
                $input = $('#' + $label.attr('for'));
                
            if ($input.length) {
                $input.focus(function() {
                    $label.hide();
                }).blur(function() {
                    $label[$input.val() ? 'hide' : 'show']();
                });
            }
        });

        // FAQ items should become (in-)active when clicked.
        $('.faq li .faq-title').click(function(e) {
            $(this).parent().toggleClass('active');
            e.preventDefault();
            return false;
        });
			
			var hash = window.location.hash;
			if(hash) {
				var target = $(hash);
				if(target.length && target.closest('.faq').length) {
					target.toggleClass('active')
				}
			}


        // Add ajax functionality to rel="ajax" links
        $('a[rel=ajax]').live('click', function() {
            var target = $(this).attr('target') || 'div',
                $parents = (target.slice(0, 1) === '#') ? $(target) : $(this).parents(target),
                $target = $parents.length && $($parents[0]);

            if ($target) {
                $target.loadAjax($(this).attr('href'));
            }

            return false;
        });

		// Transform template elements
		var XMLTemplates = function() {
			var currency = /([0-9]+\.)([0-9]{2})/;
			var date = /([0-9]{4})([0-9]{2})([0-9]{2})/;
			var months = 'januari,februari,maart,april,mei,juni,juli,augustus,september,oktober,november,december'.split(',');

			function parseLabel(label) {
				if(currency.test(label)) {
					return label.replace(currency, '$1<sup>$2</sup>');
				} else if(date.test(label)){
					return label.replace(date, function(ignored, y, m, d) {
						return d +'&nbsp;'+ months[parseInt(m, 10)-1] +' '+ y;
					});
				} else {
					return label;
				}
			}
				
			$('.template[data]').each(function() {
				var $node = $(this);
				var data = $node.attr('data');
				var template = $node.html();
				$node.html('');
				$.get(data, function(xml) {
					var $doc = $(xml);
					$node.html(template.replace(/\$([^\$]+)\$/mg, function(ignored, tag) {
						var label = $doc.find(tag).text();
						return parseLabel(label);
					}));
				});
			});
		};

		var templates = new XMLTemplates();


		// Logo rotator
		var Rotator = function(node, settings) {
			this.root = node;
			this.items = $(node).find(settings.items);
			this.amount = this.items.length;
			this.index = settings.start || 0;

			this.show(this.index);
			this.timer = setInterval(this.next.bind(this), settings.interval || 4000);
		}

		Rotator.prototype = {
			show:function(index) {
				this.items.eq(this.index).hide();
				this.items.eq(index).fadeIn();
				this.index = index;
			},

			next:function() {
				var index = (this.index +1) % this.amount;
				this.show(index);
			}
		};

		var rotators = $('.logo-rotator');
		rotators.each(function() {
			new Rotator(this, {
				items: 'li',
				start: 0,
				interval: 4000
			});
		});


		// history page paging
		var HistoryPager = function(root) {
			this.root = $(root);
			this.pages = this.root.find('.box-page');
			this.amount = this.pages.length;
			this.buttons = this.pages.find('p.buttons');
			this.links = this.buttons.find('a');
			this.buttons.click(this.handleClick.bind(this));
			this.label = this.buttons.find('.page');
			this.pages.not('.active').hide();
			this.current = this.pages.filter('.active');
			this.index = 0;
			this.checkState();
		}

		HistoryPager.prototype = {
			handleClick:function(e) {
				var link = $(e.target).closest('a')[0];
				if(link) {
					e.preventDefault();
					
					if(/back/i.test(link.className)) {
						this.index = Math.max(0, this.index -1);
					} else {
						this.index = Math.min(this.amount-1, this.index +1);
					}
					this.checkState();

					$('html,body').animate({scrollTop: this.root.offset().top});
				}
			},

			checkState:function() {
				var index = this.index;
				
				this.links.removeClass('disabled');
				if(index == 0) {
					this.links.eq(0).addClass('disabled');
				}
				if(index == this.amount -1) {
					this.links.eq(1).addClass('disabled');
				}

				this.pages.hide().eq(index).show();
				this.current = this.pages.eq(index);
				this.current.append(this.buttons);
				this.label.html((index+1) + ' van ' + this.amount);
			}
		}

		$('.box-history .box-content').each(function() {
			new HistoryPager(this);
		});

		

        // Add rounded corners to lots of elements.
		if(!/msie\s?6/i.test(navigator.userAgent)) {
			$('.darkbox, .faq li, .faq .faq-title').corner('10px');
			$('#main-nav>li>a, #main-nav>li>ul>li>a, #sub-nav>li>a, #sub-sub-nav>li>a, #meta-nav a, #footer a').corner('5px');

			$('.banner').css({border: 'none'}).corner('3px').
				wrap('<span />').parent().css({padding: '5px', display: 'block', background: 'white'}).corner('5px');
			
			$('.banner-arrow').corner('left 5px');

			$('.document-image').css({border: 'none'}).
				wrap('<span />').parent().css({display: 'block', overflow: 'hidden'}).corner('5px').
				wrap('<span />').parent().css({padding: '1px 2px 2px 1px', background: '#e5e5e5', overflow: 'hidden', display: 'block'}).corner('10px');
		}

        // Activate blocks on the home page
        $('body#home').each(function() {
            var $containers = $('.container'),
                $theBigOne = $containers.filter('.big'),
                checkUrlHash = function() {
                    var hash = window.location.hash.replace('#', '#block-');
                    return hash.length > '#block-'.length ? $(hash + '.block') : $();
                },
                activateSliders = function($block, callback) {
                    $('.slider', $block).slider({
                        slide: function(event, ui) {
                            // Update textbox when slider changes
                            $(this).siblings('input.text').val(ui.value);
                            $(this).find('.ui-slider-handle').blur(); // This is to prevent an ugly border in Chrome.
                            if (typeof callback === 'function') {
                                callback();
                            }
                        }
                    }).each(function() {
                        var $slider = $(this);
                        // Set textbox to initial slider value
                        $slider.siblings('input.text').val($slider.slider('value')).change(function() {
                            // Update slider when textbox changes - if value is within range.
                            var newValue = $(this).val(),
                                max = $slider.slider('option', 'max'),
                                min = $slider.slider('option', 'min');

                            if (newValue < min || newValue > max) {
                                $(this).val($slider.slider('value'));
                            } else {
                                $slider.slider('value', $(this).val());
                                if (typeof callback === 'function') {
                                    callback();
                                }
                            }
                        });
                    });
                },
                blocks = {
                    registry: {},
                    getId: function($block) {
                        var id = $block.attr('id');
                        if (typeof id === 'undefined') {
                            if (typeof $block.attr !== 'function') {
                               // console.log('getId: $block is not a jQuery object.', $block);
                            } else {
                               // console.log('getId: $block must have an id attribute.', $block);
                            }
                        }
                        return id;
                    },
                    register: function($block, fn) {
                        this.registry[this.getId($block)] = {block: $block, fn: fn};
                    },
                    activate: function($block) {
                        var id = this.getId($block);
                        if (id && this.registry[id] && typeof this.registry[id].fn === 'function') {
                            this.registry[id].fn.apply(this.registry[id].block);
                        }
                    },
					getBox:function($node) {
						return $.extend({
							width: $node.width(),
							height: $node.height()
						}, $node.offset());
					},
                    switchTo: function($container) {
						var $thisBlock = $container.find('.block'),
                            $currentBlock = $theBigOne.find('.block');

                        if ($container !== $theBigOne) {
							var highlight = $('<div class="highlight"></div>');
						//	highlight.append($thisBlock.clone());
							$('body').append(highlight);
							
							var from = this.getBox($container);
							var to = this.getBox($theBigOne);
							
							highlight.css(from).animate(to, function() {
								highlight.remove();

								 $container.append($currentBlock);
								$theBigOne.append($thisBlock);
							});
                           
                        }

                        blocks.activate($thisBlock);
                    }
                };

            // Switch blocks when an inactive block is clicked.
            $containers.not($theBigOne).css('cursor', 'pointer').click(function() {
                blocks.switchTo($(this));
            });

            blocks.register($('#block-nieuws'), (function() {
                var initialized = false,
                    init = function($block) {
                    };

                return function() {
                    if (!initialized) {
                        init(this);
                    }

					var url = this.find('a[rel=ajax]').attr('href');
					if(url) {
						$('#block-nieuws .big-content .darkbox').loadAjax(url);
					}

                    return this;
                };
            }()));

            blocks.register($('#block-performance'), (function() {
                var initialized = false,
                    init = function($block) {
                        var flashvars  = {};

                        var params = {};
                            params.base = "static/swf";
                            params.allowScriptAccess = "always";
							params.wmode = 'transparent';

                        var attributes = {};
                            attributes.id = "application";

                        swfobject.embedSWF("static/swf/performance.swf", "flashcontent", "454", "354", "9.0.28", "static/swf/expressInstall.swf", flashvars, params, attributes);
                    };

                return function() {
                    if (!initialized) {
                        init(this);
                    }

                    // Code that should be performed every time the block is sent to the middle can go here

                    return this;
                };
            }()));

            blocks.register($('#block-kopen'), (function() {
                var initialized = false,
                    init = function($block) {
                        $('.mijn-bank .button', $block).click(function() {
                            var url = $(this).siblings('select:first').val();
                            if (url) {
                                $(this).parents('form:first').attr('action', url).submit();
                            }
                        });
                    };

                return function() {
                    if (!initialized) {
                        init(this);
                    }

                    return this;
                };
            }()));

            blocks.register($('#block-beleggen'), (function() {
                var initialized = false,
                    recalculateTotals = function() {
                        var multiplier = parseInt($('#recurring-dropdown').val(), 10),
                            years = parseInt($('#years-textbox').val(), 10),
                            initial = parseInt($('#initial-textbox').val(), 10),
                            recurring = parseInt($('#recurring-textbox').val(), 10),
                            total = initial + (years * multiplier * recurring),
                            average = total && (years / total) * 100;

                        $('#years-label').text(years);
                        $('#total-yield').text(total);
                        $('#average-yield').text(average.toFixed(2));
                    },
                    init = function($block) {
                        activateSliders($block, recalculateTotals);

                        // Activate month/year dropdown
                        $('#recurring-dropdown').change(function() {
                            recalculateTotals();
                        });

                        // Set initial values for totals
                        recalculateTotals();

                        initialized = true;
                    };

                return function() {
                    if (!initialized) {
                        init(this);
                    }

                    // Code that should be performed every time the block is sent to the middle can go here

                    return this;
                };
            }()));

            blocks.register($('#block-test'), (function() {
                var initialized = false,
                    current = 1,
                    calculateResult = function() {
						// reducs is no-go in IE
						/*
                        var result,
                            total = [1, 2, 3, 4, 5].reduce(function(total, num) {
                            return total + (parseInt($('input[name=question-' + num + '-radios]:checked').val(), 10) || 0);
                        }, 0);
						*/
						
						var result;
						var total = 0;
						for(var i=1; i<6; i++) {
							total = total + (parseInt($('input[name=question-' + i + '-radios]:checked').val(), 10) || 0);
						}

						if (total < 5) {
                            result = 'no';
                        } else if (total < 8) {
                            result = 'maybe';
                        } else {
                            result = 'yes';
                        }

                        $('.questions-result').hide().filter('#result-' + result).show();
                    },
                    showCorrectQuestion = function() {
                        $('.question').hide().filter('#test-question-' + current).show();
                    },
                    showCorrectButtons = function() {
                        $('#question-prev')[current === 1 || current === 6 ? 'hide' : 'show']();
                        $('#question-next')[current === 6 ? 'hide' : 'show']();
                        $('#question-advisor, #question-reset')[current !== 6 ? 'hide' : 'show']();
                    },
                    goToQuestion = function(question) {
                        current = Math.max(1, Math.min(6, question));

                        if (current === 6) {
                            calculateResult();
                        }

                        showCorrectQuestion();
                        showCorrectButtons();
                    },
                    reset = function($block) {
                        $('.slider', $block).slider('value', 0);
                        $('input.text', $block).val('');
                        $('form', $block)[0].reset();
                    },
                    init = function($block) {
                        $('#question-next').click(function() {
                            goToQuestion(current + 1);
                            return false;
                        });
                        $('#question-prev').click(function() {
                            goToQuestion(current - 1);
                            return false;
                        });
                        $('#question-reset').click(function() {
                            reset($block);
                            goToQuestion(1);
                            return false;
                        });

                        activateSliders($('.question', $block));

                        goToQuestion(current);

                        initialized = true;
                    };

                return function() {
                    if (!initialized) {
                        init(this);
                    }

                    // Code that should be performed every time the block is sent to the middle can go here

                    return this;
                };
            }()));

            // Activate active block on page load.
            var $activeBlock = checkUrlHash();

            //if(checkUrlHash().length === 0) { // ? UrlHash returns document with no hash; $().length is never 0
			if(!$activeBlock.hasClass('.block')) {
                $activeBlock = $theBigOne.find('.block');
            }
            
			$activeBlock.each(function() {
                blocks.switchTo($(this).parent());
            });
        });

        $('body#downloads, body#history').each(function() {
            var switchTo = function(id) {
                    $('a.box-nav-item[href=' + id + ']').each(function() {
                        activate($(this));
                    });
                },
                activate = function($block) {
                    $block.addClass('active').siblings('.box-nav-item').removeClass('active');
                    $($block.attr('href').replace('#', '#box-content-page-') + '.box-content-page').addClass('active').siblings('.box-content-page').removeClass('active');
                };
            // Activate top bar on downloads page
            $('.box-nav-item').click(function() {
                activate($(this));

                // Prevent ugly dotted lines in some browsers.
                $(this).blur();
            });
			if(window.location.hash) {
				switchTo(window.location.hash);
			}
        });
    });

    Cufon.replace('body:not(#home) h2, p.quote, #main-nav>li>a, #meta-nav>a', {fontFamily: 'BNPP Sans', hover: true});
    Cufon.replace('h1, body#home h2, #content h3.big', {fontFamily: 'BNPP Sans Light'});
}(jQuery));

