dom = (document.getElementById) ? true : false;
nn4 = (document.layers) ? true : false;
ie = (document.all) ? true : false;
ie4 = (!dom && ie)?  true : false;
ie5 = document.all && document.getElementById;
ns6 = document.getElementById && !document.all;

function WriteLayer(Layer, Code, Doc)
{
  if(!Doc)
    Doc = 'document';
  if(nn4)
  {
    layer.document.open();
    layer.document.write(Code);
    layer.document.close();
  }
  else if(ie4)
    Layer.innerHTML = Code;
  else if(dom)
    Layer.innerHTML = Code;
}

function FindObject(ID, Doc)
{
  var i;
  if(!Doc)
    Doc = document;
  if(dom)
    return Doc.getElementById(ID);
  else if(ie4)
    return Doc.all[ID];
  for(i = 0; i<Doc.forms.length; i++)
    for(j = 0; j<Doc.forms[i].elements.length; j++)
      if(Doc.forms[i].elements[j].name==ID || Doc.forms[i].elements[j].id==ID)
        return Doc.forms[i].elements[j];
  for(i = 0; i<Doc.images.length; i++)
    if(Doc.images[i].name==ID || Doc.images[i].id==ID)
      return Doc.images[i];
  if(!Doc.layers)
    return null;
  for(i = 0; i<Doc.layers.length; i++)
  {
    if(doc.layers[i].name==ID || doc.layers[i].id==ID)
      return Doc.layers[i];
    var x = FindObject(ID, Doc.layers[i].document);
    if(x)
      return x;
  }
  return null;
}

function GetWindowWidth()
{
  return ns6 ? window.innerWidth-20 : document.body.clientWidth;
}

function GetWindowHeight()
{
  return ns6 ? window.innerHeight-20 : document.body.clientHeight;
}

function GetRadioValue(RadioButton)
{
  for(var i = 0; i < RadioButton.length; i++)
    if(RadioButton[i].checked)
      return RadioButton[i].value;
}

function SetRadioValue(RadioButton, Value)
{
  for(var i = 0; i < RadioButton.length; i++)
    if(RadioButton[i].value == Value)
    {
      RadioButton[i].checked = true;
      break;
    }
  return false;
}

function GetPosX(Control)
{
  var Result = Control.offsetLeft;
  while(Control.offsetParent != null)
  {
    Control = Control.offsetParent;
    Result += Control.offsetLeft;
  }
  return Result;
}

function GetPosY(Control)
{
  var Result = Control.offsetTop;
  while(Control.offsetParent != null)
  {
    Control = Control.offsetParent;
    Result += Control.offsetTop;
  }
  return Result;
}

function anchorPtrByName(anchorName)
{
  for (var i = 0; i < document.anchors.length; i++)
    if (document.anchors[i].name == anchorName)
      return document.anchors[i];
}

function FloatString(f, Digits)
{
  var s = new String(f);
  if(s=='NaN')
    return '0';
  var p = s.indexOf('.');
  if(p==-1)
    p = s.indexOf(',');
  var i;
  if(p==-1)
    i = s.length;
  else
    i = p;
  i -= 3;
  while(i>0)
  {
    s = s.substr(0, i)+','+s.substr(i);
    i -= 3;
    if(p>-1)
      p++;
  }
  if(Digits>0)
  {
    if(p==-1)
    {
      s = s+'.';
      p = s.length-1;
    }
    else
      s = s.substr(0, p+Digits+1);
    var ZerosToAdd = Digits-(s.length-p-1);
    for(i = 0; i<ZerosToAdd; i++)
      s = s+'0';
  }
  return s;
}

function SelectTextboxRange(Textbox, Start, Finish)
{
  if(Textbox.createTextRange)
  {
    var Range = Textbox.createTextRange();
    Range.moveStart("character", Start);
    Range.moveEnd("character", Finish-Textbox.value.length);
    Range.select();
  }
  else if (Textbox.setSelectionRange)
    Textbox.setSelectionRange(Start, Finish);
}

function CheckField(FieldName, FieldDesc)
{
  if(!ValidateField(FieldName))
  {
    alert('Please enter a value for the ' + FieldDesc + ' field.');
    return false;
  }
  return true;
}

function ValidateField(FieldName)
{
  var obj;
  obj = FindObject(FieldName);
  if(obj)
  {
    if(obj.value=='' || obj.value==0)
    {
      obj.focus();
      return false;
    }
  }
  else
  {
    alert('Field ' + FieldName + ' not found.');
    return false;
  }
  return true;
}

function ValidateEmail(FieldName)
{
  var obj;
  obj = FindObject(FieldName);
  if(!obj)
    return;

  if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(obj.value))
    return true;
  return false;
}

function isDigit(num)
{
  if(num.length>1)
    return false;
  var string = "1234567890";
  if(string.indexOf(num)!=-1)
   return true;
  return false;
}

function isLetter(str)
{
  if(str.length>1)   return false;
  var reg=/[a-zA-Z]/
  var result=reg.test(str);

  return result;
}

function isSpace(str)
{
  if(str.length>1)   return false;
  var reg=/\W/
  var result=reg.test(str);

  return result;
}

function ValidateCanadianPhone(FieldName)
{
  var obj;
  obj = FindObject(FieldName);
  if(!obj)
    return false;

  var Phone = obj.value;
  if(Phone.length>15)
    return false;

  var s = '';
  for(i = 0; i<Phone.length; i++)
    if(isDigit(Phone.substr(i, 1)))
      s += Phone.substr(i, 1)

  if(s.length<10)
    return false;
  if(s.length>15)
    return false;
  if(s.substr(0, 1)=='0')
    return false;

  return true;
}

function ValidatePostalCode(FieldName)
{
  var obj;

  obj = FindObject(FieldName);
  if(!obj)
    return false;

  if(obj.value.length==6 || obj.value.length==7)
    return ValidateCanadianPostalCode(FieldName);
//  else if(obj.value.length==5)
//    return ValidateUSAPostalCode(FieldName);

  return false;
}

function ValidateUSAPostalCode(FieldName){
  var obj;
  obj = FindObject(FieldName);
  if(!obj) return false;

  for(var i=0;i<obj.value.length;i++){
    if(!isDigit(obj.value.substr(i, 1)))
      return false;
  }
  return true;
}

function ValidateCanadianPostalCode(FieldName){
  var obj;
  obj = FindObject(FieldName);
  if(!obj) return false;

  var nextDigit = false;
  var countDigits = 0;
  var countLetters = 0;
  var newPostalCode = '';
  for(var i=0;i<obj.value.length;i++){
    if(!nextDigit && isLetter(obj.value.substr(i, 1))){
        nextDigit = true;
        countLetters++;
        newPostalCode += obj.value.substr(i, 1);
    }
    else if(nextDigit && isDigit(obj.value.substr(i, 1))){
        nextDigit = false;
        countDigits++;
        newPostalCode += obj.value.substr(i, 1);
    } else if(!isSpace(obj.value.substr(i, 1))){
        return false;
    }
  }
  if((countDigits != 3) || (countLetters != 3)){
      return false;
  }
//  else {
//      obj.value = newPostalCode.toUpperCase();
//  }

  return true;
}

function isAmount(s)
{
  var d = 1.0*s;
  return (d>0) && (d*100==Math.round(d*100));
}

function isInteger(s)
{
  for (var i = 0; i<s.length; i++)
    if (!isDigit(s.charAt(i)))
      return false;
  return true;
}

/////////////////////////////////////////////
// Declaring valid date character, minimum year and maximum year
var dtCh= ".";
var minYear=1900;
var maxYear=2100;

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
        if (i==2) {this[i] = 29}
   }
   return this
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isDate(dtStr){
    var daysInMonth = DaysArray(12)
    if(!dtStr)
      return false;
    var pos1=dtStr.indexOf('.')
    var pos2=dtStr.indexOf('.',pos1+1)
    var strDay=dtStr.substring(0,pos1)
    var strMonth=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
        if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
//        alert("Please specify the date in the following format: dd.mm.yyyy")
        return false
    }
    if (strMonth.length<1 || month<1 || month>12){
//       alert("Please enter a valid month")
        return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
//        alert("Please enter a valid day")
        return false
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
//        alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
        return false
    }
    if (dtStr.indexOf('.', pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, '.'))==false){
//        alert("Please enter a valid date")
        return false
    }
return true
}
/////////////////////////////////////////////

var SpecialSymbols = '!@#$%^&*()[]{}<>/\?~`_=+:"';

function StringContainsSpecialSymbols(s)
{
  for(var i = 0; i<s.length; i++)
    if(SpecialSymbols.indexOf(s.charAt(i))>-1)
      return true;
  return false;
}

function urlencode(str)
{
  return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

/*
HTMLEncode - Encode HTML special characters.
Copyright (c) 2006 Thomas Peri, http://www.tumuski.com/

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The Software shall be used for Good, not Evil.

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/**
 * HTML-Encode the supplied input
 *
 * Parameters:
 *
 * (String)  source    The text to be encoded.
 *
 * (boolean) display   The output is intended for display.
 *
 *                     If true:
 *                     * Tabs will be expanded to the number of spaces
 *                       indicated by the 'tabs' argument.
 *                     * Line breaks will be converted to <br />.
 *
 *                     If false:
 *                     * Tabs and linebreaks get turned into &#____;
 *                       entities just like all other control characters.
 *
 * (integer) tabs      The number of spaces to expand tabs to.  (Ignored
 *                     when the 'display' parameter evaluates to false.)
 *
 * v 0.3 - January 4, 2006
 */
function htmlEncode(source, display, tabs)
{
        function special(source)
        {
                var result = '';
                for (var i = 0; i < source.length; i++)
                {
                        var c = source.charAt(i);
                        if (c < ' ' || c > '~')
                        {
                                c = '&#' + c.charCodeAt() + ';';
                        }
                        result += c;
                }
                return result;
        }

        function format(source)
        {
                // Use only integer part of tabs, and default to 4
                tabs = (tabs >= 0) ? Math.floor(tabs) : 4;

                // split along line breaks
                var lines = source.split(/\r\n|\r|\n/);

                // expand tabs
                for (var i = 0; i < lines.length; i++)
                {
                        var line = lines[i];
                        var newLine = '';
                        for (var p = 0; p < line.length; p++)
                        {
                                var c = line.charAt(p);
                                if (c === '\t')
                                {
                                        var spaces = tabs - (newLine.length % tabs);
                                        for (var s = 0; s < spaces; s++)
                                        {
                                                newLine += ' ';
                                        }
                                }
                                else
                                {
                                        newLine += c;
                                }
                        }
                        // If a line starts or ends with a space, it evaporates in html
                        // unless it's an nbsp.
                        newLine = newLine.replace(/(^ )|( $)/g, '&nbsp;');
                        lines[i] = newLine;
                }

                // re-join lines
                var result = lines.join('<br />');

                // break up contiguous blocks of spaces with non-breaking spaces
                result = result.replace(/  /g, ' &nbsp;');

                // tada!
                return result;
        }

        var result = source;

        // ampersands (&)
        result = result.replace(/\&/g,'&amp;');

        // less-thans (<)
        result = result.replace(/\</g,'&lt;');

        // greater-thans (>)
        result = result.replace(/\>/g,'&gt;');

        if (display)
        {
                // format for display
                result = format(result);
        }
        else
        {
                // Replace quotes if it isn't for display,
                // since it's probably going in an html attribute.
                result = result.replace(new RegExp('"','g'), '&quot;');
        }

        // special characters
        result = special(result);

        // tada!
        return result;
}

function ValidateIntegerField(FieldID, FieldDisplayLabel, DontShowError)
{
  var Input;
  Input = $('#'+FieldID);
  var FieldValue;
  if(!FieldDisplayLabel)
    FieldDisplayLabel = FieldID;
  FieldValue = Input.val();
  if(FieldValue=='')
  {
    if(!DontShowError)
    {
      alert('Please specify a value for '+FieldDisplayLabel+'.');
      Input.focus();
    }
    return false;
  }
  var IntegerValue = Math.round(FieldValue);
  if(IntegerValue!=1.0*FieldValue)
  {
    if(!DontShowError)
    {
      alert('Please specify a valid integer value for '+FieldDisplayLabel+'.');
      Input.focus();
    }
    return false;
  }
  return true;
}

function ValidateMoneyField(FieldID, FieldDisplayLabel, DontShowError)
{
  var Input;
  Input = $('#'+FieldID);
  var FieldValue;
  if(!FieldDisplayLabel)
    FieldDisplayLabel = FieldID;
  FieldValue = Input.val();
  if(FieldValue=='')
  {
    if(!DontShowError)
    {
      alert('Please specify a value for '+FieldDisplayLabel+'.');
      Input.focus();
    }
    return false;
  }
  var FloatValue = 1.0*FieldValue;
  if(FloatValue*100!=Math.round(FloatValue*100))
  {
    if(!DontShowError)
    {
      alert('Please specify a value for '+FieldDisplayLabel+' using NNN.NN format.');
      Input.focus();
    }
    return false;
  }
  return true;
}

function HasDigits(s)
{
  l = s.length;
  for(i = 0; i<l; i++)
    if(isDigit(s.substr(i, 1)))
      return true;
  return false;
}

function HasLetters(s)
{
  l = s.length;
  for(i = 0; i<l; i++)
    if(isLetter(s.substr(i, 1)))
      return true;
  return false;
}

function Trim(s)
{
  return s.replace(/^\s*|\s*$/, "");
}

function ConcatURL(URL, AdditionalParams)
{
  if(URL.indexOf('?')>-1)
    URL += '&';
  else
    URL += '?';
  URL += AdditionalParams;
  return URL;
}

function SetHashParam(ParamName, Value)
{
  var HashParams = window.location.hash.substr(1).split('&');
  var HashString = '';
  var aHashParam;
  var s;
  if(Value>'')
    HashString = '#'+ParamName+'='+Value;
  for(var i = 0; i<HashParams.length; i++)
  {
    s = HashParams[i];
    aHashParam = s.split('=');
    if(aHashParam.length==2)
      if(aHashParam[0]==ParamName)
        continue;
    if(s>'')
    {
      if(HashString=='')
        HashString = '#';
      else
        HashString += '&';
      HashString += s;
    }
  }
  window.location.hash = HashString;
}

function GetHashParam(ParamName)
{
  var HashParams = window.location.hash.substr(1).split('&');
  var aHashParam;
  for(var i = 0; i<HashParams.length; i++)
  {
    aHashParam = HashParams[i].split('=');
    if(aHashParam.length==2)
      if(aHashParam[0]==ParamName)
        return aHashParam[1];
  }
  return null;
}