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

var LiveSupport = {
	
	root: RLSCommon.root,
	theme: 'danishsilver',
	supporter: null,
	timeout: null,
	delay: 2000,
	shiftDown: false,
	icons: 'http://shared.relationtechnology.dk/images/silk_icons/',
	defaultText: 'Write your question here.',
	showQueue: false,
	network: true,
	delayNullified: false,
	wrapperId: 'livesupport-wrapper',
	
	initialize: function(){
		var params = '?href=' + location.href;
		RLSCommon.loadRequest('initialize.php' + params);
		return false;
	},
	
	changeButton: function(){
		var obj = '#rls-support-box > a';
		if ($(obj).hasClass('on')) $(obj).removeClass('on');
		else $(obj).addClass('on');
	},
	
	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;">You are now number</td></tr>';
			thisHtml += '<tr><td style="text-align: center; height: 52px;"><div class="queueNumber" id="queueNumber" style="display: block; width: 100%; text-align: center;">' + row + '</td></tr>';
			thisHtml += '<tr><td style="text-align: center;">in the queue, please wait.<br /><br />Feel free to navigate around on the website while waiting.</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('Are you sure you want to close the conversation?');
		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' && data['online']){ // initialize.php
			// append files
			var css = document.createElement('link');
			css.rel = 'stylesheet';
			css.href = 'http://livesupport.slideshop.com/themes/' + LiveSupport.theme + '/livesupport.css';
			var bodyEl = document.getElementsByTagName('head').item(0);
			bodyEl.appendChild(css);
			LiveSupport.network = true;
			LiveSupport.supporter = data['supporter']['id'];
			var thisHtml = '<a href="javascript:void(0)" onclick="LiveSupport.toggle()" class="supportLink" style="float: none;">Personal Assistant</a>';
			var box = document.createElement('div');
			box.className = 'content-menu-item first last';
			box.id = 'rls-support-box';
			box.innerHTML = thisHtml;
			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;" />Welcome to Danish Silver. If you need any help, please do ask - it is free, and you will get an answer right away.</p>';
			thisHtml += '<span class="input-title">Name:</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">Question:</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" /> | <a href="javascript:void(0)" onclick="LiveSupport.showSupporters()" style="color: #333333;">Change 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(LiveSupport.wrapperId);
			box.appendChild(write_box);
			bodyEl.appendChild(box);
			if (data['load']) RLSCommon.loadRequest('updateQueue.php?load=1');
		}
		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 (data['load']) LiveSupport.toggle();
		}
		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 (data['load']) LiveSupport.toggle();
		}
		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);
				}
				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';
			if (data['length'] > 0 && data['supporters']){
				for (var i=0; i<data['length']; ++i ){
					var row = data['supporters'][i];
					var li = document.createElement('li');
					var innerHTML = "";
					innerHTML += "<a href='javascript:void(0)' onclick='";
					innerHTML += "LiveSupport.changeSupporter(\"" + row["id"] + "\")";
					innerHTML += "' title='";
					innerHTML += row["name"];
					innerHTML += "'>";
					innerHTML += "<img src='";
					innerHTML += LiveSupport.root + "images/supporters/" + row["image"];
					innerHTML += "' alt='";
					innerHTML += row["name"];
					innerHTML += "' />";
					innerHTML += "</a>";
					li.innerHTML = innerHTML;
					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>Your email has now been sent. Thanks for your interest.</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();
