/**
 * utility.js
 * Javascript to manage form fields attributes and behaviours
 */
 
$(document).ready(function() {
	
	jqueryExtendedFunctions();
	handlePromoForm();	
	handleLoginForm();
	handleForgotForm();
	handleResetForm();
	handlePopUps();
	handleRecaptcha();
	handleButtons();
	handleHelpBubble();
});

/**
 * Javascript function to show field title in the field value on being called
 */
function showTitleText(fieldID)
{

	var $input = $("#"+fieldID),
	title = $input.attr('title');
	if(!$input.val()) {
			$input.val(title);
            $input.addClass("txt_grey");
	}
	$input.bind('blur', function() {
		if (this.value === '') {
			$input.val(title);
            $input.addClass("txt_grey");
		}
	});	
	$input.bind('focus', function() { 
		if ($input.val() === title) {
            $input.removeClass("txt_grey");
			$input.val('');
		}
	});
}


/**
 * Extending Jquery password strength class
 */
$.fn.passwordStrength = function( options ){
	return this.each(function(){
		var that = this;that.opts = {};
		that.opts = $.extend({}, $.fn.passwordStrength.defaults, options);

		that.div = $(that.opts.targetDiv);
		that.defaultClass = that.div.attr('class');

		that.percents = (that.opts.classes.length) ? 100 / that.opts.classes.length : 100;

		v = $(this)
		.keyup(function(){
			if( typeof el == "undefined" )
			this.el = $(this);
			var s = getPasswordStrength (this.value);
			if(this.value.length > 0) {
				var p = this.percents;
				var t = Math.floor( s / p );
	
				if( 100 <= s )
				t = this.opts.classes.length - 1;
	
				this.div
				.removeAttr('class')
				.addClass( this.defaultClass )
				.addClass( this.opts.classes[ t ] );
			}
			else{
				this.div
				.removeAttr('class')
				.addClass( this.defaultClass );
			}
		})
		
	});

	function getPasswordStrength(H){
		var D=(H.length);
        var E=0;
        if (D) {
            var num = (/[0-9]/m.test(H)) ? 1 : 0;
            var small = (/[a-z]/m.test(H)) ? 1 : 0;
            var big = (/[A-Z]/m.test(H)) ? 1 : 0;
            var special = (/[!@#$%^&*()_+\-={}\]\[\|":;,<.>?`~']/m.test(H)) ? 1 : 0;
            var types = parseInt(num) + parseInt(small) + parseInt(big) + parseInt(special);
            if (D < 8) {
                if(types==1){E=0}else{E=5}
            } else {
                if(types==1){E=0}else if(types==2){E=5}else if((types==3) || (types==4)){E=10}
            }
		}
		var F=E*10;
		if(F<0){F=0}
		if(F>100){F=100}
		return F
	}
};

function handlePromoForm()
{
	if($("#register_promo_form").length > 0) {
		$("#register_promo_form").validate({
			rules: {
				registration_code: {
					required: true
				}
			},
			messages: {
				registration_code: {
					required: 'Registration code is required.'
				}
			},
            errorElement: "div"
		});	
	}
}

/**
 * Handle the login form
 * Validate the  form
 * If valid login redirect to profile page
 */
function handleLoginForm() {
	if($("#login_form").length > 0) {
		$("#login_form").validate({
		  rules: {
			useremail: {
				required: true,
			    emailExtended: true
			},		
			userpass: {
				required: true,
				rangelength:[6,16]
			}// ,
			// recaptcha_response_field: {
			//     recaptchaResponse: true
			// }
		  },
		  messages:{
		  	useremail:{
				required:"Email address is required"
		  	},
		  	userpass:{
				required:"Password is required",
				rangelength:'Minimum length 6 characters'
		  	}
		  },
		  errorElement: "div"
		});	
	
		$("#login_form").bind("submit", function(event){
		    
			if(!checkCookieEnabled()) {
				$("#login_message").show().html("Cookie support must be enabled in browser!")
				.addClass("error_msg");
				return false;
			}			
		   if($("#login_form").valid()) {
			  		$("#login_message").show()
			  		.html("<img src='"+siteLocation+"images/spinner.gif' /> Connecting...")
			  		.removeClass("error_msg").addClass("info_msg");
		    	$.ajax({
				    type: "POST",
				    url: securedSiteLocation + "login",
				    data: "useremail="+encodeURIComponent($("#login_email").val())+
				    "&userpass="+encodeURIComponent($("#login_pwd").val())+
				    "&recaptcha_response_field="+recaptcha_response()+"&recaptcha_challenge_field="+recaptcha_challenge(),
				    datatype: "json",
				    cache: false,
				    async: true,
				    success: function(msg){
				        try {
                             var myObject = JSON.parse(msg);
                        } catch (e) {
                            $("#login_message").html('Error occurred during authentication. Please try again.').removeClass("info_msg")
                            .addClass("error_msg").show();
                            return false;
                        }    
				        if(typeof(myObject.error) == 'undefined') {
					     	 $("#login_message").html( myObject.email + myObject.pass +
                              myObject.recaptcha).show()
					     	 .removeClass("info_msg").addClass("error_msg");
					     	 login_form_recaptcha();
				        } else {
				            if( myObject.error ) {
					     		$("#login_message").html( myObject.error ).show()
					     		.removeClass("info_msg").addClass("error_msg");
					     		login_form_recaptcha();
				     	    } else {
					     		$("#login_message").show()
					     		.html("Login successful, redirecting to your profile page...");
					     		tb_remove();
                                $("#login_link").hide();
                                 document.body.style.cursor='wait';
		                        if(typeof(overlayDropoffUrl) != 'undefined' && overlayDropoffUrl.length > 0) {
        	                        window.location = overlayDropoffUrl;
                                } else {
					     		    window.location = siteLocation + "pre-register/success";
                                }
				     	    }
				     	
				        }
				    },
			   	    error:function(){
			   	        $("#login_message").html('Error occurred during authentication. Please try again.').removeClass("info_msg")
				        .addClass("error_msg").show();
			   	    }
				 });
		    	 return false;
		     }
		});	
	}
}

/**
 * Handle the forgot password form
 * Validate the  form
 * 
 */
function handleForgotForm() {
	
	if($("#forgot_form").length > 0) {		
	
		$("#forgot_form").validate({
		  rules: {
			useremail_forgot: {
			  required: true,
			  emailExtended: true
			}// ,
			// recaptcha_response_field : {
			//      required:true
			//}
		  },
		  messages:{
		  	useremail_forgot:{
				required:"Email address is required"
		  	}// ,
		  	// recaptcha_response_field : {
		  	//     required:'Enter the words you see in the box'
		  	// }
		  },
		  errorElement: "div"
		});
		$("#forgot_form").bind("submit", function(event){
		   if($("#forgot_form").valid()) {
			  	$("#forgot_message").show()
			  	.html("<img src='"+siteLocation+"images/spinner.gif' /> Connecting...")
			  	.removeClass("error_msg").addClass("info_msg");
		    	$.ajax({
				   type: "POST",
				   url: siteLocation + "forgot_pass",
				   data: "useremail="+encodeURIComponent($("#login_email_fgt").val())+
				    "&recaptcha_response_field="+recaptcha_response()+"&recaptcha_challenge_field="+recaptcha_challenge(),
				   datatype: "json",
				   cache: false,
				   success: function(msg){	
    			       try {
                           var myObject = JSON.parse(msg);
                       } catch (e) {
                       	   $("#forgot_message").html('Sorry! Service disconnected.').removeClass("info_msg")
                           .addClass("error_msg").show();
                           return false;
                       }
    				   if(typeof(myObject.email) != 'undefined' || typeof(myObject.recaptcha) != 'undefined') {
    				   	   $("#forgot_message").html( myObject.email + myObject.recaptcha ).show().removeClass("info_msg")
    				       .addClass("error_msg");
    				       forgot_password_recaptcha();
    				   } else {
    				       if( myObject.error) {
    				           $("#forgot_message").html( myObject.error ).show().removeClass("info_msg")
    				     	   .addClass("error_msg");
    				     	   forgot_password_recaptcha();
    				     	} else {
    				     	    $("#forgot_form_area").hide();
                                $("#forgot_message").html( myObject.success ).show();
                                okButton = "<div class='btn_wrppr' id='forgotOkayButton'>"+
                                "<input type='button' value='' class='btn_ok' onClick=\""+
                                "showLogin();\""+
                                " /></div>";
                                $("#forgot_message" ).after(okButton);
    				     	}
    				   }
				   },
			   	   error:function(){
			   	       $("#forgot_message").html('Sorry! Service disconnected.').removeClass("info_msg")
				       .addClass("error_msg").show();
			   	   }
				 });
		    	return false;
		  }
		});
	}
}

function handleResetForm()
{
	if($("#reset_form").length > 0)
	{
		$('#UserNewPass')
		.passwordStrength({targetDiv: '#showPassStrength',classes : Array('weak','medium','strong')});
		$("#reset_form").validate({
		  rules: {
			usernewpass: {
			  required: true,
			  rangelength:[6,16],
			  prohibittedchars:true
			},
			usernewpassconfirm: {
			  required: true,
			  prohibittedchars:true,
			  equalTo:'#UserNewPass'
			}
		  },
		  messages:{
		  	usernewpass:{
				required:'New Password is required',
				rangelength:'Minimum length 6 characters',
				prohibittedchars:'Invalid password'				
		  	},
		  	usernewpassconfirm:{
				required:'Confirm password is required',
				prohibittedchars:'Invalid confirm password',
				equalTo:'Must match the new password'
		  	}
		  },
		  errorElement: "div"
		});
	}
}

function handlePopUps()
{
    $("#pwd_link").click(function(event){
		forgot_password_recaptcha();
		event.preventDefault();
		$("#login_form").validate().resetForm();
		document.getElementById('login_form').reset();
		$("#user_login").hide();
        $("#forgot_message").html('');
		$("#pwd_get").show();

	});
	$("#cancel_btn").click(function(event){
	    login_form_recaptcha();
        $("#forgot_form").validate().resetForm();
        document.getElementById('forgot_form').reset();
        $("#pwd_get").hide();
        $("#login_message").html('');
        $("#user_login").show();
	});
	$("#login_cancel").click(function(event){
		if(typeof(overlayReturnUrl) != 'undefined' ) {
        	window.location = overlayReturnUrl;
        }else {
        	window.location = siteLocation;
        }
        tb_remove();
		$("#login_form").validate().resetForm();
        $("#login_message").html('');
        document.getElementById('login_form').reset();       
        $("#forgot_form").validate().resetForm();
        $("#forgot_form_area").show();
        $("#forgot_message").html('');
        if($("#forgotOkayButton").length > 0) {
            $("#forgotOkayButton").remove();
        }
		$("#pwd_get").hide();
        document.getElementById('forgot_form').reset();        
	});
}

function showLogin()
{    
    $("#pwd_get").hide();
    $("#login_message").html('');
    $("#user_login").show();
    $("#forgot_form_area").show();
    $("#forgot_message").html('');
    if($("#forgotOkayButton").length > 0) {
        $("#forgotOkayButton").remove();
    }
    document.getElementById('forgot_form').reset();
}

function showRecaptcha(public_key, element, themeName){
	if(Recaptcha) {
		Recaptcha.create(public_key, element, {
	        theme: themeName,
	        tabindex: 0,
	        callback: Recaptcha.focus_response_field
		}); 
	} 
}

function destroyRecaptcha(){  
	if(Recaptcha) {
  		Recaptcha.destroy();
  	}
}

function handleRecaptcha()
{
	$("#login_box_button,#my_account_login").click(function(event){
		login_form_recaptcha();
	});
}

function recaptcha_response(){
	if(Recaptcha && Recaptcha.get_response()) {
		return Recaptcha.get_response();
	}
}

function recaptcha_challenge(){
	if(Recaptcha && Recaptcha.get_challenge()) {
		return Recaptcha.get_challenge();
	}
}

function login_form_recaptcha()
{
	var login_count = getCookie('login_count');	
	if(recaptcha_public_key && login_count && login_count >= 5) {
		destroyRecaptcha();
		$("#TB_ajaxContent").height(560);
		$("#lbl_recaptcha").show();
		showRecaptcha(recaptcha_public_key, 'dynamic_recaptcha_1', 'red');
	}	
}

function forgot_password_recaptcha()
{
	$("#TB_ajaxContent").height(490);
    destroyRecaptcha();
    showRecaptcha(recaptcha_public_key, 'dynamic_recaptcha_2', 'red');
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}

function jqueryExtendedFunctions()
{
	jQuery.fn.extend({
		wrapText: function(word_max_length){			
			return $(this).html(wordwrap($(this).text(), word_max_length));			
	  	}
	});
}

function wordwrap(text, word_max_length)
{
	var user_agent = navigator.appVersion.replace(/\s/g,'');
	var aText = text.split(' ');
	for(var i=0; i < aText.length; i++) {
		if(aText[i].length > word_max_length) {
			var aTmpTxt = aText[i].match(RegExp('.{1,'+word_max_length+'}','g'));
			if(/MSIE8.0/.test(user_agent)) {
				aText[i] = aTmpTxt.join('&#8203;');	
			} else {
				aText[i] = aTmpTxt.join('<wbr>');
			}
		}
	}
	return aText.join(' ');	
}

function daysInFebruary (year)
{	
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

//checks non white space 7 bit ascii chars 
jQuery.validator.addMethod("prohibittedchars", function(value, element){
	if ((!value) || /^[\x21-\x7E]+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Prohibitted characters!");

//checks 7 bit ascii chars
jQuery.validator.addMethod("checknonascii", function(value, element){
	if(value) {
		return (/^[\x20-\x7E]+$/.test(value)) && (!((/&(#)?[a-zA-Z0-9]*;/.test(value)) ||
           value.match(/<(\/)?script\b[^>]*>/)));
	} else {
		return true;
	}
},"Prohibitted characters!");

jQuery.validator.addMethod("checktitle", function(value, element){
	if (value == element.title) {
		return false;
	} else {
		return true;
	}
},"Oops! Invalid.");

jQuery.validator.addMethod("checkzip", function(value, element){
	if (/^[0-9]{5}$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Invalid Zip Code.");

jQuery.validator.addMethod("checkstate", function(value, element){
	if (/^[A-Za-z]{2}$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Please provide state");

jQuery.validator.addMethod("checknumtitle", function(value, element){
	if(value) {		
		if (value == element.title) {
			return true;
		} else {
			var patt=/^[0-9]+$/;
			if (patt.test(value)) {
				return true;
			} else {
				return false;
			}
		}
	} else {
		return true;
	}
},"Oops! Invalid.");

jQuery.validator.addMethod("checkchars", function(value, element){
					
	if (/^[A-Za-z]+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Invalid");

jQuery.validator.addMethod("checkTagChars", function(value, element){
    /*var newVal = value.replace(/[\s]{2,}/g,' ')
                  .replace(/[\-]{2,}/g,'-')
                  .replace(/[\_]{2,}/g,'_');*/
    element.value = $.trim(value);
    if (/^([A-Za-z0-9\_\-\s'])+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Player Tag may only contain non-international letters, numbers, spaces, underscores and dashes.");

jQuery.validator.addMethod("checkMottoChars", function(value, element){
	if (/^([A-Za-z0-9\s!._?,:'"\-])+$/.test(value)) {
	  return true;
	} else {
	  return false;
	}
},"Unsupported characters!");

jQuery.validator.addMethod("checkQAChars", function(value, element, params){
	if(params == 'Q') {
		if (/^([A-Za-z0-9\s\?])+$/.test(value)) {
		  return true;
		}
	} else {
	  if (/^([A-Za-z0-9\s])+$/.test(value)) {
		  return true;
		}
	}
	return false;
},"Unsupported characters!");

jQuery.validator.addMethod("cardexpiry", function(value, element){
		
		var expirymonth=$('#expiryMonth').val();
		var expiryyear=$('#expiryYear').val();	
		if (expirymonth != '' && expiryyear != '' && 
				!isNaN(expirymonth) && !isNaN(expiryyear)){	
						
			daysarr=DaysArray(12);
			expirydate=daysarr[expirymonth];
			if (expirymonth==2) {
				expirydate=daysInFebruary(expiryyear);
			}
			var sdate=new Date();
			//selected date
			sdate.setDate(expirydate);
			sdate.setMonth(expirymonth-1);
			sdate.setFullYear(expiryyear);
			var stime=sdate.getTime();
			//present date
			var pdate=new Date();
			var ptime=pdate.getTime()
			if (ptime > stime) {
				return false;
			} else {				
				$('#expiryYear.error_msg').removeClass('error_msg');
				return true;
			}			
		} else {
			return true;
		}
},"Please provide valid expiration date");

jQuery.validator.addMethod("checkcvv", function(value, element){
    var thisval = $.trim(value);
    var ccnum = $.trim($('#cardNum').val());
	if(/^[\*]{3,4}$/.test(thisval) && /^[\*]+[0-9]{4}$/.test(ccnum))
	return true;
	if(thisval && /^[0-9]{3,4}$/.test(thisval)) {
  	    switch($('#creditCardType').val()){
  	    	case 'AmericanExpress':
  	    		if(thisval.length==4)
  	    			return true;
  	    		else
  	    			return false;
  	    		break;
  	    	default:
  	    		if(thisval.length==3)
  	    		    return true;
  	    	    else
  	    		    return false;
  	    }
	} else {
		return false;
	}
},"Security code is invalid.");

jQuery.validator.addMethod("restrictInput", function(value, element, params){
		if (value.length > params) {
			element.value = value.substr(0,params);
		}
        return true;
},"Oops! Maximum limit:{0} reached.");

jQuery.validator.addMethod("emailExtended", function(value, element){
   var parts = value.split(".");
   //return /^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i.test(value);
   var domainName = parts[parts.length - 1];
   return /^([A-Z0-9_%+-]+([\+_.\-]?[A-Z0-9_%+-]+)*@[A-Z0-9]+[A-Z0-9.-]*)/i.test(value)
   		  && /^[A-Z]{2,4}$/i.test(domainName);
},"Please enter a valid email address");

jQuery.validator.addMethod("checkcreditcard", function(value, element, params){
  var CCNumber = value.replace(/\s|\-/g,'');
    return  $.validator.methods.creditcard.call(this, CCNumber, element) && 
            CCNumber.length < 17 && CCNumber.length > 12 && /[0-9]$/i.test(CCNumber);
},"Invalid card number");

jQuery.validator.addMethod("phoneNumber", function(value, element){
	
	var phoneNumber = value.match(/\d+/g);
	if (phoneNumber) {
		phoneNumber = phoneNumber.join('');
		if (/^[0-9]{10}$/.test(phoneNumber)) {
			return true;
		} else {
			return false;
		}
	}
	
  
},"Invalid phone number");

jQuery.validator.addMethod("recaptchaResponse", function(value, element){
 var login_count = getCookie('login_count'); 
 if(recaptcha_public_key && login_count && login_count >= 5) {
     if(value){
         return true;
     } else {
         return false;
     }
 } else {
     return true;
 }
   
}, "Enter the words you see in the box");

function getCCDisplay(CCNumber)
{
	CCNumber = String(CCNumber);
	if (CCNumber.length == 16) {
    	CCNumber = '************'+CCNumber.slice(12);
    } else if (CCNumber.length == 15) {
    	CCNumber = '***********'+CCNumber.slice(11);
    } else if (CCNumber.length == 14) {
    	CCNumber = '**********'+CCNumber.slice(10);
    } else {
    	CCNumber = '';
    }
    return CCNumber;
}

function getPhoneDisplay(mobile)
{
	var mobile= String(mobile);
	if (mobile.length == 10) {
    	  var format = '('+mobile.slice(0,3)+')'+' '+mobile.slice(3,6)+'-'+mobile.slice(6);
          return format;
    } 
    return mobile;
}

function checkCookieEnabled()
{
	var cookieEnabled=(navigator.cookieEnabled)? true : false
	//if not IE4+ nor NS6+
	if(typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){ 
	document.cookie="testcookie"
	cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
	}
	return cookieEnabled;
}

function fieldLength(element, length, e)
{	
    charLength = element.value.length - element.value.replace(/\s/g,'').replace(/\-/g,'').length; 
    if( typeof e != "undefined" ) {
        if (e.keyCode) kCode = e.keyCode;
        else if (e.which) kCode = e.which;
        
        if (!((kCode == 32) ||(kCode == 37) || (kCode == 39))) {
            element.value = element.value.substr(0, length+charLength);
        }
    } else {
    element.value = element.value.substr(0, length+charLength);
    }
}

function handleButtons(){
	$("#next_btn,#proceed_next,#confirm_btn").hover(function(){$(this).addClass("btn_next_hvr");},function(){$(this).removeClass().addClass("btn_next");});
	$("#next_btn,#proceed_next,#confirm_btn").mousedown(function(){$(this).addClass("btn_next_clk");}).mouseup(function(){$(this).removeClass("btn_next_clk");});
	
	$("btn_tryagain").hover(function(){$(this).addClass("btn_tryagain_hvr");},function(){$(this).removeClass().addClass("btn_tryagain");});
	$("btn_tryagain").mousedown(function(){$(this).addClass("btn_tryagain_clk");}).mouseup(function(){$(this).removeClass("btn_tryagain_clk");});
	
	$("#begin_btn").hover(function(){$(this).addClass("btn_begin_hvr");},function(){$(this).removeClass().addClass("btn_begin");});
	$("#begin_btn").mousedown(function(){$(this).addClass("btn_begin_clk");}).mouseup(function(){$(this).removeClass("btn_begin_clk");});
	
	$("#start_test").hover(function(){$(this).addClass("btn_scan_hvr");},function(){$(this).removeClass().addClass("btn_scan");});
	$("#start_test").mousedown(function(){$(this).addClass("btn_scan_clk");}).mouseup(function(){$(this).removeClass("btn_scan_clk");});

	$("#decline_btn").hover(function(){$(this).addClass("btn_decline_hvr");},function(){$(this).removeClass().addClass("btn_decline");});
	$("#decline_btn").mousedown(function(){$(this).addClass("btn_decline_clk");}).mouseup(function(){$(this).removeClass("btn_decline_clk");});
	
	$("#edit_btn").hover(function(){$(this).addClass("btn_edit_hvr");},function(){$(this).removeClass().addClass("btn_edit");});
	$("#edit_btn").mousedown(function(){$(this).addClass("btn_edit_clk");}).mouseup(function(){$(this).removeClass("btn_edit_clk");});

	$("#editbllng_btn").hover(function(){$(this).addClass("btn_editbllng_hvr");},function(){$(this).removeClass().addClass("btn_editbllng");});
	$("#editbllng_btn").mousedown(function(){$(this).addClass("btn_editbllng_clk");}).mouseup(function(){$(this).removeClass("btn_editbllng_clk");});

	$("#editbll_btn").hover(function(){$(this).addClass("btn_editbll_hvr");},function(){$(this).removeClass().addClass("btn_editbll");});
	$("#editbll_btn").mousedown(function(){$(this).addClass("btn_editbll_clk");}).mouseup(function(){$(this).removeClass("btn_editbll_clk");});
	
	$(".btn_ok").hover(function(){$(this).addClass("btn_ok_hvr");},function(){$(this).removeClass().addClass("btn_ok");});
	$(".btn_ok").mousedown(function(){$(this).addClass("btn_ok_clk");}).mouseup(function(){$(this).removeClass("btn_ok_clk");});
	
	$(".btn_cancel,#cancelScan").hover(function(){$(this).addClass("btn_cancel_hvr");},function(){$(this).removeClass().addClass("btn_cancel");});
	$(".btn_cancel,#cancelScan").mousedown(function(){$(this).addClass("btn_cancel_clk");}).mouseup(function(){$(this).removeClass("btn_cancel_clk");});
	
	$(".btn_save").hover(function(){$(this).addClass("btn_save_hvr");},function(){$(this).removeClass().addClass("btn_save");});
	$(".btn_save").mousedown(function(){$(this).addClass("btn_save_clk");}).mouseup(function(){$(this).removeClass("btn_save_clk");});

	$(".btn_submit").hover(function(){$(this).addClass("btn_submit_hvr");},function(){$(this).removeClass().addClass("btn_submit");});
	$(".btn_submit").mousedown(function(){$(this).addClass("btn_submit_clk");}).mouseup(function(){$(this).removeClass("btn_submit_clk");});
	
	$("#login_btn").hover(function(){$(this).addClass("btn_login_hvr");},function(){$(this).removeClass().addClass("btn_login");});
	$("#login_btn").mousedown(function(){$(this).addClass("btn_login_clk");}).mouseup(function(){$(this).removeClass("btn_login_clk");});
	
	$("#dcl_exit_btn").hover(function(){$(this).addClass("btn_dclexit_hvr");},function(){$(this).removeClass().addClass("btn_dclexit");});
	$("#dcl_exit_btn").mousedown(function(){$(this).addClass("btn_dclexit_clk");}).mouseup(function(){$(this).removeClass("btn_dclexit_clk");});

	$("#bkterms_btn").hover(function(){$(this).addClass("btn_bkterms_hvr");},function(){$(this).removeClass().addClass("btn_bkterms");});
	$("#bkterms_btn").mousedown(function(){$(this).addClass("btn_bkterms_clk");}).mouseup(function(){$(this).removeClass("btn_bkterms_clk");});
	
	$("#finish_btn").hover(function(){$(this).addClass("btn_finish_hvr");},function(){$(this).removeClass().addClass("btn_finish");});
	$("#finish_btn").mousedown(function(){$(this).addClass("btn_finish_clk");}).mouseup(function(){$(this).removeClass("btn_finish_clk");});
	
	$("#continue_btn").hover(function(){if($(this).attr("disabled")==false) $(this).addClass("btn_next_hvr");},function(){if($(this).attr("disabled")==false) $(this).removeClass().addClass("btn_next");});
	$("#continue_btn").mousedown(function(){if($(this).attr("disabled")==false) $(this).addClass("btn_next_clk");}).mouseup(function(){if($(this).attr("disabled")==false) $(this).removeClass("btn_next_clk");});

	$("#accept_btn").hover(function(){if($(this).attr("disabled")==false) $(this).addClass("btn_accept_hvr");},function(){if($(this).attr("disabled")==false) $(this).removeClass().addClass("btn_accept");});
	$("#accept_btn").mousedown(function(){if($(this).attr("disabled")==false) $(this).addClass("btn_accept_clk");}).mouseup(function(){if($(this).attr("disabled")==false) $(this).removeClass("btn_accept_clk");});	
}

function showTextCounter(element, counterID, maxLen) {   
    if (element.value.length > maxLen){
        element.value = element.value.substring(0, maxLen);
    }
    var showText = element.value.length + "/" + maxLen;
    $("#"+counterID).html(showText);
}

function handleHelpBubble(){
	$("#minreqmt_icon").hover(
		function(){
			$("#minreqmt_data").removeClass("d_none");
			var position = $(this).position();
			$("#minreqmt_data").css({'left' : position.left, 'top' : position.top+20})
		}, 
		function(){
			$("#minreqmt_data").addClass("d_none");
	});
	$("#pwd_help").hover(
		function(){
			$("#pwd_help_txt").removeClass("d_none");
		}, 
		function(){
			$("#pwd_help_txt").addClass("d_none");
		}
	);
    $("#cvv_help").hover(
		function(){
			$("#cvv_help_txt").removeClass("d_none");
		}, 
		function(){
			$("#cvv_help_txt").addClass("d_none");
	});
}
function maskNumberInput(e) {
    var keycode = e.keyCode | e.which;
    var key_code = e.charCode? e.charCode : keycode;
   
    var oElement = window.event ? window.event.srcElement : e ? e.target : null;
            /*8:'backspace',9:'tab',13:'enter',16:'shift',17:'control',
            18:'alt',27:'esc',32:'space',33:'page up',34:'page down',35:'end',
            36:'home',37:'left',38:'up',39:'right',40:'down',45:'insert',
            46:'delete',109:'subtract',116:'f5',123:'f12',224:'command'*/
    allowedKeys = new Array(8,9,13,27,32,33,34,35,36,37,38,39,40,45,46,109,116,123,189,224);
    
    if (!e.shiftKey && !e.ctrlKey && !e.altKey) {
            if ((key_code > 47 && key_code < 58) ||
                      (key_code > 95 && key_code < 106)) {
                          if (key_code > 95) {key_code -= (95-47);}
                            
                          if (oElement.value.replace(/[\s\-]/g, '').length < 16) {
                            return true; }
                          else {
                            return handleSelection(this);
                          }
            } else if (findIndexOfArray(key_code, allowedKeys)+1) {
                return true;
            }  else { return false; }
    }
    return true;
}
function removeSpecials(e)
{ 
    var keycode = e.keyCode | e.which;
    var key_code = e.charCode? e.charCode : keycode;
    allowedKeys = new Array(8,9,13,17,18,27,32,33,34,35,36,37,38,39,40,45,46,109,116,123,189,224);
    if (!((findIndexOfArray(key_code, allowedKeys)+1) || (key_code > 47 && key_code < 58) ||
                      (key_code > 95 && key_code < 106))) {
        var oElement = window.event ? window.event.srcElement : e ? e.target : null;   
            if (/[^\d\s\-]/.test(oElement.value))
            oElement.value = oElement.value.replace(/[^\d\s\-]/g, '');
    }
}

function maskPhoneNumber(e)
{
	 var keycode = e.keyCode | e.which;
   	 var key_code = e.charCode? e.charCode : keycode;		
	 var phone = this.value.replace(/[^0-9]+/g, '');
	 notAllowedKeys = new Array(8, 35, 36, 37, 38, 39, 40, 45, 46);	 		 
	 if(phone.length > 0 && !(findIndexOfArray(key_code, notAllowedKeys)+1) && 
	 	!/^\([0-9]{0,3}\)\s?[0-9]{0,3}\-[0-9]{0,4}$/.test(this.value)) 
	 {		 
	 	if(phone.length >= 1 && phone.length <= 2) {
	 		phone = '('+phone.substr(0,3);
	 	} else if(phone.length >= 1 && phone.length <= 3) {
	 		phone = '('+phone.substr(0,3)+')';
	 	} else if(phone.length >= 1 && phone.length <= 6) {
	 	 	phone = '('+phone.substr(0,3)+')' + ' ' +phone.substr(3, 3);
	 	} else {
	 		phone = '('+phone.substr(0,3)+')' + ' ' +phone.substr(3, 3) + '-' + phone.substr(6, 4);
	 	}		 	
	 	this.value = phone;
	 } else if(phone.length == 0) {
		this.value = '';
	 }
}

function maskZipNumber(e)
{	
	var zip = this.value.replace(/[^0-9]+/g, '');	
	if(zip.length > 5 && !/^[0-9]{0,5}\-[0-9]{0,4}$/.test(this.value)) {
		zip = zip.substr(0, 5);
		this.value = zip;
	} else if(/[^0-9]/.test(this.value)){
		zip = zip.substr(0, 5);
		this.value = zip;
	} else if(zip.length == 0) {
		this.value = '';
	}	
}

function findIndexOfArray(elem, list)
{
    for(var i=0; i<list.length; i++){
        if(list[i]==elem){
         return i;
        }
    }
    return -1;
}

function handleSelection(d)
{
    if (document.selection) {
        sel = document.selection.createRange();
        if(sel.text){return true;}else{return false;}
    } else {
        if (d.selectionStart || d.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = d.selectionStart;
            endPos = d.selectionEnd;
            if (startPos != endPos) {return true;} else {return false;}
        } else {return false;}
    }
}

function maskCvvInput(e)
{
    var keycode = e.keyCode | e.which;
    var key_code = e.charCode? e.charCode : keycode;
    var oElement = window.event ? window.event.srcElement : e ? e.target : null;
    allowedKeys = new Array(8,9,13,27,33,34,35,36,37,38,39,40,45,46,116,123,224);
    
    if (!e.shiftKey && !e.ctrlKey && !e.altKey) {
            if ((key_code > 47 && key_code < 58) ||
                      (key_code > 95 && key_code < 106)) {
                          if (key_code > 95) {key_code -= (95-47);}
                            
                          if (oElement.value.length < 4) {
                            return true; }
                          else {
                            return handleSelection(this);
                          }
            } else if (findIndexOfArray(key_code, allowedKeys)+1) {
                return true;
            }  else { return false; }
    }
    return true;
}