/**
 * Homepage application
 *
 * @version   1.00.091123
 * @author    LBI Lost Boys
 */
NS(function($){

	var CLASS_ACTIVE = 'active';
	var CLASS_FADING = 'fading';

	var TIME_FADING = 1000;
	var TIME_NEWS = 6000;

	/**
	 * Homepage namespace
	 */
	NS.Homepage = {
		initialize:function() {
			this.plannertips = new ReisplannerTips();
			this.campaigns   = new CampaignRotator();
			this.newsticker  = new NewsTicker();
			this.spoorkaart  = new Spoorkaart();

			this.setDateAndTime();
			
			// autopauses over campaign root, exceptions:
			this.campaigns.pauseOver($('#form-reisplanner, #navigation, #form-actuele-vertrektijden'));
		},

		setDateAndTime:function() {
			try {				
				var form = $('#form-reisplanner')[0],
					hours = form.elements['outwardTrip.hour'],
					minutes = form.elements['outwardTrip.minute'];
				
				var now = new Date(), pad = /([0-9]{2})$/;
				hours.value = pad.exec('0'+now.getHours())[1];
				minutes.value = pad.exec('0'+now.getMinutes())[1];			
			} catch (e) {
			}
		}		
	};

	/**
	 * Reisplannertips
	 */
	function ReisplannerTips() {
		var cookie = NS.getCookie('reisplannertips');
		if(!cookie || /true/i.test(cookie)) {
			this.tipsEnabled = true;
			var stations = $('fieldset.station input.station');
			stations.bind('click', this.displayReisplannerTips.bind(this));
			NS.relateInput(/reisplanner-tips/, this.toggle.bind(this));
		}		
	}

	ReisplannerTips.prototype = {
		displayReisplannerTips:function(e) {
			if(!this.tipsEnabled) {
				return;
			}

			var div = $(e.target).closest('div'),
				label = div.find('label')[0];

			NS.Dialogs.open('reisplanner', label);
		},

		toggle:function(input, id) {
			this.tipsEnabled = !input.checked;
			NS.setCookie('reisplannertips', this.tipsEnabled);
		}
	};
	
	/**
	 * CampaignRotator
	 */
	function CampaignRotator() {
		this.root = $("#campaigns");
		if(this.root.length === 0) {
			return;
		}
		
		this.pauseOver(this.root);
		this.list = $("#campaigns-index");
		this.campaigns = [];

		var campaigns = $('div.campaign', this.root),
			listItems = $('li', this.list),
			preferred = parseInt(NS.getCookie('campaignPos') || 0, 10);

		for(var i=0; i<campaigns.length; i++) {
			var camp = new Campaign(campaigns[i], listItems[i], i);
			if(camp.isCalamity) {
				preferred = i;
			}
			this.campaigns.push(camp);
		}
		
		listItems.bind('click', this.toggleItem.bind(this));

		NS.subscribe('highlight', this.preventHighlight.bind(this));
		
		this.index = Math.min(preferred, listItems.length -1);
		this.current = this.campaigns[this.index];
		this.current.setActive(true);
		this.current.setFading(false);
	
		this.animator = new NS.Animator(this.animate.bind(this), this.activate.bind(this), NS.Animator.LINEAR);
		this.reader = new NS.Animator(this.animateTime.bind(this), this.toggleNext.bind(this), NS.Animator.LINEAR, 1000);
		
		if(listItems.length > 1) {
			this.reader.run(0,1, this.current.duration);
		}
	}

	CampaignRotator.prototype = {
		toggleNext:function(){
			var amount = this.campaigns.length;
			var index = (++this.index) % amount;
			this.setCampaign(index);
		},
		
		toggleItem:function(e) {
			var item = $(e.target).closest('li')[0];
			var index = item && item.campaignIndex;
			if(index !== null) {
				this.setCampaign(index);
			}
		},

		setCampaign:function(index) {
			this.index = index;
			this.animator.stop();
			this.reader.stop();
			this.fading = this.campaigns[index];
			this.fading.setFading(true);
			this.animator.run(0,1, TIME_FADING);
			NS.setCookie('campaignPos', index);
		},

		animate:function(i) { this.fading.setOpacity(i); },
		animateTime:function(i) { this.current.setTimeLeft(i); },

		activate:function() {
			this.current.setActive(false);
			this.fading.setFading(false);
			this.current = this.fading;
			this.reader.run(0,1, this.current.duration);
		},

		preventHighlight:function(e) {
			var div = $(e.target).parent('div')[0];
			if(div && div === this.root[0]) {
				e.preventDefault();
			}
		},

		pause:function(toggle) {
			this.reader.pause(toggle);
		},

		pauseOver:function(elements) {
			var self = this;
			elements.hover(function(){
				self.pause(true);
			}, function(){
				self.pause(false);
			});
		}
	};

	/**
	 * Campaign
	 */
	function Campaign(node, item, index) {
		this.root = $(node);
		this.item = $(item);
		this.link = $('a', item);
		this.isCalamity = node.getAttribute("ns:calamity")? true:false;
		this.background = node.getAttribute("ns:background");
		this.bgColor = node.getAttribute("ns:backgroundcolor");
		this.duration = (node.getAttribute("ns:duration") || 5) * 1000;
		item.campaignIndex = index;
		
		this.root.css({
			backgroundColor: this.bgColor,
			backgroundImage: 'url("'+this.background+'")'
		});
	}

	Campaign.prototype = {
		setFading:function(toggle) {
			if(toggle) {
				this.setOpacity(0);
				this.setActive(true);
				this.root.addClass(CLASS_FADING);
			} else {
				this.root.removeClass(CLASS_FADING);
			}
		},

		setActive:function(toggle) {
			if(toggle) {
				this.root.addClass(CLASS_ACTIVE);
				this.item.addClass(CLASS_ACTIVE);
			} else {
				this.root.removeClass(CLASS_ACTIVE);
				this.item.removeClass(CLASS_ACTIVE);
			}
		},

		setOpacity: function(i) {
			this.root.css({opacity: i});
		},

		setTimeLeft:function(i) {
			var w = this.item[0].offsetWidth;
			var x = -400 + parseInt(w * i, 10);
			this.link.css({backgroundPosition: x + 'px 100%'});
		}
	};

	/**
	 * News Ticker
	 */
	function NewsTicker() {
		this.root = $('#news-tickertape');
		this.items = this.root.find('li');
		this.current = null;
		this.index = 0;
		if(this.items.length) {
			setInterval(this.toggleNext.bind(this), TIME_NEWS);
			this.toggleNext();
		}
	}

	NewsTicker.prototype = {
		toggleNext:function() {
			if(this.current) {
				this.current.hide();
			}

			this.current = $(this.items[this.index]);
			this.current.fadeIn('fast');
			this.index = (++this.index)%this.items.length;
		}
	};

	/**
	 * Spoorkaart
	 */
	function Spoorkaart() {
		NS.relateLink(/spoorkaart-/, this.handleClick.bind(this));
		NS.relateInput(/spoorkaart-/, this.handleClick.bind(this));
		this.container = $('#spoorkaart');
		
		if(/true/i.test(NS.getCookie('spoorkaart'))) {
			$('#spoorkaart-check').attr('checked', true);
			this.toggle(true);
		}
	}

	Spoorkaart.prototype = {
		handleClick:function(node, rel) {
			var type = /spoorkaart-([^ ]+)/i.exec(rel)[1];
			switch (type) {
				case 'open':  this.toggle(true); break;
				case 'close': this.toggle(false); break;
				case 'check': NS.setCookie('spoorkaart', node.checked); break;
			}
			return true;
		},

		toggle:function(toggle) {
			var apps = $('#storingen, #form-reisplanner');
			if(toggle) {
				this.container.show();
				apps.hide();
			} else {
				this.container.hide();
				apps.show();
			}
		}
	};

	/**
	 * Bind to NS.initialize
	 */
	NS.subscribe('initialize', function(){
		NS.Homepage.initialize();
	});
});