//////////////////////////////////
// Relation Technology      	//
// Live Support 3.0         	//
// Theme: minimalistic_blue 	//
// Requires: 					//
// sound/script/soundmanager.js //
// themes/common/common.js		//
//////////////////////////////////

var LiveSupport = {
	
	root: 'http://livesupport.slideshop.com/',
	theme: 'token',
	supporter: null,
	timeout: null,
	delay: 2000,
	shiftDown: false,
	icons: 'http://shared.relationtechnology.dk/images/silk_icons/',
	defaultText: 'Skriv din meddelelse her.',
	showQueue: false,
	network: true,
	delayNullified: false,
	analytics: 'UA-1715050-48',
	
	initialize: function(){
		var params = '?href=' + location.href;
		RLSCommon.loadRequest('initialize.php' + params);
		return false;
	},
	
	changeButton: function(){
		var btn = document.getElementById('rls-support-box');
		btn.className = (btn.className == "rls-support-box-white") ? ((LiveSupport.network) ? "rls-support-box-on" : "rls-support-box-off") : "rls-support-box-white";
	},
	
	toggle: function(goBack){
		if (!goBack) LiveSupport.delayNullified = true;
		var state = $("#rls-write-box").css('display');
		if (state == 'none') LiveSupport.changeButton();
		$("#rls-write-box").slideToggle("slow", function(){
			if (state == 'block') LiveSupport.changeButton();
		});
		if (goBack && !LiveSupport.delayNullified) setTimeout("LiveSupport.toggle()", 5000);
		return false;
	},
	
	submitQuestion: function(){
		var name = escape(document.getElementById('support-name').value);
		var email = escape(document.getElementById('support-email').value);
		var question = escape(document.getElementById('support-question').value);
		var params = '?name=' + name + '&email=' + email + '&question=' + question;
		RLSCommon.loadRequest('submitQuestion.php' + params);
		return false;
	},
	
	submitReply: function(){
		var message = escape(document.getElementById('chatTextarea').value);
		var params = '?message=' + message;
		RLSCommon.loadRequest('submitReply.php' + params);
		return false;
	},
	
	submitEmail: function(){
		var name = escape(document.getElementById('support-name').value);
		var email = escape(document.getElementById('support-email').value);
		var question = escape(document.getElementById('support-question').value);
		var params = '?name=' + name + '&email=' + email + '&question=' + question;
		RLSCommon.loadRequest('submitEmail.php' + params);
	},
	
	updateQueue: function(row){
		if (row != undefined){
			var thisHtml = '';
			thisHtml += '<table cellpadding="0" cellspacing="0" border="0" class="queueTable">';
			thisHtml += '<tr><td style="text-align: center;">Du er nu nummer</td></tr>';
			thisHtml += '<tr><td style="text-align: center; height: 52px;"><div class="queueNumber" id="queueNumber">' + row + '</td></tr>';
			thisHtml += '<tr><td style="text-align: center;">i k&oslash;en, vent venligst.<br /><br />Du kan frit bev&aelig;ge dig rundt p&aring; hjemmesiden imens.</td></tr>';
			thisHtml += '</table>';
			document.getElementById('rls-write-box').innerHTML = thisHtml;
			LiveSupport.timeout = setTimeout("LiveSupport.updateQueue()", LiveSupport.delay);
			LiveSupport.showQueue = true;
		}
		RLSCommon.loadRequest('updateQueue.php');
		return false;
	},
	
	updateConversation: function(){
		clearTimeout(LiveSupport.timeout);
		RLSCommon.loadRequest('conversation.php');
		return false;
	},
	
	closeSession: function(){
		var proceed = confirm('Vil du afslutte samtalen?');
		if (proceed) RLSCommon.loadRequest('killSession.php');
		return false;
	},
	
	sendCopy: function(){
		RLSCommon.loadRequest('sendCopy.php');
		return false;
	},
	
	printCopy: function(){
		var url = RLSCommon.root + 'themes/common/showConversation.php?uniqid=get&print=true';
		var name = 'Print';
		window.open(url, name);
	},
	
	showSupporters: function(){
		document.getElementById('rls-input-field-submit').innerHTML = '<input type="submit" value="Send" />';
		RLSCommon.loadRequest('getSupporters.php');
		return false;
	},
	
	changeSupporter: function(id){
		var params = '?id=' + id;
		RLSCommon.loadRequest('setSupporter.php' + params);
		return false;
	},
	
	performRequest: function(key, data){
		if (key == 'initialize'){ // initialize.php
			if (data.firstLoad){
				RLSCommon.trackEvent({
					event:'Visitor arrived',
					value:data.online
				});
			}
			if (data['online']){
				LiveSupport.network = true;
				LiveSupport.supporter = data['supporter']['id'];
				var thisHtml = '<a href="javascript:void(0)" class="title">Support</a>';
				var box = document.createElement('div');
				box.id = 'rls-support-box';
				box.className = 'rls-support-box-on';
				box.innerHTML = thisHtml;
				box.onclick = function(){
					LiveSupport.toggle();
				}
				thisHtml = '';
				thisHtml += '<form id="support-form" onsubmit="LiveSupport.submitQuestion();return false">';
				thisHtml += '<p><img src="' + RLSCommon.root + 'images/supporters/' + data['supporter']['image'] + '" alt="" style="float: left; margin: 4px 6px 0px 0px; border: #ccc 1px solid;" />Velkommen til TOKEN.<br />Har du brug for hj&aelig;lp, s&aring; sig endelig til - det koster ikke at sp&oslash;rge, og du f&aring;r svar med det samme.</p>';
				thisHtml += '<span class="input-title">Navn:</span>';
				thisHtml += '<span class="input-field"><input type="text" value="" id="support-name" autocomplete="off" /></span>';
				thisHtml += '<span class="input-title">Email:</span>';
				thisHtml += '<span class="input-field"><input type="text" value="" id="support-email" autocomplete="off" /></span>';
				thisHtml += '<span class="input-title">Sp&oslash;rgsm&aring;l:</span>';
				thisHtml += '<span class="input-field"><textarea onkeydown="LiveSupport.keyDown(event, \'submitQuestion\', this)" onkeyup="LiveSupport.keyUp(event)" id="support-question" rows="5"></textarea></span>';
				thisHtml += '<span class="input-field" id="rls-input-field-submit"><input type="submit" value="Send" />';
				//thisHtml += ' | <a href="javascript:void(0)" onclick="LiveSupport.showSupporters()">Skift supporter</a>';
				thisHtml += '</span>';
				thisHtml += '</form>';
				var write_box = document.createElement('div');
				write_box.id = 'rls-write-box';
				write_box.className = 'rls-write-box';
				write_box.innerHTML = thisHtml;
				var bodyEl = document.getElementById('support-ct');
				bodyEl.appendChild(box);
				bodyEl.appendChild(write_box);
				if (data['load']){
					RLSCommon.loadRequest('updateQueue.php');
					LiveSupport.toggle(false);
				}
				soundManagerInit();
			} else {
				LiveSupport.network = false;
				var thisHtml = '<a href="javascript:void(0)" class="title">Support</a>';
				var box = document.createElement('div');
				box.id = 'rls-support-box';
				box.className = 'rls-support-box-off';
				box.innerHTML = thisHtml;
				box.onclick = function(){
					LiveSupport.toggle();
				}
				var thisHtml = '';
				thisHtml += '<form id="support-form" onsubmit="LiveSupport.submitEmail();return false">';
				thisHtml += '<p>Velkommen til TOKEN<br />Skriv til os, hvis du har sp&oslash;rgsm&aring;l, s&aring; vender vi tilbage inden for et par timer.</p>';
				thisHtml += '<span class="input-title">Navn:</span>';
				thisHtml += '<span class="input-field"><input type="text" value="" id="support-name" autocomplete="off" /></span>';
				thisHtml += '<span class="input-title">Email:</span>';
				thisHtml += '<span class="input-field"><input type="text" value="" id="support-email" autocomplete="off" /></span>';
				thisHtml += '<span class="input-title">Sp&oslash;rgsm&aring;l:</span>';
				thisHtml += '<span class="input-field"><textarea onkeydown="LiveSupport.keyDown(event, \'submitEmail\', this)" onkeyup="LiveSupport.keyUp(event)" id="support-question" rows="5"></textarea></span>';
				thisHtml += '<span class="input-field" id="rls-input-field-submit"><input type="submit" value="Send" /></span>';
				thisHtml += '</form>';
				var el = document.createElement('div');
				el.id = 'rls-write-box';
				el.className = 'rls-write-box';
				el.innerHTML = thisHtml;
				var bodyEl = document.getElementById('support-ct');
				bodyEl.appendChild(box);
				bodyEl.appendChild(el);
			}
			if (data['firstLoad']){
				setTimeout("LiveSupport.toggle(true)", 3000);
			}
		}
		if (key == 'submitQuestion' && data['success']){ // submitQuestion.php
			LiveSupport.updateQueue(data['queue']);
		}
		if (key == 'updateQueue' && data['success']){ // updateQueue.php, submitQuestion.php
			if (!LiveSupport.showQueue) LiveSupport.updateQueue(data['queue']);
			clearTimeout(LiveSupport.timeout);
			var newSpot = data['queue'];
			document.getElementById('queueNumber').innerHTML = newSpot;
			LiveSupport.timeout = setTimeout("LiveSupport.updateQueue()", LiveSupport.delay);
		}
		if (key == 'loadConversation' && data['success']){ // updateQueue.php
			var thisHtml = '';
			thisHtml += '<div class="rls-navline">';
			thisHtml += '<a href="javascript:void(0)" onclick="LiveSupport.closeSession()" class="right"><img src="' + LiveSupport.icons + 'cross.png" alt="Afslut" title="Afslut" style="max-height: 14px; margin: 4px 4px 0px 0px;" /></a>';
			thisHtml += '<a href="javascript:void(0)" onclick="LiveSupport.sendCopy()"><img src="' + LiveSupport.icons + 'email.png" alt="Email" title="Email" style="max-height: 14px; margin: 4px 0px 0px 5px;" /></a> ';
			thisHtml += '<a href="javascript:void(0)" onclick="LiveSupport.printCopy()"><img src="' + LiveSupport.icons + 'printer.png" alt="Print" title="Print" style="max-height: 14px; margin: 0px 0px 0px 2px;" /></a>';
			thisHtml += '</div>';
			thisHtml += '<ul id="rls-conversation-list" class="rls-conversation-list"></ul>';
			thisHtml += '<textarea onkeydown="LiveSupport.keyDown(event, \'submitReply\', this)" onkeyup="LiveSupport.keyUp(event)" id="chatTextarea" rows="2" onclick="LiveSupport.checkText(this, \'on\')" onfocus="LiveSupport.checkText(this, \'on\')" onblur="LiveSupport.checkText(this, \'off\')">' + LiveSupport.defaultText + '</textarea>';
			document.getElementById('rls-write-box').innerHTML = thisHtml;
			document.getElementById('chatTextarea').focus();
			LiveSupport.updateConversation();
		}
		if (key == 'conversation' && data['success']){ // conversation.php
			var len = data['messages'].length;
			if (len > 0){
				for (var i=0; i<len; ++i ){
					var row = data['messages'][i];
					var el = document.createElement('li');
					if (row['author'] == 'System'){
						var name = (row['message'] == 'CustomerEnded') ? 'Du' : row['name'];
						el.innerHTML = '<div style="text-align: center;">' + name + ' afsluttede samtalen.</div>';
					} else {
						el.className = (row['author'] == 'Customer') ? 'black' : 'blue';
						el.innerHTML = '<span class="author">' + row['name'] + '</span>' + row['message'];
					}
					document.getElementById('rls-conversation-list').appendChild(el);
				}
				if (data['playSound']) soundManager.play('pop');
				LiveSupport.scrollToBottom('rls-conversation-list');
			}
			if (data['status'] != '0'){
				var el = document.getElementById('chatTextarea');
				el.style.display = 'none';
			} else {
				LiveSupport.timeout = setTimeout('LiveSupport.updateConversation()', LiveSupport.delay);
			}
		}
		if (key == 'submitReply' && data['success']){ // submitReply.php
			var el = document.getElementById('chatTextarea');
			el.disabled = false;
			el.value = '';
			LiveSupport.updateConversation();
		}
		if (key == 'copy-sent' && data['success']){ // sendCopy.php
			alert('Email sent to ' + data['email'] + '.');
		}
		if (key == 'copy-not-sent' && data['success']){ // sendCopy.php
			var newMail = prompt('Your email was invalid, please re-enter:', '');
			RLSCommon.loadRequest('sendCopy.php?newMail=' + newMail);
			return false;
		}
		if (key == 'showSupporters' && data['success']){ // getSupporters.php
			var el = document.getElementById('rls-write-box');
			var ul = document.createElement('ul');
			ul.className = 'rls-supporter-list';
			ul.id = 'rls-supporter-list';
			var len = data['supporters'].length;
			if (len > 0){
				for (var i=0; i<len; ++i ){
					var row = data['supporters'][i];
					var li = document.createElement('li');
					li.innerHTML = '<a href="javascript:void(0)" onclick="LiveSupport.changeSupporter(\'' + row['id'] + '\')" title="' + row['name'] + '"><img src="' + LiveSupport.root + 'images/supporters/' + row['image'] + '" alt="" /></a>';
					ul.appendChild(li);
				}
				el.appendChild(ul);
			}
		}
		if (key == 'emailSent' && data['success']){ // emailSent.php
			var thisHtml = '';
			thisHtml += '<form id="support-form" onsubmit="return false">';
			thisHtml += '<p>Din email er nu blevet sendt, tak for din interesse.</p>';
			thisHtml += '</form>';
			var el = document.getElementById('rls-write-box');
			el.innerHTML = thisHtml;
		}
		if (key == 'setSupporter' && data['success']){ // setSupporter.php
			location.reload(true);
		}
		if (key == 'killSession' && data['success']){ // killSession.php
			location.reload(true);
		}
		return false;
	},
	
	keyDown: function (event, type, object) {
		if (event.keyCode == 16) LiveSupport.shiftDown = true;
		if (event.keyCode == 13){
			object.disabled = true;
			if (!LiveSupport.shiftDown){
				if (type == 'submitQuestion') LiveSupport.submitQuestion();
				if (type == 'submitReply') LiveSupport.submitReply();
			}
		}
		return false;
	},
	
	keyUp: function (event) {
		if(event.keyCode == 16){
			LiveSupport.shiftDown = false;
		}
	},
	
	scrollToBottom: function(el){
		var obj = document.getElementById(el);
		obj.scrollTop = obj.scrollHeight;
		return false;
	},
	
	checkText: function(el, type){
		if (type == 'on' && el.value == LiveSupport.defaultText){
			el.value = '';
			el.style.color = '#000000';
		}
		if (type == 'off' && el.value == ''){
			el.value = LiveSupport.defaultText;
			el.style.color = '#777777';
		}
		return false;
	}
	
}

// Load LiveSupport
LiveSupport.initialize();
