/*
 * Project    	: Agent
 * Created on	: 17/11/2010
 * CVS Id		:
 *
 * (C) 2010 Intelligent Software Components, S.A.
 * All rights reserved.
 */

/* Global vars */
// Flash mapping
var flashAnimationMap = {
		"INIT.swf": "51",
		"espera.swf": "2",
		"SEEKING.swf": "531",
		"GREETING.swf": "51",
		"NO_RESULTS.swf": "176",
		"ISOCO_RESULTS.swf": "226",
		"YAHOO_RESULTS.swf": "316",
		"BYE.swf": "51",
		"CREATOR.swf": "226",
		"EMBARRASED.swf": "176",
		"INSULTED.swf": "126",
		"PLEASED.swf": "486",
		"TIME.swf": "406"
};
var DEFAULT_ANIMATION = "INIT.swf";

// When a url starts like one of the urls in this list, link is opened in this window
// When a url does not start like one of the urls in this list, link is opened in another window
/***** PRODUCTION (www.isoco.com) *****/
var welcomeServerList = [
		"http://www.isoco.com",
		"http://isoco.com",
		"http://avatar.isoco.net:8080"
];

// absolute server path (different static/webapp server)
var server = "http://avatar.isoco.net:8080/agent/api/dialog/";
/***** END OF PRODUCTION (www.isoco.com) *****/

/***** INTEGRATION (ppam con liferay con el tema de nino apuntando al servidor de dialgos en agintpam) *****
var welcomeServerList = [
		"http://172.19.0.88:8080", // ip ppam
		"http://agintpam.isoco.net:8080"
];

//absolute server path (different static/webapp server)
var server = "http://agintpam.isoco.net:8080/agent-backoffice/api/dialog/";
***** END OF INTEGRATION *****/

// jetty only server path
// var server = "../api/dialog/";

// tomcat only server path
// var server = "/agent/api/dialog/";

// Ask and Welcome service paths
var welcomeSentencePath = server+"welcome";
var askPath = server+"ask";
var logPath = server+"log";
var pingPath = server+"ping";

// Resources paths
var RESOURCES_PATH = "/isoco-theme/";
var IMG_PATH = RESOURCES_PATH+"images/img_nino/";
var FLASH_PATH = RESOURCES_PATH+"flash_nino/";
var FIXTURES_PATH = RESOURCES_PATH+"fixtures/";
var HTML_RESOURCES_PATH = RESOURCES_PATH+"javascript/js_nino/";

// Cookie names
var CONVERSATION_COOKIE_NAME = "conversationid";
var CURRENT_SESSION_COOKIE_NAME = "currentsessionid";
var COOKIE_EXPIRE_DAYS = 20;
var STATUS_COOKIE_NAME = "status"; // values are on, off or disabled
var HISTORY_COOKIE_NAME = "history"; // stores current user history
var WELCOME_COOKIE_NAME = "welcome"; // stores welcome sentence
var EXPANDED_CONTENTS_COOKIE_NAME ="expanded"; // stores extra results
var SOUND_COOKIE_NAME ="sound"; // values are "on" or "off"
var SOUND_TO_PLAY_COOKIE_NAME ="soundToPlay"; // clip to play after redirection

// History max height
var HISTORY_MAX_HEIGHT = 200;
var USER_NAME = "";//"Yo";
var BOT_NAME = "";//"Testis";

// Other important configuration parameters
//when true, alerts are shown
var DEBUG = false;
//Max document links to show. If value is -1, show all
var MAX_LINKS_SHOWN = 6;
//Global variable to control sound playing. The init value sets if the sound should start enabled or disabled
var soundEnabled = false;
// Titles on the sound button
var SOUND_ENABLED_TITLE = "Sonido activo. Pulsa para desactivar.";
var SOUND_DISABLED_TITLE = "Sonido desactivado. Pulsa para activar.";
// Stores the audio element
var audioElement;

// Client/server mode: when using $.jsonp
var PROTOCOL = "";
var CALLBACK_PARAMETER = "?callback=?";

// Fixtures mode: using $.ajax
// var PROTOCOL = "json";
// var CALLBACK_PARAMETER = "";



// Last message (for logging purposes)
var lastConversation = {
    question: {
      text: "hola",
      time: "456"
    },
    answer: {
      text: "hola",
      time: "456",
      lang: "es"
    }
};

/*
 * Function to be invoked on body.onload
 *
 * Reads status cookie.
 *
 * If disabled, disable system.
 * If on, start system calling loadSystem function.
 * Else ping server and disable or start system depending on result.
 * */
function init() {

	// Look for status cookie
	var status = readCookie(STATUS_COOKIE_NAME);

	if(status === "on") {
		loadSystem();
	} else if(status === "disabled") {

		// if status disable, disable system
		disableSystem();
	} else {


		// Ping server
		// Rest for ping
	    //  jetty: 			http://127.0.0.1:8888/api/dialog/ping
	     // tomcat-liferay: http://localhost:8080/agent/api/dialog/ping
	    //  calls the x-domain safe way (adds a &callback=? parameter to url)
	    $.jsonp({url: pingPath + CALLBACK_PARAMETER, // "/api/dialog/ping",
	        dataType: PROTOCOL,
	        type: "get",
	        data: "userId=666", // just to make it work
	        success: function (data) {
	    		if(data.reply.text === "ok") {
	    			loadSystem();
	    		} else {
	    			disableSystem();
	    		}
	        },
	        error: function(XMLHttpRequest, textStatus, errorThrown) {

	        	disableSystem();
	        	if(DEBUG) {
	        		alert("Error on ping" + errorThrown + ","+textStatus);
	        	}
	        },
	        fixture: FIXTURES_PATH+"ping.json" // debug mode (reads json answer from file), enable including fixtures script
	    });
	}
}

/* Loads html */
function loadSystem() {

	var status = readCookie(STATUS_COOKIE_NAME);

	// Make launch button visible
	showLaunchButton();

	  // Insert html and register when finished loading
	  $("#main-panel").load(HTML_RESOURCES_PATH + "nino.html", function (){

		  loadNinoWindowImages();

		  registerEventHandlers();

		  // Look for status cookie
		  if(status!==null) {

		    // Load welcome sent from cookie
		    var welcomeSentence = readCookie(WELCOME_COOKIE_NAME);
		    if(welcomeSentence!==null) {
		      $("#welcome-sentence-text").text(welcomeSentence);
		    }

		    // Load history from cookie
		    var history = readCookie(HISTORY_COOKIE_NAME);
		    if(history !== null) {
		    	history = unescape(history);
		    	 if(isBrowserIE()) {
		 	        // If ie, remove __
		 	        var historyRegexp = /<\/P>__<P/g;
		 	        history = history.replace(historyRegexp, "</P><P");

				 // Remove also __ at </A>: </A>__
			 	 historyRegexp = /<\/A>__/g;
		 	        history = history.replace(historyRegexp, "</A>");

		 	        if(DEBUG) {
		 	        	alert("history replaced: "+history);
		 	        }
		 	      }
		    	$("#history-panel").append(history);
		    }

		    // Load extra panel contents from cookie
		    var extraPanel = readCookie(EXPANDED_CONTENTS_COOKIE_NAME);
		    if(extraPanel!== null && extraPanel.length > 0) {
		    	$("#extra-results-panel").html(extraPanel);
		    	$("#extra-results-container-panel").show();
		    }

		    if(status === "on") {
			    // Act as launched
			    launchNino();

			    if(isBrowserIE()) {
					// retry packH with IE 7 after some time
					$("#history-panel").delay(300).queue(function () {

						packHistory();
					});
			    }

			    // Play pending sound
			    // Look for clip to play
				var clipToPlay = readCookie(SOUND_TO_PLAY_COOKIE_NAME);
				soundManager.onready(function() {

					// Ready to use; soundManager.createSound() etc. can now be called.
					playSound(unescape(clipToPlay));
				});

				// Clear cookie
				createCookie(SOUND_TO_PLAY_COOKIE_NAME,null);
		    }
		  }
	  });
}

/* Hides button, shows nino panel*/
function launchNino(language) {
  hideLaunchButton();
  showNino();
  initNinoInt(language);
  createCookie(STATUS_COOKIE_NAME, "on");
  packHistory();
  //Focus on input
  $("#chat-input").focus();
}

function showNino() {
  $("#main-panel").show();
}

// Hides nino
function hideNino() {
	// Stop current sound
	stopSound();
	$("#main-panel").hide();
	$("#ninoLauncher").toggle();
	createCookie(STATUS_COOKIE_NAME, "off");
}

function hideLaunchButton() {
  $("#ninoLauncher").hide();
}

function showLaunchButton() {
  $("#ninoLauncher").show();
}


function welcomeSentenceReceived(data) {

	// Add to special entry
	var welcomeSentence = data.reply.text;
	$("#welcome-sentence-text").text(welcomeSentence);

	// Create cookie with session and user
	createCookie(CURRENT_SESSION_COOKIE_NAME,data.reply.currentSessionId);

	// Create conversation only if nothing set
	var conversationCookieValue = readCookie(CONVERSATION_COOKIE_NAME);
	if(conversationCookieValue===null) {
		createCookie(CONVERSATION_COOKIE_NAME,data.reply.userId,COOKIE_EXPIRE_DAYS);
	} else {
		// Update expire date
		createCookie(CONVERSATION_COOKIE_NAME,conversationCookieValue,COOKIE_EXPIRE_DAYS);
	}

  // Save welcome sentence to cookie
  createCookie(WELCOME_COOKIE_NAME, welcomeSentence);
}

function answerReceived(data) {

	// Add answer to history
	var answer = data.reply.text;
	var lang = data.reply.language;
	addBotMsgToHistory(answer,lang);

	// Try to get animation and url
	var action = null;
	var url = null;
	var animation = null;
	for (i = 0; i < data.actionsList.length; i += 1) {
		action = data.actionsList[i];

		if(url === null) {
			if(action.url !== undefined) {
				url = action.url;
			}
		}

    if(animation === null) {
			if(action.emotionFile !== undefined) {
				animation = action.emotionFile;
			}
		}
	}

	if(!showAnimation(animation)) {
	  // If no animation played, use default
	  showAnimation(DEFAULT_ANIMATION);
	}
	showResults(data);
	if(showUrl(url)) {
		// Redirection is happening, save sound to cookie
		createCookie(SOUND_TO_PLAY_COOKIE_NAME, escape(data.reply.sound));
	} else {
		// Play sound now
		playSound(data.reply.sound);
	}
}

function sendMessage() {

	var userInput = $("#chat-input").val();

	// escape user input
	userInput = escapeUserInput(userInput);

	if(userInput.length>0) {

		// Add to history
		addUserMsgToHistory(userInput);

		// Clear user input
		$("#chat-input").val("");

		// Animate thinking
    showAnimation("SEEKING.swf");

    // Rest for ask
    // http://localhost:8080/agent/api/dialog/ask?userId=666&question=holas
    $.jsonp({url: askPath  + CALLBACK_PARAMETER,//"/api/dialog/ask",
        dataType: PROTOCOL,
        type: "get",
        data: "userId="+readCookie(CONVERSATION_COOKIE_NAME)+"&question="+userInput,
        success: function (data) {
          answerReceived(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	if(DEBUG) {
        		alert("Problems calling ask");
        	}
        	disableSystem();
        },
        fixture: FIXTURES_PATH + "kindex-results.json" // debug mode (reads json answer from file), enable including fixtures script
        // fixture: "fixtures/catalog-results.json"
    });
	}
}

// Registers event handlers and calls welcome sentence service (only first time)
function initNino() {

  // welcome animation
  showAnimation(DEFAULT_ANIMATION);

  // if no cookie, get welcome sentence
  var status = readCookie(STATUS_COOKIE_NAME);

  if(status === null) {

    // Rest for welcome sentence
    //  jetty: 			http://127.0.0.1:8888/api/dialog/welcome?userId=655
     // tomcat-liferay: http://localhost:8080/agent/api/dialog/welcome?userId=666
    //  calls the x-domain safe way (adds a &callback=? parameter to url)
    $.jsonp({url: welcomeSentencePath  + CALLBACK_PARAMETER, // "/api/dialog/welcome",
        dataType: PROTOCOL,
        type: "get",
        data: "userId="+readCookie(CONVERSATION_COOKIE_NAME)+"&lang="+readLangFromHeaders(),
        success: function (data) {
          welcomeSentenceReceived(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	if(DEBUG) {
        		alert("Problems on welcomeSentece. Err: "+errorThrown+"| Text: "+textStatus);
        	}
        	disableSystem();
        },
        fixture: FIXTURES_PATH+"hola.json" // debug mode (reads json answer from file), enable including fixtures script
    });
  }
}

function initNinoInt(language) {

  // welcome animation
  showAnimation(DEFAULT_ANIMATION);

  // if no cookie, get welcome sentence
  var status = readCookie(STATUS_COOKIE_NAME);

  if(status === null || status == 'off') {

    // Rest for welcome sentence
    //  jetty: 			http://127.0.0.1:8888/api/dialog/welcome?userId=655
     // tomcat-liferay: http://localhost:8080/agent/api/dialog/welcome?userId=666
    //  calls the x-domain safe way (adds a &callback=? parameter to url)
    $.jsonp({url: welcomeSentencePath  + CALLBACK_PARAMETER, // "/api/dialog/welcome",
        dataType: PROTOCOL,
        type: "get",
        data: "userId="+readCookie(CONVERSATION_COOKIE_NAME)+"&lang="+language,
        success: function (data) {
          welcomeSentenceReceived(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	if(DEBUG) {
        		alert("Problems on welcomeSentece. Err: "+errorThrown+"| Text: "+textStatus);
        	}
        	disableSystem();
        },
        fixture: FIXTURES_PATH+"hola.json" // debug mode (reads json answer from file), enable including fixtures script
    });
  }
}

function registerEventHandlers() {
  // register event to catch enter key
  $("#chat-input").keypress(function (event) {
    if (event.keyCode == '13') {
      event.preventDefault();
      sendMessage();
    }
  });

  // Register click button with same handler
  $("#send-button").click(sendMessage);

  // Register sound enable/disable button
  $("#sound-button").click(toggleSound);

  // Register minimize and close button
  $("#minimize-button").click(hideNino);
  $("#close-button").click(function () {
	  	clearHistory();
	  	hideNino();
	  });

  // Wait for click to clear text
  $("#chat-input").click(function () {
    $("#chat-input").val("");
  });


	// Create a new YUI instance and populate it with the required modules.
	YUI().use('dd-plugin', function (Y) {

		var node = Y.one('#main-panel');
		node.plug(Y.Plugin.Drag);

		//Now you can only drag it from the header-panel in the top
		node.dd.addHandle('#header-panel');
	});


	// Load flash nino
	var flashvars = {};
	var params = {};
	params.Loop = "false";
	params.quality = "high";
	params.wmode = "transparent";
	params.allowScriptAccess = "sameDomain";
	var attributes = {id: "flashMovie"};
	swfobject.embedSWF(FLASH_PATH+"nino.swf",
	"animation-panel-alternative", "214", "160",
	"9.0.0", false, flashvars, params, attributes);


}

/* flash implementation of showAnimation */
function showAnimation(animation) {

	if(!DEBUG) {
		if(animation !== null) {
			var frame = flashAnimationMap[animation];

			if(frame != null) {
				var flashMovie = window.document["flashMovie"];
				if(flashMovie !== null && flashMovie !== undefined) {
						if(isBrowserIE() || flashMovie.GoToFrame) {
						flashMovie.GotoFrame(frame);
						flashMovie.Play();
						return true;
					}
				}
			}
		}
	}
}

// This method should be overridden depending on implementation (top,other,same)
// This is the implementation for same window
// Returns true if redirection occurs
function showUrl(url) {
  if(url!==null && url !== undefined) {
	  if(isWelcomeUrl(url)) {

		  // Open here
		  // Debug mode
		  if(DEBUG) {
			alert("Should be moving to "+url);
		  } else {
			// same
			window.location = url;
			// other
			// window.opener.location = url;
			return true;
		  }
	  } else {
		  if(DEBUG) {
			  alert("Should be opening other window to "+url);
		  } else {
			  // Open in other window
			  window.open(url);
		  }
	  }
	}
}

function addUserMsgToHistory (input) {

	// format and add to history
  var formatted = "<p class='isoco-chat-user-history-header'>"+ USER_NAME +"</p>"+
					"<p class='isoco-chat-user-history-text'>"+input+"</p>";

	addToHistory(formatted);

	// add to lastConversation
	lastConversation.question.text = input;
	lastConversation.question.time = new Date().getTime();
}

function addBotMsgToHistory (input,lang) {

	// format and add to history
  var formatted = "<p class='isoco-chat-bot-history-header'>"+ BOT_NAME +"</p>"+
          "<p class='isoco-chat-bot-history-text'>"+input+"</p>";

	addToHistory(formatted);

	// add to lastConversation and log
	lastConversation.answer.text = input;
	lastConversation.answer.time = new Date().getTime();
	lastConversation.answer.lang = lang;
	log(lastConversation);
}

function addToHistory(formattedData) {

	$("#history-panel").append(formattedData);
  // save at cookie
  var historyContents = $("#history-panel").html();

  // Escape &nbsp;
  var escapedHistoryContents = escape(historyContents);

  if(escapedHistoryContents !== null) {
	  if(escapedHistoryContents.length > 4000){
		  // Need to trim
		  escapedHistoryContents = escapedHistoryContents.substring(escapedHistoryContents.length - 4000,escapedHistoryContents.length);
		  // Find the first header, to avoid broken html code
		  var startAt = escapedHistoryContents.indexOf(escape("<p class=\"isoco-chat-user-history-header\">"));
		  escapedHistoryContents = escapedHistoryContents.substring(startAt,escapedHistoryContents.length);
	  }
  }
  createCookie(HISTORY_COOKIE_NAME, escapedHistoryContents);

  // If history is too big, limit height and flow
  packHistory();

}

// If history is too big, limit height and flow.
// Call this method when history is visible, otherwise it will not work
function packHistory() {
	var currentHistoryHeight = $("#history-panel").height();
	  if(currentHistoryHeight >= HISTORY_MAX_HEIGHT) {
	    $("#history-panel").css("height",""+HISTORY_MAX_HEIGHT+"px");
	    $("#history-panel").css("overflow","auto");
	    // Flow history
	    $("#history-panel").scrollTop($("#history-panel")[0].scrollHeight);
	  }
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else {
		var expires = "";
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// uses log rest service:
// 		@RequestParam(value = "question", required = false) String question,
//@RequestParam(value = "questionTime", required = false) String questionTime,
//@RequestParam(value = "answer", required = false) String answer,
//@RequestParam(value = "answerTime", required = false) String answerTime,
// @RequestParam(value = "detectedLang", required = false) String detectedLang,
//@RequestParam(value = "conversationId", required = false) String conversationId,
//@RequestParam(value = "currentSessionId", required = false) String currentSessionId,
function log(lastConversation) {

	// Build data
	var data = "question="+lastConversation.question.text+"&";
	data+= "questionTime="+lastConversation.question.time+"&";
	data+= "answer="+lastConversation.answer.text+"&";
	data+= "answerTime="+lastConversation.answer.time+"&";
	data+= "detectedLang="+lastConversation.answer.lang+"&";
	data+= "conversationId="+readCookie(CONVERSATION_COOKIE_NAME)+"&";
	data+= "currentSessionId="+readCookie(CURRENT_SESSION_COOKIE_NAME);

	// Call rest service
	$.jsonp({url: logPath, // "/api/dialog/log",
      dataType: PROTOCOL,

		  type: "get",
		  data: data,
//		  success: function (data) {
//				alert("logging successful");
//			},
      error: function(XMLHttpRequest, textStatus, errorThrown) {
	  		// unreachable
	  		//disableSystem();
  	  },
		  fixture: FIXTURES_PATH+"hola.json" // debug mode (reads json answer from file), enable including fixtures script
	});
}

function showResults(data) {
  showKt2qResults(data,MAX_LINKS_SHOWN);
	showKindexResults(data,MAX_LINKS_SHOWN);
}

function showKindexResults(data,max) {

	if(data.resultsTable.kindex !== null && data.resultsTable.kindex !== undefined) {

		var results = data.resultsTable.kindex;
		if(max === -1) {
		  // Show all
		  max = results.length;
		}

		var i;
		var formattedOutput = "";
		for (i = 0; i < results.length && i < max; i += 1) {
			formattedOutput += formatKindexResult(results[i]);
	    }

		addToHistory(formattedOutput);
	}
}

function formatKindexResult (kindexEntry) {
	return "<a class='isoco-chat-bot-history-results' href=javascript:showUrl('"+kindexEntry.url+"')>"+kindexEntry.title+"</a>";
}

function showKt2qResults(data,max) {
  if(data.kt2qResult.namesAndLinks !== undefined) {


		var results = data.kt2qResult.namesAndLinks;

		var i;
		var formattedOutput = "";
		var title;
		var counter = 0;


		for (title in results) {
		  if(max === -1 || counter < max) {
			  formattedOutput += formatKt2qResult(title,results[title]);
			}
			counter += 1;
	  }

		addToHistory(formattedOutput);
	}
}

function formatKt2qResult (title,link) {
	return "<a class='isoco-chat-bot-history-results' href=javascript:showUrl('"+link+"')>"+title+"</a>";
}

//Browser specific function
function isBrowserIE() {

  var browser=navigator.appName;

  if(browser=="Microsoft Internet Explorer") {
    return true;
  }
  return false;
}

function isWelcomeUrl(url) {
	var i;
	for (i = 0; i < welcomeServerList.length; i += 1) {
	    if(startsWith(url,welcomeServerList[i])) {
	    	return true;
	    }
	}

	return false;
}

function startsWith(str1,str2) {
	return (str1.match("^"+str2)==str2);
}

//Hide both button and panel
function disableSystem() {

	// Show button
	showLaunchButton();
	// Change launcher img
	$("#ninoLauncherImg").attr("src",IMG_PATH+"nino_animat_v2-unavailable.gif");
	$("#ninoLauncherLink").removeAttr("href");

	// hide panel
	$("#main-panel").hide();
	createCookie(STATUS_COOKIE_NAME,"disabled");
}

// Loads images using RESOURCE_FOLDER
function loadNinoWindowImages() {
	$("#minimize-button img").attr("src",IMG_PATH+"minimize-btn.gif");
	$("#close-button img").attr("src",IMG_PATH+"close-btn.jpg");
	$("#flashMovie").attr("data",FLASH_PATH+"nino.swf");
	$("#send-button img").attr("src",IMG_PATH+"chatIcon.png");
	$("#animation-panel-alternative img").attr("src",IMG_PATH+"nino.gif");
	// Load sound icon depending on soundEnabled
	var soundCookieValue = readCookie(SOUND_COOKIE_NAME);
	if(soundCookieValue==="on") {
		soundEnabled = true;
	}
	if(soundEnabled) {
		$("#sound-button img").attr("src",IMG_PATH+"sound-icon-on.png");
		$("#sound-button img").attr("title",SOUND_ENABLED_TITLE);
	} else {
		$("#sound-button img").attr("src",IMG_PATH+"sound-icon-off.png");
		$("#sound-button img").attr("title",SOUND_DISABLED_TITLE);
	}
}

// Reads lang from headers
function readLangFromHeaders() {
  if (navigator.browserLanguage){language=navigator.browserLanguage}

 if (navigator.userLanguage){language=navigator.userLanguage}

 if (navigator.systemLanguage){language=navigator.systemLanguage}

 if (navigator.language){language=navigator.language}

 if (language.indexOf('-')==2) {
    language=language.substring(0,2);
   }
   return language;
}

// Escapes user input from html
function escapeUserInput(userInput) {

	// Create div containing input and return text from it
	return $('<div>'+userInput+'</div>').text();
}

// Clears history
function clearHistory() {
	// Clear panel
	$("#history-panel").html('');
	// Clear cookie
	createCookie(HISTORY_COOKIE_NAME, '');
}

// Plays a sound of mp3 clip at soundUrl
function playSound(soundUrl) {

	if(soundUrl !== null && soundUrl !== undefined && soundEnabled) {
		// html 5 mp3 audio method
		// Audio element is already declared at start
		if(audioElement === null || audioElement === undefined) {
			audioElement = document.createElement('audio');
		}
		var mp3Support = !!(audioElement.canPlayType && audioElement.canPlayType('audio/mpeg;').replace(/no/, ''));

		if(mp3Support) {
			audioElement.pause();
			audioElement.setAttribute('src', soundUrl);
			audioElement.play();

		} else {
			// Alt method (flash)
			soundManager.destroySound('sound');
			soundManager.createSound('sound',soundUrl);
			soundManager.play('sound');
		}
	}
}

// Stops current sound
function stopSound() {

	// html 5 mp3 audio method
	var mp3Support = false;
	// Audio element is already declared at start
	if(audioElement !== null && audioElement !== undefined) {

		mp3Support = !!(audioElement.canPlayType && audioElement.canPlayType('audio/mpeg;').replace(/no/, ''));
	}

	if(mp3Support) {
		audioElement.pause();

	} else {
		// Alt method (flash)
		soundManager.stop('sound');
	}
}

// Activates or deactivates sound
function toggleSound() {
	if(soundEnabled) {
		// Try to stop current
		stopSound();
		// Set disabled
		soundEnabled = false;
		createCookie(SOUND_COOKIE_NAME,'off',COOKIE_EXPIRE_DAYS);
		// Change icon
		$("#sound-button img").attr("src",IMG_PATH+"sound-icon-off.png");
		// Change title
		$("#sound-button img").attr("title",SOUND_DISABLED_TITLE);

	} else {
		// Set enabled
		soundEnabled = true;
		createCookie(SOUND_COOKIE_NAME,'on',COOKIE_EXPIRE_DAYS);
		// Change icon
		$("#sound-button img").attr("src",IMG_PATH+"sound-icon-on.png");
		// Change title
		$("#sound-button img").attr("title",SOUND_ENABLED_TITLE);
	}
}



