/** 
 *         Form validator
 *        (c) 2004 NEGESO
 *    Changed by Yuri Shanoilo
 *
 * In all forms which should be validated
 * please add onSubmit="return validate(this)"
 * all forms with class="contact". Please
 * insert required="true" attribute-value pair
 * into such validated objects:
 * - required text field;
 * - fieldset, in which at least one checkbox
 *   should be checked.
 * 
 * 
 * Example:
 * <form class="contact" onSubmit="return validate(this)">
 * <input type="text" required="true">
 * <fieldset required="true"><input type="checkbox"><input type="checkbox"></fieldset>
 * <input type="submit">
 * </form>
 */

function doShow(form) {
    form.style.display = "block";
} 

//=====================================Menu Function=============================================
var menuTime;   // Timer identifier used to hide submenus
var hideSub = null;    // Menu item, for which submenu should be hidden
var closetype; //If 'all' then all menus must be closed. Else only 1 menu will be closed

//This function add some test data to title (convenient for testing)
function addTitle(text)
{
  if (document.title.length > 55) {
    document.title = '';
  }                                 
  document.title += ' ' + text + ' ';
  
}


/* check if obj is menu item or its contents (oblect if true, null if false) */
function isMenuItem(obj) {
    while (obj && (obj != document) && (obj.tagName.toLowerCase() != "ul")) {
        if (obj.tagName.toLowerCase() == "li") return obj;
        obj = (obj.parentElement) ? obj.parentElement : obj.parentNode;
    }
    return false;
}

/* handling multiple styles applied to an element */
function addStyle(obj, class_name) {
    var cn = obj.className;
    var re = new RegExp("(^| )" + class_name + "($| )");
    var re1 = new RegExp("(^| )"  + "*cust" + class_name + "($| )");
    var re2 = new RegExp("cust");
    if (cn.search(re) != -1) return false;
    if (cn.search(re1) != -1) return false;
    if ((cn.search(re2) != -1) && ((class_name == "sub") || (class_name == "sub over"))) {
    cn = cn.replace(re2, "cust" + class_name);
  } else {
      if (cn != "" && cn.charAt(cn.length - 1) != " ") cn += " ";
      cn += class_name;
  }
    obj.className = cn;
}
function removeStyle(obj, class_name) {

    if (!obj) return;
    var re = new RegExp(" " + class_name + " ");
    var re1 = new RegExp("(^" + class_name + " )|( " + class_name + "$)|(^"
                           + class_name + "$)");
    var re2 = new RegExp("cust" + class_name + "($| )");
    if ( closetype == 'all' )
    {
      while (obj && (obj != document) && (obj.className != "menu") && (obj.className != "menu1")) {
          if (obj.tagName.toLowerCase() == "li")
    {
        var cn = obj.className;
        cn = cn.replace(re, " ");
        cn = cn.replace(re1, "");
        cn = cn.replace(re2, "cust");
        obj.className = cn;
    }

          obj = (obj.parentElement) ? obj.parentElement : obj.parentNode;
      }
  hideSub = null;
    }
    else
    {
      var cn = obj.className;
      cn = cn.replace(re, " ");
      cn = cn.replace(re1, "");
      cn = cn.replace(re2, "cust");
      obj.className = cn;
    }
}

function parentUL(obj) {
  parentul = ((obj.parentElement) ? obj.parentElement : obj.parentNode);
  return parentul;
}

function parentLI(obj) {
  parentul = ((obj.parentElement) ? obj.parentElement : obj.parentNode);
  if ((parentul.className == "menu") || (parentul.className == "menu1")) return null;
  parentli = ((parentul.parentElement) ? parentul.parentElement : parentul.parentNode);
  return parentli;
}

function doubleParentUL(obj) {
  parentul = ((obj.parentElement) ? obj.parentElement : obj.parentNode);
  if ((parentul.className == "menu") || (parentul.className == "menu1")) return null;
  doubleparentul = ((parentul.parentElement) ? parentul.parentElement.parentElement : parentul.parentNode.parentNode);
  return doubleparentul;
}

function handleMouseOver(e) {
    var el = (e) ? e.target : event.srcElement;
    var menuitem = isMenuItem(el);
    if (menuitem) {
  var vParentUL = null;
  var vParentLI = null;
  var vDoubleParentUL = null;
  var vHideParentUL = null;
  var vHideParentLI = null;
  var vHideDoubleParentUL = null;

  vParentUL = parentUL(menuitem);
  vParentLI = parentLI(menuitem);
  vDoubleParentUL = doubleParentUL(menuitem);
  if (hideSub != null)
  {
    vHideParentUL = parentUL(hideSub);
    vHideParentLI = parentLI(hideSub);
    vHideDoubleParentUL = doubleParentUL(hideSub);
  }

  if (menuitem == hideSub)
  {
    clearTimeout(menuTime);
    addStyle(menuitem, "over");
    hideSub = menuitem;
  }
  else if (hideSub == null)
  {
    addStyle(menuitem, "sub over");
  }

  else if (vParentUL == vHideParentUL)
  {
    clearTimeout(menuTime);
    closetype = 'current';
    removeStyle(hideSub, "sub");
    addStyle(menuitem, "sub over");
    hideSub = menuitem;
  }
  else if ((vParentLI != null) && (vParentLI == hideSub))
  {
    clearTimeout(menuTime);
    addStyle(menuitem, "sub over");
    hideSub = menuitem;
  }
  else if ((vHideParentLI != null) && (vHideParentLI == menuitem))
  {
    clearTimeout(menuTime);
    closetype = 'current';
    removeStyle(hideSub, "sub");
    addStyle(menuitem, "over");
    hideSub = menuitem;
  }
  else if ((vHideDoubleParentUL != null) && (vHideDoubleParentUL == vParentUL))
  {
    clearTimeout(menuTime);
    closetype = 'current';
    removeStyle(hideSub, "sub");
    removeStyle(vHideParentLI, "sub");
    addStyle(menuitem, "sub over");
    hideSub = menuitem;
  }
  else
  {
    clearTimeout(menuTime);
    closetype = 'all';
    removeStyle(hideSub, "sub");
  } 


    }
}

function handleMouseOut(e) {
    var el = (e) ? e.target : event.srcElement;
    var toel = (e) ? e.relatedTarget : event.toElement;
    var menuitem = isMenuItem(el);
    if (menuitem && (menuitem != isMenuItem(toel))) {
        removeStyle(menuitem, "over");
        hideSub = menuitem;
  closetype = 'all';
        menuTime = setTimeout('removeStyle(hideSub, "sub")', 200);
    }
}

function handleClick(e) {
    var el = (e) ? e.target : event.srcElement;
    var menuitem = isMenuItem(el);
    if (menuitem && el.tagName.toLowerCase() != "a") {
    neededA = menuitem.getElementsByTagName("a");
    if ( neededA.length != 0 ) {
      neededLink = neededA[0].getAttribute('href',2);
      neededLocation = neededA[0].getAttribute('target',2);
      if (neededLocation && neededLocation == "_blank")
      {
        window.open(neededLink,"","");
      } else {
        location.assign(neededLink);
      }
    }
  }
}

function handleLoad() {
   
    
    // This overcomes event-handling bug in menuitems in Mozilla
    if (navigator.appName.indexOf('Netscape') != -1) {
        var re = new RegExp("(^| )menu($| )");
        var re1 = new RegExp("(^| )menu1($| )");
        var menus = document.getElementsByTagName("ul");
        var mozMenuItem;
        
        for (var i = 0; i < menus.length; i++) {
            if ((menus[i].className.search(re) != -1) || (menus[i].className.search(re1) != -1)) {
                var menuItems = document.getElementsByTagName("li");
                for (var k = 0; k < menuItems.length; k++) {
                    mozMenuItem = document.createElement("div");
                    mozMenuItem.className = "moz";
                    menuItems[k].appendChild(mozMenuItem);
                }
            }
        }
    }
    
  //Adding validator to forms
  var forms = document.getElementsByTagName("FORM");
        for (var i = 0; i < forms.length; i++) {
            if (forms[i].className.indexOf("contact") != -1) {
    doShow(forms[i]);
            }
        }

}

function dPopup(url){
    newPopup = window.open(
        url,
        "",
        "height=300, width=400, menubar=no, resizable=yes, " +
        "scrollbars=no, status=no, titlebar=yes, toolbar=no, " +
        "left=" + (screen.availWidth/5*2) + ", " +
        "top=" + (screen.availHeight/5*1)
        );
}

function errorTrap() {
    return true;
}

function loadImage(imgName, imgWidth, imgHeight)
{
  imgWidth += 12;
  imgHeight += 15;
  var myt = "newWin = window.open(\"\", \"\", \"height="+ imgHeight + ", width=" + imgWidth + ",resizable=yes\")";
  eval(myt);
  newWin.document.write("<body style=\"padding: 0px; margin: 0px;\">");
  newWin.document.write("<table>");
  newWin.document.write("<tr>");
  newWin.document.write("<td style=\"background-color: #FFFFFF; padding: 5px;\">");
  newWin.document.write("<img src=\"" + imgName + "\" border=\"0\">");
  newWin.document.write("</td>");
  newWin.document.write("</tr>");
  newWin.document.write("</table>");
  newWin.document.write("</body>");
  newWin.document.close();
}

function loadFlash(swfName, swfWidth, swfHeight)
{
  var myt = "newWin = window.open(\"\", \"\", \"height="+ swfHeight + ", width=" + swfWidth + ",resizable=no\")";
  eval(myt);
  newWin.document.write("<body style=\"padding: 0px; margin: 0px;\">");
  newWin.document.write("<OBJECT classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\" WIDTH=\"" + swfWidth + "\" HEIGHT=\""+ swfHeight + "\" id=\"animation\">");
  newWin.document.write("<PARAM NAME=\"movie\" VALUE=\"media/" + swfName + "\">");
  newWin.document.write("<PARAM NAME=\"quality\" VALUE=\"high\">");
  newWin.document.write("<PARAM NAME=\"bgcolor\" VALUE=\"#FFFFFF\">");
  newWin.document.write("<EMBED src=\"media/" + swfName + "\" quality=\"high\" bgcolor=\"#FFFFFF\" WIDTH=\"" + swfWidth + "\" HEIGHT=\""+ swfHeight + "\" NAME=\"animation\" ALIGN=\"\" TYPE=\"application/x-shockwave-flash\" PLUGINSPAGE=\"http://www.macromedia.com/go/getflashplayer\">");
  newWin.document.write("</EMBED>");
  newWin.document.write("</OBJECT>");
  newWin.document.write("</body>");
  newWin.document.close();
}

document.onmouseover = handleMouseOver;
document.onmouseout = handleMouseOut;
document.onclick = handleClick;
window.onload = handleLoad;
//window.onerror=errorTrap;

// New Adds: 10.05.2006: Rostislav Brizgunov: begin
// Numeric format validating: used in validate(frm)
// How it works:
//             obj: must be object, or ID of object: INPUT type=("text"|"password")
//       int_limit: if int_limit is integer number, and int_limit>=1, then, for example:
//                  int_limit=8: .0 - valid
//                               123.0 - valid
//                               12345678.0 - valid
//                               123456789.0 - NOT VALID
//                  otherwise: valid will be numbers with integer part of any size
//     fract_limit: if fract_limit is integer number, and fract_limit>=0, then, for example:
//                  fract_limit=8: 0. -valid
//                                 0.123 - valid
//                                 0.12345678 - valid
//                                 0.123456789 - NOT VALID
//                  fract_limit=0: 65 - valid
//                                 65.1 - NOT VALID
//                  otherwise: valid will be numbers with fractal part of any size
//   val_limit_min: minimum limitation of value. 
//                  if not number (for example: val_limit_min=='none' <-- string), then
//                  limit is OFF (or == -INF)
//   val_limit_max: maximum limitation of value. 
//                  if not number (for example: val_limit_max=='none' <-- string), then
//                  limit is OFF (or == +INF)
// ---------------------------------------------------------------------------
// Function returns: 0 - validete success!
//                   1 - int part overload
//                   2 - fractal part overload
//                   3 - value less than minimum
//                   4 - value more than maximum
//                  -1 - wrong numeric format
// ---------------------------------------------------------------------------
// Last added feature: you can enter 0.4356  34543.  .65765   123.6741e+12  3.5672E-12   67.35e+123aBbRaCaDabBra
//                                   0,4356  34543,  ,65765   123,6741e+12  3,5672E-12   67,35e+123aBbRaCaDabBra
function NumericFormatValid(obj,int_limit,fract_limit,val_limit_min,val_limit_max)
{
  if ( obj.tagName=="INPUT" && ( obj.type=="text" || obj.type=="password" ) )
  {
    var val = obj.value;

        // apererva -> TLNC-156: number more 999 in the text field contains
        // dots, i.e. "1.000.234,45". It should be normalized
        // excluding dots from number.  
    val = val.replace(new RegExp("\\.","gi"), "");

    // For our calculations we have to convert our value to corresponding format:
    // 5,67 --> 5.67
    val = val.replace(",",".");

    // 5.0E+6 --> 5000000
    val = parseFloat(val);

    // !!!:FIRST CHECK: value in the field has absolutely incorrect numeric-format
    if ( (typeof(val) != 'number') || (isNaN(val)) ) {return -1;}

    // !!!:SECOND CHECK: value is more than maximum or less than minimum
    if ((typeof(val_limit_min) == 'number')&&(val < val_limit_min)) {return 3;}
    if ((typeof(val_limit_max) == 'number')&&(val > val_limit_max)) {return 4;}

        // Beginning creating formated output
        var int_part = "";
        var fract_part = "";
        var sign = (val < 0) ? "-" : "";

    // !!!:THIRD CHECK: integer validation (i.e. 2345678 or 1234,00000, but not 123.4567)
    val = val + "";
    var re = '^[+-]?\\d+$';
        var t1 = val.search(re);
        if (t1==0)
        {
      // Continue creating formated output
      int_part = val;
      if (typeof(fract_limit) == 'number')
      {
        for (var i = 0; i<fract_limit; i++) fract_part = fract_part + "0";
          }
          
          t1 = val;
          if ((typeof(int_limit) == 'number')&&(int_limit >= 1)&&(t1.length > int_limit)) {return 1;}
        }
    // !!!:FOURTH CHECK: floating-point validation (i.e. 123.456 or .456)
    else if (val.search('^[+-]?(\\d*)\\.(\\d*)$')==0)
    {
      re = '^[+-]?(\\d*)\\.(\\d*)$';
      t1 = val.match(re);
      int_part = t1[1];
      fract_part = t1[2];

      // Continue creating formated output
      if (typeof(fract_limit) == 'number')
      {
        for (var i = fract_part.length; i<fract_limit; i++) fract_part = fract_part + "0";
          } 
                    
      if ((typeof int_limit == 'number')&&(int_limit >= 1)&&(int_part.length > int_limit)) {return 1;}
          else if ((typeof fract_limit == 'number')&&(fract_limit >= 0)&&(fract_part.length > fract_limit)) {return 2;}
    }

    // Here we are returning parsed and correct value into the field
    var val_as_string = int_part;
    if (fract_part && fract_part.length>0) val_as_string = sign + val_as_string + "," + fract_part;
    val_as_string = val_as_string.replace("--","-");
    obj.value = val_as_string;
    return 0;   
  }
}

// New Adds: 12.05.2006: Rostislav Brizgunov: begin
// Time-date format validating: used in validate(frm)
// ---------------------------------------------------------------------------
// format_string FORMAT: (DD)? (MM)? (YY|YYYY)? (hh)? (mm)? (ss)? - in any order with any separators
//                       Example: hh:mm;  MM-DD-YY hh'mm''ss; MMdfgrdtYY etc.
//                       hh - 0-24 or 00-24
//                       mm - 00-59
//                       ss - 00-59
//                       YY - 00-99
//                       YYYY - 0000-9999
//                       MM - 01-12
//                       DD - 01-31
// ---------------------------------------------------------------------------
// Function returns: 0 - validete success!
//                  -1 - wrong time-date format
// ---------------------------------------------------------------------------
function TimeDateFormatValid(obj,format_string)
{
    // Creating regular expression template from format_string
    // Step 1: monitoring special-expression-symbols
  var expression_template = format_string;
  var re = /\\/g;
  expression_template = expression_template.replace(re,"\\\\");
  re = /\./g;
  expression_template = expression_template.replace(re,"\\.");
    re = /\(/g;
  expression_template = expression_template.replace(re,"\\(");
    re = /\)/g;
  expression_template = expression_template.replace(re,"\\)");
  re = /\[/g;
  expression_template = expression_template.replace(re,"\\[");
    re = /\]/g;
  expression_template = expression_template.replace(re,"\\]");
    re = /\{/g;
  expression_template = expression_template.replace(re,"\\{");
    re = /\}/g;
  expression_template = expression_template.replace(re,"\\}");
    // Step 2: transforming to the main template
    re = /hh/g;
  expression_template = expression_template.replace(re,"(?:(0|1|)(?=[0-9])|2(?=[0-4]))[0-9]");
  re = /mm/g;
  expression_template = expression_template.replace(re,"[0-5][0-9]");
  re = /ss/g;
  expression_template = expression_template.replace(re,"[0-5][0-9]");
  re = /YYYY/g;
  expression_template = expression_template.replace(re,"[0-9]{4}");
  re = /YY/g;
  expression_template = expression_template.replace(re,"[0-9]{2}");
    re = /MM/g;
  expression_template = expression_template.replace(re,"(?:0(?=[1-9])|1(?=[0-2]))[0-9]");
    re = /DD/g;
  expression_template = expression_template.replace(re,"(?:0(?=[1-9])|[1-2](?=[0-9])|3(?=[0-1]))[0-9]");
    expression_template = "^" + expression_template + "$";
  // Step 3: Checking
  if (obj.value.search(expression_template) != 0) {return -1;}
  return 0; 
}

function SimpleTimeDateFormatValid(obj) {
  if (obj.value.search("^[a-zA-Z\\d\\-/:()\\\\]+$") != 0)
  	return -1;
  return 0;
}
// New Adds: 04.10.2006: Rostislav Brizgunov
// Phone format validating: used in validate(frm)
function PhoneFormatValid(obj)
{
	if (obj.value.search(new RegExp("^[\\d\+)(-]{1,20}$", "i")) != 0)
		return -1;
	return 0; 	
}
// New Adds: 12.05.2006: Rostislav Brizgunov: end
