if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

jQuery.preLoadImages("../images/loading.gif");

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function isValidPhoneNumber(phoneNumber){
	var pattern2 = new RegExp(/\d{3}\-\d{3}\-\d{4}/);
	return pattern2.test(phoneNumber);
}

// Password strength meter
// This jQuery plugin is written by firas kassem [2007.04.05]
// Firas Kassem  phiras.wordpress.com || phiras at gmail {dot} com
// for more information : http://phiras.wordpress.com/2007/04/08/password-strength-meter-a-jquery-plugin/

var shortPass = 'Must be at least 6 characters';
var badPass = 'Weak';
var goodPass = 'Good';
var strongPass = 'Strong';

function passwordStrength(password)
{
    score = 0;
    
    //password < 4
    if (password.length < 6 ) { return shortPass }

    //password length
    score += password.length * 4
    score += ( checkRepetition(1,password).length - password.length ) * 1
    score += ( checkRepetition(2,password).length - password.length ) * 1
    score += ( checkRepetition(3,password).length - password.length ) * 1
    score += ( checkRepetition(4,password).length - password.length ) * 1

    //password has 3 numbers
    if (password.match(/(.*[0-9].*[0-9].*[0-9])/))  score += 5 
    
    //password has 2 sybols
    if (password.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/)) score += 5 
    
    //password has Upper and Lower chars
    if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))  score += 10 
    
    //password has number and chars
    if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/))  score += 15 
    //
    //password has number and symbol
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([0-9])/))  score += 15 
    
    //password has char and symbol
    if (password.match(/([!,@,#,$,%,^,&,*,?,_,~])/) && password.match(/([a-zA-Z])/))  score += 15 
    
    //password is just a nubers or chars
    if (password.match(/^\w+$/) || password.match(/^\d+$/) )  score -= 10 
    
    //verifing 0 < score < 100
    if ( score < 0 )  score = 0 
    if ( score > 100 )  score = 100 
    
    if (score < 34 )  return badPass 
    if (score < 68 )  return goodPass
    return strongPass
}


// checkRepetition(1,'aaaaaaabcbc')   = 'abcbc'
// checkRepetition(2,'aaaaaaabcbc')   = 'aabc'
// checkRepetition(2,'aaaaaaabcdbcd') = 'aabcd'

function checkRepetition(pLen,str) {
    res = ""
    for ( i=0; i<str.length ; i++ ) {
        repeated=true
        for (j=0;j < pLen && (j+i+pLen) < str.length;j++)
            repeated=repeated && (str.charAt(j+i)==str.charAt(j+i+pLen))
        if (j<pLen) repeated=false
        if (repeated) {
            i+=pLen-1
            repeated=false
        }
        else {
            res+=str.charAt(i)
        }
    }
    return res
}

function checkCreditCard(value) {
	
	// accept only digits and dashes
	if (/[^0-9-]+/.test(value))
		return false;
	var nCheck = 0,
		nDigit = 0,
		bEven = false;

	value = value.replace(/\D/g, "");

	for (var n = value.length - 1; n >= 0; n--) {
		var cDigit = value.charAt(n);
		var nDigit = parseInt(cDigit, 10);
		if (bEven) {
			if ((nDigit *= 2) > 9)
				nDigit -= 9;
		}
		nCheck += nDigit;
		bEven = !bEven;
	}

	return (nCheck % 10) == 0;
}

// Function to handle ajax.
function checkKeyword(str){
    $('#keyword').next().remove('span');
	$('#keyword').after('<span class="check">&nbsp;</span>');
	$.ajax({
	    url: 'check_keyword.php',
	    type: 'POST',
		data: "keyword="+str,
		dataType: "text",
		async: false,
	    success: function(msg){
			if (msg != 'true') {
				$('#keyword').next().remove('span');
				$('#keyword').after('<span class="error">'+msg+'</span>');
				check_response += msg+"\n";
				check_return = false;
			} else {
				$('#keyword').next().remove('span');
				$('#keyword').after('<span class="ok">Available</span>');
			}
	    }
	});
	return true;
}

// Function to handle ajax.
function checkReferralCode(str){
    $('#referral_code').next().remove('span');
	$('#referral_code').after('<span class="check"></span>');
	$.ajax({
	    url: 'check_referral_code.php',
	    type: 'POST',
		data: "code="+str,
		dataType: "text",
		async: false,
	    success: function(msg){
			if (msg.substring(0, 4) != 'true') {
				$('#referral_code').next().remove('span');
				$('#referral_code').after('<span class="error">'+msg+'</span>');
			} else {
				var parts = msg.split('|');
				$('#referral_code').next().remove('span');
				$('#referral_code').after('<span class="ok">'+parts[1]+'</span>');
			}
	    }
	});
	return true;
}
var check_return;
var check_response = '';
function checkInput(this_input) {
	check_return = true;
	var field_id = $(this_input).attr('id');
	
	

	if (field_id == 'contact_name') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('contact_name') == -1)
				checked.push('contact_name');
			$(this_input).next().remove('span');
			$(this_input).after('<span class="ok">&nbsp;</span>');
		} else if (checked.indexOf('contact_name') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Please enter your first name</span>');
			check_response += "Please enter your first name\n";
			check_return = false;
		}	
	
	} else if (field_id == 'last_name') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('last_name') == -1)
				checked.push('last_name');
			$(this_input).next().remove('span');
			$(this_input).after('<span class="ok">&nbsp;</span>');
		} else if (checked.indexOf('last_name') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Please enter your last name</span>');
			check_response += "Please enter your last name\n";
			check_return = false;
		}
	
	} else if (field_id == 'agency_name') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('agency_name') == -1)
				checked.push('agency_name');
			$(this_input).next().remove('span');
			$(this_input).after('<span class="ok">&nbsp;</span>');
		} else if (checked.indexOf('agency_name') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Please enter your company</span>');
			check_response += "Please enter your company\n";
			check_return = false;
		}
		
		
	} else if (field_id == 'contact_phone') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('contact_phone') == -1)
				checked.push('contact_phone');
			if (!isValidPhoneNumber( $(this_input).val() ) ) {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="error">Please enter a valid phone</span>');
				check_response += "Please enter a correct email\n";
				check_return = false;
			} else {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="ok">&nbsp;</span>');
			}
		} else if (checked.indexOf('contact_phone') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Please enter a correct phone</span>');
			check_response += "Please enter a correct email\n";
			check_return = false;
		}
	
	} else if (field_id == 'contact_email') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('contact_email') == -1)
				checked.push('contact_email');
			if (!isValidEmailAddress( $(this_input).val() ) ) {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="error">Please enter a correct email</span>');
				check_response += "Please enter a correct email\n";
				check_return = false;
			} else {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="ok">&nbsp;</span>');
			}
		} else if (checked.indexOf('contact_email') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Please enter a correct email</span>');
			check_response += "Please enter a correct email\n";
			check_return = false;
		}
	
		
	} else if (field_id == 'timezone') {
		if ($(this_input).val() == '') {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Please select your timezone</span>');
			check_response += "Please select your timezone\n";
			check_return = false;
		} else {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="ok">&nbsp;</span>');
		}
	
	} else if (field_id == 'keyword') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('keyword') == -1)
				checked.push('keyword');
			key_check = checkKeyword($(this_input).val());
		} else if (checked.indexOf('keyword') >= 0) {
			key_check = checkKeyword($(this_input).val());
		}
	
	} else if (field_id == 'referral_code') {
		if ($(this_input).val() != '') {
			referral_check = checkReferralCode($(this_input).val());
		} else {
			$(this_input).next().remove('span');
		}
	
	} else if (field_id == 'password') {
		if ( $(this_input).val() != '') {
			if (checked.indexOf('password') == -1)
				checked.push('password');
			var check = passwordStrength($(this_input).val());
			if (check == 'Weak' || check == 'Good' || check == 'Strong') {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="ok">&nbsp;</span>');
			} else {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="error">'+check+'</span>');
				check_response += check+"\n";
				check_return = false;
			}

		} else if (checked.indexOf('password') >= 0) {
			$(this_input).next().remove('span');
			$('#user_pass2').next().remove('span');
			$(this_input).after('<span class="error">You must enter a password</span>');
			check_response += "You must enter a password\n";
			check_return = false;
		}
			
	} else if (field_id == 'password2') {
		if ( $(this_input).val() == '' && $('#password').val() == '') {
			$(this_input).next().remove('span');
		} else if ($(this_input).val() != $('#password').val()) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Passwords do not match</span>');
			check_response += "Your passwords do not match\n";
			check_return = false;
		} else {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="ok">&nbsp;</span>');
		}

	} else if (field_id == 'credit_card_number') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('credit_card_number') == -1)
				checked.push('credit_card_number');
		 	if (!checkCreditCard($(this_input).val())) {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="error">&nbsp</span>');
				check_response += "Enter a valid credit card number\n";
				check_return = false;
			} else {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="ok">&nbsp;</span>');
			}
		} else if (checked.indexOf('credit_card_number') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">&nbsp</span>');
			check_response += "Enter a valid credit card number\n";
			check_return = false;
		}
	
	} else if (field_id == 'expires_year') {
		var curTime = new Date();
		var month = curTime.getMonth()+1;
		var year = curTime.getFullYear();
		if ($('#expires_year').val() < year) {
			$(this_input).parent().next().remove('span');
			$(this_input).parent().after('<span class="error">This date has expired</span>');
			check_response += "Your credit card expiration date has expired\n";
			check_return = false;
		} else if ($('#expires_year').val() == year && $('#expires_month').val() <= month) {
			$(this_input).parent().next().remove('span');
			$(this_input).parent().after('<span class="error">This date has expired</span>');
			check_response += "Your credit card expiration date has expired\n";
			check_return = false;
		} else {
			$(this_input).parent().next().remove('span');
			$(this_input).parent().after('<span class="ok">&nbsp;</span>');
		}
	
	} else if (field_id == 'security_code') {
		if ($(this_input).val() != '') {
			if (checked.indexOf('security_code') == -1)
				checked.push('security_code');
		 	if (isNaN(parseInt($(this_input).val()))) {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="error">Enter a valid security code</span>');
				check_response += "Enter a valid security code\n";
				check_return = false;
			} else {
				$(this_input).next().remove('span');
				$(this_input).after('<span class="ok">&nbsp;</span>');
			}
		} else if (checked.indexOf('security_code') >= 0) {
			$(this_input).next().remove('span');
			$(this_input).after('<span class="error">Enter a valid security code</span>');
			check_response += "Enter a valid security code\n";
			check_return = false;
		}
	}
	return check_return;
}

var checked = [];
$(document).ready(function(){
	$("input").blur(function () {
		checkInput(this);
		if (checked.indexOf($(this).attr('id')) >= 0) {
			$('#'+$(this).attr('id')).keyup(function () {
				checkInput(this);
			});
		}
	});

	$('form#create_account').submit(function() {
		var submit_check = true;
		check_response = "Please correct the following:\n-----------------------------\n";
		$('#create_account input').each( function(i) {
			checked.push($(this).attr('id'));
			if (!checkInput(this)) {
				submit_check = false;
			}
		});
		$('#create_account select').each( function(i) {
			checked.push($(this).attr('id'));
			if (!checkInput(this)) {
				submit_check = false;
			}
		});
		if (!submit_check) alert(check_response);
		return submit_check;
	});

	$("#timezone").change(function () {
		checkInput(this);
	});
	
	$("#expires_year").change(function () {
		checkInput(this);
	});
});

