'use strict';
define([''], function() {

	var app={};
	var sounds = [];

	var soundUrlList = {
		"success": sg.relativeRootPath + "/sounds/success.mp3",
		"success-low": sg.relativeRootPath + "/sounds/success-low.mp3",
		"error": sg.relativeRootPath + "/sounds/error.mp3",
		"claps": sg.relativeRootPath + "/sounds/claps.mp3",
		"clock": sg.relativeRootPath + "/sounds/clock-ticking.mp3"
	};

	function getSoundObj(url) {
		var i, len = sounds.length;
		for (i = 0; i < len; i++) {
			//console.log(url, sounds[i].getAttribute("data-relativeSrc"));
			if (url == sounds[i].getAttribute("data-relativeSrc")) {
				return sounds[i];
			}
		}
		return null;
	}

	// play flag is for loading and not reproduce
	app.sg_sound= function (elementOrPath, playFlag, setName) {
		if (!elementOrPath) {
			throw "sg_sound에서 element값이 " + elementOrPath;
			return;
		}

		var soundName;
		var soundUrl;
		var $element;
		//console.log(element);
		//console.log(typeof element);
		if (typeof elementOrPath === "string") {
			//is url
			soundName = elementOrPath;
		} else {
			soundName = elementOrPath.getAttribute("data-sg-sound");
		}

		//var soundName = element.dataset["sgSound"];
		if (soundName) {
			if (soundUrlList[soundName]) {
				//UrlList에 있는 사운드 이름이면
				soundUrl = soundUrlList[soundName];
			} else {
				soundUrl = soundName;
				if (setName) {
					soundUrlList[setName] = soundUrl;
				}
			}

			var audio = getSoundObj(soundUrl);

			if (!audio) {
				audio = new Audio(); //$('<audio src="' + soundUrl + '"/>')[0];
				audio.src = soundUrl;
				audio.setAttribute("data-relativeSrc", soundUrl);
				audio.load();
				sounds.push(audio);
			}
			if (playFlag == true || playFlag == undefined) {
				try {
					audio.currentTime = 0;
				} catch (e) {}
				audio.play();
			}
		}
	}

	//that is neceesary for the pilot templates work 
	sg.sound = app.sg_sound;

	return app;

});