///////////////////////////////////////////////////////////////////////////////////////////
// BSmart Web Applications (c) all rights reserved.
// BSmartFormValidation.js - Provide Javascript functions for Form validation.
///////////////////////////////////////////////////////////////////////////////////////////
//
// Function bsmartformvalidation
// Description: Validates the data of a HTML form
// Return value: True if the validation is succesful, false if not.
//
// The function bsmartformvalidation takes an array of parameters in the following order:
// The first parameter is the form-name
// Then a series of 3 parameters in the following order:
// 1. Field name as specified in the HTML
// 2. Validation Fromat. 
//	  The char: '#' should be assigned in the begining of the string to indicate that a field value is required.
//    Then, the required characters number should be assigned
//    Examples: "#17" - minimum, "17"
//    For Dates however, regular expresion should be used instead of a number, for exxample:
//		Value is Optional  DD-MM-YYYY: "^\([0-9][0-9]\)\\-\([0-9][0-9]\)\\-\([0-9]{4}\)$#1#2#3"
//		Value is Optional  DD/MM/YYYY: "^\([0-9][0-9]\)\\/\([0-9][0-9]\)\\/\([0-9]{4}\)$#1#2#3"
//      Value is Mandatory DD-MM-YYYY: "#^\([0-9][0-9]\)\\-\([0-9][0-9]\)\\-\([0-9]{4}\)$#1#2#3"
// 3. Validation Types
//	  Text   0: Text (no Validation)
//	  Text,  1: eMail
//	  Text,  2: Number
//	  Text,  3: Read Only 
//    Text,  10: Phone number (include '-','+',' ','(',')','#','/','\' as well as digits)
//	  Text,  20: Date
//	  Text,  21: Time

function bsmartformfindObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=bsmartformfindObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function bsmartformvalidation() { 	
  var a=bsmartformvalidation.arguments,oo=true,v='',datavalid=true,required,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+3){
    if (a[i+1].charAt(0)=='#'){required=true; a[i+1]=a[i+1].substring(1);}else{required=false}
    o=bsmartformfindObj(a[i].replace(/\[\d+\]/ig,""));
    if (!o) return true;
    o1=bsmartformfindObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    //alert("Type: " + o.type + ", Validation type: " + t + ", Required: " + required)
    if (o.type=='text'||o.type=='password'||o.type=='hidden')    
    { // ---- Text / Password / Hidden ----                  
      if (required&&v.length==0) {datavalid=false}
      else if (!required&&v.length==0) {datavalid=true}
      else if (t==0)
      { //Text (check minimum number of chars)
			if (v.length<a[i+1]) {datavalid=false}
      }
      else if (t==1)
      { // email
			rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v)) {datavalid=false;}
      } 
      else if (t==3)
      { //number			
			if (isNaN(v)||(v.length<(a[i+1]))) {datavalid=false}						
      }       
      else if (t==4) {} // read-only field
      else if (t==10)
      { //phone
           rx=new RegExp("^[-+(\s)/\\#0-9]*$");if(!rx.test(v)) {datavalid=false;}
			//ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){datavalid=false}
      } 
      else if (t==20)
      { // date
			ma=a[i+1].split("#");at=v.match(ma[0]);
			if(at)
			{
				cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
				dte=new Date(cy,cm,cd);
				if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){datavalid=false};
			}
			else{datavalid=false}
      } 
      else if (t==21)
      { // time
			ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){datavalid=false}
      }
      else if (t==96)
      { // Domain Name
			rx=new RegExp("^([0-9]+)(\.[0-9]+)(\.[0-9]+)(\.[0-9]+)$");if(!rx.test(v)) {datavalid=false;}
      } 
      else if (t==97)
      { // check URL
			rx=new RegExp("^([a-zA-Z0-9][\-a-zA-Z0-9]*)((\.[a-zA-Z0-9][\-a-zA-Z0-9]*)+)$");if(!rx.test(v)) {datavalid=false;}
      } 
      else if (t==98)
      { // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){datavalid=false}
      } 
      else if (t==99)
      { // the same
			if(v!=bsmartformfindObj(a[i+1]).value){datavalid=false}
      }
    } 
    else if (!o.type&&o.length>0&&o[0].type=='radio')
    { // ---- Radio ----
		at = a[i].match(/(.*)\[(\d+)\].*/i);
		o2=(o.length>1)?o[at[2]]:o;
		if (required&&o2&&o2.checked&&o1&&o1.value.length/1==0){datavalid=false}		
    } 
    else if (o.type=='checkbox')
    { // ---- checkbox ----
      //if(required&&o.checked==false){datavalid=false}
    } 
    else if (o.type=='select-one'||o.type=='select-multiple')
    { // ---- select-one / select-multiple ----
      if(required&&o.selectedIndex/1==0){datavalid=false}
    }
    else if (o.type=='textarea')
    { // ---- textarea ----	  
	  if (required&&v.length==0) {datavalid=false}
      else if (!required&&v.length==0) {datavalid=true}
      else if (v.length<(a[i+1])) {datavalid=false}      
    }
  }  
  //alert('datavalid: ' + datavalid)  
  return (datavalid);  
}

function NumericOnly  () {if (!(event.keyCode >= 48 && event.keyCode <= 57)) event.returnValue=false;}

function Format(total,decimals)
 {
      var num = parseFloat(total);
      // First section sets non-number value to zero
          if (!(num = parseFloat(num)))
               num = "0.00";
      // Second section sets two decimal place format
          var Pad = "";
          num = "" + Math.floor(num * Math.pow(10,decimals + 1) + 5);
          // Pad if less than 0.10
          if(num.length < decimals+1) 
          {
               for(Count = num.length; Count <= decimals; Count++)
                    Pad += "0";
          }
          num = Pad + num;
     // Parse into final string
          num = num.substring(0,num.length - decimals - 1) + 
               "." + num.substring(num.length - decimals -1, num.length -1);
     // If less than 1 then add 0 to the left of the decimal
          if((num == "") || (parseFloat(num) < 1))
               num = "0" + num;
     // Final section returns formatted number
          return num;
}

function bsOnComboPropValChange(fieldID,fieldsArrayName,itemID)
{    
    var i
    var path = new String(document.location);    
    //var url=path.substring(0,path.lastIndexOf("/"))+"/bsmart/BSmartFreeHTMLs/BSmartFreeAJX.aspx?Action=propsearch&itemid="+itemID    
    var url="bsmart/BSmartFreeHTMLs/BSmartFreeAJX.aspx?Action=propsearch&itemid="+itemID
    var combo
    var flag=true
    var changedComboID=0
    for (i=0;i<fieldsArrayName.length;i++)
    {
        // Continue Collect Field Values        
        if (flag)
        {
            combo = document.all(fieldsArrayName[i])
            url=url+"&"+fieldsArrayName[i]+"="+combo.options[combo.selectedIndex].value
            if (fieldsArrayName[i] == fieldID) 
            {
                flag=false
                changedComboID=i
            }
        }        
    }
    if (changedComboID<(fieldsArrayName.length-1))        
    {
        var tmpStr = BSmartDirectCall(url)
        if (tmpStr>"")
        {   
            // Convert returned string to Combo Values array
            // Retunred string format:
            // <id>|,|<val>|,<id>|,|<val>|,|…|;|…
            var comboValsArray = new Array();
            // Temp arrays to help extract retuned string
            var tmpComboValListArray=tmpStr.split("|;|");
            var tmpComboValArray
            // Extract splitted arrays.
            for (i=0;i<tmpComboValListArray.length;i++)
            {
                tmpComboValArray=tmpComboValListArray[i].split("|,|");
                comboValsArray[i]=new Array();
                // Extract splitted ids and vals.
                for (j=0;j<tmpComboValArray.length;j++){comboValsArray[i][j]=tmpComboValArray[j];}
            }            
            // Update Combo Content And selctions
            for (i=0;i<comboValsArray.length;i++)
            {
                combo=document.all(fieldsArrayName[i+changedComboID+1])        
                combo.options.length=0
                for (j=0;j<comboValsArray[i].length;j=j+2)
                {
                    var oOption = document.createElement("OPTION");
		            oOption.text=comboValsArray[i][j+1];
		            oOption.value=comboValsArray[i][j];
		            combo.add(oOption);            
                }
            }
        }
    }
}

function bsValidateDomainName(domainName)
{    
    var url= "../BSmartFreeHTMLs/BSmartFreeAJX.aspx?Action=validation&type=1&text="+domainName    
    return BSmartDirectCall(url)
}

function bsGetUserPrice(prodID)
{    
    var path = new String(document.location);    
    //var url=path.substring(0,path.lastIndexOf("/"))+"/bsmart/BSmartFreeHTMLs/BSmartFreeAJX.aspx?Action=userprice&prodid="+prodID       
    var url= "bsmart/BSmartFreeHTMLs/BSmartFreeAJX.aspx?Action=userprice&prodid="+prodID    
    return BSmartDirectCall(url)
}
