var SM2_DEFER, DEBUG;

var Nuxleus = (function() {

	var Nuxleus = function() {
		return new Nuxleus.fn.init();
	},

	_Nuxleus = window.Nuxleus,

	_nux = window.nux,

	rootNuxleus,

	urlParams = {},

	userAgent = navigator.userAgent,

	class2type = {};

	// Nuxleus = window.Nuxleus = window.$nux = window.nux = function () {
	//     return new Nuxleus.core.init();
	// };
	// Nuxleus.fn = Nuxleus.prototype = {
	//   	_initialized: false,
	// 		constructor: Nuxleus,
	// 		nuxleus: "@VERSION",
	//     init: function () {
	//         if (! this._initialized) {
	// 					var e,
	// 			        a = /\+/g,  // Regex for replacing addition symbol with a space
	// 			        r = /([^&=]+)=?([^&]*)/g,
	// 			        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
	// 			        q = window.location.search.substring(1);
	// 
	// 			    while (e === r.exec(q))
	// 			       this.urlParams[d(e[1])] = d(e[2]);
	//         // window.fbAsyncInit = function () {
	//         //             FB.init({ appId: '187466327955609', status: true, cookie: true, xfbml: true });
	//         //         };
	// 				if(this.urlParams["debug"] === 'true'){
	// 				        window.DEBUG = true;
	// 				}
	//         this._initialized = true;
	//         }
	//     }
	// };
	//Nuxleus.fn.init.prototype = Nuxleus.fn;

	Nuxleus.fn = Nuxleus.prototype = {
		constructor: Nuxleus,
		_initialized: false,
		init: function() {
			if (!this._initialized) {
				var e, a = /\+/g,
					// Regex for replacing addition symbol with a space
				r = /([^&=]+)=?([^&]*)/g,
					d = function(s) {
					return decodeURIComponent(s.replace(a, " "));
				},
					q = window.location.search.substring(1);

				while (e === r.exec(q))
				urlParams[d(e[1])] = d(e[2]);
				// window.fbAsyncInit = function () {
				//             FB.init({ appId: '187466327955609', status: true, cookie: true, xfbml: true });
				//         };
				if (urlParams["debug"] == 'true') {
					window.DEBUG = true;
				}
				this._initialized = true;
			}
			return this;
		},

		nuxleus: "@VERSION",

		map: function(callback) {

		},
		end: function() {

		}
	};

	Nuxleus.fn.init.prototype = Nuxleus.fn;

	Nuxleus.extend = Nuxleus.fn.extend = function() {
		var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {},
			i = 1,
			length = arguments.length,
			deep = false;

		// Handle a deep copy situation
		if (typeof target === "boolean") {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if (typeof target !== "object" && !Nuxleus.isFunction(target)) {
			target = {};
		}

		// extend Nuxleus itself if only one argument is passed
		if (length === i) {
			target = this;
			--i;
		}

		for (; i < length; i++) {
			// Only deal with non-null/undefined values
			if ((options = arguments[i]) != null) {
				// Extend the base object
				for (name in options) {
					src = target[name];
					copy = options[name];

					// Prevent never-ending loop
					if (target === copy) {
						continue;
					}

					// Recurse if we're merging plain objects or arrays
					if (deep && copy && (Nuxleus.isPlainObject(copy) || (copyIsArray = Nuxleus.isArray(copy)))) {
						if (copyIsArray) {
							copyIsArray = false;
							clone = src && Nuxleus.isArray(src) ? src : [];

						} else {
							clone = src && Nuxleus.isPlainObject(src) ? src : {};
						}

						// Never move original objects, clone them
						target[name] = Nuxleus.extend(deep, clone, copy);

						// Don't bring in undefined values
					} else if (copy !== undefined) {
						target[name] = copy;
					}
				}
			}
		}
		// Return the modified object
		return target;
	};

	Nuxleus.extend({

		uid: null,

		username: null,

		profile_url: null,
		
		isFunction: function(target) {
			return !! (target && target.constructor && target.call && target.apply);
		},
		
		getDecodedEmail: function () {
 				coded = "zAkAdMzMk2@HQCAkCpQcAk.SJz";
 				key = "J1SAvtYBCrDfbMn35xgmZwy8Gsuq9RV2EO0QoUcakHiXdz6INeThpj74LFWKPl";
 				shift = coded.length;
 				link="";
 				for (i=0; i<coded.length; i++) {
 					if (key.indexOf(coded.charAt(i))==-1) {
 					ltr = coded.charAt(i)
 					link += (ltr)
 				}
 				else {     
 					ltr = (key.indexOf(coded.charAt(i))-shift+key.length) % key.length
 					link += (key.charAt(ltr))
 				}
			}
				return link;
		},

		isArray: Array.isArray ||
		function(obj) {
			return Nuxleus.type(obj) === "array";
		},

		// A crude way of determining if an object is a window
		isWindow: function(obj) {
			return obj && typeof obj === "object" && "setInterval" in obj;
		},

		isNumeric: function(obj) {
			return !isNaN(parseFloat(obj)) && isFinite(obj);
		},

		type: function(obj) {
			return obj == null ? String(obj) : class2type[toString.call(obj)] || "object";
		},

		isEmptyObject: function(obj) {
			for (var name in obj) {
				return false;
			}
			return true;
		},
		isPlainObject: function(obj) {
			// Must be an Object.
			// Because of IE, we also have to check the presence of the constructor property.
			// Make sure that DOM nodes and window objects don't pass through, as well
			if (!obj || Nuxleus.type(obj) !== "object" || obj.nodeType || Nuxleus.isWindow(obj)) {
				return false;
			}

			try {
				// Not own constructor property must be Object
				if (obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
					return false;
				}
			} catch(e) {
				// IE8,9 Will throw exceptions on certain host objects #9897
				return false;
			}

			// Own properties are enumerated firstly, so to speed up,
			// if last one is own, then all properties are own.
			var key;
			for (key in obj) {}

			return key === undefined || hasOwn.call(obj, key);
		},

		error: function(msg) {
			throw new Error(msg);
		},

		noop: function() {},

		browser: {},

		// args is for internal usage only
		each: function(object, callback, args) {
			var name, i = 0,
				length = object.length,
				isObj = length === undefined || Nuxleus.isFunction(object);

			if (args) {
				if (isObj) {
					for (name in object) {
						if (callback.apply(object[name], args) === false) {
							break;
						}
					}
				} else {
					for (; i < length;) {
						if (callback.apply(object[i++], args) === false) {
							break;
						}
					}
				}

				// A special, fast, case for the most common use of each
			} else {
				if (isObj) {
					for (name in object) {
						if (callback.call(object[name], name, object[name]) === false) {
							break;
						}
					}
				} else {
					for (; i < length;) {
						if (callback.call(object[i], i, object[i++]) === false) {
							break;
						}
					}
				}
			}

			return object;
		},

		onloginReady: function(id) {
			// fb.uid = id;
			//         fb._inituser(fb.updateLoginStatus);
		}

	});

	Nuxleus.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
		class2type["[object " + name + "]"] = name.toLowerCase();
	});

	return Nuxleus;

})();



function loadMediaPlaylist() {
	$("ul.playlist li").each(function(i) {
		//$(this).replaceWith("<fb:share-button class='url' href='" + $(this).attr('href') + "'>" + $(this).html() + "</fb:share-button>");
	});
}



function getMediaPlayerHtmlContainer(id, self) {
	var mp3playercontainerid = 'mp3-player-container-' + id;
	var progresscontainerid = 'progresscontainer-' + id;
	var progressbarid = 'progressbar-' + id;
	var playprogressbar = 'playprogressbar-' + id;
	var mp3timecontainerid = 'mp3-time-container-' + id;

	return "<div class='mp3-player finger-cursor' id='" + mp3playercontainerid + "'>" 
	+"<div class='mp3-player-state'>" 
		+"<div class='progress-container finger-cursor' id='" + progresscontainerid + "'>"
	/*+"<div class='loadingprogressbar opacity-35 finger-cursor' id='" + progressbarid + "'></div>"*/
		+"<div id='" + id + ('-mp3-time-position') + "' class='mp3-time-position finger-cursor opacity-85'>0</div>" 
		+"<div class='mp3-time-container finger-cursor' id='" + mp3timecontainerid + "'>" + "<div> of </div>" 
		+"<div id='" + id + '-mp3-time-total' + "' class='mp3-time-total finger-cursor'>(estimating)</div>"
	/*+"<div id='" + id + '-mp3-percent-complete' + "' class='mp3-percent-complete finger-cursor'>00</div>" */
		+"</div>"
		+"<div class='playingprogressbar opacity-75 finger-cursor' id='" + playprogressbar + "'></div>"
	+"</div>"
	+"<div class='mp3-title finger-cursor'>" + self.html() + "</div>" 
	+"<div class='mp3-meta-data finger-cursor'>" 
		+"<div class='mp3-artist finger-cursor'>by <span class='strong'>" + self.attr('rel') + "</span></div>"
	/*+"<div class='mp3-album finger-cursor'>from <span class='strong'>" + self.html() + "</span></div>"*/
	+"</div>" 
	+"</div>" 
	+"</div>";
}

function playNextListItemInPlaylist(id){
	el = $('#' + id + ' + li.mp3');
	if (el.length > 0) {
		el.each(function(index) {
			$.log();
			try{
				createSMSound(this);
			} catch(err) {
				$.log(err);
			}
		});
	} else {
		loadFirstListItemInPlaylist();
	}
}
function loadFirstListItemInPlaylist(){
	$("ul.playlist li.mp3").filter(':first').each(function(index) {
		$.log();
		try{
			createSMSound(this);
		} catch(err) {
			$.log(err);
		}
		return false;
	});
}

function load_SMEvents() {
	//loadFirstListItemInPlaylist();
	$("ul.playlist li.mp3").click(function() {
		$.log();
		try{
			createSMSound(this);
		} catch(err) {
			$.log(err);
		}
		return false;
	});
	$(".youtube-player").click(function() {
		$.log();
		try{
			soundManager.pauseAll();
		} catch(err) {
			$.log(err);
		}
		return false;
	});
}

function createSMSound(obj){
	var self = $(obj).find("a");
	var id = obj.id;
	$.log(id);
	var mp3playercontainerid = 'mp3-player-container-' + id;
	var progresscontainerid = 'progresscontainer-' + id;
	var progressbarid = 'progressbar-' + id;
	var playprogressbar = 'playprogressbar-' + id;
	var mp3timecontainerid = 'mp3-time-container-' + id;
	//$('.mp3-player.playing').removeClass('playing').addClass('paused');
	var mySound = soundManager.getSoundById(id);

	if (mySound == null) {
		$.log("sound ".concat(id).concat(" doesn't exist. Creating..."));
		soundManager.pauseAll();
		self.replaceWith(getMediaPlayerHtmlContainer(id, self));
		// $('#' + progressbarid).progressbar({
		// 						              value: 0
		// 						       	});
    $('#' + playprogressbar).progressbar({
       value: 0
    });
		soundManager.createSound({
			id: id,
			serverURL: "rtmp://us-standard.streaming.beta1.amp.fm/cfx/st",
			url: self.attr("href"),
			autoPlay: true,
			bufferTime: 0,
			onconnect: function(bConnect) {
				$.log("onconnect fired for ".concat(id));
				$.log(this.sID + ' connected: ' + (bConnect ? 'true' : 'false'));
				//this.play();
			},
			whileloading: function() {
				/*var total = parseInt((this.bytesLoaded / this.bytesTotal) * 100);
                      $('#' + id + '-mp3-percent-complete').html('<span>' + total + '% loaded</span>');
                      $('#' + progressbarid).progressbar('option', 'value', total);*/
			},
			whileplaying: function() {
				if (this.passes == undefined) this.passes = 0;
				this.passes = this.passes + 1;
				if (this.passes % 50 == 0) {
					$('#' + id + '-mp3-time-total').html('~'.concat(parseInt((this.durationEstimate / 1000), 10)));
				}
				if (this.loaded) {
					$('#' + id + '-mp3-time-total').html(parseInt((this.duration / 1000), 10));
				}
				$('#' + id + '-mp3-time-position').html(parseInt((this.position / 1000), 10));
				$('#' + playprogressbar).progressbar('option', 'value', parseInt(((this.position / this.duration) * 100), 10));
			},
			onfinish: function() {
				$.log("onfinish fired for ".concat(id));
				$('#mp3-player-container-' + id).removeClass('playing');
				$('#' + progresscontainerid).css('display', 'none');
				this.position = 0;
				//$('#' + id + '-mp3-time-position').empty();
				playNextListItemInPlaylist(id);
			},
			onid3: function() {
				/*for( var prop in this.id3 ){
								alert(prop + this.id3[prop]);
								}*/
			},
			onmetadata: function() {
				for( var prop in this.metadata ){
					$.log("property: ".concat(prop).concat(' value: ').concat(this.metadata[prop]));
				}
			},
			onpause: function() {
				$.log("onpause fired for ".concat(id));
				$('#' + mp3playercontainerid).removeClass('playing').addClass('paused');
			},
			onplay: function() {
				$.log("onplay fired for ".concat(id));
				$('#' + progresscontainerid).css('display', 'block');
				$('#' + mp3playercontainerid).removeClass('paused').addClass('playing');
			},
			onresume: function() {
				$.log("onresume fired for ".concat(id));
				$.log("current position ".concat(this.position));
				$('#' + mp3playercontainerid).removeClass('paused').addClass('playing');
			}
		});

		//$('#' + mp3playercontainerid).addClass('playing');
		
	} else if (mySound.paused == true) {
		$.log("resuming ".concat(id));
		soundManager.pauseAll();
		//$(this).find('.mp3-player').removeClass('paused').addClass('playing');
		mySound.resume();
	} else if (mySound.playState == 0) {
		$.log("playstate == 0 for ".concat(id));
		soundManager.pauseAll();
		//$(this).find('.mp3-player').removeClass('paused').addClass('playing');
		mySound.play();
	} else if (mySound.playState == 1) {
		$.log("pausing ".concat(id));
		mySound.pause();
		//$(this).find('.mp3-player').removeClass('playing').addClass('paused');
		//mySound.unload();
	} else {
		$.log("Something isn't right for id ".concat(id));
	}

	return false;

}



var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();

if(urlParams["debug"] == 'true'){
        window.DEBUG = true;
}

if(urlParams["autoplay"] == 'true'){
        window.AUTOPLAY = true;
} else {window.AUTOPLAY = false;}

$(document).ready(function() {

	if (window.DEBUG == true) {
      $('#DEBUG').slideToggle('fast').addClass('opacity-75');
  }

	var link = Nuxleus.getDecodedEmail();
	$('#'.concat('managementemail')).attr('href', 'mailto:' + link).html(link);

});

