var LiveSupport = {
	
	root : 'http://livesupport.slideshop.com/',
	ajaxDir : 'v2/ajax/',
	location : window.location,
	country : '',
	doShow : '1',
	inAnimation : '0',
	shown : '0',
	z : '0',
	timeOuts : new Array,
	iniTimeout : '',
	soundValid : false,
	shiftDown : false,
	state: 'default',
	analytics: 'UA-8103287-1',
	
	// Google Analytics
	trackEvent: function(obj){
		if (LiveSupport.analytics && window._gaq){
			obj.category = (obj.category ? obj.category : 'Live Support');
			obj.action = (obj.action ? obj.action : '');
			obj.label = (obj.label ? obj.label : '');
			obj.value = (obj.value ? obj.value : '');
			window._gaq.push(function(){
				var pageTracker = window._gat._getTracker(LiveSupport.analytics);
				pageTracker._trackEvent(obj.category, obj.action, obj.label, obj.value);
			});
		}
	},
	
	// File Requests
	killScript : function (theID) {
		child = document.getElementById(theID);
		if (child) child.parentNode.removeChild(child);
		return false;
	},
	
	loadRequest : function (file) {
		var newDate = new Date;
		var uniqueID = newDate.getTime();
		var id = 'rtSupport_' + uniqueID;
		var arr = file.split('?');
		var symbol = (arr.length == 1) ? '?' : '&';
		var url = LiveSupport.root + LiveSupport.ajaxDir + file + symbol + 'scriptElementID=' + id;
		var script = document.createElement('script');
		script.src = url;
		script.type = 'text/javascript';
		script.id = id;
		document.getElementsByTagName('head')[0].appendChild(script);
		return false;
	},
	
	// Manipulation
	scrollToBottom : function (objID) {
		var objDiv = document.getElementById(objID);
		objDiv.scrollTop = objDiv.scrollHeight;
		return false;
	},
	
	adjustActiveBox : function () {
		//Ext.get('LSActiveBox').alignTo("live_support", "tl-bl", [Ext.get("live_support").getWidth()-280, -1]);
		Ext.get('LSActiveBox').alignTo("live_support", "tr-br");
		//Ext.get('LSActiveBox').setStyle("top", "88px");
		return false;
	},
	
	keyDown : function (event, type, object) {
		if(event.keyCode == 16){
			LiveSupport.shiftDown = true;
		}
		if(event.keyCode == 13){
			if(!LiveSupport.shiftDown){
				object.disabled = true;
				if(type == "question"){
					LiveSupport.sendQuestion();
				} else {
					LiveSupport.sendReply();
				}
			}
		}
		return false;
	},
	
	keyUp : function (event) {
		if(event.keyCode == 16){
			LiveSupport.shiftDown = false;
		}
	},
	
	clearAll : function () {
		Ext.get('LSContent').update('');
		return false;
	},
	
	checkFocus : function (obj, text) {
		if(Ext.get(obj).dom.innerHTML == text){
			Ext.get(obj).update('');
		}
		return false;
	},
	
	// Actions using Requests
	initialize : function () {
		var header = document.getElementsByTagName("head").item(0);
		var obj = document.createElement("link");
		obj.rel = "stylesheet";
		obj.type = "text/css";
		obj.href = "http://livesupport.slideshop.com/v2/livesupport.css";
		header.appendChild(obj);
		var ab = document.createElement('div');
		ab.id = 'LSActiveBox';
		ab.innerHTML = "<span class='LSTop'><span style='float: right; margin: 10px 10px 0px 0px;'><img id='topRightIconMinimize' src='http://livesupport.slideshop.com/design/minimize_greyscale.png' alt='' style='margin-right: 5px; cursor: pointer; display: none;' onclick='LiveSupport.toggleSupport()' /><img id='topRightIconClose' src='http://livesupport.slideshop.com/design/cross_greyscale.png' alt='' style='cursor: pointer;' onclick='LiveSupport.closeSession()' /></span></span><span class='LSMiddle'><span id='LSContent'></span></span><span class='LSBottom'></span>";
		document.getElementsByTagName('body')[0].appendChild(ab);
		function checkCSS(){
			setTimeout(function(){
				var pos = Ext.get('LSActiveBox').getStyle('position');
				if (pos == 'absolute'){
					LiveSupport.loadRequest('initialize.php?LSCountry=' + LiveSupport.country + '&LSHref=' + location.href);
				} else {
					checkCSS();
				}
			}, 100);
		}
		checkCSS();
		return false;
	},
	
	sendReply : function () {
		var form = document.getElementById('LSWriteReply');
		var textarea = escape(form.textarea.value);
		if(textarea.length > 0){
			Ext.get('LSWriteReplyTextArea').dom.disabled = true;
			LiveSupport.loadRequest('send_reply.php?textarea=' + textarea);
		}
		return false;
	},
	
	sendQuestion : function () {
		var form = document.getElementById('LSWriteMessage');
		var textarea = escape(form.textarea.value);
		var location = LiveSupport.location;
		if(textarea.length > 0){
			Ext.get('LSWriteMessageTextArea').dom.disabled = true;
			LiveSupport.loadRequest('send_question.php?textarea=' + textarea);
		}
		return false;
	},
	
	sendEmail : function () {
		var form = document.getElementById('LSEmailForm');
		var name = escape(form.name.value);
		var email = escape(form.email.value);
		var question = escape(form.question.value);
		var href = LiveSupport.location.href
		LiveSupport.loadRequest('email_submit.php?name=' + name + '&email=' + email + '&question=' + question + '&href=' + href);
		return false;
	},
	
	forwardEmail : function () {
		var recipient = prompt('Enter recipient email address.');
		if(recipient){
			if(recipient.length > 0){
				LiveSupport.loadRequest('send_email_conversation.php?recipient=' + recipient);
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	},
	
	printConversation : function (uniqid) {
		var name = "SlideShop";
		var url = "http://livesupport.slideshop.com/" + uniqid + ".print";
		window.open(url, name);
		return true;
	},
	
	loadWelcomeMessage : function (set) {
		LiveSupport.loadRequest('welcome_message.php?set=' + set);
		return true;
	},
	
	loadSupporters : function() {
		LiveSupport.loadRequest('supporters.php');
		return true;
	},
	
	loadConversation : function(a) {
		LiveSupport.z = "1";
		LiveSupport.loadRequest('conversation.php?a=' + a);
		return true;
	},
	
	loadQueue : function () {
		LiveSupport.loadRequest('queue.php');
		return true;
	},
	
	setShow : function () {
		if(LiveSupport.doShow == '0'){
			LiveSupport.loadRequest("set_show.php");
			LiveSupport.doShow = '1';
			return true;
		} else {
			return false;
		}
	},
	
	selectSupporter : function (id) {
		LiveSupport.loadRequest('select_supporter.php?id=' + id);
		return true;
	},
	
	closeSession : function () {
		LiveSupport.loadRequest('close_session.php');
		LiveSupport.doShow = '0';
		return true;
	},
	
	closeInstance : function () {
		if(confirm('Are you sure you want to close the support?')){
			LiveSupport.loadRequest('close_instance.php');
		}
		return true;
	},
	
	// Toggles
	toggleSupport : function (setFocus, callback, duration) {
		/*
		if (typeof(ProductSupport) == 'object'){
			if (ProductSupport.state == 'default'){
				window.location.hash = 'ProductSupportAnchor';
				return false;
			}
		}
		*/
		var doProceed = true;
		theDuration = duration ? duration : .5;
		if(LiveSupport.inAnimation == '0'){
			LiveSupport.inAnimation = '1';
			if(LiveSupport.iniTimeout){
				clearTimeout(LiveSupport.iniTimeout);
			}
			if(callback != "email"){
				LiveSupport.setShow();
			}
			if(LiveSupport.shown == "0"){
				// Show
				Ext.get("live_support").setStyle("background-image", "url('http://livesupport.slideshop.com/design/menu_bg.png')");
				Ext.get("live_support_a").setStyle("color", "#444444");
				Ext.get("live_support_span").removeClass("group-icon-silhouette-white");
				Ext.get("live_support_span").addClass("group-icon-silhouette-black");
				Ext.get('LSActiveBox').slideIn("t", {
					duration: theDuration,
					easing: 'easeOut',
					callback: function() {
						LiveSupport.adjustActiveBox();
						if(setFocus == "yes"){
							document.getElementById('LSWriteMessage').focus();
						}
						LiveSupport.inAnimation = '0';
					}
				});
				var newShown = "1";
			} else {
				// Hide
				Ext.get('LSActiveBox').slideOut("t", {
					duration: theDuration,
					easing: 'easyOut',
					callback: function() {
						if(LiveSupport.z == "0"){
							LiveSupport.clearAll();
							LiveSupport.loadSupporters();
						}
						Ext.get("live_support").setStyle("background-image", "");
						Ext.get("live_support_a").setStyle("color", "#ffffff");
						Ext.get("live_support_span").removeClass("group-icon-silhouette-black");
						Ext.get("live_support_span").addClass("group-icon-silhouette-white");
						LiveSupport.inAnimation = '0';
					}
				});
				var newShown = "0";
			}
			
			LiveSupport.shown = newShown;
			return true;
		} else {
			return false;
		}
	},
	toggleEmail : function () {
		LiveSupport.loadRequest("email.php");
		return true;
	},
	
	// AJAX
	performRequest : function (id, data) {
		if (!id) return false;
		else {
			// close_instance.php
			if (id == 1) {
				history.go(0);
			}
			// close_session.php
			if (id == 2) {
				LiveSupport.closeInstance();
			}
			if (id == 3) {
				LiveSupport.toggleSupport('', '', 0.5);
			}
			// conversation.php
			if (id == 4) {
				Ext.get('topRightIconMinimize').setStyle('display', 'inline');
				var thisHtml = "";
				thisHtml += "<span class='LSSupporterField'>";
				thisHtml += "<div style='height: 70px; overflow: hidden;'>";
				thisHtml += "<img src='http://livesupport.slideshop.com/images/supporters/" + data["supporterImage"] + "' alt='' id='LSSupporterImage' />";
				thisHtml += "<span class='LSTitle'>" + data["title"] + "</span><span class='LSMessage'>" + data["message"] + "</span>";
				thisHtml += "<br clear='all' />";
				thisHtml += "</div>";
				thisHtml += "<ul id='LSMessageContainer'></ul>";
				thisHtml += "<form id='LSWriteReply' class='LSWriteMessage' onsubmit='LiveSupport.sendReply(); return false'>";
				thisHtml += "<textarea id='LSWriteReplyTextArea' name='textarea' rows='3' onfocus='LiveSupport.checkFocus(this, \"" + data["textarea"] + "\")' onkeydown='LiveSupport.keyDown(event, \"reply\", this)' onkeyup='LiveSupport.keyUp(event)'>" + data["textarea"] + "</textarea>";
				thisHtml += "<div class='LSButtons'><a href='javascript:void(0)' onclick='LiveSupport.forwardEmail()'>Email</a> or <a href='javascript:void(0)' onclick='LiveSupport.printConversation(\"" + data["uniqid"] + "\")'>Print</a><input type='image' src='http://livesupport.slideshop.com/design/chat_button.png' style='cursor: pointer;' class='LSRight' /></div>";
				thisHtml += "</form>";
				thisHtml += "</span>";
				Ext.get('LSContent').update(thisHtml);
				if (data["doTrack"]){
					LiveSupport.trackEvent({
						action:'To user',
						label:'Answer sent',
						value:data["answerTime"]
					});
				}
			}
			if (id == 5) {
				var el = new Array;
				var soundValidMessages = 0;
				for(var i=0; i<data["amount"]; i++){
					var doDisable = false;
					var thisMessage = data.messages["msg" + i];
					if(thisMessage["message"] == "SupporterEnded"){
						thisMessage["message"] = "The supporter ended the conversation.";
						doDisable = true;
					}
					if(thisMessage["message"] == "CustomerEnded"){
						thisMessage["message"] = "The customer ended the conversation.";
						doDisable = true;
					}
					if(doDisable == true){
						Ext.get('LSWriteReplyTextArea').setStyle('background-color', '#efefef');
						document.getElementById('LSWriteReplyTextArea').disabled = 'disabled';
						document.getElementById('LSWriteReplyTextArea').value = '';
					}
					if(thisMessage["system"] == "true") var thisHtml = "<div style='text-align: center; font-style: italic;'>" + thisMessage["message"] + "</div>";
					else var thisHtml = "<span class='LSName' style='color: " + thisMessage["color"] + ";'>" + thisMessage["name"] + "</span>" + thisMessage["message"];
					el[i] = document.createElement('li');
					el[i].innerHTML = thisHtml;
					document.getElementById('LSMessageContainer').appendChild(el[i]);
					if(thisMessage["soundValid"] == "true"){
						soundValidMessages += 1;
					}
				}
				var act = Ext.get('LSActiveBox').getStyle('display');
				if (act != "block"){
					window.focus();
					if (typeof(ProductSupport) != 'object') LiveSupport.toggleSupport();	
				}
				LiveSupport.scrollToBottom('LSMessageContainer');
				LiveSupport.soundValid = true;
				return true;
			}
			// email.php
			if (id == 6) {
				var thisHtml = "";
				thisHtml += "<span class='LSSupporterField'>";
				thisHtml += "<span class='LSTitle'>Support Offline</span>The live support is currently not online. It will be online in " + data["untilOnline"] + ". If you cannot wait, you can send an email - and our supporter will reply you as soon as he or she gets online.";
				thisHtml += "</span>";
				thisHtml += "<div id='LSEmailErrors' style='display: none; margin: 10px 0px 0px 0px; background-color: #ffe0e0; padding: 5px; border: #cccccc 1px solid;'></div>";
				thisHtml += "<form id='LSEmailForm' class='LSEmailForm' onsubmit='LiveSupport.sendEmail(); return false'>";
				thisHtml += "<div class='LSEmailFormTitle'>Name:</div>";
				thisHtml += "<input class='LSEmailFormName' type='text' name='name' />";
				thisHtml += "<div class='LSEmailFormTitle'>Email:</div>";
				thisHtml += "<input class='LSEmailFormEmail' type='text' name='email' />";
				thisHtml += "<div class='LSEmailFormTitle'>Question:</div>";
				thisHtml += "<textarea class='LSEmailFormQuestion' name='question' rows='10'></textarea><br />";
				thisHtml += "<input type='image' src='http://livesupport.slideshop.com/design/chat_button.png' style='cursor: pointer;' />";
				thisHtml += "</form>";
				Ext.get('LSContent').update(thisHtml);
				LiveSupport.toggleSupport('no', 'email', 1);
				LiveSupport.trackEvent({
					action:'From user',
					label:'Email form shown',
					value:1
				});
				return true;
			}
			// email_submit.php
			if (id == 7) {
				if(data["success"] == "true"){
					Ext.get('LSEmailErrors').setStyle('display', 'none');
					Ext.get('LSEmailForm').update("<div style='border: #cccccc 1px solid; padding: 5px; margin: 10px 0px 0px 0px; background-color: #fefefe;'>The email was sent!</div>");
					setTimeout("LiveSupport.toggleEmail()", 5000);
				} else {
					var text = "Error. We could not send your email, because of lack of information. Please fill in your";
					for(var i=0; i<data["amount_errors"]; i++){
						var thisErr = data["errors"][i];
						var thisSelector = ".LSEmailForm" + thisErr;
						Ext.select(thisSelector).setStyle('background-color', '#ffe0e0');
						var errOut = " " + thisErr;
						if(i == data["amount_errors"]-1) errOut += ".";
						else {
							if(i == data["amount_errors"]-2) errOut += " and";
							else errOut += ",";
						}
						text += errOut;
					}
					for(var i=0; i<data["amount_positive"]; i++){
						var thisErr = data["positive"][i];
						var thisSelector = ".LSEmailForm" + thisErr;
						Ext.select(thisSelector).setStyle('background-color', '#e0ffe0');
					}
					Ext.get('LSEmailErrors').update(text);
					Ext.get('LSEmailErrors').setStyle('display', 'block');
				}
				return true;
			}
			// supporters.php
			if (id == 8) {
				var thisHtml = "";
				thisHtml += "<span class='LSSupportersText'>Following supporters are now online, please choose:</span>";
				thisHtml += "<span class='LSSupporterList'>";
				for(var i=0; i<data["amount"]; i++){
					var thisSupporter = data["supporters"]["sup" + i];
					thisHtml += "<a href='javascript:void(0)' onclick='LiveSupport.selectSupporter(\"" + thisSupporter["id"] + "\")'>";
					thisHtml += "<img src='" + thisSupporter["image"] + "' alt='' style='max-height: 32px; max-width: 32px; vertical-align: middle; margin-right: 5px;' />";
					thisHtml += "<span style='vertical-align: middle;'>" + thisSupporter["name"] + "</span>";
					thisHtml += "</a>";
				}
				thisHtml += "</span>";
				Ext.get('LSContent').update(thisHtml);
				return true;
			}
			// queue.php
			if (id == 9) {
				if (LiveSupport.state != 'queue'){
					LiveSupport.state = 'queue';
					var thisHtml = "";
					thisHtml += "<div class='LSWaitText'>Please wait while " + data["supporterName"] + " is answering your question.</div>";
					thisHtml += "<div class='LSNumLine'>You are now <strong>" + data["numOut"] + "</strong> in line, please wait..</div>";
					thisHtml += "<div class='LSLoadingCont'><img src='" + data["image"] + "' alt='Loading..' /></div>";
					Ext.get('LSContent').update(thisHtml);
					setTimeout("LiveSupport.loadQueue()", 7000);
				}
				return true;
			}
			if(id == 14) {
				if (LiveSupport.state != 'conversation'){
					LiveSupport.state = 'conversation';
					LiveSupport.loadConversation('true');
				}
				return true;
			}
			// send_reply.php
			if (id == 10) {
				var el = Ext.get('LSWriteReplyTextArea').dom;
				el.disabled = false;
				el.value = '';
				for(key in LiveSupport.timeOuts){
					clearTimeout(LiveSupport.timeOuts[key]);
				}
				LiveSupport.loadConversation('false');
				LiveSupport.trackEvent({
					action:'From user',
					label:'Send reply',
					value:1
				});
				return true;
			}
			// select_supporter.php
			if (id == 11) {
				LiveSupport.clearAll();
				LiveSupport.loadWelcomeMessage();
				LiveSupport.trackEvent({
					action:'From user',
					label:'Select supporter',
					value:1
				});
				return true;
			}
			// send_email_conversation.php
			if (id == 12) {
				if(data["message"].length > 0){
					alert(data["message"]);
				}
				LiveSupport.trackEvent({
					action:'From user',
					label:'Email sent (copy of conversation)',
					value:1
				});
				return true;
			}
			// send_question.php
			if (id == 13) {
				LiveSupport.clearAll();
				LiveSupport.loadQueue(data["uniqid"]);
				LiveSupport.trackEvent({
					action:'From user',
					label:'Send question',
					value:1
				});
				return true;
			}
			// initialize.php
			if (id == 15) {
				LiveSupport.trackEvent({
					action:'From user',
					label:'Pageload',
					value:1
				});
				if(data["online"] == "true"){
					var thisAction = "LiveSupport.toggleSupport()";
					var thisClass = "LSSupportOnline";
				} else {
					var thisAction = "LiveSupport.toggleEmail()";
					var thisClass = "LSSupportIdle";
				}
				var div = document.createElement('div');
				div.id = 'live_support';
				div.innerHTML = "<a id='live_support_a' href='javascript:void(0)' onclick='" + thisAction + "'><span class='span1'><span id='live_support_span' class='span2 group-icon-silhouette-white'>Live Support</span></span></a>";
				div.className = thisClass;
				Ext.select('.top-groups-ct-1').elements[0].getElementsByTagName('table')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[0].getElementsByTagName('td')[0].appendChild(div);
				if(data["isSet"] == "true"){
					LiveSupport.loadQueue();
				} else {
					if(data["online"] == "true"){
						if(data["validPageCount"] == "true"){
							LiveSupport.loadWelcomeMessage(data["set"]);
						} else {
							LiveSupport.loadSupporters();
						}
					}
				}
				if(data["validExtra"] == "true"){
					if (typeof(ProductSupport) != 'object'){
						if(data["delay"] > 0){
							LiveSupport.iniTimeout = setTimeout("LiveSupport.toggleSupport()", data["delay"]);
						} else {
							LiveSupport.toggleSupport('', '', 0.01);
						}
					}
				}
				LiveSupport.adjustActiveBox();
			}
			// welcome_message.php
			if (id == 16) {
				var thisHtml = "";
				thisHtml += "<span class='LSSupporterField'>";
				thisHtml += "<div style='height: 70px; overflow: hidden;'>";
				thisHtml += "<img src='http://livesupport.slideshop.com/images/supporters/" + data["image"] + "' alt='' id='LSSupporterImage' onclick='LiveSupport.clearAll(); LiveSupport.loadSupporters();' />";
				thisHtml += "<span class='title'>" + data["msgSet"]["title"] + "</span><span class='message'>" + data["msgSet"]["message"] + "</span>";
				thisHtml += "<br clear='all' />";
				thisHtml += "</div>";
				thisHtml += "<form id='LSWriteMessage' class='LSWriteMessage' onsubmit='LiveSupport.sendQuestion(); return false'>";
				thisHtml += "<textarea id='LSWriteMessageTextArea' name='textarea' rows='3' onfocus='LiveSupport.checkFocus(this, \"" + data["msgSet"]["textarea"] + "\")' onkeydown='LiveSupport.keyDown(event, \"question\", this)' onkeyup='LiveSupport.keyUp(event)'>" + data["msgSet"]["textarea"] + "</textarea>";
				thisHtml += "<div class='LSButtons'><input type='image' src='http://livesupport.slideshop.com/design/chat_button.png' style='cursor: pointer;' /></div>";
				thisHtml += "</form>";
				thisHtml += "</span>";
				Ext.get('LSContent').update(thisHtml);
			}
			// initialize.php
			if (id == 17) {
				//alert('Domain not found: ' + data.domain + '.');
			}
		}
	},
	
	// Setup
	setCountry : function (value) {
		LiveSupport.country = value;
		return true;
	}
	
}

Ext.onReady(function(){
	LiveSupport.initialize();
	Ext.EventManager.onWindowResize(function(){
		if(Ext.get('LSActiveBox').getStyle('display') == 'block'){
			LiveSupport.adjustActiveBox();
		}
	});
	Ext.EventManager.on(window, "focus", function(){
		if(Ext.get('LSActiveBox').getStyle('display') == 'block'){
			LiveSupport.adjustActiveBox();
		}
	});
});
