function FlashXmlHttpRequest() {};

FlashXmlHttpRequest.prototype.init = function() {
	this.flashLoaded = false;
	this.documentLoaded = false;

	this.addLoadEvent(onload);
	function onload() 
	{
		xmlHttpRequest.documentLoaded = true;
		xmlHttpRequest.load();
	}
};

FlashXmlHttpRequest.prototype.isFlashInstalled = function() {
	var ret;

	if (typeof(this.isFlashInstalledMemo) != "undefined") { return this.isFlashInstalledMemo; }

	if (typeof(ActiveXObject) != "undefined") 
	{
		try {
			var ieObj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
		} catch (e) { }
		ret = (ieObj != null);
	} else {
		var plugin = navigator.mimeTypes["application/x-shockwave-flash"];
		ret = (plugin != null) && (plugin.enabledPlugin != null);
	}
	this.isFlashInstalledMemo = ret;
	return ret;
};

FlashXmlHttpRequest.prototype.getFlash = function() {
	return document.getElementById("storage");
};

FlashXmlHttpRequest.prototype.checkFlash = function() {
  try {
     return (this.getFlash().ping() == "pong");
  }
  catch (e) { return false; }
};

FlashXmlHttpRequest.prototype.writeFlash = function(swfName) { 
	document.write('<div id="divStorage" style="POSITION:absolute;top:-2000px;height:0px;">');
  if (window.ActiveXObject && !this.isFlashInstalled())
  {
    document.write('<object id="storage" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
    document.write(' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,5,0,0"');
    document.write(' height="' + this.height + '" width="' + this.width + '">');
    document.write(' <param name="movie" value="' + swfName + '">');
    document.write(' <param name="quality" value="high">');
    document.write(' <param name="swliveconnect" value="true">');
    document.write('<\/object>');
  }
  else
  {
    document.write('<object id="storage" data="' + swfName + '"');
    document.write(' type="application/x-shockwave-flash" height="' + this.height + '" width="' + this.width + '">');
    document.write('<param name="movie" value="' + swfName + '">');
    document.write('<param name="quality" value="high">');
    document.write('<param name="swliveconnect" value="true">');
    document.write('<param name="pluginurl" value="http://www.macromedia.com/go/getflashplayer">');
    document.write('<param name="pluginspage" value="http://www.macromedia.com/go/getflashplayer">');
    document.write('<p>You need Flash for this. Get the latest version from');
    document.write(' <a href="http://www.macromedia.com/software/flashplayer/">here<\/a>.');
    document.write('<\/p>');
    document.write('<\/object>'); 
  }
  document.write('</div>');
};


FlashXmlHttpRequest.prototype.addLoadEvent = function(func) {
	var oldonload = window.onload;

	if (typeof(window.onload) != 'function') 
	{
		window.onload = func;
	} 
	else 
	{
		window.onload = function() 
		{
			oldonload();
			func();
		}
	}
};

FlashXmlHttpRequest.prototype.load = function() {
  if (typeof(this.onload) != "function") { return; } 

  if (this.isFlashInstalled()) {
    var finishedLoading = this.flashLoaded && this.documentLoaded;
    if (!finishedLoading) { return; }
  }
  
  var fs = this.getFlash();
  if ((!this.isFlashInstalled() || this.flashLoaded) && fs) {
    if (this.checkFlash()) {
      callAppOnLoad(fs);
    } else {
			callAppOnLoad(null);
    }
  } else {
     callAppOnLoad(null);
  }
  
  function callAppOnLoad(fs) {
    if (this.onloadCalled) { return; }
    this.onloadCalled = true;
    this.onload(fs);
  }
};

function AuthenticationHandler(xmlnamespace, url)
{
	this._xmlnamespace = xmlnamespace;
	this._url = url;
};

AuthenticationHandler.prototype.send = function(soapAction, soapMessage) 
{
  var fs = xmlHttpRequest.getFlash();
  var _self = this;
  function callback(varName) {
    var response = fs.GetVariable(varName);
    _self.responseText = response;
    if (typeof(_self.responseLoad) == 'function') {
        _self.responseLoad();
    }
  }
  fs.XmlHttp(this._url, callbackManager.registerCallback(callback), soapMessage, this.createHeader(soapAction), "text/xml; charset=utf-8");
};


AuthenticationHandler.prototype.requestLogin = function(id, password, onValid, onLeave, onInvalidId, onInvaliedPassword, onBannedId, onError) 
{
	if(!this.isfunction(onValid, "onValid") 
		|| !this.isfunction(onLeave, "onLeave") 
		|| !this.isfunction(onInvalidId, "onInvalidId") 
		|| !this.isfunction(onInvaliedPassword, "onInvaliedPassword") 
		|| !this.isfunction(onBannedId, "onBannedId")
		|| !this.isfunction(onError, "onError") )
	{
		return;
	}
	this._onValid = onValid;
	this._onLeave = onLeave;
	this._onInvalidId = onInvalidId
	this._onInvaliedPassword = onInvaliedPassword;
	this._onBannedId = onBannedId;
	this._onError = onError;
	this._userId = id;
	var paramNames = ["userId", "password"];
	var paramValues = [id, password];
	
	var soapMessage = this.createSoap("SetLogin", paramNames, paramValues);
	this.responseLoad = this.responseLogin;
	this.send(this._xmlnamespace + "/SetLogin", soapMessage);
};
AuthenticationHandler.prototype.requestLogout = function(onComplete) 
{
	var soapMessage = this.createSoap("SetLogout");
	this.responseLoad = (onComplete == null) ? this.responseLogout : onComplete;
	this.send(this._xmlnamespace + "/SetLogout", soapMessage);
};

AuthenticationHandler.prototype.responseLogin = function() 
{
	var response = this.responseText;
	if (response == 'undefined') 
	{
		alert("Sign in service, an error has occurred.\nIn a few minutes, please try again.");
		this._onError.call(this, this._userId);
		return;
	}
	var res = this.createDocument(response);	
	
	switch (this.getNode(res, 'Flag')) 
	{
	  case "0":
				var status = parseInt(this.getNode(res, 'UserAgree'));
				var loginUser = this.getLoginUser(res, this._userId, status);
				if(loginUser != null)
				{
					this._onValid.call(this, loginUser);
					this.loginStatus(status);
				}
			break;
	  case "1":
				this._onLeave.call();
			break;
	  case "2":
				this._onInvalidId.call();
			break;
	  case "3":
				this._onInvaliedPassword.call(this, this._userId);
			break;
     case "15":
				this._onBannedId.call(this, this._userId);
			break;			
	  default :
				this._onError.call(this, this._userId);
			break;
	}		
};

AuthenticationHandler.prototype.responseLogout = function() 
{
	var response = this.responseText;
	if (response != 'undefined') 
	{
		location.href='http://www.redbana.com/Home/Home.aspx'
	}
};

AuthenticationHandler.prototype.getLoginUser = function(res, userId, status) 
{
	alert("please override getLoginUser function");
	return null;
};

AuthenticationHandler.prototype.loginChangeUrl = function(status) 
{
	return (status == 0 || status == -1 || status == 1) ? false : true;
};

AuthenticationHandler.prototype.loginStatus = function(status) 
{
	alert("please override loginStatus function");
	return null;
};

AuthenticationHandler.prototype.createHeader = function(soapAction) 
{
	var headers = new Array();
	headers.push("Cache-Control");
	headers.push("public, no-cache, max-age=0");
	headers.push("Pragma");
	headers.push("public, no-cache");
	headers.push("expires");
	headers.push("0");
	headers.push("SOAPAction");
	headers.push(soapAction);
	return headers;
};
AuthenticationHandler.prototype.createSoap = function(methodName, names, values) 
{
	var strEnvelope = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + 
	"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
	"<soap:Body><" + methodName + " xmlns=\"" + this._xmlnamespace + "\">";
	
	if (names !=null && values !=null) 
	{
		for (i = 0; i < names.length; i++)
		{
			strEnvelope += "<" + names[i] + ">" + values[i] + "</" + names[i] + ">";
		}
	}

	return strEnvelope + "</" + methodName + "></soap:Body></soap:Envelope>";
};
AuthenticationHandler.prototype.createDocument = function(message) {
   var xmlDocument;
   var xmlParser;
   if(window.ActiveXObject) {
	  xmlDocument = new ActiveXObject('Microsoft.XMLDOM');
	  xmlDocument.async = false;
	  xmlDocument.loadXML(message);
   } else if (window.XMLHttpRequest) {
	  xmlParser = new DOMParser();
	  xmlDocument = xmlParser.parseFromString(message, 'text/xml');
   } else {
	  return null;
   }
   return xmlDocument;	
};

AuthenticationHandler.prototype.getNode = function(xml, node) {
	return (xml.getElementsByTagName(node)[0].firstChild ==null) ? "" : xml.getElementsByTagName(node)[0].firstChild.nodeValue;
}
AuthenticationHandler.prototype.isfunction = function(functionObj, parameterName) 
{
	if(functionObj ==null || typeof(functionObj) != 'function')
	{
		alert(parameterName + " - Please specify the script function");
		return false;
	}
	else
		return true;
};

var callbackManager = new Object();
callbackManager.callbacks = new Array();
callbackManager.registerCallback = function(callback) {
    var length = this.callbacks.push(selfDeleteCallback);
    var callbackID = length - 1;
    
    return "callbackManager.callbacks[" + callbackID + "]";
    
    function selfDeleteCallback(obj) {
        delete callbackManager.callbacks[callbackID];
        setTimeout(function() { callback(obj); }, 0);
        return;
    } 
};


var xmlHttpRequest = new FlashXmlHttpRequest();
xmlHttpRequest.init();
xmlHttpRequest.writeFlash("/HanbitSoftXHR.swf");

function storageOnLoad() { 
  xmlHttpRequest.flashLoaded = true;
  xmlHttpRequest.load();
};

function storageOnError() {
  alert("storageOnError"); 
  xmlHttpRequest.flashLoaded = true;
  xmlHttpRequest.load();
};

