//
//                Copyright (c) 2004 Smartlink Corp.
//                       All rights reserved.
//

var dicService = null;

function DicService (url) {
   this.frame = window.frames ["service"];
   this.frameElement = document.getElementById ("service");
   this.form = document.forms ["form"];
   this.supportedOnLoad = !(browser.opera && browser.operaVer < 7.5 || browser.ie && browser.ieVer < 5.5);
   this.timerOnLoad = null;
   this.listener = null;
   this.sendQuery = serviceSendQuery;
   this.getDics = serviceGetDics;
   this.lookup = serviceLookup;
   this.isBusy = false;
   this.nextQuery = null;
   this.url = url;
   this.onResponse = serviceOnResponse;
   dicService = this;
}

function serviceGetDics (lang) {
   var query = { flags: "DICS", lang: lang };
   this.sendQuery (query);
}

function serviceLookup (flags, text, lang, dicID) {

   var query = { flags: flags, text: text, lang: lang, dicID: dicID };
   this.sendQuery (query);

}

function serviceSendQuery (query) {
   if (this.isBusy) {
      this.nextQuery = query;
      return;
   }
   this.isBusy = true;
   this.form.action = this.url + "/" + (query.flags == "DICS" ? "getDics" : "lookup");
   this.form.text.value  = (query.text  ? query.text  : "");
   this.form.lang.value  = (query.lang  ? query.lang  : "");
   this.form.flags.value = (query.flags ? query.flags : "");
   this.form.dicID.value = (query.dicID ? query.dicID : "");
   this.form.submit ();
   
   if (!this.supportedOnLoad) {
      this.frameElement.onload = null;
      this.timerOnLoad = setInterval ("serviceTestOnLoad()", 100);
   }
}

function serviceTestOnLoad () {
   if (dicService.frame.location.href != "about:blank") {
      if (dicService.timerOnLoad) {
         window.clearInterval (dicService.timerOnLoad);
         dicService.timerOnLoad = null;
      }
      window.setTimeout ("dicService.onResponse()", 100);
   }
}

function serviceOnLoad () {
   if (dicService)
      dicService.onResponse ();
}

function serviceOnResponse () {
   try { // possible Access Denied for this.frame.document
      if (!this.frame || !this.frame.document)
         return;
   }
   catch (err) {
      this.listener.onError ("<pre>" + htmlEncode (err.message) + "</pre>");
      this.isBusy = false;
      return;
   }

   var xml = this.frame.document.XMLDocument;
   if (!xml)
      xml = this.frame.document;

   if (xml.documentElement.tagName != "HTML")
      this.listener.onResult (xml);
   else
      this.listener.onError (xml.body.innerHTML);
   if (!this.supportedOnLoad)
      this.frame.location.href = "about:blank";

   this.isBusy = false;
   if (this.nextQuery) {
      var query = this.nextQuery; this.nextQuery = null;
      this.sendQuery (query);
   }
}
