﻿/*
 * Global js framework
 * version: 1.1 (03/01/2008)
 * @requires jQuery v1.2 or later
 */


//<asp:TextBox ID="txtCli" runat="server" MaxLength="12" onpaste="return HandelNumericPaste(this);"  onkeypress="return HandelNumericKey(event);"></asp:TextBox>


function getElm(elm) {
   // alert(elm.value);
    return $get(elm);
}


    //onkeypress="return HandelNumericKey(event);"
    function HandelNumericKey(evt) {

      evt = (evt) ? evt : ((event) ? event : null);
      if (evt) {
          var key = evt.charCode//firefox
          if (!key) {
             key = evt.keyCode;
          }
          //alert(key);
          
          if (key == 0 || key == 8 || key == 36 || key == 35 || key == 39 || key == 37 || key == 46) {
              //back,home,end,right,left,del keys
              return true;
          }
          else if (key < 48 || key > 57) {
              return false;
          }
      }
            return true;
    }

    //onpaste="return HandelNumericPaste(this);"
    function HandelNumericPaste(obj) {
 
        data = window.clipboardData.getData('Text');
        if (!isNaN(data)) {
            event.returnValue = obj.value + data;
            return true;
        }
        event.returnValue = obj.value;
        return false;
    }

    //onpaste="return false;"
    function HandelAnyPaste(obj) {
        return false;
    }

    //onkeypress="return false;"
    function HandelAnyKey(event) {
        return false;
    }


    // validate that the user made a selection other than default
    function isChosen(select) {
        if (select.selectedIndex == 0) {
            //alert("Please make a choice from the list.");
            return false;
        } else {
            return true;
        }
    }
    
    
   function confirmSubmit(text)
    {
        var agree = confirm(text);

        if (agree)
            return true;
        else
            return false;
    }

    function confirmElement(elem, text) {
        if (isEmptyElement(getElm(elem)))
            return false;
        return confirm(text);
    }
    function confirmMobileElement(elem, text) {
        if (!isMobileElement(getElm(elem), true))
            return false;
        return confirm(text);
    } 
        
    function confirmDelete()
    {

        var agree = confirm("?האם למחוק");

        if (agree)
            return true;
        else
            return false;
    }

           
function ShowDialog(sUrl,name,width,height)
{
   
   //This string specifies the features of the Dialog Box
   Args = "height: "+ height +"px; width: "+ width + "px; edge: Raised; center: Yes; help: No; resizable: No; status: No";

   window.open(sUrl, name, Args);

}

function ShowModalDialog(sUrl, Params, width, height) {

    //This string specifies the features of the Dialog Box
    Args = "dialogHeight: " + height + "px; dialogWidth: " + width + "px; edge: Raised; center: Yes; help: No; resizable: No; status: No";

    // Show a Modal Dialog, pass the oSelection parameter
    // and display the result
    window.showModalDialog(sUrl, Params, Args);

}

function ModalDialog(sUrl,Params)
{
   
   //This string specifies the features of the Dialog Box
   Args = "dialogHeight: 300px; dialogWidth: 500px; edge: Raised; center: Yes; help: No; resizable: No; status: No";

   // Show a Modal Dialog, pass the oSelection parameter
   // and display the result
   alert(window.showModalDialog(sUrl, Params, Args));

    return Params;
   //Show the Region and Territory returned from the Modal Dialog Box
   //txtRegion.value = oSelection.Method;
   //txtTerritory.value = oSelection.Text;
}


function AddChars(count,chars){
	count.value = parseInt(count.value) + chars;
}

function uncheck_me(obj_id){

 var obj = document.getElementById(obj_id);
 obj.checked = false;
}


function IsNumericKey(evt) {

 evt = (evt) ? evt : ((event) ? event : null);
 if (evt) {
     var key = evt.charCode//firefox
     if (!key) {
         key = evt.keyCode;
     }
     if (key < 48 || key > 57) {
         return false;
     }
 }
return true;
}

function IsDelKey(evt) {

    evt = (evt) ? evt : ((event) ? event : null);
    if (evt) {
        var key = evt.charCode//firefox
        if (!key) {
            key = evt.keyCode;
        }
        return key == 46;
    }
    return false;
}

// validates that the field value string has one or more characters in it
function isNotEmpty(elem) {
    var str = elem.value;
    var re = /.+/;
    if (!str.match(re)) {
        //alert("Please fill in the required field.");
        //setTimeout("focusElement('" + elem.form.name + "', '" + elem.name + "')", 0);
        return false;
    } else {
        return true;
    }
}

//validates that the entry is a positive or negative number
function isNumeric(str) {
    if (isEmpty(str))
        return false;

    var re = /^[-]?\d*\.?\d*$/;
    str = str.toString();
    if (!str.match(re)) {
        return false;
    }
    return true;
}
//validates that the entry is a positive or negative number
function isNumberElement(elem) {
    if (isEmptyElement(elem))
        return false;
    return isNumeric(elem.value);
}

function isMobile(str) {
    if (isEmpty(str))
        return false;
    var re = /^(052[0-9]{7}|050[0-9]{7}|054[0-9]{7}|057[0-9]{7}|052-[0-9]{7}|050-[0-9]{7}|054-[0-9]{7}|057-[0-9]{7}|972[0-9]{9})$/
    //var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
    return re.test(str);
}

function isPhone(str) {
    if (isEmpty(str))
        return false;

    var re = /^(052[0-9]{7}|050[0-9]{7}|054[0-9]{7}|057[0-9]{7}|972[0-9]{9}|0[0-9]{8})$/
    //var re = /^\(?[2-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/
    return re.test(str);
}


// validates that the entry is formatted as an e-mail address
function isMobileElement(elem, showAlert) {
    var ok =elem? isMobile(elem.value):false;
    if (!ok && showAlert)
        alert("מספר טלפון נייד אינו תקין");
    return ok;
}
// returns true if the string is a valid email
function isEmail(str) {
    if (isEmpty(str)) return false;
    var re = /^[^\s()<>@,;:\/]+@\w[\w\.-]+\.[a-z]{2,}$/i
    return re.test(str);
}

// validates that the entry is formatted as an e-mail address
function isEmailElement(elem, showAlert) {
    var ok = elem? isMobile(elem.value):false;
    if (!ok && showAlert)
        alert("כתובת דואר אלקטרוני אינה תקינה");
    return ok;
}


/* validator 
isEmail = true;          // valid email address
isAlpha = true;          // A-Z a-z characters only
isNumeric = true;        // 0-9 characters only
isAlphaNumeric = true;   // A-Z a-z 0-9 characters only
isLength = number;       // must be exact length
isLengthBetween = array; // [lowNumber, highNumber] must be between lowNumber and highNumber
isPhoneNumber = true;    // valid US phone number. See "isPhoneNumber()" comments for the formatting rules
isDate = true;           // valid date. See "isDate()" comments for the formatting rules
isMatch = string;        // must match string
optional = true;         // element will not be validated
*/

// returns true if the string is empty
function isEmpty(str){
  return (str == null) || (str.length == 0);
}

function isEmptyLessThen(str,len){
  return (str == null) || (str.length < len);
}
function isEmptyElement(elem) {
    if (!elem) return false;
    return (str == null) || (str.length == 0);
}

// returns true if the string only contains characters A-Z or a-z
function isAlpha(str){
  var re = /[^a-zA-Z]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string only contains characters 0-9
function isDigits(str){
  var re = /[\D]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string only contains characters A-Z, a-z or 0-9
function isAlphaNumeric(str){
  var re = /[^a-zA-Z0-9]/g
  if (re.test(str)) return false;
  return true;
}
// returns true if the string's length equals "len"
function isLength(str, len){
  return str.length == len;
}
// returns true if the string's length is between "min" and "max"
function isLengthBetween(str, min, max){
  return (str.length >= min)&&(str.length <= max);
}
// returns true if the string is a valid date formatted as...
// mm dd yyyy, mm/dd/yyyy, mm.dd.yyyy, mm-dd-yyyy
//^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})[\s](\d{1,2})[\:](\d{1,2})+$
//^(\d{4})[\-](\d{1,2})[\-](\d{1,2})[\sT](\d{1,2})[\:](\d{1,2})+$
//^((\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})[\s]|(\d{4})[\-](\d{1,2})[\-](\d{1,2})[\sT])(\d{1,2})[\:](\d{1,2})$

function isDate(str){
  var re = /^(\d{1,2})[\s\.\/-](\d{1,2})[\s\.\/-](\d{4})$/
  if (!re.test(str)) return false;
  var result = str.match(re);

  var sm = result[2];
  var sd = result[1];
  var y = parseInt(result[3]);


  if (sm.length > 1 && sm.charAt(0) == "0")
      sm = sm.charAt(1);
  if (sd.length > 1 && sd.charAt(0) == "0")
      sd = sd.charAt(1);

  /*
  var m = parseInt(result[2]);
  var d = parseInt(result[1]);
  var y = parseInt(result[3]);
*/
  m = parseInt(sm);
  d = parseInt(sd);
  
  
  if (m < 1 || m > 12 || y < 1900 || y > 2100) return false;
  if(m == 2){
          var days = ((y % 4) == 0) ? 29 : 28;
  }else if(m == 4 || m == 6 || m == 9 || m == 11){
          var days = 30;
  }else{
          var days = 31;
      }
  return (d >= 1 && d <= days);
}
// returns true if "str1" is the same as the "str2"
function isMatch(str1, str2){
  return str1 == str2;
}
// returns true if the string contains only whitespace
// cannot check a password type input for whitespace
function isWhitespace(str){ // NOT USED IN FORM VALIDATION
  var re = /[\S]/g
  if (re.test(str)) return false;
  return true;
}

// removes any whitespace from the string and returns the result
// the value of "replacement" will be used to replace the whitespace (optional)
function stripWhitespace(str, replacement){// NOT USED IN FORM VALIDATION
  if (replacement == null) replacement = '';
  var result = str;
  var re = /\s/g
  if(str.search(re) != -1){
    result = str.replace(re, replacement);
  }
  return result;
}


/*  generate password */


function generatePassword(elm) {
//length=8, 
//extraChars='', firstNumber=true, firstLower=true, firstUpper=true, firstOther=false,
//latterNumber=true, latterLower=true, latterUpper=true, latterOther=false
    var box = $get(elm);
    box.value = getPassword(8, '', true, true, true, false, true, true, true, false);
}


function getRandomNum(lbound, ubound) {
    return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}
function getRandomChar(number, lower, upper, other, extra) {
    var numberChars = "0123456789";
    var lowerChars = "abcdefghijklmnopqrstuvwxyz";
    var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var otherChars = "`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/? ";
    var charSet = extra;
    if (number == true)
        charSet += numberChars;
    if (lower == true)
        charSet += lowerChars;
    if (upper == true)
        charSet += upperChars;
    if (other == true)
        charSet += otherChars;
    return charSet.charAt(getRandomNum(0, charSet.length));
}
function getPassword(length, extraChars, firstNumber, firstLower, firstUpper, firstOther,
latterNumber, latterLower, latterUpper, latterOther) {
    var rc = "";
    if (length > 0)
        rc = rc + getRandomChar(firstNumber, firstLower, firstUpper, firstOther, extraChars);
    for (var idx = 1; idx < length; ++idx) {
        rc = rc + getRandomChar(latterNumber, latterLower, latterUpper, latterOther, extraChars);
    }
    return rc;
}

/*  end generate */

/////////////// Ajax //////////////////////////////////
function GetXmlPage(URL) {
    if (window.XMLHttpRequest) //mozilla
    {
        oXMLHTTP = new XMLHttpRequest();
        oXMLHTTP.onreadystatechange = statechanged;
    }
    else //ie
    {

        oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
        oXMLHTTP.onreadystatechange = statechanged;

    }
    var d = new Date();
    var time;

    time = "&time=" + d.getTime();

    oXMLHTTP.open("GET", URL + time, true);

    oXMLHTTP.send(null);
    //	alert(URL);
}

function statechanged() {
    if (oXMLHTTP.readyState == 4 || oXMLHTTP.readyState == "complete") {
        sXMLResponse = oXMLHTTP.responseText;
    }

}

//////////////////////////////////////////////////////////////////

function GetXmlResponse(LinkPage, DivEffected) {

    gDivEffected = DivEffected;

    if (window.XMLHttpRequest) //mozilla
    {
        oXMLHTTP = new XMLHttpRequest();
        oXMLHTTP.onreadystatechange = stateChanged;
    }
    else //ie
    {
        oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
        oXMLHTTP.onreadystatechange = stateChanged;
    }

    //this segement is for the xml caching to disable itself..
    //i send every time a different url (because of the time i attach)
    //so it has no other possibility but to reload...
    var d = new Date();
    var time;

    time = "&time=" + d.getTime();
    //till here the time addon ...
    //alert(LinkPage);
    oXMLHTTP.open("GET", LinkPage + time, false);
    oXMLHTTP.send(null);
    //	alert(LinkPage);
}

function stateChanged() {
    //alert(oXMLHTTP.readyState);
    if (oXMLHTTP.readyState == 4 || oXMLHTTP.readyState == "complete") {
        sXMLResponse = oXMLHTTP.responseText;

        gDivEffected.innerHTML = sXMLResponse;
    }

}

/////////////////////// Ajax /////////////////////////////////

