/*
 *  Function Called via Ajax to prepopulate
 *  The State and City field based on the entered Zip Code
 *  The write to your congressman and call your congressman have almost the same
 *  functionalities. The function should return checkboxes for the write to your congressman
 *  functionality and Radio Buttons for the call your congressman functionality. 
 *  To differntiate the 2 we will use an extra variable called 'call'
 */
function doStealthAjax(caller, call){
	var extra = '';
	if(!call)
		var call = false;
	
	
	if(call == true)
		extra = "&callOption=true";
		
	if(caller == 'signup'){
			var txt;
			jQuery('#field_59').keyup(function() {
				setupZipdata();
			});
	} else if(caller == 'letter'){
		jQuery('#ZipCode').keyup(function() {
			var txt;
			var address = jQuery('#Address').val();
			if((jQuery('#ZipCode').val().length == 5) && (!isNaN(jQuery('#ZipCode').val()))){
				if(empty(address)){
					alert("Please Specify your address first.");
					jQuery('#ZipCode').val('');
					jQuery('#Address').focus();
				} else {
					jQuery.ajax({
						type: "POST",
						url: "/wp-content/themes/stealth/php/getZipData.php",
						data: "zipcode=" + jQuery('#ZipCode').val() + "&address=" + address + extra,
						success: function(msg){
						var txt = msg.split("~");
							if(txt[0] == 0 && txt.length == 5 ){
								jQuery('#City').val(txt[1]);
								jQuery('#State').val(txt[2]);
								jQuery('#ZipCode').val(txt[3]);
								jQuery('#legislatorBox').html(txt[4]);
							}
						}
					});
				}
			} else if ((jQuery('#ZipCode').val().length != 5)){
				jQuery('#City').val('');
				jQuery('#State').val('');
				jQuery('#legislatorBox').html('&nbsp;');
				
				//The following is for the call ur congressman functionality we will disable the call button
				//Since the legislator box have been emptied.
				jQuery("#callNow").fadeTo(0, 0.33);
				jQuery('#callNow').attr('makeCall', false);
				jQuery('#callNow').css("cursor","default");
			}
		});
		
	}
}

//Prepopulate city and state based on zip data
function setupZipdata(){
	if((jQuery('#field_59').val().length == 5) && (!isNaN(jQuery('#field_59').val()))){
		//Do ajax calls
		jQuery.ajax({
			type: "POST",
			url: "/wp-content/themes/stealth/php/getZipData.php",
			data: "zip=" + jQuery('#field_59').val(),
			success: function(msg){
			var txt = msg.split("~");
				if(txt.length == 4){
					jQuery('#field_4').val(txt[0]);
					jQuery("#field_5").val(txt[1]);
				}
			}
		});
	} else {
		//Reset the values
		jQuery('#field_4').val('');
		jQuery("#field_5").val('');
	}
}


function shareContent(name){
	var msgContent = jQuery("#shareContent").val();
	if(name == 'twitThis'){
		var myUrl = 'http://twitter.com/home?status=' + msgContent
		window.open(myUrl);
	} else if(name == 'facebookShare'){
		var thisUrl = urlencode(window.location.href);
		var myUrl = 'http://www.facebook.com/sharer.php?u=' + thisUrl + '&t=' + msgContent;
		window.open(myUrl);
	}
	pic_log_spread_the_word(name);
}

function validateMultiEmail(){
	jQuery('#friends_email').keyup(function() {
		
		jQuery('.uniqError').remove();
		
		if (this.value == '')
			jQuery('.multiEmail').append('<div class=\"error uniqError\">Please Enter valid email addresses.</div>');
		
		if(!validateMultipleEmailsCommaSeparated(this.value))
			jQuery('.multiEmail').append('<div class=\"error uniqError\">Please Enter valid email addresses.</div>');
		else 
			jQuery('.uniqError').remove();
		
		if(this.value.split(",").length > 10)
			jQuery('.multiEmail').append('<div class=\"error uniqError\">Please enter up to 10 Email Addresses.</div>');
	});
}

function processSubmission(caller){
	var submitForm = true;
	jQuery('.uniqError').remove();
	
	if(caller == 'sword'){
		//In case the email content is empty
		var emailTxt = trim(jQuery("#emailContent").val());
		if(empty(emailTxt)){
			jQuery('.msgContent').append('<div class=\"error uniqError\">Email content cannot be empty.</div>');
			submitForm = false;
		}
		
		var friendsEmails = jQuery("#friends_email").val();
		
		if(!validateMultipleEmailsCommaSeparated(friendsEmails)){
			jQuery('.multiEmail').append('<div class=\"error uniqError\">Please Enter valid email addresses.</div>');
			submitForm = false;
		}
		
	} else if(caller == 'contactUs'){
		alert("Email empty");
		var emailTxt = trim(jQuery("#emailContent").val());
		if(empty(emailTxt)){
			jQuery('.msgContent').append('<div class=\"error uniqError\">Email content cannot be empty.</div>');
			submitForm = false;
		}
	} else if(caller == 'letter'){
			//submitForm = checkCaptcha(); this if block is no longer used
		var list = $("input:checked").length;
		submitForm = false;
	}
	
	return submitForm;
}

function checkCaptcha(){
	var captcha,capEncrypt;
	var reponse = true;
	captcha = jQuery("#Captcha").val();
	captchaEncrypt = jQuery("#capEncrypt").val();
	if(!empty(captcha) && !empty(captchaEncrypt)){
		jQuery("#waitBox").addClass("ajaxLoader");
		jQuery.ajax({
			type: "POST",
			url: "/getZipData.php",
			async: false,
			data: "captcha=" + captcha + "&captchaEncrypt=" + captchaEncrypt,
			success: function(msg){
				if(msg == 0){
					getCaptcha();
					reponse = false;
				} else if (msg == 1){
					jQuery('.captchaError').remove();
					jQuery("#waitBox").removeClass("ajaxLoader");
					reponse = true;
				}
			}
		});
	}
	return reponse;
}

function getCaptcha(){
	jQuery.ajax({
		type: "POST",
		url: "/getZipData.php",
		data: "getCaptcha=1",
		success: function(msg){
			var txt =  msg.split("~");
			if(!empty(msg) && txt.length == 3){
				var image = "<img src='" + txt[1] + "' width=\"314\" height=\"50px\" />";
				jQuery('#captchaContainer').html(image);
				jQuery('#capEncrypt').val(txt[2]);
				jQuery('#mainCaptcha').append('<div class=\"error captchaError\">Invalid Captcha - Please enter captcha again.</div>');
				jQuery('#Captcha').val('');
				jQuery('#Captcha').focus();
				jQuery("#waitBox").removeClass("ajaxLoader");
			}
		}
	});
}


function validateEmail(field) {
	var regex=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
	return (regex.test(field)) ? true : false;
}

function validateMultipleEmailsCommaSeparated(value) {
	if(value == '')
		return false;
	
	var result = value.split(",");
	for(var i = 0;i < result.length;i++)
	if(!validateEmail(result[i]))
	return false;
	return true;
}

function processCall(){
	jQuery('#number-to-call').keyup(function() {
		if(jQuery('#number-to-call').val().indexOf('_',0) < 0){
			if(isValidPhoneNumber(jQuery('#number-to-call').val()) && is_numeric(jQuery('input.styleRadio:checked').val())){
				jQuery("#callNow").fadeTo(1000, 1);
				jQuery('#callNow').attr('makeCall', true);
				jQuery('#callNow').css("cursor","pointer");
			} else {
				jQuery("#callNow").fadeTo(0, 0.33);
				jQuery('#callNow').attr('makeCall', false);
				jQuery('#callNow').css("cursor","default");
			}
		} else {
			jQuery("#callNow").fadeTo(0, 0.33);
			jQuery('#callNow').attr('makeCall', false);
			jQuery('#callNow').css("cursor","default");
		} 
	});
	
}

function activateCallButton(){
	//Activate the call Button if the phone number have been filled already
	if(isValidPhoneNumber(jQuery('#number-to-call').val()) && is_numeric(jQuery('input.styleRadio:checked').val())){
		jQuery("#callNow").fadeTo(1000, 1);
		jQuery('#callNow').attr('makeCall', true);
		jQuery('#callNow').css("cursor","pointer");
	}
}

function placeCall(){
	var myurl, userNumber, repNumber, repID;
	jQuery("#callNow").hide();
	userNumber = str_replace('-', '', jQuery("#number-to-call").val());
	repNumber = jQuery('input.styleRadio:checked').val();
	repID = jQuery('input.styleRadio:checked').attr("repid");
	
	var html = "<span class=\"callLoader left\"><h4 class=\"loadingText\">Calling...</h4></span>";
	jQuery("#callArea").append(html);
	
	if(is_numeric(userNumber) && is_numeric(repNumber) && userNumber.length == 10 && repNumber.length == 10){
		var myurl = "https://secure.ifbyphone.com/click_to_xyz.php?app=ctc&id=" + userNumber + "&phone_to_call=" + repNumber + "&type=2&key=17940347f58d77f2c64d10c3b096698ed39ec85e";
		pic_log_call(userNumber,repID,repNumber);
		jQuery.ajax({
			type: "GET",
			url: myurl ,
			async: false,
			success: function(msg){
				if(msg.length == 0){
					jQuery(".callLoader").remove();
					html =  "<span class=\"left\"><h4 class=\"loadingText\">Connected...</h4></span>";
					jQuery("#callArea").append(html);
				}
			}
		});
	} else {
		alert("Some unknow error occured");
		jQuery(".callLoader").remove();
		jQuery("#callNow").show();
	}
}


function pic_log_call(user_phone,repid,rep_phone){
	var zipcode = jQuery("#ZipCode").val();
	jQuery.ajax({
		type: "post",url: "admin-ajax.php",data: { action: 'pic_log_call', pic_zip: zipcode, pic_repid: repid, pic_userphone: user_phone, pic_repphone: rep_phone}
	});
}

function pic_log_spread_the_word(spread_action){
	jQuery.ajax({
		type: "post",url: "admin-ajax.php",data: { action: 'pic_log_spread_the_word', action_name: spread_action}
	});
}


/*
 * Custom Phone Number validation. Let's keeping
 * mind that the mask function inserts '_' && '-' characters in the
 * phone numbers.
 */
function isValidPhoneNumber(number){
	//In our case the mask insert '_' and '-' in the phone number
	//So we gonna split the spring by '-' and check that all parts of the array are number
	var numberPart = number.split("-");

	if (is_numeric(numberPart[0]) && is_numeric(numberPart[1]) && is_numeric(numberPart[2]))
		return true;
	else
		return false; 
}


/*
 * Implementation of PHP empty function
 */
function empty (mixed_var) {
    var key;    
    if (mixed_var === "" ||
        mixed_var === 0 ||
        mixed_var === "0" ||
        mixed_var === null ||        
        mixed_var === false ||
        typeof mixed_var === 'undefined'
    ){
        return true;
    }
    
    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }        return true;
    }
    return false;
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
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 urlencode (str) {
	str = (str+'').toString();
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}

function is_numeric (mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function str_replace (search, replace, subject, count) {
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}        }
    }
    return sa ? s : s[0];
}
