/**
 * ZVA application
 *
 * @version   1.00.090527
 * @author    LBI Lost Boys
 */
NS(function($){

	var CLASS_ACTIVE =	 'vraag-en-antwoord';
	var CLASS_FLOATING = 'vraag-en-antwoord-float';
	var CLASS_FEEDBACK = 'vraag-en-antwoord-feedback';
	var CLASS_LOADING =	 'vea-loading';

	var OFFSET_TOP =	/webkit/i.test(navigator.userAgent)? 30:31;
	var OFFSET_RIGHT =	-3;

	var TYPE_STRING = 'string';
	
	/**
	 * Zoek, Vraag en Antwoord controller, manages multiple forms
	 */
	function ZVA() {
		// do as little as possible onload
		this.addForm('search', $("#search"));
		NS.subscribe('submit', this.handleSubmit.bind(this));
		NS.relateLink(/zva|search-/, this.handleClick.bind(this));
	}

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

		initialize:function() {
			// initialize when requested the first time

			NS.subscribe('change', this.handleChange.bind(this));

			this.container = $("#vraag-en-antwoord");
			this.virtualAgent = $("#virtual-agent");
			this.answers = $('div', this.container).eq(0);
			this.results = $(".search-results", this.container);
			this.assistance = $(".search-assistance", this.container);
			this.animator = new NS.Animator(
				this.animatePanel.bind(this),
				this.animateEnd.bind(this)
			);

			// iframe for covering up select boxes in IE
			this.ieFrame = NS.Interface.createIEFrame();
		},

		owns: function(form) {
			for(var i in this.forms) {
				if(typeof i === TYPE_STRING) {
					var owned = this.forms[i][0];
					if(form === owned) {
						return true;
					}
				}
			}
			return false;
		},
		
		prefers: function(setting) { 
			return this.Defaults[setting]; 
		},

		// ZVA manages multiple forms
		addForm: function(name, form) {
			this.forms = this.forms || {};
			this.forms[name] = form;
		},

		handleSubmit:function(e) {
			var form = e.target;
			for(var name in this.forms) {
				if(typeof name === TYPE_STRING) {
					var owned = this.forms[name][0];
					if(form === owned) {
						if(!this.container) { 
							this.initialize(); 
						}

						switch(name) {
							case 'search':
								this.setFloatingMode(false);
								e.preventDefault();
								NS.XHR.sendForm(form, NS.getProperty('POST_VEA_DETAILS'), this.handleResponse.bind(this));
								this.setWaitingMode(true);
							break;
							case 'panel':
								e.preventDefault();
								NS.XHR.sendForm(form, NS.getProperty('POST_VEA_DETAILS'), this.handleResponse.bind(this));
								this.setWaitingMode(true);
							break;
							case 'escalated':
								e.preventDefault();
								if(NS.XHR.sendForm(form, null, this.handleResponse.bind(this))) {
									this.setWaitingMode(true);
								}
							break;
						}
					}
				}
			}
		},

		handleChange:function(e) {
			var input = e.target;
			if(/form-subject/.test(input.id)) {
				var form = input.form, post = NS.getFormValues(form);
				NS.XHR.sendAndLoad(post, NS.getProperty('POST_VEA_FORM'), this.handleResponse.bind(this));
			}
		},

		handleClick:function(link, rel) {
			switch (rel) {
				case 'zva':
				case 'search-failure':
					this.searchByLink(link, this.floating, true);
				break;
				case 'search-close':
				case 'search-success':
					this.toggle(false);
				break;
				case 'search-assist':
					this.searchByLink(link, true);
				break;
			}
			return true;
		},

		searchByLink:function(link, floating, allowFollow) {
			if(!this.container) {
				this.initialize();
			}

			var href = link.getAttribute("href");
			var url = allowFollow? (''+(/^[^?#]+/).exec(href)) : NS.getProperty('POST_VEA_DETAILS');
			var post = /\?(.*)$/.exec(href);
			
			NS.XHR.sendAndLoad(post? post[1]:' ', url, this.handleResponse.bind(this));
			this.setFloatingMode(floating);
		},

		handleResponse:function(xml) {
			var pagepush = $("pagepush", xml).text();
			if(/http/i.test(pagepush)) {
				window.location = pagepush;
				return;
			}

			this.container.removeClass(CLASS_LOADING);
			var results = $("results", xml).text(),
				escalation = $("escalation", xml).text(),
				assistance = $("assistance", xml).text(),
				questions = $("questions", xml).text(),
				expression = $("expression", xml).text();
			
			NS.DOM.write(this.results, results);
			if(escalation === "0") {
				NS.DOM.write(this.assistance, assistance + questions);
			} else {
				var form = $("form", xml).text();
				NS.DOM.write(this.assistance, assistance + form + questions);
			}

			this.addForm('panel', 
				$('.virtual-agent form', this.container)
			);
			
			var escalated = $('#form-container form', this.container);
			if(escalated.length) {
				this.addForm('escalated', escalated);
			}

			this.toggle(true);
			this.initAgentAndFocus(expression);
		},

		toggle:function(toggle) {
			var body = $(document.body);
			if(toggle) {
				body.addClass(CLASS_ACTIVE);
				if(!this.isOpen && !this.floating) {
					this.animator.run(6, 10, 600);
				}
			} else {
				body.removeClass(CLASS_FEEDBACK);
				body.removeClass(CLASS_ACTIVE);
			}

			this.toggleIEFrame(this.answers, toggle);
			this.isOpen = toggle;
		},

		animatePanel:function(top) {
			this.answers.css({paddingTop : top + 'px'});
			this.virtualAgent.css({paddingTop : top + 'px'});
		},

		animateEnd:function() {
			NS.Interface.highlight(this.answers);
		},

		initVirtualAgent:function(expression) {
			var swf = null;
			if(!this.agent) {
				swf = NS.getProperty('GET_VEA_AGENT');
				var base = NS.getProperty('GET_VEA_BASE');

				this.agent = new SWFObject(swf, "virtualagent", "175", "130", "8");
				this.agent.addParam("wmode", "transparent");
				this.agent.addParam("base", base);
				this.agent.addParam("quality", "high");
				this.agent.addParam("scale", "noscale");
				this.agent.write("virtual-agent");
			}

			try {
				swf = /msie/i.test(navigator.userAgent)? 
					window.virtualagent : document.virtualagent;
				swf.showExpression(expression);
			} catch (e) {}
		},

		initAgentAndFocus:function(expression) {
			setTimeout(function(){
				this.initVirtualAgent(expression);
				this.focusSearchField();
			}.bind(this), 100);
		},

		setFloatingMode:function(toggle) {
			var body = $(document.body), offset = $(window).scrollTop() -60;
			this.floating = toggle && (offset > OFFSET_TOP);
			body[this.floating? 'addClass':'removeClass'](CLASS_FLOATING);
			this.answers.css(this.floating?
				{top:offset+'px', right:'50px'} : {top:OFFSET_TOP+'px', right:OFFSET_RIGHT+'px'}
			);
		},

		setWaitingMode:function() {
			var element = $('#agent-response'), query = $("#query"), zquery = $("#zva-query");
			var msg = NS.getProperty('MSG_LOADING'), 
				img = NS.getProperty('GET_VEA_LOADER');

			element.html('<p>' + msg + '</p><p class="loading"><img src="' + img + '" alt="" /></p>');

			if(query.val() && !zquery.val()) {
				zquery.val(query.val());
				query.val('');
				query.blur();
			}
			this.toggle(true);
			this.container.addClass(CLASS_LOADING);
			this.initAgentAndFocus('neutraal');
		},

		focusSearchField:function() {
			$("#zva-query").focus();
		},

		toggleIEFrame:function(target, toggle) {
			if(this.ieFrame){
				if(toggle) {
					var offset = target.offset();
					this.ieFrame.css({
						left: offset.left + 'px',
						top: offset.top + 'px',
						width: (target[0].offsetWidth) + 'px',
						height: (target[0].offsetHeight) + 'px'
					});
				} else {
					this.ieFrame.css({
						left: -9999 + 'px',
						top: -9999 + 'px'
					});
				}
			}
		}
	};

	NS.subscribe('initialize', function(){
		NS.addApplication('zva', new ZVA());
	});

});