/**
 *	Global Arena
 *	--------------------------
 */

var GlobalArena = (function($){

	/**
	 *	Constants
	 *	--------------------------
	 */

	var CLASS_ACTIVE = 'active',
		CLASS_HOVER = 'hover',
		CLASS_OPEN = 'open',
		CLASS_HIDDEN = 'hidden',
		CLASS_REQUIRED = 'required',
		CLASS_DISABLED = 'disabled',
		CLASS_ERROR = 'error',
		CLASS_CONTENTPAGE = 'content-page';

	var TYPE_TEXT = 'text',
		TYPE_AREA = 'textarea',
		TYPE_SELECT = 'select-one',
		TYPE_MULTI = 'select-multiple',
		TYPE_CHECK = 'checkbox',
		TYPE_RADIO = 'radio';

	var MAP_VISIBLE = 'visible',
		MAP_FULLSCREEN = 'fullscreen',
		MAP_BALLOON = 'balloon',
		MAP_IMAGE = 'image';

	var TOGGLE_OPEN = 'open',
		TOGGLE_CLOSE = 'close',
		TOGGLE_PARENT = 'parent',
		TOGGLE_LIST = 'list';


	/**
	 *	GlobalArena controller
	 *	--------------------------
	 */

	var GlobalArena = {
		loadHandlers: [],
		init:function() {
			
			$('body').addClass('js-enabled');
            
			$(
				'#content .rounded, ' +
				'.location-spotlight .figure img, ' + 
				'.list-locations .figure img, ' + 
				'.content-box h2 span, ' + 
				'.list-media li img, ' + 
				'#content .criteria img, ' + 
				'#content .results img'
			).roundImages();
            
			$('#navigation ul.menu li ul li:first-child').addClass('first');
			$('#content .column-content .content:last, #content .testimonials .column:last').not('.content-page #content .column-content .content:last').addClass('last');
            
			$('.list-top-countries li li').hover(function() {
                $(this).addClass('hover');
            }, function() {
                $(this).removeClass('hover');
            });
            
            $("#content .table-solution .zebra tr:nth-child(even)").not('.thead').addClass("even");
            
			$('#navigation ul.menu').simpleMenu();

			$('div.carrousel').carrousel({
				elements: 'div.column',
				amount: 3
			});

			$('#filter #carrousel-promo').carrousel({
                elements: 'div.column',
				amount: 1,
				autoScroll: 6000
			});

			$('.list-media a, a.media').nyroModal({
				minWidth:820,
				minHeight:460
			});
			
			$('a.media-large').nyroModal({
				minWidth:950,
				minHeight:460
			});
			
            $("#content .list-case-studies li").hover(function() {
                $(this).addClass('hover')
            }, function() {
                $(this).removeClass('hover')
            });
			$("#content .list-case-studies li").click(function(){
                window.location=$(this).find("a").attr("href");
                return false;
            });


			this.initFilters();
			this.initForms();
			this.initGoogleMaps();
			this.initTooltips();
			this.initDelicious();
			this.initToggleables();
			this.initTabs();
			this.initStatistics();
			this.initLocations();

			for(var i=0; i<this.loadHandlers.length; i++) {
				this.loadHandlers[i].call(this);
			}
		},

		addOnload:function(method) {
			this.loadHandlers.push(method);
		},

		initFilters:function() {
			$('div#filter-panel a.toggle').bindScoped('click', this.toggleFilter, this);
			
			var select = $('div#filter-panel h1 select');
			select.bindScoped('change', this.changeTotals, this);
			select.triggerHandler('change');

			this.panelMouseoverMargin = '20px';
			this.panelMouseoutMargin = 0;

			SliderController.init();

			$('.filter-box input').each(function(){
				var slider = document.createElement('span');
				var value = document.createElement('span');
				var indicator = document.createElement('span');
				var thumb = document.createElement('a');
				slider.className = 'slider';
				value.className = 'value';
				indicator.className = 'indicator';
				thumb.setAttribute('href', '#');
				thumb.className = 'thumb';
				slider.appendChild(value);
				slider.appendChild(indicator);
				slider.appendChild(thumb);
				$(this).hide();
				this.parentNode.appendChild(slider);
			});

			$('span.slider').slider({min:0, max:100, increment:10});
		},

		toggleFilter:function(e, chained) {
			var panel = $("div#filter-panel"),
				filter = $("div#filter"),
				self = this;
		
			// open panel, hide map controls
			if(!panel.hasClass(CLASS_ACTIVE)) {
				this.panelMouseoverMargin = '203px';
				this.panelMouseoutMargin = '203px';

				filter.animate({height:'340px'}, 500, function(){
					panel.animate({marginBottom: '203px'}, 500, function(){ 
						panel.addClass(CLASS_ACTIVE); 
						self.onResize();
					});
				});
				this.arenaMap && this.arenaMap.toggleControls(false);
			} else {
			// hide panel, 
				this.panelMouseoverMargin = '7px';
				this.panelMouseoutMargin = 0;
				
				if(chained) {
					filter.animate({height:'135px'}, 500, chained);
					panel.animate({marginBottom: '0'}, 500, function(){ 
						panel.removeClass(CLASS_ACTIVE);
						self.onResize();
					});
				} else {
					panel.animate({marginBottom: '0'}, 500, function(){ 
						panel.removeClass(CLASS_ACTIVE); 
						self.arenaMap && self.arenaMap.toggleControls(true);
						self.onResize();
					});
				}
			}

			e && e.preventDefault();
		},

		changeTotals:function(e) {
			var select = e.target;
			var option = select[select.selectedIndex];
			var numReg = /\(([0-9]+)/;

			if(numReg.test(option.text)) {
				var label = numReg.exec(option.text)[1];
				$('#location-totals strong').html(label);
			}
		},

		toggleMap:function(type) {
		//	if($('body').hasClass(CLASS_CONTENTPAGE)) return;

			var panel = $("div#filter-panel"),
				filter = $("div#filter"),
				map = $('div#map'),
				self = this,
				height = 340,
				currentHeight = filter.height();

			switch(type) {
				case MAP_VISIBLE:
					height = (currentHeight <= 340)? 340 : currentHeight;
				break;
				case MAP_FULLSCREEN:
					height = (filter.height() > 340)? 340 : 
					  (window.innerHeight || document.documentElement.clientHeight) - 120;
				break;
			}
			
			var toHeight = {height: height+'px'};
			filter.animate(toHeight, 500, function(){
				panel.animate({marginBottom: '0'}, 500, function(){ panel.removeClass(CLASS_ACTIVE); });
				self.arenaMap && self.arenaMap.toggleControls(true);
				self.onResize();
			});
		},

		onResize:function() {
			$('body').toggleClass('ping');
			this.arenaMap && this.arenaMap.checkResize();
		},

		initForms:function() {
			this.htmlLoader = XMLHttp.getInstance('HTMLLoader');
			$(document).addRelation(/form-/, this.handleFormClick, this);
			Forms.replaceInputs();
		},

		handleFormClick:function(link, rel) {
			if($(link).hasClass(CLASS_DISABLED)) {
				return true;
			}

			var type = /form-([^ \$]+)/.exec(rel)[1],
				form = $(link).parents('form')[0];

			var self = this;
			switch (type) {
				case 'filter':
					if(Forms.validate(form)) {
						var content = $('div#content'),
							post = XMLHttp.getFormValues(form);

						this.setPending(content);
						this.htmlLoader.sendForm(form, null, function(fragment){
							self.toggleFilter(null, function(){
								var h = content.height();
								//dit was voor het laden van markers via json
								//self.arenaMap && self.arenaMap.loadJSONData(form['GOOGLE_MAPS_ACTION'].value, post);
								self.arenaMap && self.arenaMap.loadRSSData(form['GOOGLE_MAPS_ACTION'].value, post);
								content.slideUp(500, function(){
									content.empty().append(fragment).slideDown(750, function(){
										self.onResize();
									});
								})
							});
						});
					}
					return true;
				break;
				case 'submit':
					Forms.submit(form);
					return true;
				case 'reset':
					form.reset();
					return true;
				break;
			}
		},

		setPending:function(element) {
			element.html('<p class="loading"><img src="static/images/loading.gif" /></p>').show();
		},

		scrollTo:function(y) {
			var self = this;
			clearInterval(this.scrollTimer);
			this.scrollTimer = setInterval(function(){
				var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
				var dy = y - scrollTop;
				window.scrollBy(0, dy/5);
				if(Math.abs(dy) < 5) {
					clearInterval(self.scrollTimer);
				}
			}, 40);
		},

		initGoogleMaps:function() {
			try {
				var element = document.getElementById("map");
				if(element && GBrowserIsCompatible()) {
					this.arenaMap = new ArenaMap.Map(element, this);
					if(!$("div#filter-panel").hasClass(CLASS_ACTIVE) &&
					  !$('body').hasClass(CLASS_CONTENTPAGE)) {
						this.arenaMap.toggleControls(true);
					}
				}
				
			} catch (e) {
				console.log(e)
			
			}
		},

		initTooltips: function() {
			var tooltips = ArenaFilters.Tooltip;

			tooltips.init();
			tooltips.add('div.filters label[title]');
			tooltips.add('div.filters li[title]');
			tooltips.add('ul.continents input[title]');
		},

		initDelicious:function() {
			var linkReg = /^a$/i;
			$('div.delicious-tags').click(function(e){
				var node = e.target;
				if(linkReg.test(node.nodeName)) {
					window.open(node.getAttribute('href'));
					e.preventDefault();
				}
			})
		},

		initToggleables:function() {
			$(document).addRelation(/(^|\s)toggle-/, this.handleToggleClick.bind(this));
		},

		handleToggleClick:function(link, rel) {
			var type = /toggle-([^ ]+)/i.exec(rel)[1];
			var $link = $(link);
					
			switch (type) {
				case TOGGLE_LIST:
					var parent = $link.closest('div');
					if(!parent[0].className) {
						parent = parent.parent().closest('div');
					}
					parent.toggleClass(CLASS_ACTIVE);
					$link.toggleClass(CLASS_OPEN);
				break;
				case TOGGLE_OPEN:
				break;
				case TOGGLE_CLOSE:
				break;
			}
			return true;
		},

		initTabs:function() {
			var menus = $('div.tabs');
			for(var i=0; i<menus.length; i++) {
				this.activateTab(menus[i]);
			}

			menus.click(this.handleTabClick.bind(this));

			var hash = document.location.hash;
			var link = hash? $('a[href$=' + hash + ']') : [];
			if(link.length) {
				this.handleTabClick({ 
					target: link[0], 
					scroll: true 
				});
			}
		},

		handleTabClick:function(e) {
			if(e.shiftKey || e.ctrlKey) {
				return;
			}

			var link = $(e.target).closest('a');
			var menu = link.closest('div.tabs');
			if(menu.length) {
				menu.find('li').removeClass(CLASS_ACTIVE);
				link.parent().addClass(CLASS_ACTIVE);				
				this.activateTab(menu, e.scroll);
				if(e.preventDefault) {
					e.preventDefault();
				}
			}
		},

		activateTab:function(menu, scroll) {
			var active = /active/;
			var hashReg = /(#.+)$/;
			var tabs = $(menu).find('li');
			var activeHash = null;
			var activeClass = null;
			var body = $(document.body);

			tabs.each(function(){
				var tab = this;
				var link = $(this).find('a')[0];
				var href = link.href;
				var cls = link.className;

				if(cls) {
					body.removeClass(cls);
				}

				if(hashReg.test(href)) {
					var hash = hashReg.exec(href)[1];
					var node = $(hash);
					if(active.test(tab.className)) {
						activeHash = hash;
						activeClass = cls;
						node.show();
					} else {
						node.hide();
					}
				}
			});

			if(activeClass) { 
				body.addClass(activeClass); 
			}

			if(scroll && activeHash) {
				document.location.hash = activeHash;
			}
		},

		initStatistics:function() {
			this.statistics = new Statistics();
		},

		initLocations:function() {
			var loc = $('.location-select');
			if(loc.length) {
				var selects = loc.find('select');
				var country = selects[0];
				var regions = selects[1];
				var action = loc.attr('ga:locations');

				$(country).bind('change', function(e) {
					regions.disabled = true;
					var params = { 'countryid' : this.value };

					$.getJSON(action, params, function(response) {
						regions.disabled = false;
						regions.selectedIndex = 0;
						var options = regions.options;
						options.length = 1;
						var l = response.options.length;
						for (var i=0; i<l; i++) {
							var opt = response.options[i];
							options[i+1] = new Option(opt.name, opt.value);
						}
					});
				});
			}
		}
	}


	/**
	 *	Forms
	 *	--------------------------
	 */

	var Forms = {
		replaceInputs:function() {
			var inputs = $('input.button');
			inputs.each(function () {
				var input = this,
					form = input.form,
					template = '<a href="#" class="button $className"><span>$value</span></a>',
					jInput = $(input);
				
				var jButton = $(
					template.replace(
						/\$([a-z]+)/mig, 
						function(match, attr){
							return input[attr] || '';
						}
					)
				);
				
				jInput.addClass('replaced');
				jInput.after(jButton);
				
				jButton.bind('click', function(e){
					e.preventDefault();
					if($(form).triggerHandler('submit') !== false && Forms.validate(form) == true) {
						jInput.trigger('click');
					}
				});
			
			});
		},

		validate:function(form) {
			var elements = form.elements, valid = true, input, type;
			for (var i=0; i<elements.length; i++) {
				input = elements[i], type = input.type;
				if (type && ($(input).hasClass(CLASS_REQUIRED) || $(input).parent().hasClass(CLASS_REQUIRED))) {
					type = type.toLowerCase();
					switch (type) {
						case TYPE_TEXT: case TYPE_AREA:
							valid &= this.displayError(input, !input.value);
						break;
						case TYPE_CHECK: case TYPE_RADIO: 
							valid &= this.displayError(input, !this.checkedOne(input));
						break;
						case TYPE_SELECT: case TYPE_MULTI: 
							valid &= this.displayError(input, !this.selectedOne(input)); 
						break;
					}
				}
			}

			return valid;
		},

		submit:function(form) {
			if(this.validate(form)) {
				$(form).submit();
			}
		},

		checkedOne:function(input) {
			var name = input.name,
				checks = (name && input.form.elements[name]) || [];

			for (var i=0; i<checks.length; i++) {
				if(checks[i].checked) {
					return true;
				}
			}
			return false;
		},

		selectedOne:function(input) {
			var options = input.options;
			for (var i=0; i<options.length; i++) {
				if(options[i].selected) {
					return true;
				}
			}
			return false;
		},

		displayError:function(input, toggle) {
			$(input).closest('.field')[toggle? 'addClass' : 'removeClass'](CLASS_ERROR);
			return toggle? false : true;
		}
	}

	/**
	 * Carrousel
	 */
	function Carrousel(element, settings) {
		this.container = $(element);
		this.settings = $.extend({}, Carrousel.Defaults, settings);
		this.elements = this.container.find(this.settings.elements);
		
		if(this.elements.length <= this.settings.amount) {
			return;
		}

		this.position();
		this.initialize();
	}

	Carrousel.prototype = {
		position: function() {
			var height = 0;
			var width = 0;
			for(var i=0; i<this.elements.length; i++) {
				var item = this.elements[i];
				
				$(item).css({
					position: 'absolute',
					left: width + 'px',
					top: 0
				});

				width  += item.offsetWidth;
				height = Math.max(height, item.offsetHeight);
			}

			if(height > 0) {
				this.container.css({ 
					position: 'relative',
					overflow:'hidden', 
					height: height + 'px' 
				});
			}

			this.totalWidth = width;
			this.itemWidth = Math.ceil(width / this.elements.length);
			this.excessWidth = width - this.container[0].offsetWidth;			
			
			var page = this.settings.amount * this.itemWidth;
			this.pages = 1 + Math.ceil(this.excessWidth / page);
			this.page = 0;
		},

		initialize: function() {
			var controls = [];
			controls.push('<p class="carrousel-controls">');
			controls.push('<a href="#" class="prev" rel="carrousel-previous"><span>previous</span></a> ');

			for(var i=0; i<this.pages; i++) {
				controls.push('<a href="#" class="page" rel="carrousel-', i, '"><span>', i, '</span></a> ');
			}

			controls.push('<a href="#" class="next" rel="carrousel-next"><span>next</span></a> ');
			controls.push('</p>');

			this.controls = $(controls.join(''));
			this.thumbs = this.controls.find('a.page');
			this.container.after(this.controls);
			this.controls.bind('click', this.handleClick.bind(this));

			var width = 0;
			var links = this.controls.find('a');
			for(var i=0; i<links.length; i++) {
				width += links[i].offsetWidth;
			}

			var offset = (this.controls.width() - width)/2;
			this.controls.css({ paddingLeft: offset + 'px' });
			this.thumbs.eq(0).addClass('active');

			var auto = this.settings.autoScroll;
			if(auto && parseInt(auto, 10) > 0) {
				this.direction = 1;
				setInterval(this.autoNext.bind(this), auto);
				this.container.bind('mouseenter', this.pause.bind(this));
				this.container.bind('mouseleave', this.unpause.bind(this));
				this.controls.bind('mouseenter', this.pause.bind(this));
				this.controls.bind('mouseleave', this.unpause.bind(this));
			}
		},

		handleClick: function(e) {
			var link = $(e.target).closest('a');
			if(link.length) {
				var reg = /carrousel-([^ ]+)/i;
				var rel = link.attr('rel');

				if(reg.test(rel)) {
					e.preventDefault();
					var command = reg.exec(rel)[1];
					this.scroll(command);
				}
			}
		},

		pause: function(e) {
			this.paused = true;
		},

		unpause: function(e) {
			this.paused = false;
		},

		autoNext:function() {
			if(!this.paused) {			
				var i = this.page + this.direction;
				if(i < 0 || i >= this.pages) {
					this.direction *= -1;
				}
				
				if(this.direction > 0) {
					this.next();
				} else {
					this.previous();
				}
			}
		},

		next: function() {
			var page = (this.page +1) % this.pages;
			this.scroll(page);
		},

		previous: function() {
			var page = (this.pages + this.page -1) % this.pages;
			this.scroll(page);
		},

		scroll: function(page) {
			switch (page) {
				case 'previous':
					this.previous();
					return;
				break;
				case 'next':
					this.next();
					return;
				break;
				default:
					page = parseInt(page, 10);
					if(isNaN(page)) {
						return;
					}
				break;
			}

			var amount = this.settings.amount;
			var offset = page * amount;
			var excess = this.excessWidth - (offset * this.itemWidth);
			var end = Math.min(excess, 0);

			for(var i=0; i<this.elements.length; i++) {
				var left = (i - offset) * this.itemWidth - end;
				$(this.elements[i]).animate({
					left: left + 'px'
				}, this.settings.speed);
			}

			this.thumbs.removeClass('active');
			this.thumbs.eq(page).addClass('active');
			
			this.page = page;
		}
	}

	Carrousel.Defaults = {
		elements: 'li',
		autoScroll: 0,
		amount: 1,
		wrap: false,
		speed: 'slow'
	}

	$.registerPlugin('carrousel', Carrousel);


	/**
	 *	Statistics
	 *	--------------------------
	 */
	function Statistics() {
		$(document).bind('click', this.handleClick.bind(this));
	}

	Statistics.prototype = {
		handleClick:function(e) {
			var target = $(e.target).closest('a,input');
			if(target.length) {
				this.hit(target[0]);
			}
		},

		hit:function(node) {
			var stat = node.getAttribute('ga:analytics');
			if(stat) {
				try {
					pageTracker._trackPageview(stat);
					console && console.log('hit: ' + stat);
				} catch (e) {
					console && console.log(e.message);
				}
			}
		}
	};

	/**
	 *	console fallback
	 *	--------------------------
	 */

	if(!window.console) {
		window.console = {
			log:function(){},
			debug:function(){},
			info:function(){}
		}
	}
	
	/**
	 *	Init
	 *	--------------------------
	 */

	$(function(){
		GlobalArena.init();
	});

	/**
	 *	Return 
	 *	--------------------------
	 */

	return GlobalArena;

})(jQuery);
			
$(function() {
  $.nyroModalSettings({
    processHandler: function(settings) {
      var from = settings.from;
      if (from && from.href && from.href.indexOf('http://www.youtube.com/watch?v=') == 0) {
        $.nyroModalSettings({
          type: 'swf',
          height: 355,
          width: 425,
          url: from.href.replace(new RegExp("watch\\?v=", "i"), 'v/')
        });
      }
    }
  });
});

