var EWD = {} ;
EWD.page = {
   errorMessage: function(message) {
      if (message != '') alert(message) ;
   },
   goNextPage: function(page,token,sessionToken) {
      if (page == "*") return ;
      var x ;
      eval(x) ;
   },
   showConfirmMessage: false,
   displayConfirm: function(confirmText) {
      if (!EWD.page.showConfirmMessage) return true ;
      confirmText= EWD.utils.replace(confirmText,"&#39;","'") ;
      var ok = confirm(confirmText) ;
      EWD.page.showConfirmMessage = false ;
      return ok ; 
   },
   openWindow: function(url,winHandle,winName,x,y,height,width,toolbar,location,directories,status,menubar,scrollbars,resizable) {
      var noOfParams = EWD.page.openWindow.arguments.length ;
      if (noOfParams > 14) {
         for (nParam = 14; nParam < noOfParams; nParam++) {
            url = url.replace(/\[x]/, EWD.page.openWindow.arguments[nParam]) ;
         }
      }
      var winRef = winHandle;
      var arrIndex = winHandle.indexOf("[");
      if(arrIndex != -1) {
         winRef = winHandle.substring(0,arrIndex) ;
         winHandle = winRef + "[" + winRef + ".length]" ;
      }
      if (winName == "") winName = winRef + Math.floor(Math.random()*100) ;
      var openWin = winHandle + '=window.open("' + url + '","' + winName + '","' ; 
      if (navigator.appName == 'Netscape') { 
         openWin = openWin + 'ScreenX=' + x + ',ScreenY=' + y + ',' ;
      }
      else {
         openWin = openWin + 'left=' + x + ',top=' + y + ',' ;
      }
      openWin = openWin + 'height=' + height + ',width=' + width + ',toolbar=' + toolbar + ',location=' + location + ',directories=' + directories + ',' ;
      openWin = openWin + 'status=' + status + ',menubar=' + menubar + ',scrollbars=' + scrollbars + ',resizable=' + resizable + '")' ;
      eval(openWin) ; 
   },
   spinnerKeyDown: false,
   incrementSpinner:  function(fieldId,max,interval) {
      var field = document.getElementById(fieldId) ;
      field.focus() ;
      if (EWD.page.spinnerKeyDown) {
         if (field.value < max) {
            field.value++ ;
         }
         setTimeout("EWD.page.incrementSpinner('" + fieldId + "'," + max + "," + interval +")",interval) ;
      }
   },
   decrementSpinner:  function(fieldId,min,interval) {
      var field = document.getElementById(fieldId) ;
      field.focus() ;
      if (EWD.page.spinnerKeyDown) {
         if (field.value > min) {
            field.value-- ;
         }
         setTimeout("EWD.page.decrementSpinner('" + fieldId + "'," + min + "," + interval +")",interval) ;
      }
   },
   spinnerControl:  function(e,fieldId,min,max) {
      var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
      if (keyCode == 38) {
         if (document.getElementById(fieldId).value < max) {
            document.getElementById(fieldId).value++ ;
         }
      }
      if (keyCode == 40) {
         if (document.getElementById(fieldId).value > min) {
            document.getElementById(fieldId).value-- ;
         }
      }
   },                                  
   spinnerValueCheck:  function(value,fieldName,min,max) {
      if (!EWD.utils.isInteger(value)) {
         alert("Value of " + fieldName+ " is invalid!") ;
         return ;
      }
      if (value < min) {
         alert("Value of " + fieldName+ " is less than the minimuml!") ;
         return ;
      }
      if (value > max) {
         alert("Value of " + fieldName+ " is larger than the maximum!") ;
         return ;
      }
   },
   addStylesheet: function(doc,src) {
      if(doc.createStyleSheet) {
         doc.createStyleSheet(src);
      }
      else {
         var linkNode=doc.createElement('link');
         linkNode.setAttribute("href",src) ;
         linkNode.setAttribute("media","screen") ;
         linkNode.setAttribute("rel","stylesheet") ;
         linkNode.setAttribute("type","text/css") ;
         doc.getElementsByTagName("head")[0].appendChild(linkNode);
      }
   },
   printDiv: function(divId,height,width,top,left,title,styleSrc,autoprint) {
      if (!height) height= "500" ;
      if (!width) width= "500" ;
      if (!top) top= "50" ;
      if (!left) left= "100" ;
      var domNode = document.getElementById(divId) ;
      var params="height=" + height + ",width=" + width ;
      if (navigator.appName == 'Netscape') { 
        params = params + ',ScreenX=' + left + ',ScreenY=' + top ;
      }
      else {
        params = params + ',left=' + left + ',top=' + top + ',' ;
      }
      var outputWindow=window.open("","",params);
      outputWindow.document.open("text/html", "replace");
      if (!title) title = "Print" ;
      outputWindow.document.write("<html><head><title>" + title + "</title>\n");
      outputWindow.document.write("</head><body>\n");
      if (!autoprint) outputWindow.document.write("<div id='printButton'><input type='button' value='Print' onClick='document.getElementById(\"printButton\").innerHTML = \"\" ; window.print()' /><hr/></div>\n");
      outputWindow.document.write("<div id='add'></div>\n");
      outputWindow.document.write("</body></html>\n");
      outputWindow.document.close();
      if (styleSrc) EWD.page.addStylesheet(outputWindow.document,styleSrc) ;
      var importedMarkup = domNode.innerHTML ;
      outputWindow.document.getElementById('add').innerHTML = importedMarkup ;
      if (autoprint) {
        outputWindow.print() ;
        outputWindow.close() ;
      }
   }
} ;
EWD.utils = {
   replace: function (string,text,by) {
      var strLength = string.length, txtLength = text.length;
      if ((strLength == 0) || (txtLength == 0)) return string;
      var i = string.indexOf(text);
      if ((!i) && (text != string.substring(0,txtLength))) return string;
      if (i == -1) return string;
      var newstr = string.substring(0,i) + by;
      if (i+txtLength < strLength) newstr = replace(string.substring(i+txtLength,strLength),text,by);
      return newstr;
   },
   findPosX: function (obj) {
      var curleft = 0;
      if(obj.offsetParent) while(1) {
         curleft += obj.offsetLeft;
         if(!obj.offsetParent) break;
         obj = obj.offsetParent;
      }
      else if(obj.x) curleft += obj.x;
      return curleft;
   },
   findPosY: function (obj) {
      var curtop = 0;
      if(obj.offsetParent) while(1) {
         curtop += obj.offsetTop;
         if(!obj.offsetParent) break;
         obj = obj.offsetParent;
      }
      else if(obj.y) curtop += obj.y;
      return curtop;
   },
   getPiece: function(refStr,delim,pieceNo) {
      var tempArray;
      if (refStr == "") return "";
      if (delim == "") return string;
      if (pieceNo == "") return string;
      tempArray = refStr.split(delim);
      return tempArray[pieceNo - 1];
   },
   contains: function(inString,subString) {
      if (inString.indexOf(subString) == -1) return false;
      return true;
   },
   getBrowserInfo: function() {
      var sig = navigator.userAgent ;
      EWD.browserType="firefox" ;
      if (EWD.utils.contains(sig,"MSIE 6")) EWD.browserType="ie6" ;
            if (EWD.utils.contains(sig,"MSIE 7")) EWD.browserType="ie7" ;
            EWD.browserOS="linux" ;
            if (EWD.utils.contains(sig,"Windows NT 5.1")) EWD.browserOS="xp" ;
            if (EWD.utils.contains(sig,"Windows NT 5.0")) EWD.browserOS="2000" ;
            if (EWD.utils.contains(sig,"Windows NT 6")) EWD.browserOS="vista" ;
   },
   isInteger: function(sText) {
      var validChars = "0123456789";
      if (sText.substring(0,1) == '-') sText = sText.substring(1) ;
      var isInt = true;
      var charx;
      for (var i = 0; i < sText.length && isInt == true; i++) {
         charx = sText.charAt(i);
         if (validChars.indexOf(charx) == -1) {
            isInt = false;
         }
      }
      return isInt;
   },
   getOption: function(fieldName) {
     var obj = document.getElementById(fieldName) ;
     return obj.options[obj.selectedIndex].value;
   }
};
EWD.utils.getBrowserInfo() ;
    
EWD.ajax = {
   makeRequest: function (url,id,method,payload,traceFlag) {
      var noOfParams = EWD.ajax.makeRequest.arguments.length ;
      var noOfFixedParams = 5 ;
      if (noOfParams > noOfFixedParams) {
         for (var nParam = noOfFixedParams; nParam < noOfParams; nParam++) {
            url = url.replace(/\[x]/, escape(EWD.ajax.makeRequest.arguments[nParam])) ;
         }
      }
      //force unique URL to prevent IE using Cached URL
      var rn = (Math.round(Math.random()*999999999)+1) ;
      if (url.indexOf('?') == -1) {
          url = url + "?" ;
      }
      else {
          url = url + "&" ;
      }
      url = url + "ewdrn=" + rn ;
      if (EWD.ajax.base) {
         url = EWD.ajax.base + url ;
      }
      var http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            //http_request.overrideMimeType('text/xml');
         }
      } 
      else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } 
         catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {}
         }
      }
      if (!http_request) {
         alert('Ajax error : Your browser may not support the XMLHTTP Request Object needed to support Ajax');
         setTimeout("document.body.style.cursor = 'default'",1);
         return false;
      }
      while (url.indexOf('&amp;') != -1) {
         url = url.replace("&amp;","&") ;
      }
      if (method == "synch") {
         http_request.open('GET', url, false);
         http_request.send(null);
         EWD.ajax.replaceContent(http_request,id,traceFlag);
      }
      else {
         http_request.onreadystatechange = function() { EWD.ajax.replaceContent(http_request,id,traceFlag); };
         if (method != "post") {
            http_request.open('GET', url, true);
            http_request.send(null);
         }
         else {
            http_request.open('POST', url, true);
            http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            http_request.send(payload);
         }
         setTimeout("document.body.style.cursor = 'default'",1);
      }
   },
   replaceContent: function (http_request,id,traceFlag) {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            var text = http_request.responseText ;
            if (traceFlag == 'window') {
               document.getElementById("traceContent").value = text ;
               document.getElementById("traceWindow").style.display = "block" ;
            }
            if (text.indexOf('<b>CSP Error') != -1) {
               var i = text.indexOf('<ul>');   
               text = text.substring(i+4) ;
               i = text.indexOf("</ul>");
               text = text.substring(0,i)
               text = "CSP runtime error : " + text ;
               alert(text) ;
            }
            if (text.indexOf('id="ewdEBResponse">') != -1) {
               var i = text.indexOf('id="ewdEBResponse">');
               text = text.substring(i+19) ;
               i = text.indexOf("</div>");
               text = text.substring(0,i)
               eval(text) ; 
            }
            else if (text.indexOf('<title>eXtc Web Developer : A run-time error has occurred') != -1) {
               var i = text.indexOf('<h3>eXtc Web Developer Error');   
               text = text.substring(i+28) ;
               i = text.indexOf("</h3>");
               text = text.substring(0,i)
               text = "EWD runtime error : " + text ;
               alert(text) ;
            }
            else if (text.indexOf('The Server reported the following error:') != -1) {
               var i = text.indexOf('</FONT></B><P>');   
               text = text.substring(i+14) ;
               text = "EWD runtime error : " + text ;
               alert(text) ;
            }
            else {
               var i = text.indexOf('id="ewdajaxonload">');
               if (i != -1) {
                  text = text.substring(i+19) ;
                  i = text.indexOf("</span>");
                  text = text.substring(0,i)
               }
               else {
                  text = '' ;
               }
               if ((text != '')&&(text.indexOf("var ewdtext = ''") == -1)) {
                  eval(text) ;         
               }              
		         else {
                  document.getElementById(id).innerHTML = http_request.responseText;
                  var jsID = "ewdButtonJS" ;
                  var newJSPointer = document.getElementById(jsID) ;
                  EWD.ajax.activateJS(newJSPointer) ;
                  var newJSPointer = document.getElementById('ewdscript') ;
                  setTimeout("document.body.style.cursor = 'default'",1) ;
                  if (traceFlag == 'alert') {
                     alert(http_request.responseText) ;
                  }
                  var jsText = "" ;
                  if (document.getElementById("ewdajaxonload")) {
                     onloadPointer = document.getElementById("ewdajaxonload") ;
                     jsText = onloadPointer.firstChild.data ;
                     var par = onloadPointer.parentNode ;
                     par.removeChild(onloadPointer) ;
                  }
                  EWD.ajax.activateJS(newJSPointer) ;
                  eval(jsText) ;
               }
            }
         } 
         else {
            alert('There was a problem with the Ajax request.');
         }
      }
   },
   activateAjaxError: function (errorText) {
      if (errorText != "") {
         var errorPointer = document.getElementById('ajaxErrorText') ;
         errorPointer.firstChild.data = errorText ;
         var alertPointer = document.getElementById("ajaxAlert") ;
         if (alertPointer != null) {
            var par = alertPointer.parentNode ;
            par.removeChild(alertPointer) ;
         }
         var head = document.getElementsByTagName("head").item(0) ;
         alertPointer = document.createElement("script") ;
         alertPointer.id = "ajaxAlert" ;
         alertPointer.type = "text/javascript" ;
         head.appendChild(alertPointer) ;
         alertPointer.text = "EWD.ajax.errorOn() ;" ;
      }  
   },
   activateJS: function (newJSPointer) {
      if (newJSPointer != null) {
         var newJSCode = "" ;
         if (newJSPointer != null) newJSCode = newJSPointer.firstChild.data ;
         if (newJSCode != "") {
            var node = newJSPointer.firstChild ;
            var jsText = "" ;
            while (node) {
               jsText = jsText + node.data
               node = node.nextSibling ;
            }
            var par = newJSPointer.parentNode ;
            par.removeChild(newJSPointer) ;
            if (window.execScript) {
               window.execScript(jsText) ;
            }
            else {
               window.eval(jsText) ;
            }
         }
      }
   },
   errorOn: function () {
      document.getElementById('ewdAjaxError').className='ewdDispOn' ;
   },
   errorOff: function () {
      document.getElementById('ewdAjaxError').className='ewdDispOff' 
   },
   allowSubmit: true,
   confirmSubmit: function (confirmText) {
      if (confirmText == "") confirmText = "Click OK if OK to continue" ;
      EWD.ajax.allowSubmit=EWD.page.displayConfirm(confirmText) ;
   },
   getFragment: function(url,targetId,synch) {
      var method = "synch" ;
      if (!synch) method = "GET"
      EWD.ajax.makeRequest(url,targetId,method) ;
   },
   submit: function (buttonName,formPointer,nextPage,url,id,traceFlag) {
      if (EWD.ajax.allowSubmit != false) {
         var nFields = formPointer.elements.length ;
         var payload = "ewdAjaxSubmit=1&ewd_action=" + buttonName + "&ewd_pressed=" + buttonName + "&ewd_nextPage=" + nextPage ;
         //var payload = "ewdAjaxSubmit=1&ewd_nextPage=" + nextPage ;
         for (var nField = 0; nField < nFields; nField++) {
            var fieldPointer = formPointer.elements[nField] ;
            var name = fieldPointer.name ;
            var type = fieldPointer.type ;
            if ((type == "text")||(type == "password")) {
               payload = payload + "&" + name + "=" + escape(fieldPointer.value) ;
            }
            if (type == "hidden") {
               if (EWD.utils.getPiece(name,"_",1) != "ewd") {
                  payload = payload + "&" + name + "=" + escape(fieldPointer.value) ;
               }
            }
            if (type == "select-one") {
               payload = payload + "&" + name + "=" + escape(fieldPointer.value) ;
            }
            if (type == "textarea") {
               payload = payload + "&" + name + "=" + escape(fieldPointer.value) ;
            }
            if (type == "radio") {
               if (fieldPointer.checked) {
                  payload = payload + "&" + name + "=" + escape(fieldPointer.value) ;
               }
            }
            if (type == "checkbox") {
               if (fieldPointer.length == undefined) {
                  if (fieldPointer.checked) {
                     payload = payload + "&" + name + "=" + escape(fieldPointer.value) ;
                  }                
               } 
               else {
                  for (var i = 0 ; i < fieldPointer.length ; i++) {
                     if (fieldPointer[i].checked) {
                        payload = payload + "&" + name + "=" + escape(fieldPointer[i].value) ;
                     }
                  }
               }
            }
         }
         EWD.ajax.makeRequest(url,id,"post",payload,traceFlag) ;
      }
      EWD.ajax.allowSubmit = true ;
   }
} ;

if (!Object.prototype.toJSONString) {
    Array.prototype.toJSONString = function () {
        var a = ['['],
            b,
            i,
            l = this.length,
            v; 
        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }
        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;
            default:
                p(v.toJSONString());
            }
        }
     a.push(']');
        return a.join('');
    };
    Boolean.prototype.toJSONString = function () {
        return String(this);
    };
    Date.prototype.toJSONString = function () {
        function f(n) {
            return n < 10 ? '0' + n : n;
        }
        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };
    Number.prototype.toJSONString = function () {
        return isFinite(this) ? String(this) : "null";
    };
    Object.prototype.toJSONString = function () {
        var a = ['{'],
            b,
            k,
            v;
        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(k.toJSONString(), ':', s);
            b = true;
        }
        for (k in this) {
            if (this.hasOwnProperty(k)) {
                v = this[k];
                switch (typeof v) {
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;
                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;
                default:
                    p(v.toJSONString());
                }
            }
        }
        a.push('}');
        return a.join('');
    };
    (function (s) {
        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };
        s.parseJSON = function (filter) {
            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this)) {
                    var j = eval('(' + this + ')');
                    if (typeof filter === 'function') {
                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) {
                                        v[i] = walk(i, v[i]);
                                    }
                                }
                            }
                            return filter(k, v);
                        }
                        j = walk('', j);
                    }
                    return j;
                }
            } catch (e) {
            }
            throw new SyntaxError("parseJSON");
        };
        s.toJSONString = function () {
            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
} ;
