﻿// JScript File
function _validate_multi_vins(app_mode,vin_src,vin_dest,err_tbody,dlm_code)
{   

    //lert("addasd");
    //return false;
    _clear_table(err_tbody);
    
    var e=document.getElementById(vin_src);
    if (e.value=="") {alert("Empty: please enter at least one VIN.");return false;}
    var s_vins=e.value;
    var delimiter;
    
    switch (dlm_code){
        case "comma":
        {
            delimiter=",";break;
        }
        case 'carriage_return':
        {
            delimiter="\n";break;
        }   
        case "pipe":
        {
            delimiter="|";break;
        }
        case "space":
        {
            delimiter="\ ";break;
        }
        case "tab":
        {
            delimiter="\t";break;
        }
        case "ampersand":
        {
            delimiter='\&';break;
        }
        case "backslash":
        {
            delimiter="\\";break;
        }
    }
    //alert("Delimiter:"+delimiter);
    var s_vins_array=s_vins.split(delimiter);
    if (s_vins_array.length==1) 
    {   switch (app_mode)
        {
            case "batch":
            {
                alert("Please specify a proper delimiter.");break;
            }
            case "multi":
            {
                alert("Please enter at least two VINs.");break;
            }
        }   
        return false;
    }
    var i;
    var s_validate_return;
    var eVINs=document.getElementById(vin_dest);
    var s_vins_csv="";
    var b_vins_all_passed=true;
    for (i=0;i<s_vins_array.length;i++)
    {
        s_vin=s_vins_array[i];
        s_validate_return=_validate_single_vin(s_vin);
        if (s_validate_return!="Valid"){b_vins_all_passed=false;}
        if (dlm_code=="tab" || dlm_code=='carriage_return'){
            _insert_validationn_msg(vin_src,err_tbody,s_vin,s_validate_return,delimiter);
            }
            else
            {
            _insert_validationn_msg(vin_src,err_tbody,s_vin,s_validate_return,"\\"+delimiter);
            }
        s_vins_csv +=trim(s_vin.toUpperCase())+",";
    }
    s_vins_csv=s_vins_csv.substr(0,s_vins_csv.length-1);
    eVINs.value=s_vins_csv;
    //var errDiv =document.getElementById("tblErrors");
    //var errDiv=err_tbody.parentNode;
    //if (!b_vins_all_passed) {
    //    errDiv.style.display="";
    //}
    //else{
    //    errDiv.style.display="none";
    //}
   
    return b_vins_all_passed;
}

function _validate_single_vin(s_vin_raw)
{
    var s_vin=trim(s_vin_raw);
    if(s_vin=="")
    {
        return "Invalid: Please enter your VIN.";
    } 
    
    /// invalidate "Less Than 17 character entry"
     if(s_vin.length<17)
     {
        return "Invalid: Less than 17 characters in length. A valid VIN must be exactly 17 characters long.";
    }
    /// invalidate "Longer Than 17 character entry"
     if(s_vin.length>17)
     {
        return "Invalid: More than 17 characters in length. A valid VIN must be exactly 17 characters long.";
     }
     /// invalidate a VIN containing letter U and letter 0 in the 10th digit(Model Year digit)
     var sYearDigit;
     sYearDigit=s_vin.substr(9,1);     
    if (sYearDigit=='U' || sYearDigit=='u')
    {
        return "Invalid: A VIN cannot contain letter U in the 10th position.";
    }
    if (sYearDigit=='Z' || sYearDigit=='z')
    {
        return "Invalid: A VIN cannot contain letter Z in the 10th position.";
    }        
    if (sYearDigit=='0')
    {
        return "Invalid: A VIN cannot contain number 0 in the 10th position.";
    }     
     //// invalidate Non-Alphnumeric characters
     var reAlphnumeric = /^[a-zA-Z0-9]+$/;
     if (!reAlphnumeric.test(s_vin))
     {
        return "Invalid: A VIN can only contain Alphanumeric characters.";
     }
     /// invalidate any entries containing "I or i", "O or o" or "Q or q"
     var reI =/I/i;
     
     if (reI.test(s_vin))
     {
         return "Invalid: A VIN cannot contain letters I, O or Q.";
     }     
     var reO=/O/i;
     if (reO.test(s_vin))
     {
        return "Invalid: A VIN cannot contain letters I, O or Q.";
     }          
     var reQ=/Q/i;
     if (reQ.test(s_vin))
     {
        return "Invalid: A VIN cannot contain letters I, O or Q.";
     }              
     var sLastFiveDigits=s_vin.substr(12,5);
     if (!IsNumeric(sLastFiveDigits))
     {  
        return "Invalid: Each and every digit of the last five positions in a VIN must be numeric.";
     }
          
     if (!_validate_check_digit(s_vin))
     {
         return "Invalid: This VIN did not pass checksum test.";
     }
     return "Valid";
}

function _validate_check_digit(s_vin_raw)
{
    var s_vin=s_vin_raw.toUpperCase();
    var s_chk_digit_user;
    var s_chk_digit_calced;
    s_chk_digit_user=s_vin.substr(8,1);
    s_chk_digit_calced=_calced_remainder(s_vin);
    if(s_chk_digit_user==s_chk_digit_calced)
    {
        return true;
    }
    else{
        return false;
    }
}

function _calced_remainder(s_vin)
{
    var i, iTotal, iRemainer;
    iTotal=0;
    for(i=1;i<18;i++)
    {
        iTotal +=_calced_product(i,s_vin);
    }
    iRemainder=iTotal%11;
    if (iRemainder==10)
    {
        return "X";
    }
    else
    {
        return iRemainder;
    }
}

function _calced_product(iPos,s_vin)
{
    return _get_numeric_value(iPos,s_vin)*_get_weight_factor(iPos);
}

function _get_numeric_value(iPos,s_vin)
{
    var s_digit=s_vin.substr(iPos-1,1);
    if (isNaN(parseInt(s_digit)))
    {
        return _assign_numeric_value(s_digit);
    }
    else
    {
        return parseInt(s_digit);
    }
}
function _assign_numeric_value(s_digit)
{
    switch(s_digit)
    {
        case "A":
            return 1;
        case "B":
            return 2;
        case "C":
            return 3;
        case "D":
            return 4;
        case "E":
            return 5;
        case "F":
            return 6;
        case "G":
            return 7;
        case "H":
            return 8;
        case "J":
            return 1;
        case "K":
            return 2;
        case "L":
            return 3;
        case "M":
            return 4;
        case "N":
            return 5;
        case "P":
            return 7;
        case "R":
            return 9;
        case "S":
            return 2;
        case "T":
            return 3;
        case "U":
            return 4;
        case "V":
            return 5;
        case "W":
            return 6;
        case "X":
            return 7;
        case "Y":
            return 8;
        case "Z":
            return 9;
    }
}

function _get_weight_factor(iPos)
{
    switch(iPos)
    {
        case 1:
            return 8;
        case 2:
            return 7;
        case 3:
            return 6;
        case 4:
            return 5;
        case 5:
            return 4;
        case 6:
            return 3;
        case 7:
            return 2;
        case 8:
            return 10;
        case 9:
            return 0;
        case 10:
            return 9;
        case 11:
            return 8;
        case 12:
            return 7;
        case 13:
            return 6;
        case 14:
            return 5;
        case 15:
            return 4; 
        case 16:
            return 3;
        case 17:
            return 2;                                
    }
}



function _insert_validationn_msg(src,tbody,s_data1,s_data2,delimiter)
{
    if (s_data2!="Valid"){
        if (s_data1=="") {s_data1="EMPTY VIN";}
        var mytablebody=document.getElementById (tbody);
        var rows=mytablebody.rows;
        //alert(rows.length)
        var mycurrent_row = document.createElement("tr");
        var mycurrent_cell = document.createElement("td");
        //s_data1=s_data1.replace()
        //currenttext = document.createTextNode(s_data1);
        //mycurrent_cell.appendChild(currenttext);
        mycurrent_cell.innerHTML="<span style='font-weight:bold;'>"+s_data1+"</span>";
        mycurrent_row.appendChild(mycurrent_cell);
        mycurrent_cell = document.createElement("td");
        mycurrent_cell.innerHTML="<span style='color:Red;'>"+s_data2+"</span>&nbsp;<a style='color:blue' href='javascript:locate_it(\""+src+"\",\""+s_data1+"\",\""+delimiter+"\")'>locate it...</a>";
        mycurrent_row.appendChild(mycurrent_cell);
        mytablebody.appendChild(mycurrent_row);
        //var i=rows.length+1;
        //if(i%2==0) { 
            //mycurrent_row.style.backgroundColor = "#EEEEEE";
        //}   
        //else {
            //mycurrent_row.style.backgroundColor = "white";
        //}
    }
    return;
}

function locate_it(src,svin,delimiter)
{
    _find_in_TextArea(src,svin,delimiter);
    return;
}

//var NS = (document.layers);
//var IE = (document.all);
var win = this;
var n = 0;
function _find_in_TextArea(strTextAreaId,strToFind,delimiter)
{
    n=0;
    if (strToFind=="EMPTY VIN"){strToFind=",,";}
    if (strToFind.length<17 || strToFind.length>0 || delimiter==",")
    {
        strToFind=="\,"+strToFind+"\,";
    }
    //if (strToFind.length<17 || delimiter=="")
    //{
    //    strToFind=strToFind+"\r\n";
    //}    
    var txt, i, found;
    //if (strToFind == "")return false;
    if (navigator.appName=="Netscape")
    {
        if (!win.find(strToFind))while(win.find(strToFind, false, true))n++;else n++;
        if (n == 0) alert(strToFind + " was not found on this page.");
    }
    if (navigator.appName.indexOf("Microsoft")!=-1)
     {
        //txt = document.body.createTextRange();
        var ta=document.getElementById(strTextAreaId);
        txt=ta.createTextRange();
        //txt = document.aspnetForm.ctl00$SiteMaster$txtVINsUploaded.createTextRange();
        for (i = 0; i <= n && (found = txt.findText(strToFind,2)) != false; i++)
        {
            //if (delimiter==","){
                txt.moveStart("character", 1);
            //}else{
                //txt.moveStart("word", 1);
            //}
            txt.moveEnd("textedit");
        }
        
        if (found)
        {
            //if (delimiter==","){
                txt.moveStart("character", -1);
            //else{
                //txt.moveStart("word", -1);
            //}
            txt.findText(strToFind,2);
            txt.select();
            txt.scrollIntoView();
            n++;
        }
        else
        {
            if (n > 0)
            {
                n = 0;
                findInTextArea(strTextAreaId,strToFind);
            }
            else { alert("After correct or remove a VIN, click the 'Decode them' button to refresh Validation Messages.");}
         }
    }
    return;
}
function _clear_table(sTbodyId)
{   
    var tbl=document.getElementById ("tblErrors");
    tbl.removeChild(tbl.tBodies[0]);
    _create_tbody(sTbodyId);
    return;
}

function _create_tbody(sTbodyId)
{
      var tbl=document.getElementById("tblErrors");
      var tbd=document.createElement("tbody");
      tbd.id="tbdErrors";
      tbl.appendChild(tbd);
}

//First, leading and trailing spaces are removed from the string in a couple 
//of statements. Build a regular expression statement that will find one or 
//more starting white space characters (space, tab, form feed, or line feed), 
//then any character (\W\w ends up being anything), then one or more ending 
//white spaces after a word boundary. If that pattern is found in the input 
//string, maintain only the middle characters (the \W\w part). 

//To trim interior consecutive spaces, set up the regular expression object 
//to hold two spaces (var obj = /  /g; has 2 spaces). While 2 spaces is somewhere 
//in the string, replace all consecutive spaces with a single space. This only 
//does one pass through, so if there were 3 consecutive spaces, it would replace 
//the first 2 with a single space and end up with 2 spaces still. So the while 
//loop is necessary. 

//Note that if you only want to trim the leading and trailing spaces 
//(and not get rid of interior consecutive spaces), you can get rid 
//of the second instance where "obj" is set, and the while loop. 

function trim(value) {
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp)) { temp = temp.replace(obj, '$2'); }
   var obj = /  /g;
   while (temp.match(obj)) { temp = temp.replace(obj, " "); }
   return temp;
}

function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }
