/**
 * @author Adam Radabaugh
 */
/////////////////////////////////////////////////////////
///////////		AJAX	CORE FUNCTIONS 			  ///////
///////////////////////////////////////////////////////
//set jquery ajax ready event handlers
$(document).ajaxStart(function() {
	if ($("#ajaxBusy"))
		$("#ajaxBusy").show();
}).ajaxStop(function() {
	if ($("#ajaxBusy"))
		$("#ajaxBusy").hide();
});
var JSONData; //raw JSON data returned from PHP
var obj; //parse JSON data available for use in JS
var dev;
var submitURL;
///////////////////////////////////////////////////////////
///////////		AJAX	SUPPORT FUNCTIONS 		////////
/////////////////////////////////////////////////////////
function processForm() {
	var newValues = JSON.stringify(values);
	$.post(
		"gateway-server.html",
		{data: newValues},
		function(response) {
			obj = JSON.parse(response);
			switch(obj['result']) {
				case 'DECLINED':
				case 'ERROR_AUTH':
					$('#processingForm').hide();
					enableBtn('checkoutNext', verifyCC);
					//$('#checkoutNext').unbind().bind('click', verifyCC);
					alert("We're sorry but there seems to be a problem with your details:\n\n"+obj['result']+': '+obj['resultText']+"\n\nPlease check the information and try again.");
					break;
				case 'ERROR':
					$('#processingForm').hide();
					enableBtn('checkoutNext', verifyCC);
					alert(obj['result']+': '+obj['resultText']+"\n\nPlease try again.");
					break;
				case 'SUCCESS':
					var finalURL = submitURL + obj['id'] + '&m=9';
					$('#billingForm').attr('action',finalURL).submit();
					break;
			}
		},
		"JSON"
	);
}
///////////////////////////////////////////////////////////////////
///////////		NON-AJAX	SUPPORT FUNCTIONS    		////////
////////////////////////////////////////////////////////////////
var values = {};
var billForm = ' ';
var startnowForm = ' ';
//starter function to prep the page for additional
//js/ajax events
$(document).ready(function() {
	 $("#billingFormWrapper").bind("keypress", function(e) {
         if (e.keyCode == 13) {
             return false;
        }
     });
	 $("#startnowFormWrapper").bind("keypress", function(e) {
         if (e.keyCode == 13) {
             return false;
        }
     });
	dev = $('#server').val();
	if (dev == 'n') {
		submitURL = 'https://www.biglocal.com/terms.html?id=';
	}
	else {
		submitURL = 'http://www.biglocal.com.bd/terms.html?id=';
	}
	$('#checkoutNext').bind('click', verifyForm);
	billForm = $('#billingFormWrapper').html();
	startnowForm = $('#startnowFormWrapper').html();
});
function verifyForm() {
	var theForm = document.getElementById("startnowForm");
	var validForm = true;
	var single9 = document.getElementById("entry_9");
	
	theForm.first_name.style.backgroundColor='#FFF';
	theForm.last_name.style.backgroundColor='#FFF';
	theForm.account_name.style.backgroundColor='#FFF';
	theForm.emailAddress0.style.backgroundColor='#FFF';			
	theForm.primary_address_street.style.backgroundColor='#FFF';		
	single9.style.backgroundColor='#FFF';
	theForm.primary_address_city.style.backgroundColor='#FFF';		
	theForm.primary_address_state.style.backgroundColor='#FFF';
	theForm.primary_address_postalcode.style.backgroundColor='#FFF';		
	theForm.phone_work.style.backgroundColor='#FFF';

	if(theForm.first_name.value == '') {
		theForm.first_name.style.backgroundColor='#FFC6C6';
		validForm = false;
	} 
	if(theForm.last_name.value == '') {
		theForm.last_name.style.backgroundColor='#FFC6C6';
		validForm = false;
	}		
	if(theForm.account_name.value == '') {
		theForm.account_name.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.emailAddress0.value == '') {
		checkEmail(theForm);
	}
	function checkEmail(theForm) {
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(theForm.emailAddress0.value)){
			return (true)
		}
		theForm.emailAddress0.style.backgroundColor='#FFC6C6';			
		validForm = false;
		alert("Invalid E-mail Address! Please re-enter.")
		return (false)
	}
	if(theForm.primary_address_street.value == '') {
		theForm.primary_address_street.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(single9.value == '') {
		single9.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.primary_address_city.value == '') {
		theForm.primary_address_city.style.backgroundColor='#FFC6C6';
		validForm = false;
	} 
	if(theForm.primary_address_state.value == '') {
		theForm.primary_address_state.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.primary_address_state.value == '') {
		theForm.primary_address_postalcode.style.backgroundColor='#FFC6C6';
		validForm = false;
	} 
	if(theForm.phone_work.value.length != 10) {
		theForm.phone_work.style.backgroundColor='#FFC6C6';
		alert('Please enter a valid 10 Digit number. Use numbers only.');
		validForm = false;
	}
	
	if(validForm) {
		
		var inputs = $('#startnowFormWrapper input, #startnowFormWrapper textarea, #startnowFormWrapper select');
    
	    inputs.each(function(i, el) {
	        values[el.name] = $(el).val();
	    });
		
		values['group:26'] = $("input[@name=group:26]:checked").val()
		
		$('#startnowFormWrapper').fadeOut('slow', function() {
			$(this).html(billForm).fadeIn('slow');
		});
		$('#billingFormWrapper').html(' ');
		$('#checkoutNext').unbind().bind('click', verifyCC);
	}
}
// BEGIN - VALIDATE CREDIT CARD FORM
function verifyCC() {
	theForm = document.getElementById("billingForm");
	var validForm = true;
	
	theForm.cc_first_name_c.style.backgroundColor='#FFF';
	theForm.cc_last_name_c.style.backgroundColor='#FFF';
	theForm.cc_num.style.backgroundColor='#FFF';
	
	if(theForm.cc_first_name_c.value == '') {
		theForm.cc_first_name_c.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.cc_last_name_c.value == '') {
		theForm.cc_last_name_c.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.cc_num.value == '') {
		theForm.cc_num.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	
	if (validForm) {
		disableBtn('checkoutNext');
		
		var inputs = $('#startnowFormWrapper input, #startnowFormWrapper select');
    
	    inputs.each(function(i, el) {
	        values[el.name] = $(el).val();
	    });
		
		$('#processingForm').show('fast');
		
		processForm();
	}
}
// END - VALIDATE CREDIT CARD FORM

//START - VALIDATE SMS FORM
function verifySMS() {
	theForm = document.getElementById("smsForm");
	var validForm = true;
	
	theForm.name.style.backgroundColor='#FFF';
	theForm.business.style.backgroundColor='#FFF';
	theForm.address.style.backgroundColor='#FFF';
	theForm.phone.style.backgroundColor='#FFF';
	theForm.email.style.backgroundColor='#FFF';
	
	if(theForm.name.value == '') {
		theForm.name.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.business.value == '') {
		theForm.business.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.address.value == '') {
		theForm.address.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.address.value == '') {
		theForm.phone.style.backgroundColor='#FFC6C6';
		validForm = false;
	}
	if(theForm.address.value == '') {
		theForm.email.style.backgroundColor='#FFC6C6';
		validForm = false;
	}		
	if (validForm) {
		theForm.submit();
	}
}
//END - VALIDATE SMS FORM
function disableBtn(eleId) {
	$('#'+eleId+'').unbind().hide('slow');
}
function enableBtn(eleId, fnc) {
	$('#'+eleId+'').bind('click', fnc).show('slow');
}
////////////////////////////////////////////////////////////
///////////		AJAX	DIAGNOSTIC FUNCTIONS 	///////// DO NOT USE IN PRODUCTION
//////////////////////////////////////////////////////////
//var dump function... akin to php's print_r(array)
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}