/**
 * NS Campagnes
 * 
 * @version   1.00.090706
 * @author    LBI Lost Boys
 */
NS(function($){

	function Campaigns() {
		this.form = $('form');
		this.galleries = [];

		// gallery
		var galleries = $(".photogallery");
		for(var i=0; i<galleries.length; i++) {
			this.galleries[i] = new PhotoGallery(galleries[i]);
		}

		// forms
		NS.relateLink(/form-/i, this.handleClick.bind(this), this);
		NS.relateLink(/-back/i, this.handleBackClick.bind(this));
	}

	Campaigns.prototype = {
		Defaults: {
			validateRequired: true,
			validateServer: false,
			replaceInputs: true,
			simulateClick: false
		},

		owns: function(form) {
			var reg = /(poll|sendafriend)/i;
			if(reg.test(form.id) || reg.test(form.className)) {
				return true;
			} else {
				return false;
			}
		},

		prefers: function(setting) {
			return this.Defaults[setting];
		},

		handleClick:function(link, rel) {
			var type = /form-([^ ]+)/i.exec(rel)[1],
				form = $(link).closest('form')[0];

			switch (type) {
				case 'submit':
					NS.forms.submit(form);
				break;
				case 'reset':
					form.reset();
				break;
				case 'sendafriend':
					NS.XHR.sendForm(form, NS.getProperty('GET_SENDAFRIEND_FEEDBACK'), this.handleSendAFriend.bind(this));
				break;
				case 'postpoll':
					this.pollForm = $(form);
					NS.XHR.sendForm(form, NS.getProperty('GET_POLL_RESULTS'), this.handlePoll.bind(this));
				break;
				case 'getpoll':
					this.pollForm = $(form);
					var params = "?id="+form.elements['pollID'].value;
					NS.XHR.load(NS.getProperty('GET_POLL_RESULTS')+params, this.handlePoll.bind(this));
				break;
			}
			return true;
		},

		handleFormResponse:function(form, html) {
			var fragment = $('<div></div>');
				fragment.html(html);

			NS.DOM.append(form.parent(), fragment);
			form.hide();

			return fragment;
		},

		handleSendAFriend:function(response) {
			var form = $('form#sendafriend'),
				html = $('feedback', response).text();

			this.handleFormResponse(form, html);
		},

		handlePoll:function(response) {
			var results = $('results', response).text();

			this.handleFormResponse(this.pollForm, results);
		},

		handleBackClick:function(link, rel) {
			var type = /([^ \-]+)-back/i.exec(rel)[1],
				form = $(link).closest('div.' + type + '-container').find('form'),
				feedback = form.nextAll('div');

			feedback.hide();
			form.show();

			return true;
		}
	};


	/**
	 * Photo gallery
	 */
	function PhotoGallery(container) {
		this.container = $(container);
		this.elements = this.container.find("li");
		this.list = this.elements.parent();
		this.scroller = $(".photogallery-list", container); 
		this.viewer = $(".photogallery-visual img", container);
		this.current = $(".active", this.list);
		this.itemWidth = 66;
		this.speed = 5;
		this.visibleWidth = this.scroller.width();
		this.prevReg = /photogallery-prev/i;
		this.nextReg = /photogallery-next/i;
		this.imgReg = /\.(jpg|png|gif)/i;
		this.init();
	}

	PhotoGallery.prototype = {
		init:function() {
			var last = this.elements[this.elements.length -1],
				width = last.offsetLeft + last.offsetWidth;

			this.list.css({ position:'absolute', left:0, top:0, width:width+'px' });
			this.totalWidth = width;
			this.container.bind('click', this.handleClick.bind(this));
			this.animator = new NS.Animator(this.doScroll.bind(this));
		},

		handleClick:function(e) {
			e.preventDefault();

			var link = $(e.target).closest('a')[0];
			if(link) {
				var cls = link.className,
					href = link.href,
					prevent = false;

				if(this.prevReg.test(cls)) { // scroll to the left
					prevent = this.scroll(this.speed);
				} else if(this.nextReg.test(cls)) { // scroll to the right
					prevent = this.scroll(-this.speed);
				} else if(this.imgReg.test(href)){ // display image
					prevent = this.displayImage(link, href);
				}

				if(prevent) {
					e.preventDefault();
				}
			}
		},

		scroll:function(direction) {
			var current = this.list[0].offsetLeft,
				target = current + (direction * this.itemWidth); // current offset +/- speed * item's width
			target = Math.max((this.visibleWidth - this.totalWidth), Math.min(target, 0)); // limit inside viewer
			this.animator.run(current, target, 1000);
			return true;
		},

		doScroll:function(i) {
			this.list.css({left: Math.floor(i) + 'px'});
		},

		displayImage:function(link, href) {
			if(this.current) {
				this.current.removeClass('active');
			}

			this.viewer.attr('src', href);
			(this.current = $(link)).addClass('active');
			return true;
		}
	};

	/**
	 * Bind to NS.initialize
	 */
	NS.subscribe('initialize', function(){
		NS.addApplication('campagnes', new Campaigns());
	});
});
