/*
 * Function name   : isCharsInBag()
 * Description     : This function for common validation
 * Created On      : 01-07-2010 (11:20am)
 *
 */
function isCharsInBag (s, bag)
  {
    var i;
    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) return false;
    }
    return true;
 }

/*
 * Function name   : validateemail()
 * Description     : This function for email validation
 * Created On      : 01-07-2010 (11:49am)
 *
 */
function validateemail(email) {
    var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
     if(email=="")
     {
         return true;
     }
     if(!email.match(emailRegex))
      {
        return true;
      }
    return false;
}
/*
 * Function name   : isUserName()
 * Description     : This function for UserName validation
 * Created On      : 01-07-2010 (11:49am)
 *
 */

function isUserName(s){
    return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_@.");
}
/*
 * Function name   : isFirstName()
 * Description     : This function for FirstName validation
 * Created On      : 01-07-2010 (11:49am)
 *
 */
function isFirstName(s){
	s=trim(s);
	return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' ");
}
/*
 * Function name   : isCity()
 * Description     : This function for City validation
 * Created On      : 01-07-2010 (11:49am)
 *
 */
function isCity(s){
	s=trim(s);
	return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ");
}
/*
 * Function name   : isnumerice()
 * Description     : This function for numeric field validation
 * Created On      : 01-07-2010 (11:49am)
 *
 */
function isnumerice(s){
	s=trim(s);
	return isCharsInBag (s, "0123456789");
}

function isalphanumerice(s){
	s=trim(s);
	return isCharsInBag (s, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
}

//end
/*
 * Function name   : ParseUSNumber()
 * Description     : This function for phone number validation 
 * Created On      : 29-06-2010 (12:52pm)
 *
 */
function ParseUSNumber(PhoneNumberInitialString)
  {
    var FmtStr="";
    var index = 0;
    var LimitCheck;

    LimitCheck = PhoneNumberInitialString.length;
    while (index != LimitCheck)
      {
        if (isNaN(parseInt(PhoneNumberInitialString.charAt(index))))
          { }
        else
          { FmtStr = FmtStr + PhoneNumberInitialString.charAt(index); }
        index = index + 1;
      }
    if (FmtStr.length == 10)
      {
        FmtStr = "(" + FmtStr.substring(0,3) + ") " + FmtStr.substring(3,6) + "-" + FmtStr.substring(6,10);
      }
    else
      {
        FmtStr=PhoneNumberInitialString;
        return false;
      }
    return true;
  }

function defaultfocus()
{
	$(document).ready(function() {
	    $('form:first *:input[type!=hidden]:first').focus();
	});
}


var commonPasswords = new Array('password', 'pass', '1234', '1246'); 
 
var numbers = "0123456789"; 
var lowercase = "abcdefghijklmnopqrstuvwxyz"; 
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
var punctuation = "!.@$£#*()%~<>{}[]"; 
 
function checkPassword(password) { 
    
    var combinations = 0; 
  
    if (contains(password, numbers) > 0) { 
        combinations += 10; 
    } 
 
    if (contains(password, lowercase) > 0) { 
        combinations += 26; 
    } 
 
    if (contains(password, uppercase) > 0) { 
        combinations += 26; 
    } 
 
    if (contains(password, punctuation) > 0) { 
        combinations += punctuation.length; 
    } 
 
    // work out the total combinations 
    var totalCombinations = Math.pow(combinations, password.length); 
 
    // if the password is a common password, then everthing changes... 
    if (isCommonPassword(password)) { 
        totalCombinations = 75000 // about the size of the dictionary 
    } 
 
    // work out how long it would take to crack this (@ 200 attempts per second) 
    var timeInSeconds = (totalCombinations / 200) / 2; 
 
    // this is how many days? (there are 86,400 seconds in a day. 
    var timeInDays = timeInSeconds / 86400 
 
    // how long we want it to last 
    var lifetime = 365; 
 
    // how close is the time to the projected time? 
    var percentage = timeInDays / lifetime; 
 
    var friendlyPercentage = cap(Math.round(percentage * 100), 100); 
    if (totalCombinations != 75000 && friendlyPercentage < (password.length * 5)) { 
        friendlyPercentage += password.length * 5; 
    } 
 
    var progressBar = document.getElementById("progressBar"); 
    progressBar.style.width = friendlyPercentage + "%"; 
 
    if (percentage > 1) { 
        // strong password 
        progressBar.style.backgroundColor = "#3bce08"; 
        return; 
    } 
 
    if (percentage > 0.5) { 
        // reasonable password 
        progressBar.style.backgroundColor = "#ffd801"; 
        return; 
    } 
 
    if (percentage > 0.10) { 
        // weak password 
        progressBar.style.backgroundColor = "orange"; 
        return; 
    } 
 
    // useless password! 
    if (percentage <= 0.10) { 
        // weak password 
        progressBar.style.backgroundColor = "red"; 
        return; 
    } 
 
 
} 
 
function cap(number, max) { 
    if (number > max) { 
        return max; 
    } else { 
        return number; 
    } 
} 
 
function isCommonPassword(password) { 
 
    for (i = 0; i < commonPasswords.length; i++) { 
        var commonPassword = commonPasswords[i]; 
        if (password == commonPassword) { 
            return true; 
        } 
    } 
 
    return false; 
 
} 
 
function contains(password, validChars) { 
 
   var count = 0; 
   var i;
    for (i = 0; i < password.length; i++) { 
        var char = password.charAt(i); 
        if (validChars.indexOf(char) > -1) { 
            count++; 
        } 
    } 
 
    return count; 
} 
 
 

/*
 * Function name   : passwordChanged()
 * Description     : This function for change the password 
 * Created On      : 17-02-10 (12:15am)
 *
 */	
 
 
function passwordChanged() {
var strength = document.getElementById('strength');
var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
var enoughRegex = new RegExp("(?=.{6,}).*", "g");
var pwd = document.getElementById("password");
if (pwd.value.length==0) {
strength.innerHTML = 'Type Password';
} else if (false == enoughRegex.test(pwd.value)) {
strength.innerHTML = 'More Characters';
} else if (strongRegex.test(pwd.value)) {
strength.innerHTML = '<span style="color:green">Strong!</span>';
} else if (mediumRegex.test(pwd.value)) {
strength.innerHTML = '<span style="color:orange">Medium!</span>';
} else {
strength.innerHTML = '<span style="color:red">Weak!</span>';
}
}

/*
 * Function name   : passwordChanged()
 * Description     : This function for check  the hasWhiteSpace 
 * Created On      : 17-02-10 (12:15am)
 *
 */	
 

function hasWhiteSpace(strg) 
{
	var whiteSpaceExp=/^\s+$/;
	if (whiteSpaceExp.test(strg))
	return true;
	else
	return false;
}
function tagValidate(strg)
{
var tagexp =/([\<])([^\>]{1,})*([\>])/i;
if (tagexp.test(strg)) {
	return true;
}
	else {
	return false;
}
}


//START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;  
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80); 
  arrow.src = "/img/msg_arrow.gif"; 
}



/*
 * Function name   : trim()
 * Description     : This function for trim the white space 
 * Created On      : 17-02-10 (12:15am)
 *
 */	
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}


/*
 * Function name   : checkadminpasswordform()
 * Description     : This function for check the admin password 
 * Created On      : 15-02-11 (11:00pm)
 *
 */	
function checkadminpasswordform() {
	var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
	var email = document.getElementById('Field1');
	 if(email.value =="")
	 {
		 inlineMsg('Field1','<strong>You must enter your Email-ID</strong>',2);
		 return false;
	 }
	 if(!email.value.match(emailRegex)) 
	  {
	    inlineMsg('Field1','<strong>Invalid Email.</strong>',2);
	    return false;
	  }
	return true;
}



function trimNumber(s) {
	  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
	  return s;
	}


/*
 * Function name   : validateholder()
 * Description     : This function is used for validation of holder (add/edit)
 * Created On      : 16-02-2011 (05:50am)
 *
 */

function validatecontact(){	

    if(trim(document.getElementById('address').value) == '')
	 {
		 alert('street address required.');
		 document.getElementById('address').focus();
		 return false;
	 }
	 if(tagValidate(document.getElementById('address').value) == true){		
		 alert('Please dont use script tags.');
		 document.getElementById('address').focus();
		 return false; 
	 } 
	  if(trim(document.getElementById('city').value) == '')
	 {
		 alert('city required.');
		 document.getElementById('city').focus();
		 return false;
	 }
	 if(tagValidate(document.getElementById('city').value) == true){		
		 alert('Please dont use script tags.');
		 document.getElementById('city').focus();
		 return false; 
	 } 

	   if(trim(document.getElementById('postal').value) == '')
	 {
		 alert('postal required.');
		 document.getElementById('postal').focus();
		 return false;
	 }
	 if(tagValidate(document.getElementById('postal').value) == true){		
		 alert('Please dont use script tags.');
		 document.getElementById('postal').focus();
		 return false; 
	 } 

	 

	if(!(document.getElementById('agree').checked))
	 {
		  alert('Please accept terms.');
		 document.getElementById('agree').focus();
		 return false; 
	 }
	 return true;
	
	
}

function getstates(countryid,modelname) {
	   if(countryid==""){
	      return false;
	   }

       jQuery.ajax({
             type: "GET",
             url: '/users/selectstate/'+countryid+'/'+modelname,
             cache: false,
             success: function(rText){
                 //  alert(rText);
                     jQuery('#statediv').html(rText);
             }
     });
	  
}
function getstates1(countryid,modelname) {
	   if(countryid==""){
	      return false;
	   }

       jQuery.ajax({
             type: "GET",
             url: '/users/selectstate/'+countryid+'/'+modelname,
             cache: false,
             success: function(rText){
                 //  alert(rText);
                     jQuery('#statediv1').html(rText);
             }
     });
	  
}
