//  Keyring Installer object ver 0.34
//  * require: krins.cab(ver:1.0.0.20 and above) for using ActiveX

var KRInsObj = function() {
  this.check_activex_result = "";
}

KRInsObj.prototype = {
 
  /////////////////////////////////////////////////////////
  //  ActiveX event handler
  onDownload:function(url, path) {
  },
  onError:function(event) {
    _kractivex_.status = "Error";
    if(typeof(event) == "string") {
      _kractivex_.error_message = event;
    }
  },
  onCancel:function() {
    _kractivex_.status = "Cancel";
  },
  onSuccess:function() {
    _kractivex_.status = "Success";
  },

  /////////////////////////////////////////////////////////
  //  set/get ActiveX property
  //  *you have to call writeActiveX() before this function.
  setLicenseServer:function(server) {
    _kractivex_.server = server;
  },
  setAppName:function(name) {
    _kractivex_.appName = name;
  },
  setAppType:function(type) {
    //  *must be "Type". lower-case "type" is invalid.
    _kractivex_.Type = type;  //  tyep = 0 : KeyringPDF, type = 1 : KeyringLibrary
  },
  getStatus:function() {
    return _kractivex_.status;
  },
  getErrorMessage:function() {
    return _kractivex_.error_message;
  },
  getInstalledVer:function() {
    return _kractivex_.ver_local; //  set by checkAppVersion()
  },
  getLatestVer:function() {
    return _kractivex_.ver_server;  //  set by checkAppVersion()
  },

  /////////////////////////////////////////////////////////
  //  <obect> tag and <embed> tag.
  
  //  write <object> tag for ActiveX.
  //  element: tag-id for <object>.
  writeObjectTag:function(element, id, class_id, code_base, params) {
    //  create <object> string
    var object_tag = '<object id="' + id + '" width="0" height="0" classid="' + class_id + '" codebase="' + code_base + '">';
    for(var key in params) {
      object_tag += '<param name="' + key + '" value="' + params[key] + '" />';
    }
    object_tag += '</object>';
    //  write
    if(!element) {
      document.write(object_tag);
    } else {
      var target = (typeof element=="string")?document.getElementById(element):element;
      target.innerHTML = object_tag;
    }
  },

  //  write <embed> tag.
  //  element: tag-id for <embed>. if not specified, using document.write()
  writeEmbedTag:function(element, id) {
    var embed_tag = '<embed id="' + id + '" width="0" height="0" type="application/x-keyringclient">';
    if(!element) {
      document.write(embed_tag);
    } else {
      var target = (typeof element=="string")?document.getElementById(element):element;
      target.innerHTML = embed_tag;
    }
  },
  
  /////////////////////////////////////////////////////////
  //  ActiveX Install

  //  begin ActiveX installation.
  //  codebase: codebase for <object>.
  //  element: tag-id for <object>. if not specified, using document.write()
  //  handler: event handler.
  writeActiveX:function(codebase, element, handler) {
      params = new Object();
      this.writeObjectTag(element, "_kractivex_", "CLSID:92EB41C4-A271-42C5-999A-4816A3CFCB27", codebase, params);
      _kractivex_.attachEvent("onerror", (handler && handler.onError) ? handler.onError : this.onError);
      _kractivex_.attachEvent("ondownload", (handler && handler.onDownload) ? handler.onDownload : this.onDownload);
      _kractivex_.attachEvent("oncancel", (handler && handler.onCancel) ? handler.onCancel : this.onCancel);
      _kractivex_.attachEvent("onsuccess", (handler && handler.onSuccess) ? handler.onSuccess : this.onSuccess);
  },
      
  //  check update required.	
  //  1. get latest version and installed version.
  //  2. check not installed or old version installed.
  //  return true: not required. false: required.
  //  *you have to call writeActiveX(), setLicenseServer(), setAppName() before this function.
  checkAppVersion:function() {
    try {
      if(_kractivex_.checkVersion() == "OK") {return true;}
    }catch(e) {
    }
    this.checkActiveXStatus();
    return false;
  },
    
  //  install latest version.	
  //  *you have to call writeActiveX() before this function.
  installApp:function(arg) {
    _kractivex_.setup_arg = arg;
    try {
      _kractivex_.install();
    }catch(e) {
    }
    this.checkActiveXStatus();
  },
  
  //  check "_kractivex_.status" and throw Error.
  //  *you have to call writeActiveX() before this function.
  checkActiveXStatus:function() {
  	if(_kractivex_.status == "Error") {
  		throw new Error("[Error]: " + _kractivex_.error_message);
  	} else if(_kractivex_.status == "Cancel") {
  		throw new Error("[Cancel]");
  	}
  },
  
  //  check Adobe Reader or Adobe Acrobat installed. 
  checkAdobeAcrobat:function() {
    try {
      if(_kractivex_.checkReader() == "OK") {return true;}
    }catch(e) {
    }
    this.checkActiveXStatus();
    return false;
  },
  
  //  get installed Adobe Acrobat, Adobe Reader.
  //  *format: [sign][version][separator]
  //   [sign] = "a": AdobeAcrobat, "r": AdobeReader
  //   [version] = "5", "6", "7", "8", "9" 
  //   [separator] = ";"
  getAdobeAcrobat:function() {
    var ret;
    try {
      ret = _kractivex_.getReader();
    }catch(e) {
    }
    this.checkActiveXStatus();
    return ret;
  },

  /////////////////////////////////////////////////////////
  //  Check Browser Plugins

  //  check ActiveX installed.
  //  return true: installed. false: not installed.
  //  * false: set result status to this.check_activex_result.
  isActivexAvailable:function() {
    try{
        //  ActiveX is not installed.
        var plugin = new ActiveXObject("KRMInstaller.InstallerObject");
        if(!plugin) {this.check_activex_result = "Need Install"; return false;}
        //  check update of ActiveX needed. 
        //  if updete nedded, _kractivex_ is just a object.  
        if(_kractivex_.server == undefined) {this.check_activex_result = "Need Update"; return false;}
        //  check ok.
        return true;
      }catch(e){
      }
      return false;
  }, 
  
  //  check KeyringBrowser plugin installed.
  //  return true: installed. false: not installed.
  isKRBrowserPluginAvailable:function() {
    var plugin;
    if(this.getBrowser() == "IE") {
      //  for IE
			try{plugin = new ActiveXObject("KRKeyring.KeyringClient");} catch(e) {}
				if(plugin) {return true;}
			} else {
			//  for Firefox, Safari
      plugin = navigator.plugins["Keyring Plugin"];
      if(plugin) {return true;}
    }
    return false;
  },
  
  //  get KeyringBrowser plugin object.
  getKRBrowserPlugin:function(element) {
    var plugin;
    if(this.getBrowser() == "IE") {
      //  for IE
      try{plugin = new ActiveXObject("KRKeyring.KeyringClient");} catch(e) {}
		} else {
      //  for Firefox, Safari
			navigator.plugins.refresh(false); 
			if(navigator.plugins["Keyring Plugin"]) {
				plugin = document.getElementById("_npkrclient_");
				if(!plugin) {
					this.writeEmbedTag(element, "_npkrclient_");
					plugin = document.getElementById("_npkrclient_");
				}
			}
    }
    return plugin;
  },

  /////////////////////////////////////////////////////////
  //  Check KeyringClient application

	//	check Keyring Client supported.
	//	type	:	1 = KeyringPDF
	//				  2 = KeyringFLASH
	isKeyringClientSupported: function(client_type) {
		var os = this.getOS();
		var browser = this.getBrowser();
		//	KeyringPDF
		if(client_type == 1) {
			if(os == "Windows" && !this.isOldWindows()) {return true;}
		}
		//	KeyringFLASH
		else if(client_type == 2) {
			if(os == "Windows" && !this.isOldWindows()) {
				if(browser == "IE") {return true;}
				else if(browser == "Firefox") {return true;}
				//else if(browser == "Chrome") {return true;}
			}
			else if(os == "Mac") {
				if(browser == "Safari") {return true;}
				else if(browser == "Firefox") {return true;}
				//else if(browser == "Chrome") {return true;}
			}
		}
		return false;
	},
  
	//	get version of the KeyringFLASH client application for current browser
  getCurrentBrowserKeyringFlashClientVersion:function() {
		var ver;
    if(this.getBrowser() == "IE") {
      //  for IE
			try{
				var plugin = new ActiveXObject("KRKeyring.KeyringClient");
				if(plugin) {ver = plugin.getVersion("KeyringFlashDecryptorIE");}
			}catch(e){
			}
    } else {
      //  for Firefox, Safari
			navigator.plugins.refresh(false); 
      var plugin = navigator.plugins["KeyringFLASH Plugin"];
      if(plugin) {ver = plugin.description.replace(/([a-zA-Z]|\s)+/,"");}
    }
    return ver;
  },

	//	get version of the KeyringFLASH client application for specified browser
  getSpecifiedBrowserKeyringFlashClientVersion:function(element, browser) {
		var ver;
		if(browser == "IE") {
			var plugin = this.getKRBrowserPlugin(element);
			try{ver = plugin.getVersion("KeyringFlashDecryptorIE");} catch(e) {}
    }
		else {
			throw new Error("specified browser \"" + browser + "\" is not supported.");
		}
		return ver;
  },
	
  //  get version of the KeyringFLASH client application.
  //  [Windows]
  //    IE: need 1.6.0 and above. 
  //    Firefox: all version ok.
  //  [Mac] 
  //    Firefox, Safari: all version ok.  
  getKeyringFlashClientVersion:function(element, target_browser) {
		var ver;
		if(!target_browser) {
			ver = this.getCurrentBrowserKeyringFlashClientVersion();
		}
		else {
			ver = this.getSpecifiedBrowserKeyringFlashClientVersion(element, target_browser);
		}
    return ver;
  },
    
  //  get version of the KeyringPDF client application.
  //  element: tag-id for <embed>. if not specified, using document.write()
  //  [Windows]
  //     IE: need 4.8.0 and above.
  //     Firefox, Safari: need 4.9.0 and above.
  //  [Mac]
  //     not supported.
  getKeyringPdfClientVersion:function(element) {
    var ver;
    var plugin = this.getKRBrowserPlugin(element);
		try{ver = plugin.getVersion("KRMDecryptor");} catch(e) {}
    return ver;
  },
  
  //  get version of the KeyringLibrary client application.
  //  element: tag-id for <embed>. if not specified, using document.write()
  //  [Windows]
  //     IE: need KeyringPDF 4.8.0 and above.
  //     Firefox, Safari: need KeyringPDF 4.9.0 and above.
  //  [Mac]
  //     not supported.
  getKeyringLibraryVersion:function(element, custom_name) {
    var ver;
    var app_name = custom_name ? "KRMArchiver" + custom_name : "KRMArchiver";
    var plugin = this.getKRBrowserPlugin(element);
		try{ver = plugin.getVersion(app_name);} catch(e) {}
    return ver;
  },
  
  /////////////////////////////////////////////////////////
  //  Utility 
  
  //  get os 
  //  return "Windows", "Mac", "Other"
  getOS:function() {
    if(navigator.platform.indexOf('Win') != -1) {return "Windows";} 
    else if(navigator.platform.indexOf('Mac') != -1) {return "Mac";} 
    return "Other";
  },

  //  get browser
  //  return "IE", "Safari", "Firefox", "Chrome", "Other"
  getBrowser:function() {
    if(navigator.appName == "Microsoft Internet Explorer") {return "IE";} 
    else if(navigator.appName == "Netscape") {
      if(navigator.userAgent.indexOf("Chrome") != -1) {return "Chrome";} 
      else if(navigator.userAgent.indexOf("Safari") != -1) {return "Safari";} 
      else if(navigator.userAgent.indexOf("Firefox") != -1) {return "Firefox";}
    } 
    return "Other";
  },
  
  //  OS is Windows98, 98SE, Me
  isOldWindows:function() {
    if(navigator.platform.indexOf('Win') != -1 && navigator.userAgent.indexOf("Windows NT") == -1) {return true}
    return false;
  },
  
  //  check Adobe Acrobat or Adobe Reader installed.
  //  *cannot get version.
  isAdobeAcrobatIntalled:function() {
		if(this.getBrowser() == "IE") {
			try{
				var plugin = new ActiveXObject("AcroPDF.PDF");
				if(plugin) {return true;}
			}catch(e){
			}
		} else {
      var plugin = navigator.plugins["Adobe Acrobat"];
      if(!plugin) {plugin = navigator.plugins["Adobe Acrobat and Reader Plug-in"];} //  * Mac & Safari only
      if(plugin) {return true;}
    }
    return false;
  },
  
  //  get Flash Player version.
  //  *FlashPlayer 6 and adobe only.
  getFlashPlayerVersion:function() {
    var ver;
		if(this.getBrowser() == "IE") {
			try{
				var plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
				if(plugin) {ver = plugin.GetVariable("$version").split(" ")[1].replace(/,/g,".");}
			}catch(e){
			}
		} else {
      var plugin = navigator.plugins["Shockwave Flash"];
      if(plugin) {ver = plugin.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".");}
    }
    return ver;
  },  
  
  //  get CID
  //  [Windows]
  //     need KeyringPDF 4.10.4 and above.
  //     need KeyringFLASH for IE 1.8.0 and above.
  //     need KeyringFLASH for Firefox 1.2.0 and above.
  //  [Mac]
  //     not supported.
  getCID:function(element) {
    var cid = "";
		var plugin = this.getKRBrowserPlugin(element);
		try{cid = plugin.getCID();} catch(e) {}
    return cid;
  },
	  
  //  compare version number
  //  *format: "x.x.x.x" (max 4 elements)
  //  return: 
  //    ver1 > ver2 : 1
  //    ver1 == ver2 : 0
  //    ver1 < ver2 : -1
  compareVersion: function(ver1, ver2) {
    var array1 = ver1 ? ver1.split(".") : new Array(0);
    var array2 = ver2 ? ver2.split(".") : new Array(0);
    //  convert to Number
    for(i = 0; i < 4; i++) {
      if(!array1[i]) {array1[i] = 0;}
      if(!array2[i]) {array2[i] = 0;}
      array1[i] -= 0;
      array2[i] -= 0;
    }
    return compare(0);
    //  compare value of index i
    function compare(index) {
      if(array1[index] > array2[index]) {return 1;}
      else if(array1[index] == array2[index]) {return index >= 3 ? 0 : compare(index + 1);}
      else {return -1;}
    }
  }
}
	
//	check KeyringFLASH client installed and do process.
//	params: {object}
//    script:	      HTML which written with secceeded.
//    target:       element id of target contents.
//		installPHP:		installation page url.
//		installImg:		image url for 'you need install.'
//		errorImg:			image url for 'your environment is not supported.'
KRInsObj.KeyringInstallTag = function(){
  var params = {};
  var script = null;
  //  initialize parameter
  // ---------------------------------------
  if(arguments.length < 1) {return;}
  //  in case KeyringInstallTag(script, params)
  if(typeof arguments[0] == "string") {
    script = arguments[0];
    if(typeof arguments[1] == "object") {params = arguments[1];}
  }
  //  in case KeyringInstallTag(params)
  else if(typeof arguments[0] == "object") {
    params = arguments[0];
    script = params.script;
  }
  else {return;}
  // ---------------------------------------
	var krins=new KRInsObj();
	var os=krins.getOS(); 
	var br=krins.getBrowser();
	var target = params.target ? document.getElementById(params.target) : null; 
  var target_display; //  original css display value of target
	//	default param
	if(params.installImg == null){params.installImg = 'http://www.keyring.net/js/install.jpg';}
	if(params.installPHP == null){params.installPHP = 'http://www.keyring.net/scripts/install2/install.php';}
	if(params.errorImg == null){params.errorImg = 'http://www.keyring.net/js/error.jpg';}
  //  hide target
  if(target) {
    target_display = target.style.display; 
    target.style.display = "none";
  }
	//	check
	if(krins.isKeyringClientSupported(2)){
		if(krins.getKeyringFlashClientVersion()){
			// Success
      if(target) {target.style.display = target_display;}
			if(script) {document.write(script);}
		}else{
			// not install KeyringFLASH
			var redirect_url = params.installPHP + "?type=3&successUrl=" + location.href;
			if(br=="IE"){
				document.write('<input type="image" onClick="location.href(\'' + redirect_url + '\');" src="' + params.installImg + '" />');
			}else{
				document.write('<button type="button" onClick="location.href = \'' + redirect_url + '\';"><img src="' + params.installImg + '" /></button>');
			}
		}
	}else{
		document.write('<image src="' + params.errorImg + '"/>');
	}
}
