/* Gallery */
(function (window){
	
	var FWDRoyalAudioPlayer = function(props){
		
		var self = this;
	
		/* init gallery */
		self.init = function(){
		
			TweenLite.ticker.useRAF(false);
			this.props_obj = props;
			 
			this.instanceName_str = this.props_obj.instanceName;
			if(!this.instanceName_str){
				alert("FWDRoyalAudioPlayer instance name is requires please make sure that the instanceName parameter exsists and it's value is uinique.");
				return;
			}
			
			if(window[this.instanceName_str]){
				alert("FWDRoyalAudioPlayer instance name " + this.instanceName_str +  " is already defined and contains a different instance reference, set a different instance name.");
				return;
			}else{
				window[this.instanceName_str] = this;
			}
		
			if(!this.props_obj){
				alert("FWDRoyalAudioPlayer constructor properties object is not defined!");
				return;
			}
			
			this.useOnlyAPI_bl = self.props_obj.useOnlyAPI; 
			this.useOnlyAPI_bl = self.useOnlyAPI_bl == "yes" ? true : false;
			
			if(!this.props_obj.parentId && !this.useOnlyAPI_bl){		
				alert("Property parentId is not defined in the FWDRoyalAudioPlayer constructor, self property represents the div id into which the megazoom is added as a child!");
				return;
			}
			
			if(!FWDUtils.getChildById(self.props_obj.parentId) && !this.useOnlyAPI_bl){
				alert("FWDRoyalAudioPlayer holder div is not found, please make sure that the div exsists and the id is correct! " + self.props_obj.parentId);
				return;
			}

			this.stageContainer = FWDUtils.getChildById(self.props_obj.parentId);
			this.listeners = {events_ar:[]};
			this.ws = null;
			this.data = null;
			this.customContextMenu_do = null;
			this.info_do = null;
			this.main_do = null;
			this.preloader_do = null;
			this.controller_do = null;
			this.categories_do = null;
			this.playlist_do = null;
			this.audioScreen_do = null;
			this.flash_do = null;
			this.flashObject = null;
			this.facebookShare = null;
			
			this.flashObjectMarkup_str =  null;
			this.popupWindowBackgroundColor = this.props_obj.popupWindowBackgroundColor || "#000000";
			
			this.prevCatId = -1;
			this.catId = -1;
			this.id = -1;
			this.prevId = -1;
			this.lastPercentPlayed = 0;
			this.totalAudio = 0;
			this.stageWidth = 0;
			this.stageHeight = 0;
			this.maxWidth = self.props_obj.maxWidth || 2000;
			this.maxHeight = 0;
			this.popupWindowWidth = self.props_obj.popupWindowWidth || 500;
			this.popupWindowHeight = self.props_obj.popupWindowHeight || 400;
		
			this.resizeHandlerId_to;
			this.resizeHandler2Id_to;
			this.hidePreloaderId_to;
			this.orientationChangeId_to;
			this.showCatWidthDelayId_to;
			
			this.hasOpenedInPopup_bl = false;
			this.isAPIReady_bl = false;
			this.isPlaylistLoaded_bl = false;
			this.isFlashScreenReady_bl = false;
			this.orintationChangeComplete_bl = true;
			this.useDeepLinking_bl = self.props_obj.useDeepLinking;
			this.useDeepLinking_bl = self.useDeepLinking_bl == "yes" ? true : false;
			this.openInPopup_bl = false;
			
			setTimeout(function(){
				try{
					if(window.opener 
						&& window.opener.openedPlayerInstance 
						&& window.opener.openedPlayerInstance == self.instanceName_str){
						self.openInPopup_bl = true;
						self.popupWindow = window.opener[self.instanceName_str];
						window.opener[self.instanceName_str].removeAndDisablePlayer();
					}else{
						if(window.opener 
						&& window.opener.openedPlayerInstance 
						&& window.opener.openedPlayerInstance != self.instanceName_str){
							return;
						}
					}
				}catch(e){}
				
				self.isMobile_bl = FWDUtils.isMobile;
				self.hasPointerEvent_bl = FWDUtils.hasPointerEvent;
				self.setupMainDo();
				self.startResizeHandler();
				self.setupInfo();
				self.setupData();
			}, 49);
			
		
			FWDRoyalAudioPlayer.instaces_ar.push(this);	
		};
		
		
		this.popup = function(){
			if(self.popupWindow && !self.popupWindow.closed) return
			var myWindow;
			var left = (screen.width/2)-(self.popupWindowWidth/2);
			var top = (screen.height/2)-(self.popupWindowHeight/2);
			var loc = "no";
			if(FWDUtils.isSafari) loc = "yes";
			
			try{
				if(FWDUtils.isMobile){
					self.popupWindow = window.open(location.href);
				}else{
					self.popupWindow = window.open(location.href,"",'location='+loc+', width='+self.popupWindowWidth+', height='+self.popupWindowHeight+', top='+top+', left='+left);
				}
				
				if(self.popupWindow){
					self.stageContainer.style.display = "none";
					if(self.preloader_do) self.preloader_do.hide(false);
					self.data.closeData();
					self.stop();
					window.openedPlayerInstance = self.instanceName_str;
					self.hasOpenedInPopup_bl = true;
					self.isAPIReady_bl = false;
				}
				self.stopResizeHandler();
				self.dispatchEvent(FWDRoyalAudioPlayer.POPUP);
			}catch(e){
			}
		};
		
		
		this.removeAndDisablePlayer = function(){
			try{
				self.stageContainer.style.display = "none";
			}catch(e){}
		};
		
		//#############################################//
		/* setup main do */
		//#############################################//
		self.setupMainDo = function(){
			
			self.main_do = new FWDDisplayObject("div", "relative");
			self.main_do.getStyle().msTouchAction = "none";
			self.main_do.getStyle().webkitTapHighlightColor = "rgba(0, 0, 0, 0)";
			self.main_do.setBackfaceVisibility();
			if(!FWDUtils.isMobile || (FWDUtils.isMobile && FWDUtils.hasPointerEvent)) self.main_do.setSelectable(false);
			
			if(self.openInPopup_bl){
				if(!FWDUtils.isIEAndLessThen9) document.getElementsByTagName("body")[0].style.display = "none";
				document.documentElement.appendChild(self.main_do.screen);
				self.main_do.setPosition("fixed");
				self.main_do.getStyle().zIndex = "2147483646";
				document.documentElement.style.overflow = "hidden";
				document.documentElement.style.backgroundColor = self.popupWindowBackgroundColor;	
				self.main_do.setBkColor(self.popupWindowBackgroundColor);
				self.main_do.getStyle().width = "100%";
				self.main_do.setHeight(3000);
			}else{
				self.stageContainer.style.overflow = "hidden";
				self.stageContainer.style.height = "0px";
				self.stageContainer.appendChild(self.main_do.screen);
			}
			
		};
		
		//#############################################//
		/* setup info_do */
		//#############################################//
		self.setupInfo = function(){
			FWDRAPInfo.setPrototype();
			self.info_do = new FWDRAPInfo(self);
		};	
		
		//#############################################//
		/* resize handler */
		//#############################################//
		self.startResizeHandler = function(){
			if(window.addEventListener){
				window.addEventListener("resize", self.onResizeHandler);
				//window.addEventListener("orientationchange", self.orientationChange);
			}else if(window.attachEvent){
				window.attachEvent("onresize", self.onResizeHandler);
			}
			self.onResizeHandler(true);
			self.resizeHandlerId_to = setTimeout(function(){self.resizeHandler(true);}, 50);
		};
		
		self.stopResizeHandler = function(){
			clearTimeout(self.resizeHandlerId_to);
			clearTimeout(self.resizeHandler2Id_to);
			clearTimeout(self.orientationChangeId_to);
			if(window.removeEventListener){
				window.removeEventListener("resize", self.onResizeHandler);
				//window.removeEventListener("orientationchange", self.orientationChange);
			}else if(window.detachEvent){
				window.detachEvent("onresize", self.onResizeHandler);
			}	
		};
		
		self.onResizeHandler = function(e){
			self.resizeHandler();
			clearTimeout(self.resizeHandler2Id_to);
			self.resizeHandler2Id_to = setTimeout(function(){self.resizeHandler();}, 300);
		};
		
		this.orientationChange = function(){
			if(self.displayType == FWDRoyalAudioPlayer.FULL_SCREEN || self.isFullScreen_bl){
				self.orintationChangeComplete_bl = false;	
				clearTimeout(self.resizeHandlerId_to);
				clearTimeout(self.resizeHandler2Id_to);
				clearTimeout(self.orientationChangeId_to);
			
				self.orientationChangeId_to = setTimeout(function(){
					self.orintationChangeComplete_bl = true; 
					self.resizeHandler(true);
					}, 1000);
				
				self.main_do.setX(0);
				//self.main_do.setWidth(0);
			}
		};
		
		self.resizeHandler = function(overwrite){
			if(!self.orintationChangeComplete_bl) return;

			if(!self.openInPopup_bl){
				self.stageContainer.style.width = "100%";
				if(self.stageContainer.offsetWidth > self.maxWidth && !self.openInPopup_bl){
					self.stageContainer.style.width = self.maxWidth + "px";
				}
				self.stageWidth = self.stageContainer.offsetWidth;
				if(self.controller_do) self.maxHeight = self.controller_do.h;
				
				self.stageHeight = self.maxHeight;
				
				self.main_do.setWidth(self.stageWidth);
			}else{
				self.ws = FWDUtils.getViewportSize();
				self.stageWidth = self.ws.w;
			}
			
			if(self.preloader_do) self.positionPreloader();
			if(self.controller_do) self.controller_do.resizeAndPosition();
			if(self.categories_do) self.categories_do.resizeAndPosition();
			if(self.playlist_do) self.playlist_do.resizeAndPosition();
			
			if(self.data && !overwrite){
				self.setStageContainerHeight(false);
			}else{
				self.setStageContainerHeight(true);
			}
		};
		
		//#############################################//
		/* resize main container */
		//#############################################//
		this.setStageContainerHeight = function(animate){
			if(!self.controller_do){
				if(!self.openInPopup_bl){
					self.main_do.setHeight(self.stageHeight);
					self.stageContainer.style.height = self.stageHeight + "px";
				}
				return;
			}
			
			if(self.openInPopup_bl){
				if(!self.ws) self.ws = FWDUtils.getViewportSize();
				
				self.stageWidth = self.ws.w;
				self.main_do.setX(0);
				self.main_do.setY(0);
				self.main_do.getStyle().width = "100%";
				
				self.main_do.setHeight(3000);
				self.controller_do.setX(0);
				TweenMax.killTweensOf(self.controller_do);
				if(animate){
					//if(self.controller_do.y != 0) TweenMax.to(self.controller_do, .8, {y:0, ease:Expo.easeInOut});
				}else{
					self.controller_do.setY(0);
					self.controller_do.setX(0);
				}
				
				self.controller_do.setY(0);
				self.controller_do.setX(0);
			
				if(self.playlist_do){
					TweenMax.killTweensOf(self.playlist_do);
					self.playlist_do.setX(0);
					if(animate){
						//TweenMax.to(self.playlist_do, .8, {y:self.controller_do.h, delay:.4, ease:Expo.easeInOut});
					}else{
						self.playlist_do.setY(self.controller_do.h);	
					}
					self.playlist_do.setX(0);
					self.playlist_do.setY(self.controller_do.h);
				}
				return;
			}
			
			if(self.playlist_do && self.playlist_do.isShowed_bl){
				self.maxHeight += self.playlist_do.h;
			}
			if(self.playlist_do) self.playlist_do.setY(self.controller_do.h);
			
			//if(self.main_do.h == self.stageHeight)  return;
			
			TweenMax.killTweensOf(self.stageContainer);
			if(animate){
				if(self.playlist_do){
					if(self.playlist_do.isShowed_bl){
						self.main_do.setHeight(self.controller_do.h + self.playlist_do.h);
						TweenMax.to(self.stageContainer, .8, {css:{height:self.controller_do.h + self.playlist_do.h}, ease:Expo.easeInOut});
					}else{
						self.main_do.setHeight(self.controller_do.h);
						TweenMax.to(self.stageContainer, .8, {css:{height:self.controller_do.h}, ease:Expo.easeInOut});
					}
				}else{
					self.main_do.setHeight(self.controller_do.h);
					TweenMax.to(self.stageContainer, .8, {css:{height:self.controller_do.h}, ease:Expo.easeInOut});
				}
				
			}else{
				if(self.playlist_do){
					if(self.playlist_do.isShowed_bl){
						self.main_do.setHeight(self.controller_do.h + self.playlist_do.h);
						self.stageContainer.style.height = (self.controller_do.h + self.playlist_do.h) + "px";
					}else{
						self.main_do.setHeight(self.controller_do.h);
						self.stageContainer.style.height = (self.controller_do.h) + "px";
					}
				}else{
					self.main_do.setHeight(self.controller_do.h);
					self.stageContainer.style.height = self.controller_do.h + "px";
				}
			}	
		};
		
		//#############################################//
		/* setup context menu */
		//#############################################//
		this.setupContextMenu = function(){
			self.customContextMenu_do = new FWDRAPContextMenu(self.main_do, self.data.showContextMenu_bl);
		};
		
		//#############################################//
		/* Setup main instances */
		//#############################################//
		this.setupMainInstances = function(){
			if(self.controller_do) return;
			if(FWDRoyalAudioPlayer.hasHTML5Audio) self.setupAudioScreen();
			self.setupController();
			if(self.data.showPlaylistsButtonAndPlaylists_bl) self.setupCategories();
			if(self.data.showPlayListButtonAndPlaylist_bl) self.setupPlaylist();
			if(self.data.showFacebookButton_bl) self.setupFacebook();
			self.controller_do.resizeAndPosition();
		};
	
		//#############################################//
		/* setup data */
		//#############################################//
		this.setupData = function(){
			FWDRAPAudioData.setPrototype();
			self.data = new FWDRAPAudioData(self.props_obj, self.rootElement_el, self);
			self.data.addListener(FWDRAPAudioData.PRELOADER_LOAD_DONE, self.onPreloaderLoadDone);
			self.data.addListener(FWDRAPAudioData.LOAD_ERROR, self.dataLoadError);
			self.data.addListener(FWDRAPAudioData.SKIN_PROGRESS, self.dataSkinProgressHandler);
			self.data.addListener(FWDRAPAudioData.SKIN_LOAD_COMPLETE, self.dataSkinLoadComplete);
			self.data.addListener(FWDRAPAudioData.PLAYLIST_LOAD_COMPLETE, self.dataPlayListLoadComplete);
		};
		
		self.onPreloaderLoadDone = function(){
			self.maxHeight = self.data.controllerHeight;
			self.setupPreloader();
			if(!self.isMobile_bl && self.data.showContextMenu_bl) self.setupContextMenu();
			
			self.resizeHandler();
			if(!self.openInPopup_bl) self.main_do.setHeight(self.data.controllerHeight);
			self.stageContainer.style.height = self.data.controllerHeight + "px";
		};
		
		self.dataLoadError = function(e){
			self.maxHeight = 100;
			if(self.preloader_do) self.preloader_do.hide(false);
			self.main_do.addChild(self.info_do);
			self.info_do.showText(e.text);
			self.resizeHandler();
			self.main_do.setHeight(self.data.controllerHeight);
			self.stageContainer.style.height = self.data.controllerHeight + "px";
			self.dispatchEvent(FWDRoyalAudioPlayer.ERROR, {error:e.text});
		};
		
		self.dataSkinProgressHandler = function(e){};
		
		self.dataSkinLoadComplete = function(){	
			if(self.openInPopup_bl) self.data.showPopupButton_bl = false;
			if(self.useDeepLinking_bl){
				setTimeout(function(){self.setupDL();}, 200);
			}else{
				if(self.openInPopup_bl){
					self.catId = self.popupWindow.catId;
					self.id = self.popupWindow.id;
				}else{
					self.catId = self.data.startAtPlaylist;
					self.id = self.data.startAtTrack;
				}
				self.loadInternalPlaylist();
			}
			
			self.main_do.addChild(self.preloader_do);
		};
	
		this.dataPlayListLoadComplete = function(){
			if(!self.isAPIReady_bl) self.dispatchEvent(FWDRoyalAudioPlayer.READY);
			self.isAPIReady_bl = true;
			self.isPlaylistLoaded_bl = true;
			if(self.openInPopup_bl) self.data.autoPlay_bl = true;
			
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.setupMainInstances();
				self.updatePlaylist();
				self.resizeHandler();
			}else{
				if(self.flash_do){
					self.updatePlaylist();
				}else{
					self.setupFlashScreen();
				}
			}
			
			self.dispatchEvent(FWDRoyalAudioPlayer.LOAD_PLAYLIST_COMPLETE);
		};
		
		this.updatePlaylist = function(){
			if(self.main_do) if(self.main_do.contains(self.info_do)) self.main_do.removeChild(self.info_do);
			self.preloader_do.hide(true);
			self.prevId = -1;
			self.totalAudio = self.data.playlist_ar.length;
			self.controller_do.enableControllerWhileLoadingPlaylist();
	    	self.controller_do.cleanThumbnails(true);
	    	
	    	if(self.playlist_do) self.playlist_do.updatePlaylist(self.data.playlist_ar);
	    	if(self.openInPopup_bl && self.popupWindow.audioScreen_do) self.lastPercentPlayed = self.popupWindow.audioScreen_do.lastPercentPlayed;
	    	self.setSource();
			if(self.data.autoPlay_bl) self.play();
		};
		
		this.loadInternalPlaylist = function(){
			self.isPlaylistLoaded_bl = false;
			self.data.loadPlaylist(self.catId);
			
			self.stop();
			self.preloader_do.show(true);
			if(self.controller_do){
				self.controller_do.disableControllerWhileLoadingPlaylist();
				self.controller_do.loadThumb();
			}
			
			if(self.playlist_do) self.playlist_do.destroyPlaylist();
			self.dispatchEvent(FWDRoyalAudioPlayer.START_TO_LOAD_PLAYLIST);
		};
		
		
		//############################################//
		/* update deeplink */
		//############################################//
		this.setupDL = function(){
			FWDAddress.onChange = self.dlChangeHandler;
			self.dlChangeHandler();
		};
		
		this.dlChangeHandler = function(){
			if(self.hasOpenedInPopup_bl) return;
			var mustReset_bl = false;
			
			if(self.categories_do && self.categories_do.isOnDOM_bl){
				self.categories_do.hide();
				return;
			}
			
			self.catId = parseInt(FWDAddress.getParameter("catid"));
			self.id = parseInt(FWDAddress.getParameter("trackid"));
			
			if(self.catId == undefined || self.id == undefined || isNaN(self.catId) || isNaN(self.id)){
				
				self.catId = self.data.startAtPlaylist;
				self.id = self.data.startAtTrack;
				
				mustReset_bl = true;
			}
			
			if(self.catId < 0 || self.catId > self.data.totalCategories - 1 && !mustReset_bl){
				self.catId = self.data.startAtPlaylist;
				self.id = self.data.startAtTrack;
				mustReset_bl = true;
			}
			
			if(self.data.playlist_ar){
				if(self.id < 0 && !mustReset_bl){
					self.id = self.data.startAtTrack;
					mustReset_bl = true;
				}else if(self.prevCatId == self.catId && self.id > self.data.playlist_ar.length - 1  && !mustReset_bl){
					self.id = self.data.playlist_ar.length - 1;
					mustReset_bl = true;
				}
			}
			
			if(mustReset_bl){
				FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
				return;
			}
			
			if(self.prevCatId != self.catId){
				self.loadInternalPlaylist();
				self.prevCatId = self.catId;
			}else{
				self.setSource(false);
				self.play();
				
			}
		};
		
		//#############################################//
		/* setup preloader */
		//#############################################//
		this.setupPreloader = function(){
			FWDRAPPreloader.setPrototype();
			self.preloader_do = new FWDRAPPreloader(self.data.mainPreloader_img, 53, 34, 30, 80);
			self.preloader_do.show(true);
			self.main_do.addChild(self.preloader_do);
		};
		
		this.positionPreloader = function(){
			self.preloader_do.setX(parseInt((self.stageWidth - self.preloader_do.w)/2));
			if(self.controller_do){
				self.preloader_do.setY(parseInt((self.controller_do.h - self.preloader_do.h)/2));
			}else{
				self.preloader_do.setY(parseInt((self.maxHeight - self.preloader_do.h)/2));
			}
		};
		
		//###########################################//
		/* setup categories */
		//###########################################//
		this.setupCategories = function(){
			FWDRAPCategories.setPrototype();
			self.categories_do = new FWDRAPCategories(self.data);
			self.categories_do.getStyle().zIndex = "2147483647";
			self.categories_do.addListener(FWDRAPCategories.HIDE_COMPLETE, self.categoriesHideCompleteHandler);
			if(self.data.showPlaylistsByDefault_bl){
				self.showCatWidthDelayId_to = setTimeout(function(){
					self.showCategories();
				}, 1400);
			};
		};
		
		this.categoriesHideCompleteHandler = function(e){
			self.controller_do.setCategoriesButtonState("unselected");
			if(self.customContextMenu_do) self.customContextMenu_do.updateParent(self.main_do);
			
			if(self.useDeepLinking_bl){
				if(self.categories_do.id != self.catId){
					self.catId = self.categories_do.id;
					self.id = 0;
					FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
				}
			}else{
				if(self.catId == self.categories_do.id) return;
				self.catId = self.categories_do.id;
				self.id = 0;
				self.loadInternalPlaylist(self.catId);
			}
		};
		
		//###########################################//
		/* setup playslist */
		//###########################################//
		this.setupPlaylist = function(){
			FWDRAPPlaylist.setPrototype();
			self.playlist_do = new FWDRAPPlaylist(self.data, self);
			self.playlist_do.addListener(FWDRAPPlaylistItem.MOUSE_UP, self.palylistItemOnUpHandler);
			self.playlist_do.addListener(FWDRAPPlaylistItem.DOWNLOAD, self.palylistItemDownloadHandler);
			self.main_do.addChild(self.playlist_do);
		};
		
		this.palylistItemOnUpHandler = function(e){
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				if(self.audioScreen_do.isPlaying_bl && e.id == self.id){
					self.pause();
				}else if(!self.audioScreen_do.isStopped_bl && e.id == self.id){
					self.play();
				}else{
					if(self.useDeepLinking_bl && self.id != e.id){
						FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + e.id);
						self.id = e.id;
					}else{
						self.id = e.id;
						self.setSource(true);
						self.play();
					}
				}
			}else if(self.isFlashScreenReady_bl){
				if(self.flashObject.isAudioPlaying() && e.id == self.id){
					self.pause();
				}else if(!self.flashObject.isAudioStopped() && e.id == self.id){
					self.play();
				}else{
					if(self.useDeepLinking_bl && self.id != e.id){
						FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + e.id);
						self.id = e.id;
					}else{
						self.id = e.id;
						self.setSource(true);
						self.play();
					}
				}
			}
		};
		
		this.palylistItemDownloadHandler = function(e){
			self.downloadMP3(e.id);
		};
		
		//###########################################//
		/* setup controller */
		//###########################################//
		this.setupController = function(){
			FWDRAPController.setPrototype();
			self.controller_do = new FWDRAPController(self.data, self);
			self.controller_do.addListener(FWDRAPController.POPUP, self.controllerOnPopupHandler);
			self.controller_do.addListener(FWDRAPController.PLAY, self.controllerOnPlayHandler);
			self.controller_do.addListener(FWDRAPController.PLAY_NEXT, self.controllerPlayNextHandler);
			self.controller_do.addListener(FWDRAPController.PLAY_PREV, self.controllerPlayPrevHandler);
			self.controller_do.addListener(FWDRAPController.PAUSE, self.controllerOnPauseHandler);
			self.controller_do.addListener(FWDRAPController.VOLUME_START_TO_SCRUB, self.volumeStartToScrubbHandler);
			self.controller_do.addListener(FWDRAPController.VOLUME_STOP_TO_SCRUB, self.volumeStopToScrubbHandler);
			self.controller_do.addListener(FWDRAPController.START_TO_SCRUB, self.controllerStartToScrubbHandler);
			self.controller_do.addListener(FWDRAPController.SCRUB, self.controllerScrubbHandler);
			self.controller_do.addListener(FWDRAPController.SCRUB_PLAYLIST_ITEM, self.controllerPlaylistItemScrubbHandler);
			self.controller_do.addListener(FWDRAPController.STOP_TO_SCRUB, self.controllerStopToScrubbHandler);
			self.controller_do.addListener(FWDRAPController.CHANGE_VOLUME, self.controllerChangeVolumeHandler);
			self.controller_do.addListener(FWDRAPController.SHOW_CATEGORIES, self.showCategoriesHandler);
			self.controller_do.addListener(FWDRAPController.SHOW_PLAYLIST, self.showPlaylistHandler);
			self.controller_do.addListener(FWDRAPController.HIDE_PLAYLIST, self.hidePlaylistHandler);
			self.controller_do.addListener(FWDRAPController.ENABLE_LOOP, self.enableLoopHandler);
			self.controller_do.addListener(FWDRAPController.DISABLE_LOOP, self.disableLoopHandler);
			self.controller_do.addListener(FWDRAPController.ENABLE_SHUFFLE, self.enableShuffleHandler);
			self.controller_do.addListener(FWDRAPController.DISABLE_SHUFFLE, self.disableShuffleHandler);
			self.controller_do.addListener(FWDRAPController.FACEBOOK_SHARE, self.facebookShareHandler);
			self.controller_do.addListener(FWDRAPController.DOWNLOAD_MP3, self.controllerButtonDownloadMp3Handler);
			self.main_do.addChild(self.controller_do);
			if(self.openInPopup_bl && self.data.showPlaylistsButtonAndPlaylists_bl){
				self.controller_do.setPlaylistButtonState("selected");
				if(self.controller_do.playlistButton_do) self.controller_do.playlistButton_do.disableForGood();
			}
		};
		
		this.controllerOnPopupHandler = function(){
			self.popup();
		};
		
		this.controllerOnPlayHandler = function(e){
			FWDRoyalAudioPlayer.pauseAllAudio(self);
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.play();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.playAudio();
			}
		};
		
		this.controllerPlayNextHandler = function(e){
			self.playNext();
		};
		
		this.controllerPlayPrevHandler = function(e){
			self.playPrev();
		};
		
		this.controllerOnPauseHandler = function(e){
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.pause();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.pauseAudio();
			}
		};
		
		this.volumeStartToScrubbHandler = function(e){
			if(self.playlist_do) self.playlist_do.showDisable();
		};
		
		this.volumeStopToScrubbHandler = function(e){
			if(self.playlist_do) self.playlist_do.hideDisable();
		};
		
		
		this.controllerStartToScrubbHandler = function(e){
			if(self.playlist_do) self.playlist_do.showDisable();
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.startToScrub();
			}else if(self.isFlashScreenReady_bl){
				FWDRoyalAudioPlayer.pauseAllAudio(self);
				self.flashObject.startToScrub();
			}
		};
		
		this.controllerScrubbHandler = function(e){
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.scrub(e.percent);
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.scrub(e.percent);
			}
		};
		
		this.controllerPlaylistItemScrubbHandler = function(e){
			if(self.playlist_do) self.playlist_do.updateCurItemProgress(e.percent);
		};
		
		this.controllerStopToScrubbHandler = function(e){
			if(self.playlist_do) self.playlist_do.hideDisable();
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.stopToScrub();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.stopToScrub();
			}
		};
		
		this.controllerChangeVolumeHandler = function(e){
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.setVolume(e.percent);
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.setVolume(e.percent);
			}
		};
		
		this.showCategoriesHandler = function(e){
			self.showCategories();
			self.controller_do.setCategoriesButtonState("selected");
		};
		
		this.showPlaylistHandler = function(e){
			if(self.data.animateOnIntro_bl){
				self.playlist_do.show(true);
			}else{
				self.playlist_do.show(false);
			}
			
			self.controller_do.setPlaylistButtonState("selected");
		};
		
		this.hidePlaylistHandler = function(e){
			if(self.data.animateOnIntro_bl){
				self.playlist_do.hide(true);
			}else{
				self.playlist_do.hide(false);
			}
			self.controller_do.setPlaylistButtonState("unselected");
		};
		
		this.enableLoopHandler = function(e){
			self.data.loop_bl = true;
			self.data.shuffle_bl = false;
			self.controller_do.setLoopStateButton("selected");
			self.controller_do.setShuffleButtonState("unselected");
		};
		
		this.disableLoopHandler = function(e){
			self.data.loop_bl = false;
			self.controller_do.setLoopStateButton("unselected");
		};
		
		this.enableShuffleHandler = function(e){
			self.data.shuffle_bl = true;
			self.data.loop_bl = false;
			self.controller_do.setShuffleButtonState("selected");
			self.controller_do.setLoopStateButton("unselected");
		};
		
		this.disableShuffleHandler = function(e){
			self.data.shuffle_bl = false;
			self.controller_do.setShuffleButtonState("unselected");
		};
		
		this.facebookShareHandler = function(e){
			
			if(document.location.protocol == "file:"){
				var error = "Facebook is not allowing sharing local, please test online.";
				self.main_do.addChild(self.info_do);
				self.info_do.showText(error);
				return;
			}
				
			if(self.useDeepLinking_bl){
				var curItem = self.data.playlist_ar[self.id];
				var thumbPath;
				
				if(curItem.thumbPath && curItem.thumbPath.indexOf("//") !=  -1){
					thumbPath = curItem.thumbPath;
				}else{
					var absolutePath = location.pathname;
					absolutePath = location.protocol + "//" + location.host + absolutePath.substring(0, absolutePath.lastIndexOf("/") + 1);
					thumbPath = absolutePath + curItem.thumbPath;
				}
				self.facebookShare.share(location.href, curItem.titleText, thumbPath);
			}else{
				self.facebookShare.share(location.href);
			}
		};
		
		this.controllerButtonDownloadMp3Handler = function(e){
			self.downloadMP3();
		};
		
		//###########################################//
		/* setup FWDRAPAudioScreen */
		//###########################################//
		this.setupAudioScreen = function(){	
			FWDRAPAudioScreen.setPrototype();
			self.audioScreen_do = new FWDRAPAudioScreen(self.data.volume, self.data.autoPlay_bl, self.data.loop_bl);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.START, self.audioScreenStartHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.ERROR, self.audioScreenErrorHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.SAFE_TO_SCRUBB, self.audioScreenSafeToScrubbHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.STOP, self.audioScreenStopHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.PLAY, self.audioScreenPlayHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.PAUSE, self.audioScreenPauseHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.UPDATE, self.audioScreenUpdateHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.UPDATE_TIME, self.audioScreenUpdateTimeHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.LOAD_PROGRESS, self.audioScreenLoadProgressHandler);
			self.audioScreen_do.addListener(FWDRAPAudioScreen.PLAY_COMPLETE, self.audioScreenPlayCompleteHandler);
			if(self.useOnlyAPI_bl){
				document.documentElement.appendChild(self.audioScreen_do.screen);
			}else{
				self.main_do.addChild(self.audioScreen_do);	
			}
		};
		
		this.audioScreenStartHandler = function(){
			self.dispatchEvent(FWDRAPAudioScreen.START);
		};
		
		this.audioScreenErrorHandler = function(e){
			var error;
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				error = e.text;
				if(self.main_do) self.main_do.addChild(self.info_do);
				if(self.info_do) self.info_do.showText(error);
			}else{
				error = e;
				if(self.main_do) self.main_do.addChild(self.info_do);
				if(self.info_do) self.info_do.showText(error);
			}
			
			self.dispatchEvent(FWDRoyalAudioPlayer.ERROR, {error:error});
		};
		
		this.audioScreenSafeToScrubbHandler = function(){
			if(self.controller_do) self.controller_do.enableMainScrubber(); 
		};
		
		this.audioScreenStopHandler = function(e){
			if(self.main_do) if(self.main_do.contains(self.info_do)) self.main_do.removeChild(self.info_do);
			if(self.controller_do){
				self.controller_do.showPlayButton();
				self.controller_do.stopEqulizer();
				self.controller_do.disableMainScrubber();
			}
			self.dispatchEvent(FWDRoyalAudioPlayer.STOP);
		};
		
		this.audioScreenPlayHandler = function(){
			if(self.controller_do){
				self.controller_do.showPauseButton();
				self.controller_do.startEqulizer();
			}
			if(self.playlist_do) self.playlist_do.setCurItemPauseState();
			if(self.openInPopup_bl){
				setTimeout(function(){
					if(!self.scrubbedFirstTimeInPopup_bl) self.scrub(self.lastPercentPlayed);
					self.scrubbedFirstTimeInPopup_bl = true;
				},600);
			}
			self.dispatchEvent(FWDRoyalAudioPlayer.PLAY);
		};
		
		this.audioScreenPauseHandler = function(){
			if(self.controller_do){
				self.controller_do.showPlayButton();
				self.controller_do.stopEqulizer();
			}
			
			if(self.playlist_do){
				self.playlist_do.setCurItemPlayState();
			}
			self.dispatchEvent(FWDRoyalAudioPlayer.PAUSE);
		};
		
		this.audioScreenUpdateHandler = function(e){
			var percent;	
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				percent = e.percent;
				if(self.controller_do) self.controller_do.updateMainScrubber(percent);
				if(self.playlist_do) self.playlist_do.updateCurItemProgress(percent);
			}else{
				percent = e;
				if(self.controller_do) self.controller_do.updateMainScrubber(percent);
				if(self.playlist_do) self.playlist_do.updateCurItemProgress(percent);
			}
			self.dispatchEvent(FWDRoyalAudioPlayer.UPDATE, {percent:percent});
		};
		
		this.audioScreenUpdateTimeHandler = function(e, e2){
			var curTime;
			var totalTime;
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				curTime = e.curTime;
				totalTime = e.totalTime;
				if(self.controller_do) self.controller_do.updateTime(curTime, totalTime);
			}else{
				curTime = e;
				totalTime = e2;
				
				if(totalTime.length > curTime.length) curTime = (parseInt(totalTime.substring(0,1)) - 1) + ":" + curTime;
				if(self.controller_do) self.controller_do.updateTime(curTime, totalTime);
			}
		
			self.dispatchEvent(FWDRoyalAudioPlayer.UPDATE_TIME, {curTime:curTime, totalTime:totalTime});
		};
		
		this.audioScreenLoadProgressHandler = function(e){
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				if(self.controller_do) self.controller_do.updatePreloaderBar(e.percent);
			}else{
				if(self.controller_do) self.controller_do.updatePreloaderBar(e);
			}
		};
		
		this.audioScreenPlayCompleteHandler = function(){
			self.dispatchEvent(FWDRoyalAudioPlayer.PLAY_COMPLETE);
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				if(self.data.loop_bl){
					self.audioScreen_do.replay();
				}else if(self.data.shuffle_bl){
					self.playShuffle();
				}else{
					self.playNext();
				}
			}else if(self.isFlashScreenReady_bl){
				if(self.data.loop_bl){
					self.flashObject.replayAudio();
				}else if(self.data.shuffle_bl){
					self.playShuffle();
				}else{
					self.playNext();
				}
			}
		};
		
		//#############################################//
		/* Flash screen... */
		//#############################################//
		this.setupFlashScreen = function(){
			if(self.flash_do) return;
			if(!FWDFlashTest.hasFlashPlayerVersion("9.0.18")){
				if(self.useOnlyAPI_bl){
					alert("Please install Adobe flash player! <a href='http://www.adobe.com/go/getflashplayer'>Click here to install.</a>");
				}else{
					self.main_do.addChild(self.info_do);
					self.info_do.showText("Please install Adobe flash player! <a href='http://www.adobe.com/go/getflashplayer'>Click here to install.</a>");
				}
				if(self.preloader_do) self.preloader_do.hide(false);
				return;
			}
			
			self.flash_do = new FWDDisplayObject("div");
			self.flash_do.setBackfaceVisibility();
			self.flash_do.setResizableSizeAfterParent();	
			if(self.useOnlyAPI_bl){
				document.getElementsByTagName("body")[0].appendChild(self.flash_do.screen);
			}else{
				self.main_do.addChild(self.flash_do);
			}
		
			var sourcePath = "not defined!";
			
			self.flashObjectMarkup_str = '<object id="' + (self.instanceName_str +  "1") + '" name="' + (self.instanceName_str +  "1") + '" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="' + self.data.flashPath_str + '"/><param name="wmode" value="transparent"><param name=FlashVars value="instanceName=' + self.instanceName_str + '&sourcePath=' + sourcePath + '&volume=' + self.data.volume + '&autoPlay=' + self.data.autoPlay_bl + '&loop=' + self.data.loop_bl + '"/><param name = "allowScriptAccess" value="always" /><!--[if !IE]>--><object name="myCom" type="application/x-shockwave-flash" data="' + self.data.flashPath_str + '" width="100%" height="100%"><param name="swliveconnect" value="true"/><param name="wmode" value="transparent"><param name=FlashVars value="instanceName=' + self.instanceName_str + '&sourcePath=' + sourcePath + '&volume=' + self.data.volume + '&autoPlay=' + self.data.autoPlay_bl + '&loop=' + self.data.loop_bl + '"/><!--<![endif]--><!--[if !IE]>--></object><!--<![endif]--></object>';
			self.flash_do.screen.innerHTML = self.flashObjectMarkup_str;
			
			self.flashObject = self.flash_do.screen.firstChild;
			if(!FWDUtils.isIE) self.flashObject = self.flashObject.getElementsByTagName("object")[0];
		};
	
		this.flashScreenIsReady = function(){
			//console.log("flash is ready " + self.instanceName_str)
			self.isFlashScreenReady_bl = true;
			self.setupMainInstances();
			self.updatePlaylist();
		};
		
		this.flashScreenFail = function(){
			self.main_do.addChild(self.info_do);
			self.info_do.showText("External interface error!");
			self.resizeHandler();
		};
		
		//#######################################//
		/* Set source based on id */
		//#######################################//
		this.setSource = function(itemClicked){
			
			//if(self.id == self.prevId) return;
			if(self.id < 0){
				self.id = 0;
			}else if(self.id > self.totalAudio - 1){
				self.id = self.totalAudio - 1;
			}
			
			var audioPath = self.data.playlist_ar[self.id].source;
			
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.setSource(audioPath);
			}else{
				var paths_ar = audioPath.split(",");
				
				for(var i=0; i<paths_ar.length; i++){
					audioPath = paths_ar[i];
					paths_ar[i] = FWDUtils.trim(audioPath);
				}
				
				for(var i=0; i<paths_ar.length; i++){
					if(paths_ar[i].indexOf(".mp3") != -1){
						audioPath = paths_ar[i];
						break;
					}
				}
				self.flashObject.setSource(audioPath);
			}
			
			self.controller_do.stopEqulizer();
			self.controller_do.setTitle(self.data.playlist_ar[self.id].title);
			if(self.data.playlist_ar[self.id].duration == undefined){
				self.controller_do.updateTime("00:00", "00:00");
			}else{
				self.controller_do.updateTime("00:00", FWDRoyalAudioPlayer.formatTotalTime(self.data.playlist_ar[self.id].duration));
			}
			self.controller_do.loadThumb(self.data.playlist_ar[self.id].thumbPath);
			
			if(self.playlist_do) self.playlist_do.activateItems(self.id, itemClicked);
			self.resizeHandler();
		};
		
		//##########################################//
		/* Setup facebook */
		//##########################################//
		this.setupFacebook = function(){
			if(document.location.protocol == "file:") return;
			self.facebookShare = new FWDFacebookShare(self.data.facebookAppId_str);
		};
		
		//####################################//
		// API
		//###################################//
		this.loadPlaylist = function(id){
			if(!self.isAPIReady_bl) return;
			self.catId = id;
			self.id = 0;
			
			if(self.catId < 0){
				self.catId = 0;
			}else if(self.catId > self.data.totalCategories - 1){
				self.catId = self.data.totalCategories - 1;
			};
			if(self.useDeepLinking_bl){
				FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
			}else{
				self.loadInternalPlaylist();
			}
		};
		
		this.playNext = function(){	
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			self.id ++;
			if(self.id < 0){
				self.id = self.totalAudio - 1;
			}else if(self.id > self.totalAudio - 1){
				self.id = 0;
			}
			
			if(self.useDeepLinking_bl){
				FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
			}else{
				self.setSource();
				self.play();
			}
			self.prevId = self.id;
		};
		
		this.playPrev = function(){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			self.id --;	
			if(self.id < 0){
				self.id = self.totalAudio - 1;
			}else if(self.id > self.totalAudio - 1){
				self.id = 0;
			}
			if(self.useDeepLinking_bl){
				FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
			}else{
				self.setSource();
				self.play();
			}
			self.prevId = self.id;
		};
		
		this.playShuffle = function(){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			var tempId = parseInt(Math.random() * self.data.playlist_ar.length);
			while(tempId == self.id) tempId = parseInt(Math.random() * self.data.playlist_ar.length);
			self.id = tempId;	
			if(self.id < 0){
				self.id = self.totalAudio - 1;
			}else if(self.id > self.totalAudio - 1){
				self.id = 0;
			}

			if(self.useDeepLinking_bl){
				FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
			}else{
				self.setSource();
				self.play();
			}
			self.prevId = self.id;
		};
		
		this.playSpecificTrack = function(catId, trackId){	
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			
			self.catId = catId;
			self.id = trackId;
			
			if(self.catId < 0){
				self.catId = 0;
			}else if(self.catId > self.data.totalCategories - 1){
				self.catId = self.data.totalCategories - 1;
			};
			if(self.id < 0) self.id = 0;
			
			if(self.useDeepLinking_bl){
				FWDAddress.setValue(self.instanceName_str + "?catid=" + self.catId + "&trackid=" + self.id);
			}else{
				self.setSource();
				self.play();
			}
			self.prevId = self.id;
		};
		
		this.play = function(){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			FWDRoyalAudioPlayer.pauseAllAudio(self);
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.play();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.playAudio();
			}
		};
		
		this.pause = function(){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.pause();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.pauseAudio();
			}
		};
		
		this.stop = function(){
			if(!self.isAPIReady_bl) return;
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.stop();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.stopAudio();
			}
		};
		
		this.startToScrub = function(){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.startToScrub();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.startToScrub();
			}
		};
		
		this.stopToScrub = function(){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				self.audioScreen_do.stopToScrub();
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.stopToScrub();
			}
		};
		
		this.scrub = function(percent){
			if(!self.isAPIReady_bl || !self.isPlaylistLoaded_bl) return;
			if(isNaN(percent)) return;
			if(percent < 0){
				percent = 0;
			}else if(percent > 1){
				percent = 1;
			}
			if(FWDRoyalAudioPlayer.hasHTML5Audio){
				if(self.audioScreen_do) self.audioScreen_do.scrub(percent);
			}else if(self.isFlashScreenReady_bl){
				self.flashObject.scrub(percent);
			}
		};
		
		this.setVolume = function(volume){
			if(!self.isAPIReady_bl) return;
			if(self.isMobile_bl) volume = 1;
			self.controller_do.updateVolume(volume);
		};
		
		this.showCategories = function(){
			if(!self.isAPIReady_bl) return;
			if(self.categories_do){
				self.categories_do.show(self.catId);
				if(self.customContextMenu_do) self.customContextMenu_do.updateParent(self.categories_do);
				self.controller_do.setCategoriesButtonState("selected");
			}
		};
		
		this.hideCategories = function(){
			if(!self.isAPIReady_bl) return;
			if(self.categories_do){
				self.categories_do.hide();
				self.controller_do.setCategoriesButtonState("unselected");
			}
		};
		
		this.showPlaylist = function(){
			if(!self.isAPIReady_bl) return;
			if(self.playlist_do){
				if(self.data.animateOnIntro_bl){
					self.playlist_do.show(true);
				}else{
					self.playlist_do.show(false);
				}
				self.controller_do.setPlaylistButtonState("selected");
			}
		};
		
		this.hidePlaylist = function(){
			if(!self.isAPIReady_bl) return;
			if(self.playlist_do){
				if(self.data.animateOnIntro_bl){
					self.playlist_do.hide(true);
				}else{
					self.playlist_do.hide(false);
				}
				self.controller_do.setPlaylistButtonState("unselected");
			}
		};
		
		this.share = function(){
			if(!self.isAPIReady_bl) return;
			if(document.location.protocol == "file:") return;
			if(self.facebookShare){
				if(self.useDeepLinking_bl){
					var curItem = self.data.playlist_ar[self.id];
					self.facebookShare.share(location.href, curItem.titleText, curItem.thumbPath);
				}else{
					self.facebookShare.share(location.href);	
				}
			}
		};	
		
		this.getIsAPIReady = function(){
			return self.isAPIReady_bl;
		};
		
		this.getCatId = function(){
			return self.catId;
		};
		
		this.getTrackId = function(){
			return self.id;
		};
		
		this.downloadMP3 = function(pId){
			
			if(document.location.protocol == "file:"){
				var error = "Downloading mp3 files local is not allowed or possible!. To function properly please test online.";
				self.main_do.addChild(self.info_do);
				self.info_do.showText(error);
				return;
			}
			
			if(pId ==  undefined) pId = self.id;
			
			var source = self.data.playlist_ar[pId].downloadPath;
			var sourceName = self.data.playlist_ar[pId].titleText;
			self.data.downloadMp3(source, sourceName);
		};
		
		//###########################################//
		/* event dispatcher */
		//###########################################//
		this.addListener = function (type, listener){
	    	if(!this.listeners) return;
	    	if(type == undefined) throw Error("type is required.");
	    	if(typeof type === "object") throw Error("type must be of type String.");
	    	if(typeof listener != "function") throw Error("listener must be of type Function.");
	    	
	    	
	        var event = {};
	        event.type = type;
	        event.listener = listener;
	        event.target = this;
	        this.listeners.events_ar.push(event);
	    };
	    
	    this.dispatchEvent = function(type, props){
	    	if(this.listeners == null) return;
	    	if(type == undefined) throw Error("type is required.");
	    	if(typeof type === "object") throw Error("type must be of type String.");
	    	
	        for (var i=0, len=this.listeners.events_ar.length; i < len; i++){
	        	if(this.listeners.events_ar[i].target === this && this.listeners.events_ar[i].type === type){		
	    	        if(props){
	    	        	for(var prop in props){
	    	        		this.listeners.events_ar[i][prop] = props[prop];
	    	        	}
	    	        }
	        		this.listeners.events_ar[i].listener.call(this, this.listeners.events_ar[i]);
	        	}
	        }
	    };
	    
	   this.removeListener = function(type, listener){
	    	if(type == undefined) throw Error("type is required.");
	    	if(typeof type === "object") throw Error("type must be of type String.");
	    	if(typeof listener != "function") throw Error("listener must be of type Function." + type);
	    	
	        for (var i=0, len=this.listeners.events_ar.length; i < len; i++){
	        	if(this.listeners.events_ar[i].target === this 
	        			&& this.listeners.events_ar[i].type === type
	        			&& this.listeners.events_ar[i].listener ===  listener
	        	){
	        		this.listeners.events_ar.splice(i,1);
	        		break;
	        	}
	        }  
	    };		
		self.init();
	};
	
	/* set prototype */
	FWDRoyalAudioPlayer.setPrototype =  function(){
		FWDRoyalAudioPlayer.prototype = new FWDEventDispatcher();
	};
	
	FWDRoyalAudioPlayer.pauseAllAudio = function(pAudio){
	
		var totalAudio = FWDRoyalAudioPlayer.instaces_ar.length;
		var audio;
		
		for(var i=0; i<totalAudio; i++){
			audio = FWDRoyalAudioPlayer.instaces_ar[i];
			if(audio != pAudio) audio.stop();
		};
	};
	
	FWDRoyalAudioPlayer.hasHTML5Audio = (function(){
		var soundTest_el = document.createElement("audio");
		var flag = false;
		if(soundTest_el.canPlayType){
			flag = Boolean(soundTest_el.canPlayType('audio/mpeg') == "probably" || soundTest_el.canPlayType('audio/mpeg') == "maybe");
		}
		if(self.isMobile_bl) return true;
		//return false;
		return flag;
	}());
	
	FWDRoyalAudioPlayer.getAudioFormats = (function(){
		var audio_el = document.createElement("audio");
		if(!audio_el.canPlayType) return;
		var extention_str = "";
		var extentions_ar = [];
		if(audio_el.canPlayType('audio/mpeg') == "probably" || audio_el.canPlayType('audio/mpeg') == "maybe"){
			extention_str += ".mp3";
		}
		
		if(audio_el.canPlayType("audio/ogg") == "probably" || audio_el.canPlayType("audio/ogg") == "maybe"){
			extention_str += ".ogg";
		}
		
		if(audio_el.canPlayType("audio/mp4") == "probably" || audio_el.canPlayType("audio/mp4") == "maybe"){
			extention_str += ".webm";
		}
		
		extentions_ar = extention_str.split(".");
		extentions_ar.shift();
		
		audio_el = null;
		return extentions_ar;
	})();
	
	FWDRoyalAudioPlayer.hasCanvas = (function(){
		return Boolean(document.createElement("canvas"));
	})();
	
	FWDRoyalAudioPlayer.formatTotalTime = function(secs){
		
		if(typeof secs == "string" && secs.indexOf(":") != -1){
			if(secs.length <= 5){
				return secs;
			}else{
				return "0:" + secs;
			}
		} 
		
		secs = secs/1000;
		
		var hours = Math.floor(secs / (60 * 60));
		
	    var divisor_for_minutes = secs % (60 * 60);
	    var minutes = Math.floor(divisor_for_minutes / 60);

	    var divisor_for_seconds = divisor_for_minutes % 60;
	    var seconds = Math.ceil(divisor_for_seconds);
	    
	    minutes = (minutes >= 10) ? minutes : "0" + minutes;
	    seconds = (seconds >= 10) ? seconds : "0" + seconds;
	   
	    if(isNaN(seconds)) return "00:00/00:00";
		if(hours > 0){
			 return hours + ":" + minutes + ":" + seconds;
		}else{
			 return  minutes + ":" + seconds;
		}
	};
	

	FWDRoyalAudioPlayer.getAudioFormats = (function(){
		var audio_el = document.createElement("audio");
		if(!audio_el.canPlayType) return;
		var extention_str = "";
		var extentions_ar = [];
		if(audio_el.canPlayType('audio/mpeg') == "probably" || audio_el.canPlayType('audio/mpeg') == "maybe"){
			extention_str += ".mp3";
		}
		
		if(audio_el.canPlayType("audio/ogg") == "probably" || audio_el.canPlayType("audio/ogg") == "maybe"){
			extention_str += ".ogg";
		}
		
		if(audio_el.canPlayType("audio/mp4") == "probably" || audio_el.canPlayType("audio/mp4") == "maybe"){
			extention_str += ".webm";
		}
		
		extentions_ar = extention_str.split(".");
		extentions_ar.shift();
		
		audio_el = null;
		return extentions_ar;
	})();
	
	FWDRoyalAudioPlayer.instaces_ar = [];
	
	FWDRoyalAudioPlayer.READY = "ready";
	FWDRoyalAudioPlayer.START_TO_LOAD_PLAYLIST = "startToLoadPlaylist";
	FWDRoyalAudioPlayer.LOAD_PLAYLIST_COMPLETE = "loadPlaylistComplete";
	FWDRoyalAudioPlayer.STOP = "stop";
	FWDRoyalAudioPlayer.PLAY = "play";
	FWDRoyalAudioPlayer.PAUSE = "pause";
	FWDRoyalAudioPlayer.UPDATE = "update";
	FWDRoyalAudioPlayer.UPDATE_TIME = "updateTime";
	FWDRoyalAudioPlayer.ERROR = "error";
	FWDRoyalAudioPlayer.PLAY_COMPLETE = "playComplete";
	FWDRoyalAudioPlayer.PLAYLIST_LOAD_COMPLETE = "onPlayListLoadComplete";
	FWDRoyalAudioPlayer.POPUP = "popup";
	FWDRoyalAudioPlayer.START = "start";
	
	
	window.FWDRoyalAudioPlayer = FWDRoyalAudioPlayer;
	
}(window));