if(typeof(SayRadio) == "undefined") {
	var SayRadio = {
		sessId : null,
		listenUrl : null,
		radioType : null,
		radioConfigUrl : null,
		
		factory : null,
		radio : null,
		debug : false,
		startTryCnt : 0,
		createTryCnt : 0,

		redirectUrl : null,
		
		defaultCallback : {
			BeginStage : function(name, desc) {
				SayRadio.log("BeginStage(" + name + " . " + desc + ")");		
			},
			Progress : function(progress, desc) {
				SayRadio.log("Progress(" + name + " . " + desc + ")");
			},
			EndStage : function(name, result) {
				SayRadio.log("EndStage(" + name + " . " + result + ")");
			},
			Completed : function(result, pIUnk) {
				SayRadio.log("Complete(" + result + ")");
			}		
		},

		init : function(sessId, listenUrl, classid, codebase, commonConfigUrl, service, debug, referrer, introducer) {	
			this.sessId = sessId;
			this.listenUrl = listenUrl;
			//debug = true;
			this.debug = debug;
			if(this.debug) this.initDebug();

			this.log("--- Initialize ---");
			
			//----- check factory installed -----------------------------------------
			this.factory = document.getElementById("SaycastFactory");
			if(!this.factory) {
                if(navigator.appVersion.indexOf("MSIE 9") > -1)
                {
                	$("<object id=\"SaycastFactory\" classid=\"CLSID:" + classid + "\" codebase=\"" + codebase + "\" width=\"0\" height=\"0\"></object>").insertAfter("body");
                }
                else
                {
                	var obj = document.createElement("<object id=\"SaycastFactory\" classid=\"CLSID:" + classid + "\" codebase=\"" + codebase + "\" width=\"0\" height=\"0\"></object>");
                	document.body.appendChild(obj);
                }
				//----- execute application after download complete -------------------
				var iv = setInterval(function() {
					var e = document.getElementById("SaycastFactory");
					if(typeof(e.CreateExtension) != 'undefined') {
						clearInterval(iv);

						SayRadio.init(sessId, listenUrl, classid, codebase, commonConfigUrl, service, debug, referrer, introducer);
					}
				}, 100);
				//---------------------------------------------------------------------
				
				return;
			}
			//-----------------------------------------------------------------------
			this.log("--- Initialize ---");

			this.log("--- Create Common Extension ---");
			
			var common = this.factory.CreateExtension(commonConfigUrl, "", this.defaultCallback, this.factory);
			
			var radioType, owner;
			switch(service) {
				case "saycast" :
					radioType = "radio";
					owner = "saycast";
					break;
				case "pmang" :
					radioType = "radio";
					owner = "pmang";
					break;
				case "bugs" :
					radioType = "bugsradio";
					owner = "bugs";
					break;
				default :
					alert("Invalid Service Type!!!");
					return;
			}

			common.Execute("function://SelectExtension?group=radio&default=" + radioType, {
				SelectExtension : function(type, url) {
					SayRadio.radioType = type;
					SayRadio.radioConfigUrl = url;
				}
			});
			
			this.log("--- Create Common Extension ---");

			this.create(common, owner, referrer, introducer);
		},

		initDebug : function() {
			$("#sayradioDebug").remove();
			$("<textarea></textarea>").attr("id", "sayradioDebug").css("width", 800).css("height", 400).appendTo("body");
		},
		
		log : function(str) {
			if(this.debug)
				$("#sayradioDebug").append((new Date()).toString() + " " + str + "<br/>");
		},
		
		create : function(common, owner, referrer, introducer) {
			this.log("--- Create Radio Extension ---");

			try {
				this.radio = this.factory.CreateExtension(this.radioConfigUrl, "common/factory/SAYRADIO.PNG", $.extend($.extend(this.defaultCallback), {
					Completed : function(result, pIUnk) {
						SayRadio.log("Complete(" + result + ")");
						
						if(result != 0) {
							alert("SayRadio CreateExtension Error : " + result);
						}
					}
				}), common);
			}
			catch(e) {
				alert(e);
				return;
			}

			// Set owner of the radio extension
			//common.Execute("function://SetOwner?this=" + this.radioType + "&owner=" + owner, this.defaultCallback);
			
			this.log("--- Create Radio Extension ---");
			
			SayRadio.start(owner,referrer,introducer);
		},
		
		start : function(owner,referrer,introducer) {
			//----- check radio object created. have to check -----------------------
			if(!this.radio) {
				this.startTryCnt++;
				if(this.startTryCnt < 15) {
					setTimeout(function() {
						SayRadio.start(owner,referrer,introducer);
					}, 100);
				}
				else {
					alert("ERROR : CANNOT ACCESS RADIO START METHOD");
				}
				return;
			}
			//-----------------------------------------------------------------------

			if(SayRadio.radio.status & 0x800) { // running
				SayRadio.execute();
			}
			else {
				if(!(SayRadio.radio.status & 0x80)) {
					this.log("--- Verify ---");
					try {
						this.radio.Verify(SayRadio.defaultCallback);
					}
					catch(e) {}
					this.log("--- Verify ---");
				}

				this.log("--- Startup Radio Extension ---");
				this.radio.owner = owner;
				this.radio.referrer = referrer;
				this.radio.introducer = introducer;
				this.radio.Start(false, $.extend($.extend(this.defaultCallback), {
					Completed : function(result, pIUnk) {
						SayRadio.log("Complete(" + result + ")");
						
						if(result == 0 || result == 1) {
							SayRadio.execute();
						}
						else {
							if(SayRadio.redirectUrl) document.location.href = SayRadio.redirectUrl;
						}
					}
				}));
				this.log("--- Startup Radio Extension ---");
			}
		},
		
		execute : function() {
			this.log("--- Execute ---");
			try {
				var url = SayRadio.listenUrl;
				if(SayRadio.sessId) {
					if(url) url += "?";
					url += "SessionID=" + SayRadio.sessId;
				}

				SayRadio.radio.Execute(url, SayRadio.defaultCallback);
				
				if(SayRadio.redirectUrl) document.location.href = SayRadio.redirectUrl;
			}
			catch(e) {}
			
			this.log("--- Execute --- ");
		},
		
		showRadioProperty : function() {
    	this.log("--- Radio Extension Property ---");
    	try {
				this.log("Extension Name = " + this.radio.name);
				this.log("Extension Link = " + this.radio.link);
        
				var status = radio.status;
				if(status == 0)
					this.log("Extension is NOT available.");
				else {
					if(status & 0x02)
						this.log("Extension is NOT installed.");
					if(status & 0x08)
						this.log("Extension installed.");
					if(status & 0x20)
						this.log("Extension needs update.");
					if(status & 0x80)
						this.log("Extension verified.");
					if(status & 0x400)
						this.log("Extension is running.");
				}
			}
			catch (e) {alert(e);}

			this.log("--- Radio Extension Property ---");
		},
		
		setRedirectUrl : function(url) {
			this.redirectUrl = url;
		}
	};
}

function openSayRadio(type, id) 
{
	if(type == 'url')
		var url = id
	else if(id)
	{
		if(type == 'station')
			var url = "http://" + id + ".saycast.com/listen.pls";
		else
			var url = "http://www.saycast.com/" + id + ".pls";
	}
	else
	{
		var url = "";
	}

	idx = (navigator.appVersion.indexOf("MSIE"));
	if (idx < 0)
	{
		if(type == 'station')
		{				
			$.get(_staticUrl + "/ajax/html/saycast/station/getServerType/" + id, "", function(data) 
			{
				if(data == 'internal')
				{			
					var url=_staticSaycastUrl+"/saycast/widget/widgetMini/"+id;
					window.open(url, 'widgetMini', "width=169,height=106,toolbar=no,scrollbars=no,resizable=no");					
				}
				else
				{
					alert("외부서버 방송국은 세이라디오를 다운받아 청취 하거나 Internet Explorer 에서 청취 하세요.");
				}				
			});
		}
		else if(type == 'personal')
		{
			alert("개인방송은 세이라디오를 다운받아 청취 하거나 Internet Explorer 에서 청취 하세요.");			
		}
		return;
	}
	
	SayRadio.init(radioSessId, url, saycastFactoryClassid, saycastFactoryCodebase, saycastFactoryCommonConfig, radioService, false, "", "");
}

