
function trim(input) {
    var lre = /^\s*/;
    var rre = /\s*$/;
    input = input.replace(lre, "");
    input = input.replace(rre, "");
    return input;
}
function validChar(email){
    var Chars = "0123456789-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_@.";
    var tempstr = email;
    for (var i = 0; i < tempstr.length; i++) {
       if (Chars.indexOf(tempstr.charAt(i)) == -1) {
            return false;
       }
    }
    return true;
}
function checkEmail(email){
    if (email==null)return -1 ;
    if (email.length==0)return -5;
    if (!validChar(email)) return -50;
    var atIdx = email.lastIndexOf("@");
    if (atIdx==0) return -10 ;
    if (atIdx<0) return -15 ;
    if (atIdx== email.length-1) return -20 ;
    if (atIdx > 64) return -25 ;
    if (email.length - atIdx ==255 ) return -30 ;
    if (email.substring(atIdx - 1, atIdx )=="." ) return -35 ; // can't have '.' before '@'
    if (email.indexOf(".")==0)return -40 ;
    if (email.indexOf(" ")>=0)return  -45 ; // no space allowed for our mail server
    // 50 and 55 is specially for local part
    var domain = email.substring(atIdx , email.length-1);
    if (domain==null || domain.indexOf(".")<0 ) return -60 ; // missing domain
    if (email.substring(atIdx + 1, atIdx +2)=="." ) return -65 ; // can't have '.' after '@'
    return "";
}
function checkEmailWithMsg(email){return  getEmailErrorMsg(checkEmail(email)) ;}
function checkEmailLocalPartWithMsg(email){return  getEmailErrorMsg(checkLocalPart(email)) ;}

function checkLocalPart(email){
    if (email==null)return -1 ;
    if (email.length==0)return -5;
    if (!validChar(email)) return -50;
    if (email.indexOf(" ")>=0)return  -45 ; // no space allowed for our mail server
    if (email.lastIndexOf("@")>=0)  return -55 ;
    var dotidx = email.lastIndexOf("."); 
    if (dotidx>=0 && (dotidx == email.length-1) )return -35 ;// can't have '.' before '@'
    return 0;
}
function getEmailErrorMsg(resultInt) {
    switch(resultInt){
        case -5: return "It is empty";
        case -10: return "Missing local part";
        case -15: return "Missing '@'.";
        case -20: return "Should not place '@' at the end."; 
        case -25: return "No more 64 characters in local part(before @).";
        case -30: return "No more than 255 characters in domain part (after '@').";
        case -35: return "Should not place '.' before '@'.";
        case -40: return "Should not place '.' at the beginning.";
        case -45: return "Should not place space in the address."; 
        case -50: return "Invalid character"; 
        case -55: return "Should not contain more than 1 '@'";
        case -60: return "Missing domain '@'";
        case -65: return "Should not place '.' after '@'."; 
    }
    return "";
}

