/*
emailCheck (emailStr)           -   Возвращает true - если валидное мыло или false если нет
validDate (entry)               -   Возвращает true - если валидная дата или false если нет  
isInt(entry)                    -   Возвращает true - если валидное число или false если нет    
getDate()                       -   Возвращает сегодняшнее число в формате dd.mm.yyyy  
CmpDates(Date1, Date2)          -   Сравнивает две даты путем вычитания Date1- Date2, т.е. возвращает разницу

MaxDiv(nnn)                     -   Делоает слой видимым
MinDiv(nnn)                     -   Скрывает слой 
MinMaxDiv(nnn)                  -   Скрывает слой если он был видимым, делает виимым если был скрыт 

GetRadioCheckedValue(check_obj) -   Получить выбранное ралио значение, check_obj = document.getElementById
GetRadioCheckedIndex(check_obj) -   Получить выбранный радио индекс индекс работает корректно для случая если радио батоно 
                                    больше 2 и более в случае когда батонов нет или один надо обрабатывать отдельно

winSmoothOpen(div_id)           -   Функция плавного открывания окна
winSmoothClose()                -   Плавного закрывания окна

--------- ПРИМЕР ---------
  <style>  
  .closeButton {   
       position: absolute;   
       top: 0px;   
       right: 0px;   
       border-bottom: 1px solid gray;   
       border-left: 1px solid gray;   
       font-weight: bold;   
       cursor: pointer;   
       padding: 2px 4px 2px 4px;   
  }   

  .divwin {   
       position: absolute;   
       width:  300 px;   
       height: 200 px;   
       border: 1px solid gray;   
       background: white;   
       display: none;   
       padding: 20px 20px 20px 20px;   
       text-align: center;   
  }   
  </style>  

  <div class="divwin" id="divwin3">
      <div class="closeButton" onclick="winSmoothClose()">X</div>
      <br><br><h3>Это - div'ное окно!</h3>  
  </div>
  <input class="but" type="button" value=" Open " onclick="winSmoothOpen('divwin3');" />

*/



function emailCheck (emailStr) { 
   /* The following pattern is used to check if the entered e-mail address 
      fits the user@domain format.  It also is used to separate the 
   username 
      from the domain. */ 
   var emailPat=/^(.+)@(.+)$/ 
   /* The following string represents the pattern for matching all special 
      characters.  We don't want to allow special characters in the 
   address. 
      These characters include ( ) < > @ , ; : \ " . [ ]    */ 
   var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" 
   /* The following string represents the range of characters allowed in a 
      username or domainname.  It really states which chars aren't 
   allowed. */ 
   var validChars="\[^\\s" + specialChars + "\]" 
   /* The following pattern represents the range of characters allowed as 
      the first character in a valid username or domain.  I just made it 
      the same as above, but if you want to add a different constraint, 
      you would change it here. */ 
   var firstChars=validChars 
   /* The following pattern applies if the "user" is a quoted string (in 
      which case, there are no rules about which characters are allowed 
      and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com 
      is a legal e-mail address. */ 
   var quotedUser="(\"[^\"]*\")" 
   /* The following pattern applies for domains that are IP addresses, 
      rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal 
      e-mail address. NOTE: The square brackets are required. */ 
   var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/ 
   /* The following string represents at atom (basically a series of 
      non-special characters.) */ 
   var atom="(" + firstChars + validChars + "*" + ")" 
   /* The following string represents one word in the typical username. 
      For example, in john....@somewhere.com, john and doe are words. 
      Basically, a word is either an atom or quoted string. */ 
   var word="(" + atom + "|" + quotedUser + ")" 
   // The following pattern describes the structure of the user 
   var userPat=new RegExp("^" + word + "(\\." + word + ")*$") 
   /* The following pattern describes the structure of a normal symbolic 
      domain, as opposed to ipDomainPat, shown above. */ 
   var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$") 


   /* Finally, let's start trying to figure out if the supplied address is 
      valid. */ 


   /* Begin with the course pattern to simply break up user@domain into 
      different pieces that are easy to analyze. */ 
   var matchArray=emailStr.match(emailPat);
   if (matchArray==null) { 
     /* Too many/few @'s or something; basically, this address doesn't 
        even fit the general mould of a valid e-mail address. */ 
      alert("E-mail address is not valid.");
      window.document.emailform.new_email.focus(); 
      window.document.emailform.new_email.select(); 
      return false; 
   } 


   var user=matchArray[1]; 
   var domain=matchArray[2];

   // See if "user" is valid 
   if (user.match(userPat)==null) { 
       // user is not valid 
       alert("The email address is not valid."); 
       return false; 
       window.document.emailform.new_email.focus(); 
       window.document.emailform.new_email.select(); 
   } 


   /* if the e-mail address is at an IP address (as opposed to a symbolic 
      host name) make sure the IP address is valid. */ 
   var IPArray=domain.match(ipDomainPat); 
   if (IPArray!=null) { 
       // this is an IP address 
       for (var i=1;i<=4;i++) { 
         if (IPArray[i]>255) { 
             alert("Destination IP address is invalid");
             window.document.emailform.new_email.focus(); 
             window.document.emailform.new_email.select(); 
             return false; 
         } 
       } 
       return true; 
   } 


   // Domain is symbolic name 
   var domainArray=domain.match(domainPat) 
   if (domainArray==null) { 
      alert("E-mail address is invalid."); 
      window.document.emailform.new_email.focus(); 
      window.document.emailform.new_email.select(); 
      return false; 
   } 


   /* domain name seems valid, but now make sure that it ends in a 
      three-letter word (like com, edu, gov) or a two-letter word, 
      representing country (uk, nl). 
      If there's a country code at the end of the address, the full domain 
      must include a hostname and category (e.g. host.co.uk or 
   host.pub.nl). 
      If it ends in a .com or something, make sure there's a hostname.*/ 

   /* Now we need to break up the domain to get a count of how many atoms 
      it consists of. */ 
   var atomPat=new RegExp(atom,"g") 
   var domArr=domain.match(atomPat) 
   var len=domArr.length 
   if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>10) { 
      // the address must end in a two letter or three letter word. 
      alert("The address must end in a three-letter domain, or two letter country.");
      window.document.emailform.new_email.focus(); 
      window.document.emailform.new_email.select(); 
      return false; 
   } 


   /* If it ends in a country code, we want to make sure there are at 
      least 2 atoms preceding it (representing host and category (i.e. 
      com, gov, etc.)) */ 
   /*if (domArr[domArr.length-1].length==2 && len<3) { 
      var errStr="This address ends in two characters, which is a country" 
      errStr+=" code.  Country codes must be preceded by " 
      errStr+="a hostname and category (like com, co, pub, pu, etc.)" 
      alert(errStr) 
           window.document.emailform.new_email.focus(); 
   window.document.emailform.new_email.select(); 
      return false; 
   } 
   */

   /* If it just ends in .com, .gov, etc., make sure there's a host name. 
      This case can never actually happen because earlier checks take 
      care of this implicitly, but we'll do it anyway. */ 
   if (domArr[domArr.length-1].length==3 && len<2) { 
      var errStr="This address is missing a hostname!";
      alert(errStr);
      window.document.emailform.new_email.focus(); 
      window.document.emailform.new_email.select(); 
      return false; 
   } 

   /*if (confirm("Submission of your E-mail address to the Principal 
   Financial Group means that blah blah blah...")){ 
   return true; 
   } 

   else{ 
   window.document.emailform.new_email.focus(); 
   window.document.emailform.new_email.select(); 
      return false; 
   } */ 

   return true; 
} 


//----- Валидация даты ------------------
function validDate(entry){ 
  rex=/\b(0?[1-9]|[12][0-9]|3[01])(-|\.)+(1[0-2]|0?[1-9])(-|\.)+\d\d\d\d/ 
  return rex.test(entry) 
} 


//----- Валидация числа ------------------
function isInt(entry){
    var reEval = /^\d+$/; 
    return reEval.test(entry) ;
}

//--------- Сегодняшняя Дата ----------
function getDate() 
{ 
 // displays date as 'Month d, yyyy' 
 var datestr, curdate = ""; 
 datestr = new Date(); 

 d = datestr.getDate(); 
 m = datestr.getMonth()+1; 
 yyyy = datestr.getFullYear(); 
 
 dd = (d > 9)?d:'0' + d;
 mm = (m > 9)?m:'0' + m;
 
 return dd + '.' + mm + '.' + yyyy; 
} 

//----- Сравнение дат --------------------
function CmpDates(Date1, Date2){
     return ReverseDateToInt(Date1) - ReverseDateToInt(Date2);
}

function ReverseDateToInt(entry){ 
  rex=/\b(0?[1-9]|[12][0-9]|3[01])(-|\.)+(1[0-2]|0?[1-9])(-|\.)+(\d\d\d\d)/
  entry = entry.replace(rex, "$5$3$1") 
  return entry;
} 


//------- Свернуть развернуть DIV --------
function MaxDiv(nnn) {
     document.getElementById(nnn).style.display = 'block';
}

function MinDiv(nnn) {
     document.getElementById(nnn).style.display = 'none';
}

function MinMaxDiv(nnn) {
  if ( document.getElementById(nnn).style.display == 'none' )
     MaxDiv(nnn);
  else 
     MinDiv(nnn);
}

//#####################################################################
// -------- Получить выбранный ралио индекс работает корректно для случая если радио батоно больше 2 и более 
// -------- в случае когда батонов нет или один надо обрабатывать отдельно  -------------
function GetRadioCheckedIndex(check_obj) { 
  for(var i=0; i<check_obj.length; i++) { 
    if (check_obj[i].checked){
       return i; 
    }
  }
} 

// -------- Возвращает значение выбранного radio button- a -------------
function GetRadioCheckedValue(check_obj) { 
   if (check_obj && !check_obj.length){
     return check_obj.checked?check_obj.value:false;
   }
   else{
     var i = GetRadioCheckedIndex(check_obj);
     return (i>=0 && check_obj[i].checked)?check_obj[i].value:false;
   }
} 

//####################################################################
//  Блок посвященный плавному открытию слоев 
//####################################################################
var smoothStep    = 16; 
var smoothTimeout = 15;
var smoothLeft    = 0;
var smoothRight   = 0;
var wObj;

function winSmoothOpen( oDiv, x, y ) { 
    wObj               = document.getElementById(oDiv);
    wObj.style.display = 'block';
    wObj.style.left    = x?x:event.x;   
    wObj.style.top     = y?y:event.y;   
    smoothLeft         = wObj.offsetWidth/2;
    smoothRight        = wObj.offsetWidth/2;
    winSmoothRise();
}

function winSmoothRise() {
    wObj.style.display = 'block';
    if (smoothLeft > 0) {
       smoothRight    += smoothStep; 
       smoothLeft     -= smoothStep;                
       var rect        = 'rect(auto, '+ smoothRight +'px, auto, '+ smoothLeft +'px)';          
       wObj.style.clip = rect;                
       setTimeout(winSmoothRise, smoothTimeout); 
    }
}

function winSmoothClose() {
    if ( smoothLeft < smoothRight )   {
       smoothRight    -= smoothStep; 
       smoothLeft     += smoothStep; 
       var rect        = 'rect(auto, '+ smoothRight +'px, auto, '+ smoothLeft +'px)';
       wObj.style.clip = rect;
       setTimeout(winSmoothClose, smoothTimeout);
    }
    else wObj.style.display = 'none';
}


//--- Показываение подсказок, создается динамичсекий DIV и показывается подсказка
//--------Показывать хинт у тега <a> title на событие onmouseover и скрывать на onmouseout-----
var HelpTitle;
function showTitle(oA, xshift, yshift ){
  HelpTitle = oA.title;
  oA.title = '';
  showTip(HelpTitle, xshift, yshift);
}

function hideTitle (oA){
  hideTip()
  if (oA) oA.title = HelpTitle;
}

//--------Показывать хинт у обычного текста---------
function showTip(text, xshift, yshift ) {
    if (text && text!='') {
        var which = document.createElement("DIV"); 
        if (!xshift) xshift = -150;
        if (!yshift) yshift = 15;
        which.style.top =  window.event.clientY + yshift + document.body.scrollTop;
//        alert (window.event.clientY);
//        alert (document.body.scrollTop);
        which.style.left = window.event.clientX + xshift - document.body.scrollLeft;
        which.className = "Help";
        var it = document.body.appendChild(which); 
        it.id = "tipHelp"; 
    
        which.innerHTML = '<center>'+text+'</center>';
    }
}

function hideTip() {
        if (document.getElementById('tipHelp')) {
           document.getElementById('tipHelp').style.visibility = "hidden";
           document.body.removeChild(document.getElementById('tipHelp'));
        }
}
//--- END Показываение подсказок, создается динамичсекий DIV и показывается подсказка

function openW(url, width, height, name, scroll){ 
  var w = window.open(url, name, 'scrollbars='+scroll+', status=1, location=0, menubar=0, resizable=1, width='+width+', height='+height+', top=10, left=20' );
  w.focus();
}

//парсит строку адреса и возвращает нужный параметр 
function getCgiParamValue(key, default_) {
  if( default_==null ) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"[^&#]*");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
