
function showLoginScreen(){
    
}

function clearErrors(){
    $('.errors').css('display', 'none');
    $('.errors').html('');
}

function displayErrors(error){
    $('.errors').css('display', 'block');
    $('.errors').html(error);
}

function updateContent(html){    
    showHideLoader(false);
    if(html=='invalid'){
        displayErrors('Invalid session data, please try again.');
    }
    else{
        clearErrors();
        $('#content').html(html);        
    }
}

function getFormDataSerialized(formid)
{
    return $(formid).serialize();
}

var xmlDoc;

// For IE based browsers (tested under IE6 and IE7):
if (window.ActiveXObject)
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    
    // Turn off asynchronus download.
    // Load the entire file before trying to do anything with it.
    xmlDoc.async=false;
    
    //load the country/state XML file windows only
    xmlDoc.load("country_state.xml");
    
}
// For other browsers (Netsacpe/Firefox/Chrome):
else if (document.implementation && document.implementation.createDocument)
{
    //Removed line to fix Google Chrome bug (26/01/2009):- xmlDoc = document.implementation.createDocument("","doc",null);
    //Replaced with below script
    var xmlhttp = new window.XMLHttpRequest();
    
    //load the country/state XML file other browsers
    xmlhttp.open("GET","country_state.xml",false);
    
    xmlhttp.send(null);
    xmlDoc = xmlhttp.responseXML.documentElement;
    
}
else
{
    // The 'something fails' alert!
    alert('Your browser is unable to handle this script');
}


// Populate selected dropdown list with data from XML file
// (<option value="County/StateName">County/StateName</option>)
// Function used for both Country Fill and State Fill
function fillList(selectbox,text,value, is_selected)
{
    if(empty(selectbox)) return;
    is_selected = typeof is_selected !== 'undefined' ? is_selected : false;
    
    var optionValue = document.createElement("option");
    optionValue.text = text;
    optionValue.value = value;
    optionValue.selected = is_selected;
    selectbox.options.add(optionValue);
}

// Populate Country list on page load
// Requires: <body onload="fillCountryList();"> on HTML page
function fillCountryList (id, selected_country)
{
    //console.log('id, selected_country', id, selected_country);
    selected_country = typeof selected_country !== 'undefined' ? selected_country : "";
    
    // Get country element ID
    var countryList = document.getElementById(id);
    
    // Clear any current values in select box
    // If JavaScript isn't working existing text will remain
    if(!empty(countryList)){
        for (var x = countryList.options.length-1; x >-1; x--)
        {
            countryList.options[x] = null;
        }
    }
    // Fill Country name Array from XML file
    var countryNames = xmlDoc.getElementsByTagName("country");
    // Gets total Number of countries in XML file
    var numberOfCountries = countryNames.length;
    
//    fillList(countryList,'Australia','Australia',false);
//    fillList(countryList,'Canada','Canada',false);
//    fillList(countryList,'Great Britain','Great Britain',false);
//    fillList(countryList,'Ireland','Ireland',false);
//    fillList(countryList,'New Zealand','New Zealand',false);
//    fillList(countryList,'United States','United States',false);
    
    // Loop through Country name Array and populate country select
    for (var i=0; i <numberOfCountries; i++)
    {
        var currentCountry =  countryNames[i].getAttribute("name");
        var is_selected = false;
        if(currentCountry==selected_country)
            is_selected = true;
        fillList(countryList,currentCountry,currentCountry,is_selected);
    }
}

// Populate State/Province list on Country change
function fillStateList(countryID, stateID, selected_state)
{
    console.log(countryID, stateID, selected_state);
    if(empty(countryID) && empty(stateID)) return false;    
    
    //console.log(countryID, stateID, xmlDoc.getElementsByTagName("country"));
    selected_state = typeof selected_state !== 'undefined' ? selected_state : "";
    
    // Get State/Province element ID
    var stateList = document.getElementById(stateID)
    
    // Clear any current values in select box
    // If JavaScript isn't working existing text will remain
    for (var x = stateList.options.length-1; x >-1; x--)
    {
        stateList.options[x] = null;
    }
    
    // Get currently selected ID from country element ID
    var countryListSelected = document.getElementById(countryID).selectedIndex;
    // Get number of states for current selected Country (populates Array)
    var numberStates = xmlDoc.getElementsByTagName("country")[countryListSelected].getElementsByTagName("state").length;
    
    // Loop through States/Province Array and populate State/Province selection for current Country
    for (var i=0; i < numberStates; i++)
    {
        if(!empty(xmlDoc.getElementsByTagName("country")[countryListSelected].getElementsByTagName("state")[i].firstChild)){
            var currentState =  xmlDoc.getElementsByTagName("country")[countryListSelected].getElementsByTagName("state")[i].firstChild.nodeValue;
            var is_selected = false;
            if(currentState==selected_state)
                is_selected = true;
            fillList(stateList,currentState,currentState,is_selected);
        }
    }
    
}

function validateText(field, callerEvent) {
    //console.log('field', field);
    if(field.value) {
        var fieldValue = field.value.trim();
    }
    
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONFOCUS") {
            showEmptyImg(field);
            return;
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONKEYUP") {
            
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) ) {
                showErrorImg(field);
                return;
            } else {
                showEmptyImg(field);
                return;
            }
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONCHANGE") {
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) ) {
                showErrorImg(field);
                return;
            } else {
                showEmptyImg(field);
                return;
            }
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONBLUR") {
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) || (fieldValue=='Select a country...') || (fieldValue=='Select One...') ) {
                showErrorImg(field);
                return;
            } else {
                showValidImg(field);
                return;
            }
        }
    }
    
    //	if(callerEvent.toUpperCase() == "ONLOAD") {
    //		if((fieldValue == "") || (fieldValue == null)) {
    //			showErrorImg(field);
    //			return;
    //		} else {
    //			showValidImg(field);
    //			return;
    //		}
    //	}
    //	
}
function validateSelect(field) {
    if(demoAccountHash==account_hash && $(field).attr('id')=='cboCountry') return;
    // validateSelect(this);
    
    //alert(field.value);
    var fieldValue = field.value.trim();
    
    //alert('fieldValue: ' + fieldValue);
    
    if( (!fieldValue) || (fieldValue == "") || (fieldValue == null) ) {
        showErrorImg(field);
        return;
    } else {
        showValidImg(field);
        return;
    }
}

function validateSelectDOB(field) {
    // validateBirthdate(this,'');
    var prefix = "";
    var birthdateStatus = checkBirthdateCompletion(prefix);
    
    //if(callerEvent != "onfocus") alert(birthdateStatus);
    
    if(birthdateStatus == "none") {
        showBirthdateWaitingImg(prefix);
        return;
    } else if(birthdateStatus == "some") {
        showBirthdateWaitingImg(prefix);
        return;
    } else if(birthdateStatus == "all") {
        //alert('window.regPaymeBirthdate: ' + window.regPaymeBirthdate);
        showBirthdateValidImg(prefix);
        //checkAccountBasics();
        //toggleVoiceAuth();
        //alert(window.regBDAY);
        return;
    }
}

function validateTSYSDOB(field) {
    // validateBirthdate(this,'');
    var prefix = "tsys_";
    var birthdateStatus = checkBirthdateCompletion(prefix);
    
    //if(callerEvent != "onfocus") alert(birthdateStatus);
    
    if(birthdateStatus == "none") {
        showBirthdateWaitingImg(prefix);
        return;
    } else if(birthdateStatus == "some") {
        showBirthdateWaitingImg(prefix);
        return;
    } else if(birthdateStatus == "all") {
        //alert('window.regPaymeBirthdate: ' + window.regPaymeBirthdate);
        showBirthdateValidImg(prefix);
        //checkAccountBasics();
        //toggleVoiceAuth();
        //alert(window.regBDAY);
        return;
    }
}

function validateOfficialDOB(field) {
    // validateBirthdate(this,'');
    var prefix = "official_";
    var birthdateStatus = checkBirthdateCompletion(prefix);
    
    //if(callerEvent != "onfocus") alert(birthdateStatus);
    
    if(birthdateStatus == "none") {
        showBirthdateWaitingImg(prefix);
        return;
    } else if(birthdateStatus == "some") {
        showBirthdateWaitingImg(prefix);
        return;
    } else if(birthdateStatus == "all") {
        //alert('window.regPaymeBirthdate: ' + window.regPaymeBirthdate);
        showBirthdateValidImg(prefix);
        //checkAccountBasics();
        //toggleVoiceAuth();
        //alert(window.regBDAY);
        return;
    }
}

function checkBirthdateCompletion(prefix) { // had and removed "personalRegistration2" as a variable???
    
    var validBirthday = new Array();
    validBirthday[0] = true;
    validBirthday[1] = true;
    validBirthday[2] = true;
    validBirthday[3] = true;
    
    
    
    var selectFields = new Array();
    selectFields[1] = prefix + "birth_year";
    selectFields[2] = prefix + "birth_month";
    selectFields[3] = prefix + "birth_day";
    
    for (var i=1; i < selectFields.length; i++) {
        
        //alert('i: ' + i);
        //alert(document.bangkForm[selectFields[i]].value);
        if (document.frmPayment[selectFields[i]].value.trim() == '') {
            validBirthday[0] = false;
            validBirthday[i] = false;
        } else {
            validBirthday[i] = document.frmPayment[selectFields[i]].value;
        }
    }
    
    if((validBirthday[1] != false) && (validBirthday[2] != false) && (validBirthday[3] != false)) {
        window.confirmBirthDay = validBirthday[3];
        window.confirmBirthMonth = validBirthday[2];
        window.confirmBirthYear = validBirthday[1];
        return "all";
    } else if((validBirthday[1] == false) && (validBirthday[2] == false) && (validBirthday[3] == false)) {
        return "none";
    } else {
        return "some";
    }
} 

function displayTheirFee(field) {
    
    //payme function?
    
    //alert("field.value: "+field.value);
    
    var amountToPay = parseFloat(field.value).toFixed(2);
    
    //alert("amountToPay: "+amountToPay);
    
    var thierFeePercentage = "0.000";
    
    //alert("thierFeePercentage: "+thierFeePercentage);
    
    // THEIR ACTUAL FEE
    
    var theirfee = parseFloat(amountToPay * thierFeePercentage).toFixed(2);
    
    //alert("0. theirfee: "+theirfee);
    
    if ( isNaN(theirfee) ) {
        theirfee = "0.00";
    }
    
    //alert("1. theirfee: "+theirfee);
    
    /// transactionFeeTheir
    if(
       (typeof document.getElementById('transactionFeeTheir') != 'undefined') &&
       (document.getElementById('transactionFeeTheir') != null)
       ) {
        document.getElementById('transactionFeeTheir').innerHTML = theirfee;
    }
    
    /// printCurrency0fee
    if(
       (typeof document.getElementById('printCurrency0fee') != 'undefined') &&
       (document.getElementById('printCurrency0fee') != null)
       ) {
        document.getElementById('printCurrency0fee').innerHTML = theirfee;
    }
    
    
    //alert(theirfee);
    //alert(amountToPay);
    
    var theirtotal = parseFloat(amountToPay) + parseFloat(theirfee);
    
    //alert(theirtotal);
    
    if (
        (isNaN(theirtotal)) ||
        (theirtotal == null)
        ) {
        theirtotal = "0";
    }
    
    if(
       (typeof document.getElementById('theirTotalCharge') != 'undefined') &&
       (document.getElementById('theirTotalCharge') != null)
       ) {
        document.getElementById('theirTotalCharge').innerHTML = theirtotal.toFixed(2);
    }
    
    if(
       (typeof document.getElementById('printCurrency0total') != 'undefined') &&
       (document.getElementById('printCurrency0total') != null)
       ) {
        document.getElementById('printCurrency0total').innerHTML = theirtotal.toFixed(2);
    }
    
}

function displayPersonalIdentity(e, id){
    //console.log('id, value', id , $(e).val());
    if(id=='#lbl_personal_identity_date_of_bith'){
        var prefix = "tsys_";
        var birthdateStatus = checkBirthdateCompletion(prefix);
        
        if(birthdateStatus == "all") {
            $(id).html(window.confirmBirthYear + '-' + window.confirmBirthMonth + '-' + window.confirmBirthDay);
        }
    }
    else{
        $(id).html($(e).val());
    }
}

function TOGGLE_BUSINESS_BANKING(e){
    $('.PERSONAL_business_type_block').css('display', 'none');
    $('.BUSINESS_business_type_block').css('display', 'none');
    
    $('#banking_type1').parent().parent().removeClass('has-success has-error has-feedback');
    $('#banking_type2').parent().parent().removeClass('has-success has-error has-feedback');
    
    $('.'+$(e).val() + '_business_type_block').css('display', 'block');
    
    fillPhotoIdForm();
}
function displayPersonalBusinessType(e){
    fillPhotoIdForm();
}
function displayRegisteredBusinessType(e){
    $('.registered_business_type_display').html($(e).val());
    
    fillPhotoIdForm();
}
function displayBusinessName(field, el_class){
    var text_to_display = field.value;
    text_to_display = text_to_display.replace(/ /g, "-");
    text_to_display = text_to_display.replace(/\./g, "-");
    
    $('.' + el_class).html(text_to_display);
    
    fillPhotoIdForm();
}


/// STATUS ICONS ////////////////////////////////////////////////////////////
function showDefaultImg(field) {
}

function showErrorImg(field) {
    $(field).parent().removeClass('has-success has-error has-feedback');
    $(field).parent().addClass('has-error has-feedback');
    $(field).next('.glyphicon').remove();
    $(field).after('<span class="glyphicon glyphicon-remove form-control-feedback"></span>');
}

function showWorkingImg(field) {
    
}


function showValidImg(field) {
    $(field).parent().removeClass('has-success has-error has-feedback');
    $(field).parent().addClass('has-success has-feedback');
    $(field).next('.glyphicon').remove();
    $(field).after('<span class="glyphicon glyphicon-ok form-control-feedback"></span>');
}

function showEmptyImg(field) {
}

function showBirthdateValidImg(prefix) {
    $('#' + prefix + 'birth_year').parent().removeClass('has-success has-error has-feedback');
    $('#' + prefix + 'birth_year').parent().addClass('has-success has-feedback');
}

function showBirthdateEmptyImg(prefix) {
    
}

function showBirthdateErrorImg(prefix) {
    $('#' + prefix + 'birth_year').parent().removeClass('has-success has-error has-feedback');
    $('#' + prefix + 'birth_year').parent().addClass('has-error has-feedback');
}

function showBirthdateWaitingImg(prefix) {
    $('#' + prefix + 'birth_year').parent().removeClass('has-success has-error has-feedback');
    $('#' + prefix + 'birth_year').parent().addClass('has-error has-feedback');
}


function fillCallingCode(country){
    country = $('#cboCountry').val();
    $.ajax({
           type: "GET"
           ,url:'https://gateway.payyap.network/country_to_callingcode.gate'
           ,data: { country_name: country }
           ,dataType: 'json'
           ,success:function(data){
            if(data!=null){
                $('#telephone_country_iso3').val(data.country_iso3);
                $('#telephone_calling_code').val('+' + data.calling_code);
            }
           }
           ,error:function(){
           
           }
           ,complete:function(){
           
           }
           });
    
    return false;
}

var CUSTOMER_IP = '0.0.0.0';
var viewport = null;
$(document)
.ready(function () {
      //alert('loaded');
      //goLogin();
      viewport = {
      width  : $(window).width(),
      height : $(window).height()
      };
       
       $('body').css('width', viewport.width + 'px');
      
      //CLIENT IP
      $.ajax({
         type: "GET"
         ,url: 'https://gateway.payyap.network/mobile_client_ip.gate'
         ,data: {}
         ,success:function(data){
             CUSTOMER_IP = data;
         }
      });
      
      fillCountryList('cboCountry', '');fillStateList('cboCountry', 'cboState', '');
});

var rand = function() {
    return Math.random().toString(36).substr(2); // remove `0.`
};

var token = function() {
    return rand() + rand() + rand(); // to make it longer
};

function showProgressDialog(){
    window.location.href = SITE_SCHEMA+'://showProgressDialog';
}
function hideProgressDialog(){
    window.location.href = SITE_SCHEMA+'://hideProgressDialog';
}

function checkAmountLimit(){
    var url = 'https://gateway.'+API_DOMAIN+'/get_account_limits.gate?member_hash=' + member_hash + '&account_hash=' + selected_account_hash;
    $('#recipient_requested_amount').parent().append('<div class="loading-img"><img src="loading.gif" style="width:30px;" /> Checking limit...</div>');
    $('#email_invoice_form button').attr('disabled', 'disabled');
    $.ajax({
           type: "GET"
           ,url:url
           ,data: {  }
           ,dataType: 'json'
           ,success:function(data){
           if(data!=null){
           var field = document.frmPayment['recipient_requested_amount'];
           var recipient_requested_amount = parseFloat($('#recipient_requested_amount').val());
           var minimum_amount = parseFloat(data.minimum);
           var maximum_amount = parseFloat(data.maximum);
           if(recipient_requested_amount < minimum_amount || recipient_requested_amount > maximum_amount){
           show_IOS_alert('ERROR', 'The Requested Amount must within ' + data.minimum + ' and ' + data.maximum + '.');
           showErrorImg(field);
           }
           else {
           showValidImg(field);
           }
           }
           }
           ,error:function(){
           
           }
           ,complete:function(){
           $('#recipient_requested_amount').parent().find('.loading-img').remove();
           $('#email_invoice_form button').removeAttr('disabled');
           }
           });
}

function processEmailInvoiceForm(){
    validateText(document.frmPayment['recipient_first_name'], 'onBlur');
    validateText(document.frmPayment['recipient_last_name'], 'onBlur');
    validateText(document.frmPayment['recipient_email_address'], 'onBlur');
    //validateText(document.frmPayment['recipient_invoice_no'], 'onBlur');
    //validateText(document.frmPayment['recipient_extra_note'], 'onBlur');
    validateText(document.frmPayment['recipient_requested_amount'], 'onBlur');
    
    if($('.form-group.has-error').length>0){
        show_IOS_alert('ERROR', 'Please complete the form');
    }
    else{
        showProgressDialog();
        
        setTimeout(function(){
                   var url = 'https://gateway.payyap.network/start_email_invoice.gate';
                   var post_data = 'member_hash=' + member_hash + '&account_hash=' + selected_account_hash + '&CUSTOMER_SESSION_ID=' + token() + '&CUSTOMER_IP=' + CUSTOMER_IP ;
                   
                   var recipient_first_name = $('#recipient_first_name').val();
                   var recipient_last_name = $('#recipient_last_name').val();
                   var recipient_email_address = $('#recipient_email_address').val();
                   var recipient_invoice_no = $('#recipient_invoice_no').val();
                   var recipient_extra_note = $('#recipient_extra_note').val();
                   var recipient_requested_amount = $('#recipient_requested_amount').val();
                   
                   post_data += "&firstname=" + recipient_first_name;
                   post_data += "&lastname=" + recipient_last_name;
                   post_data += "&emailaddress=" + recipient_email_address;
                   post_data += "&invoice_reference=" + recipient_invoice_no;
                   post_data += "&note=" + $('#recipient_extra_note').val();
                   post_data += "&amount=" + $('#recipient_requested_amount').val();
                   
                   console.log('post_data', post_data);
                   $.ajax({
                          type: "POST"
                          ,url: url
                          ,data: post_data
                          ,success:function(data){
                          hideProgressDialog();
                          setTimeout(function(){
                                     console.log(data);
                                     
                                     if (data.indexOf("<") == -1){
                                     if($.trim(data) == "OK"){
                                     
                                     //fill receipt form
                                     var selected_account_details = getSelectAccountDetails();
                                     $('#PAYYAP_email_invoice_amount').html(selected_account_details.amount);
                                     $('#PAYYAP_email_invoice_business_accountname').html(selected_account_details.account_name);
                                     $('#PAYYAP_email_invoice_payment_from').html(recipient_email_address);
                                     $('#PAYYAP_email_invoice_status').html('SUCCESS! (Your payment request has been sent.)');
                                     
                                     showStepPage('#email_invoice_form_receipt');
                                     }
                                     else{
                                     show_IOS_alert('ERROR', 'Failed to send Email Invoice! Please try again!' );
                                     }
                                     }
                                     else{
                                     show_IOS_alert('ERROR', 'Something went wrong! Please try again!' );
                                     }
                                     }, 1000);
                          }
                          ,error:function(){
                          console.log('error');
                          hideProgressDialog();
                          setTimeout(function(){
                                     show_IOS_alert('ERROR', 'Something went wrong! Please try again!' );
                                     }, 1000);
                          }
                          ,complete:function(){
                          hideProgressDialog();
                          }
                          });
                   }, 1000);
        
    }
    
    return false;
}

function processVerificationForm(){
    validateText(document.frmPayment['official_first_name'], 'onBlur');
    validateText(document.frmPayment['official_last_name'], 'onBlur');
    validateOfficialDOB(document.frmPayment['official_birth_year']);
    validateOfficialDOB(document.frmPayment['official_birth_month']);
    validateOfficialDOB(document.frmPayment['official_birth_day']);
    validateText(document.frmPayment['official_country_of_citizenship'], 'onBlur');
    validateText(document.frmPayment['goverment_id_number'], 'onBlur');
    
//    validateText(document.frmPayment['residential_country'], 'onBlur');
//    validateText(document.frmPayment['residential_state'], 'onBlur');
//    validateText(document.frmPayment['residential_postalcode'], 'onBlur');
//    validateText(document.frmPayment['residential_city'], 'onBlur');
//    validateText(document.frmPayment['residential_street_1'], 'onBlur');
//    
//    
//    if($('#banking_type1').is(':checked') || $('#banking_type2').is(':checked') ){
//        $('.PERSONAL_business_type_block').removeClass('has-success has-error has-feedback');
//        $('.BUSINESS_business_type_block').removeClass('has-success has-error has-feedback');
//        
//        if($('#banking_type1').is(':checked')){
//            $('.PERSONAL_business_type_block').addClass('has-success has-feedback');
//            
//            validateText(document.frmPayment['personal_business_type'], 'onBlur');
//            validateText(document.frmPayment['personal_business_name'], 'onBlur');
//            validateText(document.frmPayment['personal_business_web_address'], 'onBlur');
//        }
//        if($('#banking_type2').is(':checked') ){
//            $('.BUSINESS_business_type_block').addClass('has-success has-feedback');
//            
//            validateText(document.frmPayment['registered_business_type'], 'onBlur');
//            validateText(document.frmPayment['registered_business_name'], 'onBlur');
//            validateText(document.frmPayment['registered_business_tax_id_number'], 'onBlur');
//            validateText(document.frmPayment['registered_business_web_address'], 'onBlur');
//            
//            validateText(document.frmPayment['business_country'], 'onBlur');
//            validateText(document.frmPayment['business_state'], 'onBlur');
//            validateText(document.frmPayment['business_postalcode'], 'onBlur');
//            validateText(document.frmPayment['business_city'], 'onBlur');
//            validateText(document.frmPayment['business_street_1'], 'onBlur');
//        }
//    }
//    else{
//        $('#banking_type1').parent().parent().addClass('has-error has-feedback');
//        $('#banking_type2').parent().parent().addClass('has-error has-feedback');
//    }
//    
//    validateText(document.frmPayment['bank_name'], 'onBlur');
//    validateText(document.frmPayment['account_number'], 'onBlur');
//    validateText(document.frmPayment['local_routing_number'], 'onBlur');
//    validateText(document.frmPayment['swift_code'], 'onBlur');
//    
//    validateText(document.frmPayment['banking_country'], 'onBlur');
//    validateText(document.frmPayment['banking_state'], 'onBlur');
//    validateText(document.frmPayment['banking_postalcode'], 'onBlur');
//    validateText(document.frmPayment['banking_city'], 'onBlur');
//    validateText(document.frmPayment['banking_street_1'], 'onBlur');
//    validateText(document.frmPayment['banking_phone_number'], 'onBlur');
    
    if($('.form-group.has-error').length>0){
        show_IOS_alert('ERROR', 'Please complete the form');
    }
    else{
//        showStepPage('#identity_verification_photo_form');
//        fillPhotoIdForm();
        
        
        showStepPage('#verification_form_advanced');
        fillPhotoIdForm();
        //saveVerificationForm('personal');
        
    }
    
    return false;
}

function fillPhotoIdForm(){
    if($('#banking_type1').is(':checked')){
        $('.personal-block').css('display', 'block');
        $('.business-block').css('display', 'none');
    }
    else if($('#banking_type2').is(':checked')){
        $('.personal-block').css('display', 'none');
        $('.business-block').css('display', 'block');
    }
    
    var official_first_name = $('#official_first_name').val();
    var official_middle_name = $('#official_middle_name').val();
    var official_last_name = $('#official_last_name').val();
    var birth_date = $('#official_birth_year').val() + '-' + $('#official_birth_month').val() + '-' + $('#official_birth_day').val();
    var official_country_of_citizenship = $('#official_country_of_citizenship').val();
    var goverment_id_number = $('#goverment_id_number').val();
    
    $('.lbl_personal_identity_firstname').html(official_first_name);
    $('.lbl_personal_identity_middlename').html(official_middle_name);
    $('.lbl_personal_identity_lastname').html(official_last_name);
    $('#lbl_personal_identity_date_of_bith').html(birth_date);
    $('#lbl_personal_identity_country').html(official_country_of_citizenship);
    $('#lbl_personal_identity_id_number').html(goverment_id_number);
    
    var residential_country = $('#residential_country').val();
    var residential_street_1 = $('#residential_street_1').val();
    
    $('#lbl_residential_street_address').html(residential_street_1);
    $('#lbl_residential_country').html(residential_country);
    
    var personal_business_name = $('#personal_business_name').val();
    $('.lbl_personal_business_name').html(personal_business_name);
    
    var registered_business_name = $('#registered_business_name').val();
    var registered_business_tax_id_number = $('#registered_business_tax_id_number').val();
    var business_country = $('#business_country').val();
    var business_street_1 = $('#business_street_1').val();
    
    $('.lbl_business_name').html(registered_business_name);
    $('#lbl_business_tax_id').html(registered_business_tax_id_number);
    $('.lbl_business_country').html(business_country);
    
    var account_number = $('#account_number').val();
    
    $('#lbl_business_address').html(business_street_1);
    $('.lbl_bank_account_number').html(account_number);
    
}

function displayAccountNumber(){
    var account_number = $('#account_number').val();
    $('.lbl_bank_account_number').html(account_number);
}
function displayAdvancedFieldValues(e, id){
    $(id).html($(e).val());
}

function saveVerificationForm(formType){
    
    if(formType == 'advanced'){
//        validateText(document.frmPayment['residential_country'], 'onBlur');
//        validateText(document.frmPayment['residential_state'], 'onBlur');
//        validateText(document.frmPayment['residential_postalcode'], 'onBlur');
//        validateText(document.frmPayment['residential_city'], 'onBlur');
//        validateText(document.frmPayment['residential_street_1'], 'onBlur');
        
        
        if($('#banking_type1').is(':checked') || $('#banking_type2').is(':checked') ){
            $('.PERSONAL_business_type_block').removeClass('has-success has-error has-feedback');
            $('.BUSINESS_business_type_block').removeClass('has-success has-error has-feedback');
            
            if($('#banking_type1').is(':checked')){
                $('.PERSONAL_business_type_block').addClass('has-success has-feedback');
                
                validateText(document.frmPayment['personal_business_type'], 'onBlur');
                validateText(document.frmPayment['personal_business_name'], 'onBlur');
                //validateText(document.frmPayment['personal_business_web_address'], 'onBlur');
            }
            if($('#banking_type2').is(':checked') ){
                $('.BUSINESS_business_type_block').addClass('has-success has-feedback');
                
                validateText(document.frmPayment['registered_business_type'], 'onBlur');
                validateText(document.frmPayment['registered_business_name'], 'onBlur');
                validateText(document.frmPayment['registered_business_tax_id_number'], 'onBlur');
                //validateText(document.frmPayment['registered_business_web_address'], 'onBlur');
                
//                validateText(document.frmPayment['business_country'], 'onBlur');
//                validateText(document.frmPayment['business_state'], 'onBlur');
//                validateText(document.frmPayment['business_postalcode'], 'onBlur');
//                validateText(document.frmPayment['business_city'], 'onBlur');
//                validateText(document.frmPayment['business_street_1'], 'onBlur');
            }
        }
        else{
            $('#banking_type1').parent().parent().addClass('has-error has-feedback');
            $('#banking_type2').parent().parent().addClass('has-error has-feedback');
        }
        
//        validateText(document.frmPayment['bank_name'], 'onBlur');
//        validateText(document.frmPayment['account_number'], 'onBlur');
//        validateText(document.frmPayment['local_routing_number'], 'onBlur');
//        validateText(document.frmPayment['swift_code'], 'onBlur');
//        
//        validateText(document.frmPayment['banking_country'], 'onBlur');
//        validateText(document.frmPayment['banking_state'], 'onBlur');
//        validateText(document.frmPayment['banking_postalcode'], 'onBlur');
//        validateText(document.frmPayment['banking_city'], 'onBlur');
//        validateText(document.frmPayment['banking_street_1'], 'onBlur');
//        validateText(document.frmPayment['banking_phone_number'], 'onBlur');
        
        if($('.form-group.has-error').length>0){
            show_IOS_alert('ERROR', 'Please complete the form');
            return false;
        }
        //fillPhotoIdForm();
    }
    
    showProgressDialog();
    
    var post_data = 'member_hash=' + member_hash + '&account_hash=' + account_hash + '&BUSINESS_ACCOUNT_ID=' + selected_account_hash + '&CUSTOMER_SESSION_ID=' + token() + '&CUSTOMER_IP=' + CUSTOMER_IP ;
    var url = 'https://gateway.payyap.network/KYC_Wizard.gate';
    
    url = 'https://gateway.payyap.network/QUALIFY_Wizard.gate';
    
        var official_first_name = $('#official_first_name').val();
        var official_middle_name = $('#official_middle_name').val();
        var official_last_name = $('#official_last_name').val();
        var birth_date = $('#official_birth_year').val() + '-' + $('#official_birth_month').val() + '-' + $('#official_birth_day').val();
        var official_country_of_citizenship = $('#official_country_of_citizenship').val();
        var goverment_id_number = $('#goverment_id_number').val();
        
        post_data += "&official_first_name=" + official_first_name;
        post_data += "&official_middle_name=" + official_middle_name;
        post_data += "&official_last_name=" + official_last_name;
        post_data += "&official_birth_date=" + birth_date;
        post_data += "&official_birth_year=" + $('#official_birth_year').val();
        post_data += "&official_birth_month=" + $('#official_birth_month').val();
        post_data += "&official_birth_day=" + $('#official_birth_day').val();
        post_data += "&official_country_of_citizenship=" + official_country_of_citizenship;
        post_data += "&goverment_id_number=" + goverment_id_number;
        
        var business_category = 'SERVICE:Other';// $('#business_category').val();
        var verification_region = $('#verification_region').val();
        post_data += "&business_category=" + business_category;
        post_data += "&region=" + verification_region;
    //}
    if(formType == 'advanced') {
        var residential_country = $('#residential_country').val();
        var residential_state = $('#residential_state').val();
        var residential_postalcode = $('#residential_postalcode').val();
        var residential_city = $('#residential_city').val();
        var residential_street_1 = $('#residential_street_1').val();
        var residential_street_2 = $('#residential_street_2').val();
        
        post_data += "&residential_country=" + residential_country;
        post_data += "&residential_state=" + residential_state;
        post_data += "&residential_postalcode=" + residential_postalcode;
        post_data += "&residential_city=" + residential_city;
        post_data += "&residential_street_1=" + residential_street_1;
        post_data += "&residential_street_2=" + residential_street_2;
        
        
        var business_type = "PERSONAL";
        if($('#banking_type1').is(':checked')){
            business_type = "PERSONAL";
            
            var personal_business_type = $('#personal_business_type').val();
            var personal_business_name = $('#personal_business_name').val();
            //var personal_business_web_address = $('#personal_business_web_address').val();
            
            post_data += "&personal_business_type=" + personal_business_type;
            post_data += "&personal_business_name=" + personal_business_name;
            //post_data += "&personal_business_web_address=" + personal_business_web_address;
            
        }
        if($('#banking_type2').is(':checked') ){
            business_type = "BUSINESS";
            
            var registered_business_type = $('#registered_business_type').val();
            var registered_business_name = $('#registered_business_name').val();
            var registered_business_tax_id_number = $('#registered_business_tax_id_number').val();
            //var registered_business_web_address = $('#registered_business_web_address').val();
            
            post_data += "&registered_business_type=" + registered_business_type;
            post_data += "&registered_business_name=" + registered_business_name;
            post_data += "&registered_business_tax_id_number=" + registered_business_tax_id_number;
            //post_data += "&registered_business_web_address=" + registered_business_web_address;
            
//            var business_country = $('#business_country').val();
//            var business_state = $('#business_state').val();
//            var business_postalcode = $('#business_postalcode').val();
//            var business_city = $('#business_city').val();
//            var business_street_1 = $('#business_street_1').val();
//            var business_street_2 = $('#business_street_2').val();
//   
//            post_data += "&business_country=" + business_country;
//            post_data += "&business_state=" + business_state;
//            post_data += "&business_postalcode=" + business_postalcode;
//            post_data += "&business_city=" + business_city;
//            post_data += "&business_street_1=" + business_street_1;
//            post_data += "&business_street_2=" + business_street_2;
        }
        post_data += "&business_type=" + business_type;
        
//        var bank_name = $('#bank_name').val();
//        var account_number = $('#account_number').val();
//        var local_routing_number = $('#local_routing_number').val();
//        var swift_code = $('#swift_code').val();
//        
//        var banking_country = $('#banking_country').val();
//        var banking_state = $('#banking_state').val();
//        var banking_city = $('#banking_city').val();
//        var banking_postalcode = $('#banking_postalcode').val();
//        var banking_street_1 = $('#banking_street_1').val();
//        var banking_phone_number = $('#banking_phone_number').val();
//        
//        post_data += "&bank_name=" + bank_name;
//        post_data += "&account_number=" + account_number;
//        post_data += "&local_routing_number=" + local_routing_number;
//        post_data += "&swift_code=" + swift_code;
//        
//        post_data += "&banking_country=" + banking_country;
//        post_data += "&banking_state=" + banking_state;
//        post_data += "&banking_city=" + banking_city;
//        post_data += "&banking_postalcode=" + banking_postalcode;
//        post_data += "&banking_street_1=" + banking_street_1;
//        post_data += "&banking_phone_number=" + banking_phone_number;
    }
    console.log('post_data', post_data);
    $.ajax({
        type: "POST"
        ,url: url
        ,data: post_data
        ,success:function(data){
           hideProgressDialog();
           
           console.log(data);
           
//           if (data.indexOf("<") == -1){
//               if($.trim(data) == "OK"){
           
                   if(formType == 'personal'){
                    //showStepPage('#verification_form_advanced');
           showStepPage('#identity_verification_form_result');
                   }
                    else if(formType == 'advanced'){
                        showStepPage('#identity_verification_form_result');
                    }
//               }
               else{
                show_IOS_alert('ERROR', 'Account verification failed! Please try again!');
               }
//           }
//           else{
//            show_IOS_alert('ERROR', 'Something went wrong! Please try again!');
//           }
        }
        ,error:function(){
           console.log('error');
           hideProgressDialog();
           show_IOS_alert('ERROR', 'Something went wrong! Please try again!');
        }
        ,complete:function(){
           hideProgressDialog();
        }
    });
    return false;
}

var freeeswitch_uuid = '';
function processPayment1(){
    $('.processPayment1-error-message').html('');
    
    validateText(document.frmPayment['amount'], 'onBlur');
    validateText(document.frmPayment['name_on_card'], 'onBlur');
    
    validateSelectDOB(document.frmPayment['birth_year']);
    validateSelectDOB(document.frmPayment['birth_month']);
    validateSelectDOB(document.frmPayment['birth_day']);
    
    validateText(document.frmPayment['cardholder_email_address'], 'onBlur');
    validateText(document.frmPayment['billing_country'], 'onBlur');
    validateText(document.frmPayment['billing_state'], 'onBlur');
    validateText(document.frmPayment['billing_postalcode'], 'onBlur');
    validateText(document.frmPayment['billing_city'], 'onBlur');
    validateText(document.frmPayment['billing_street_1'], 'onBlur');
    //validateText(document.frmPayment['telephone_calling_code'], 'onBlur');
    validateText(document.frmPayment['telephone_country_iso3'], 'onBlur');    
    validateText(document.frmPayment['telephone_number'], 'onBlur');
    
    if(document.frmPayment['agreement_ACK1'].checked == false){
        var field = document.frmPayment['agreement_ACK1'];
        $(field).parent().parent().removeClass('has-success has-error has-feedback');
        $(field).parent().parent().addClass('has-error has-feedback');
    }
    else{
        var field = document.frmPayment['agreement_ACK1'];
        $(field).parent().parent().removeClass('has-success has-error has-feedback');
        $(field).parent().parent().addClass('has-success has-feedback');
    }
    if(document.frmPayment['agreement_ACK2'].checked == false){
        var field = document.frmPayment['agreement_ACK2'];
        $(field).parent().parent().removeClass('has-success has-error has-feedback');
        $(field).parent().parent().addClass('has-error has-feedback');
    }
    else{
        var field = document.frmPayment['agreement_ACK2'];
        $(field).parent().parent().removeClass('has-success has-error has-feedback');
        $(field).parent().parent().addClass('has-success has-feedback');
    }
    
    if($('.form-group.has-error').length>0){
        show_IOS_alert('ERROR', 'Please complete payment form');
    }
    else{
        
        showProgressDialog();
        
        //show_IOS_alert('SUCCESS', 'Success');
        var form_data = $('#frmPayment').serialize();
        
        var amount = $('#amount').val();
        var name_on_card = $('#name_on_card').val();
        var cardholder_email_address = $('#cardholder_email_address').val();
        var telephone_country_iso3 = $('#telephone_country_iso3').val();
        var telephone_number = $('#telephone_number').val();
        
        //var telephone_calling_code = $('#telephone_calling_code').val();
        var telephone_calling_code_text = $('#telephone_country_iso3 option:selected').text();
        var telephone_calling_code = telephone_calling_code_text.substr(telephone_calling_code_text.indexOf('|')+2);
        
        var birth_date = $('#birth_year').val() + '-' + $('#birth_month').val() + '-' + $('#birth_day').val();
        
        var url = 'https://gateway.v-sign.network/voice_authorization.api';
        var post_data = 'API_VERSION=vSIGN_For_payBANGK&member_hash=' + member_hash + '&BUSINESS_ACCOUNT_ID=' + selected_account_hash + '&CUSTOMER_SESSION_ID=' + token() + '&CUSTOMER_IP=' + CUSTOMER_IP + '&AUTHORIZATION_CATEGORY=PAYMENT&CUSTOMER_CANCEL_URL=mobile&CUSTOMER_APPROVED_URL=mobile&CUSTOMER_STATUS_URL=mobile&AUTHORIZATION_AMOUNT=' + amount + '&CUSTOMER_NAME=' + name_on_card + '&CUSTOMER_EMAIL_ADDRESS=' + cardholder_email_address + '&CUSTOMER_TELEPHONE_COUNTRY_ISO3=' + telephone_country_iso3;
        
        post_data += '&CUSTOMER_TELEPHONE_COUNTRY_CODE=' + telephone_calling_code;
        post_data += '&CUSTOMER_TELEPHONE_NUMBER=' + telephone_number;
        
        post_data += "&CUSTOMER_BILLING_COUNTRY_ISO3=" + telephone_country_iso3;
        post_data += "&CUSTOMER_BILLING_STATE_ISO2=" + $('#billing_state').val();
        post_data += "&CUSTOMER_BILLING_CITY=" + $('#billing_city').val();
        post_data += "&CUSTOMER_BILLING_POSTALCODE=" + $('#billing_postalcode').val();
        post_data += "&CUSTOMER_BILLING_STREET_1=" + $('#billing_street_1').val();
        post_data += "&CUSTOMER_BILLING_STREET_2=" + $('#billing_street_2').val();
        
        post_data += "&CUSTOMER_BIRTH_DATE=" + birth_date;
        post_data += "&CUSTOMER_BIRTH_YEAR=" + $('#birth_year').val();
        post_data += "&CUSTOMER_BIRTH_MONTH=" + $('#birth_month').val();
        post_data += "&CUSTOMER_BIRTH_DAY=" + $('#birth_day').val();
        
        $.ajax({
            type: "POST"
            //,url:'https://pay.'+API_DOMAIN+'/processing_secured_payment_authorization_mobile.nsdb'
            ,url: url
            ,data: post_data
            ,success:function(data){
               hideProgressDialog();
               
               console.log(data);
               
               if (data.indexOf("<") == -1){
                   freeeswitch_uuid = data;
                   get_payBANGK_authorization_status();
               
                   var phone_number_full = telephone_number;
                   if(phone_number_full.indexOf('+')===-1 && phone_number_full.indexOf('/')===-1) phone_number_full = telephone_calling_code + '/' + telephone_number;
                   $('#phone_number_called').html(phone_number_full);
               
                    showStepPage('#payment_result');
                    paymentStatusAnimation();
               }
               else{
                    $('.processPayment1-error-message').html(data);
                    setTimeout(function(){
                        show_IOS_alert('ERROR', 'Something went wrong! Please try again!' );
                    }, 500);
               }
            }
            ,error:function(){
               console.log('error');
               hideProgressDialog();
               setTimeout(function(){
                          show_IOS_alert('ERROR', 'Something went wrong! Please try again!' );
                          }, 500);
            }
            ,complete:function(){
               hideProgressDialog();
            }
        });
    }
    
    return false;
}

var paymentStatusAnimationTimer = null;
function paymentStatusAnimation(){
    
    var total_rows = $('.row_status').length;
    var payment_row_completed = 0;
    var payment_row_pending = 0;
    var paymentStatusAnimationRow = -1;
    //if(empty(paymentStatusAnimationRow)) paymentStatusAnimationRow = $('.row_status').length;
    
    $('.row_status').each(function(i, row){
                          //$(row).parent().parent().css('background-color', '#ff0000');
                          if($(row).find('img').attr('src')=='PAYYAP_status_GREEN.png') payment_row_completed += 1;
                          else if($(row).find('img').attr('src')=='PAYYAP_status_MEDIUMGRAY.png') { /*payment_row_pending += 1;*/ }
                          else paymentStatusAnimationRow = i;
                          });
    payment_row_pending = total_rows - payment_row_completed;
    console.log('total_rows:', total_rows, ', payment_row_completed:', payment_row_completed, ', payment_row_pending:', payment_row_pending, ', paymentStatusAnimationRow:', paymentStatusAnimationRow);
    
    var need_to_clear = false;
    if(payment_row_pending>0){
        if($('.row_status').eq(paymentStatusAnimationRow).find('img').attr('src')=='PAYYAP_status_MEDIUMGRAY.png') need_to_clear = true;
        if($('.row_status').eq(paymentStatusAnimationRow).find('img').attr('src')!='PAYYAP_status_GREEN.png'){
            $('.row_status').eq(paymentStatusAnimationRow).html("<img src='PAYYAP_status_MEDIUMGRAY.png' />");
        }
        paymentStatusAnimationTimer = setTimeout(function(){ paymentStatusAnimation(); }, 500);
        //setTimeout(function(){ paymentStatusAnimationTestFill(); }, 4000);
    }
    
    if(paymentStatusAnimationRow < payment_row_completed){
        if(need_to_clear){
            clearStatusIcons();
            paymentStatusAnimationRow = total_rows;
        }
    }
}

function paymentStatusAnimationTestFill(){
    
    var total_rows = $('.row_status').length;
    var payment_row_completed = 0;
    var payment_row_pending = 0;
    var paymentStatusAnimationRow = -1;
    
    $('.row_status').each(function(i, row){
                          if($(row).find('img').attr('src')=='PAYYAP_status_GREEN.png') payment_row_completed += 1;
                          });
    payment_row_pending = total_rows - payment_row_completed;
    console.log('2. total_rows:', total_rows, ', payment_row_completed:', payment_row_completed, ', payment_row_pending:', payment_row_pending, ', paymentStatusAnimationRow:', paymentStatusAnimationRow);
    
    $('.row_status').eq(payment_row_completed).html("<img src='PAYYAP_status_GREEN.png' />");
    blinkGreenStatus($('.row_status').eq(payment_row_completed));
}

function clearStatusIcons(){
    $('.row_status').each(function(i, row){
                          if($(row).find('img').attr('src')=='PAYYAP_status_MEDIUMGRAY.png'){
                          $(row).html("<img src='PAYYAP_status_DEFAULT.png' />");
                          }
                          });
}

function blinkGreenStatus(el){
    if($(el).find('img').attr('src')=='PAYYAP_status_MEDIUMGRAY.png' || $(el).find('img').attr('src')=='PAYYAP_status_DEFAULT.png'){
        if(!empty(paymentStatusAnimationTimer)) clearTimeout(paymentStatusAnimationTimer);
        clearStatusIcons();
        
        $(el).html("<img src='PAYYAP_status_GREEN.png' />");
        
        $(el).addClass('blink-status');
        setTimeout(function(){  $(el).removeClass('blink-status'); paymentStatusAnimation(); }, 4000);
    }
}

var xhr_status = null;
function get_payBANGK_authorization_status() {
    
    window.authorization_status_current = "";
    window.authorization_status_new = "";
    
    var url = 'https://gateway.payyap.network/payBANGK_authorization_status_update.gate?fuuid=' + freeeswitch_uuid;
    xhr_status = $.ajax({
           method: "GET",
           url: url,
           data: {  },
           /* dataType: "json" */
           })
    .done(function( status_new ) {
          //console.log( "Data saved: " + msg );
          
          /// if( (status_new == "Calling") || (status_new == "Call Made") ) {
          ///
          /// 	status_new = "status: CALLING (<? echo $_SESSION['payBANGK']['incoming_vars']['telephone_number']; ?>)";
          /// 	$('.authorization_status').html(status_new);
          
          
          if(status_new == "CONNECTED") {
          //$('.status_CONNECTED').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_CONNECTED'));
          }
          
          if(status_new == "IDENTITY") {
          //$('.status_IDENTITY').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_IDENTITY'));
          }
          
          if(status_new == "NAME_ON_CARD") {
          //$('.status_NAME_ON_CARD').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_NAME_ON_CARD'));
          }
          
          if(status_new == "CARD_NUMBER") {
          //$('.status_CARD_NUMBER').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_CARD_NUMBER'));
          }
          
          if(status_new == "CARD_EXPIRATION") {
          //$('.status_CARD_EXPIRATION').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_CARD_EXPIRATION'));
          }
          
          if(status_new == "CARD_CVV") {
          //$('.status_CARD_CVV').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_CARD_CVV'));
          }
          
          if(status_new == "AMOUNT") {
          //$('.status_AMOUNT').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_AMOUNT'));
          }
          
          if(status_new == "TERMS") {
          $('.status_TERMS').html("<img src='PAYYAP_status_GREEN.png' />");
          //$('.status_PROCESSING').html("<img src='PAYYAP_status_GREEN.png' />");
          blinkGreenStatus($('.status_PROCESSING'));
          
          }
          
          window.authorization_status_current = status_new;
          
          if(
             (window.authorization_status_current == "APPROVED") ||
             (window.authorization_status_current == "DECLINED") ||
             (window.authorization_status_current == "CANCELED")
             ) {
          setTimeout(makeTheJump, 3000);
          }
          else{
          get_payBANGK_authorization_status();
          }
          
          })
    .fail(function( jqXHR, textStatus ) {
          //console.log( "Data not saved: " + textStatus );
          //setTimeout(makeTheJump, 3000);
          });
    
    function makeTheJump() {
        //window.location = "https://pay.payyap.network/transaction_receipt.nsdb";
        $.ajax({
            type: "GET"
            ,url:'https://gateway.payyap.network/PAYYAP_receipt.php?freeswitch_uuid=' + freeeswitch_uuid
            ,data: {}
            ,success:function(data){
               $('#payment_receipt').html(data);
               if(!empty(paymentStatusAnimationTimer)) clearTimeout(paymentStatusAnimationTimer);
               showStepPage('#payment_receipt');
            }
            ,error:function(){
               
            }
            ,complete:function(){
               
            }
        });
    }
}	


function cancel_hangup() {
    if(xhr_status!=null) xhr_status.abort();
    showStepPage('#payment_form');
    $('#payment_form #amount').focus();
    $('.form-group').removeClass('has-error has-success has-feedback');
    $('.form-group .glyphicon').remove();
    return false;
}

function startNewBillingAddress(){
    cancel_hangup();
    resetPaymentForm();
    showStepPage('#account_form');
}
function startSameBillingAddress(){
    clearPaymentMessages();
    cancel_hangup();    
}

function sendNewEmailInvoice(){
    resetPaymentForm();
    showStepPage('#account_form');
    return false;
}

function resetPaymentForm(){
    document.getElementById("frmSignIn").reset();
    document.getElementById("frmPayment").reset();
    clearPaymentMessages();
}

function clearPaymentMessages(){
    $('#phone_number_called').html("");
    $('.status_CONNECTED').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_IDENTITY').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_NAME_ON_CARD').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_CARD_NUMBER').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_CARD_EXPIRATION').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_CARD_CVV').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_AMOUNT').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_TERMS').html('<img src="PAYYAP_status_DEFAULT.png" />');
    $('.status_PROCESSING').html('<img src="PAYYAP_status_DEFAULT.png" />');
        
    $('.form-group').removeClass('has-error has-success has-feedback');
    $('.form-group .glyphicon').remove();
}

function fillDemoForm(){
    $('#birth_year option:eq(2)').prop('selected', true);
    $('#birth_month option:eq(2)').prop('selected', true);
    $('#birth_day option:eq(2)').prop('selected', true);
    console.log($('#cardholder_email_address'));
    $('#cardholder_email_address').val('j.doe@example.com');
    console.log($('#cardholder_email_address'));
    $('#cboCountry').val('USA');
    $('#cboCountry').change();
    $('#billing_postalcode').val('0000');
    $('#billing_city').val('city');
    $('#billing_street_1').val('address1');
    $('#billing_street_2').val('address2');
    
    //$('#telephone_country_iso3').html('');
    
    $('#agreement_ACK1').prop('checked', true);
    $('#agreement_ACK2').prop('checked', true);
    
    //$('#telephone_number').val('+');
    
    $('.form-block').css('display', 'none');
}


function empty(v){
    if(v == '' || v == null || v == undefined) return true;
    return false;
}


function showHideLoader(show){
    if(show){
        $('#loading').html('<img src="loading.gif" />');
    }
    else $('#loading').html('');
}

function getAuthText_old(){
    clearErrors();
    //window.location.href = SITE_SCHEMA + '://getauthtext';
    showHideLoader(true);
    var email = $('#inputEmail').val();
    var password = $('#inputPassword').val();
    $.ajax({
           type: "GET"
           ,url:'https://gateway.'+API_DOMAIN+'/ios.gate?action=getPhotoBANGKUser'
           ,data: { email: email, password: password }
           ,dataType: 'json'
           ,success:function(data){
           //console.log(data);
           //updateContent(data);
           if(!empty(data.error)){
           displayErrors(data.error);
           }
           else{
           var remember = "false";
           if($("#remember").is(':checked')) remember = "true";
           goLogin(data.hash + ":" + remember);
           showHome(data.hash);
           }
           }
           ,error:function(){
           displayErrors('An error occurred, please try again.');
           }
           ,complete:function(){
           showHideLoader(false);
           }
           });
    return false;
}

//var additionalParameters = {};
function getMemberEmailAddress(){
    clearErrors();
    showHideLoader(true);
     $('#signin-input').addClass('hide_tell_friend_row');
    window.location.href = SITE_SCHEMA+'://account_access?emailaddress=&callback=showMemberEmailAddress';
    return false;
}

function showMemberEmailAddress(params){
    if(!empty(params)) additionalParameters = $.parseJSON(params);
    var newParams = {};
    if(!empty(additionalParameters.PAYYAP_version)) newParams.PAYYAP_version = additionalParameters.PAYYAP_version;
    if(!empty(additionalParameters.PAYYAP_device_type)) newParams.PAYYAP_device_type = additionalParameters.PAYYAP_device_type;
    $.ajax({
           type: "GET"
           ,url:'https://gateway.'+API_DOMAIN+'/get_member_emailaddress.gate'
           ,data: $.extend( { member_hash: member_hash, account_hash: account_hash }, newParams )
           //,dataType: 'json'
           ,success:function(data){
           console.log('data', data);
           try
           {
           data = $.parseJSON(data);
           }
           catch(err)
           {
           console.log('err', err);
            data = {member_emailaddress: data, force_update: 'NO'};
           }
           if(!empty(data)){
           if(data.force_update.toUpperCase() == 'YES'){
           $('#signin-input').addClass('hide_tell_friend_row');
           displayErrors("To login, please update PAYYAP now.");
           }
           else{
           $('#signin-input').removeClass('hide_tell_friend_row');
           $('#inputEmail').val(data.member_emailaddress);
           $('#inputEmail').focus();
           }
           }
           }
           ,error:function(){
           //reset
           $('#signin-input').removeClass('hide_tell_friend_row');
           $('#inputEmail').val('');
           $('#inputEmail').focus();
           }
           ,complete:function(){
           showHideLoader(false);
           }
           });
}

function getAccountAccess(){
    clearErrors();
    showHideLoader(false);
    var email = $('#inputEmail').val();
    email = $.trim(email);
    if(empty(email)) {
        displayErrors("Email Address can't be empty!");
        $('#inputEmail').focus(); return false;
    }
    showHideLoader(true);
    email_address = email;
    
    window.location.href = SITE_SCHEMA+'://account_access?emailaddress=' + email + '&callback=getAuthText';
    
    return false;
}

var demoAccountHash = '97d1ea8d7fb372558954fc6554e15215'; //'728872d4704be61221050fffc74c704f'; //'fc053601513728fe23a5e1008950bf4a';
function getAuthText(params){
    console.log('params', params);
    if(typeof params != 'object' ){
        if(!empty(params)) additionalParameters = $.parseJSON(params);
        console.log('params', additionalParameters);
    }
    //open_social_blast_options_form(); return;
    clearErrors();
    //window.location.href = SITE_SCHEMA+'://getauthtext';
    
    var email = $('#inputEmail').val();
    email = $.trim(email);
    if(empty(email)) { $('#inputEmail').focus(); return false;}
//    if(email == 'demo@corp.nsdb.com' || email == 'demo@payyap.network' || email == 'shahid@corp.nsdb.com'){
//        if(email == 'demo@payyap.network') demoAccountHash = '2a31b58f2a89687254ba451be3114b97';
//        else if(email == 'shahid@corp.nsdb.com') demoAccountHash = '728872d4704be61221050fffc74c704f';
//        account_hash = demoAccountHash;
//        
//        //showHome(account_hash);
//        showHideLoader(false);
//        
//        goLogin('account_hash=' + account_hash);
//        
//        return false;
//    }
    
    //showHideLoader(true);
    $.ajax({
           type: "GET"
           ,url:'https://gateway.'+API_DOMAIN+'/nsdbAPP_account_access.gate'
           ,data: $.extend( { SITE_SCHEMA: SITE_SCHEMA, PAYYAP_device_IP: CUSTOMER_IP }, additionalParameters )
           //,dataType: 'json'
           ,success:function(data){
               //console.log(data);
               //updateContent(data);
               
               if(data == 'OK'){
                    displayErrors("<span style='color:green;'>A validation email has been sent! Please check your INBOX (or SPAM Folder) and click on the link.</span>");
               }
               else{
                   if(!empty(data)) data = $.parseJSON($.trim(data));
                   console.log(account_hash, member_hash);
                   if(typeof data == 'object' ){
                       account_hash = data.account_hash;
                       member_hash = data.member_hash;
                       
                       showHome(account_hash);
                   }
                   else{
                       displayErrors('An error occurred, please try again.');
                   }
               }
           }
           ,error:function(){
           displayErrors('An error occurred, please try again.');
           }
           ,complete:function(){
           showHideLoader(false);
           }
           });
    
    return false;
}

function logout(){
    resetPaymentForm();
    //member_hash = '';
    goLogout();
    //showLogin();
    return false;
}


function goHome(){
    window.location.href = SITE_SCHEMA+'://home';
}

function goLogin(hash){
    window.location.href = SITE_SCHEMA+'://login?' + hash;
}
function goLogout(){
    window.location.href = SITE_SCHEMA+'://logout';    
}

function showPhotoActionMenu(){
    window.location.href = SITE_SCHEMA+'://showPhotoActionMenu';
}

function showHome(hash){
    member_hash = '';
    selected_account_hash = null;
    accountLists = null;
    searchHistory = [];
    
    account_hash = hash;
    $('#logo').css('width', '100%');
    $('#logo').css('padding-top', '20px');
    //$('#logo').css('padding-bottom', '40px');
    $('#logo').attr('src', 'PAYYAP_2048x452T.png');
    
    //$('.sologan').css('position', 'relative');
    //$('.sologan').css('top', '0px');
    
    $('#frmSignIn').css('display', 'none');
    $('#frmPayment').css('display', 'block');
    
    //showAccountLists();
    
    showStepPage('#account_form');
    //galleryStats();
    
    //showStepPage('#payment_result');
    //paymentStatusAnimation();
}
function showLogin(){
    $('#logo').css('width', '50%');
    $('#logo').css('padding-top', '0px');
    //$('#logo').css('padding-bottom', '0px');
    $('#logo').attr('src', 'PAYYAP_1024x852.png');
    
    //$('.sologan').css('position', 'relative');
    //$('.sologan').css('top', '-40px');
    
    //$('#inputEmail').val(email_address);
    $('#frmSignIn').css('display', 'block');
    $('#frmPayment').css('display', 'none');
    
    getMemberEmailAddress();
}

function takePhoto(imageNo){
    window.location.href = SITE_SCHEMA+'://takePhoto?imageNo=' + imageNo;
    return false;
}

function selectPhoto(imageNo){
    window.location.href = SITE_SCHEMA+'://selectPhoto?imageNo=' + imageNo;
    return false;
}

function photoLoaded(imageNo){
    //
}

function formatImageNo(imageNo){
    var tempimageNo  = imageNo;
    if(tempimageNo>3) tempimageNo -= 1;
    return tempimageNo;
}

function showSelectedImage(data, imageNo){
    var html = '<div class="photo-container photo' + imageNo + '">';
    //html += '<div class="upload-no">DOCUMENT #'+formatImageNo(imageNo)+'</div>';
    html += '<div class="upload-no"></div>';
    
    html += '<div class="progress" style="margin-bottom:0; display:none;">';
    html += '<div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">';
    html += '0%';
    html += '</div>';
    html += '</div>';
    
    html += '<div class="photo"><img src="'+data + '?' + generateRandomNumber()+'" onload="photoLoaded(' + imageNo + ');" /></div>';
    html += '<div class="editForm"></div>';
    html += '</div>';
    
    //$('#selectedImage img').attr('src', data + "?" + generateRandomNumber() );
    //$('#selectedImage img').css('display', 'inline-block');
    
    //$('#selectedImage').prepend(html);
    $('#selectedImage' + imageNo).html(html);
    
    var n = $( ".photo-container" ).length;
    //$('#selectedImage').css('width', (n * 320) + 'px' );
    
    //$('.photo-container').css('max-width', viewport.width);
    //$('.photo-container .photo img').css('max-height', '100px');
    
    /*
     var r = confirm("Want to keep the image?");
     if (r == true) {
     
     } else {
     window.location.href = SITE_SCHEMA+'://removePhoto';
     }
     */
    window.location.href = SITE_SCHEMA+'://openConfirmModal';
    //open_social_blast_options_form();
    
}

function setProgress(value, imageNo){
    //console.log('progress=', value, 'imageNo=', imageNo);
    //$('.photo' + imageNo +' .progress').css('display' , 'block');
    $('.photo' + imageNo +' .progress-bar').html(value + '%');
    $('.photo' + imageNo +' .progress-bar').css('width', value + '%');
    $('.photo' + imageNo +' .progress-bar').attr('aria-valuenow', value );
    //console.log($('.photo' + imageNo +' .progress'));
}

function deleteSelectedImage(imageNo){
    //$('#selectedImage img').attr('src', 'null');
    //$('#selectedImage img').css('display', 'none');
    $('.photo' + imageNo ).remove();
}

function startUploading(imageNo){
    //$('#uploading').css('display', 'inline-block');
    //$('.photo' + imageNo).find('.upload-no').html('DOCUMENT #'+formatImageNo(imageNo)+' Uploading... <img src="loading.gif" style="width:16px;" />');
    $('.photo' + imageNo).find('.upload-no').html('Uploading... <img src="loading.gif" style="width:16px;" />');
    $('.photo' + imageNo +' .progress').css('display' , 'block');
    setTimeout(function(){ uploadPhoto(); }, 1000);
    
}

function uploadPhoto(){
    window.location.href = SITE_SCHEMA+'://uploadPhoto';
}

function uploadFinished(data){
    data = $.parseJSON(data);
    //console.log(data);
    if(!empty(data.msg)){
        $('.photo' + data.imageNo ).find('.progress').css('display' , 'none');
        $('.photo' + data.imageNo ).find('.upload-no').html('<span style="color:red;">' + data.msg + '</span>');
    }
    else {
        $('.photo' + data.imageNo ).find('.progress').css('display' , 'none');
        $('.photo' + data.imageNo ).find('.upload-no').html('<span style="color:green;">Uploaded</span>');
    }
}

function goToTopOfPage(){
    $('html, body').animate({
                            scrollTop: $(".form-signin-heading").offset().top
                            }, 1000);
}

function showStepPage(id){
    $('.logout').parent().css('display', 'none');
    
    $('.step-page').css('display', 'none');
    $(id).css('display', 'block');
    
    searchHistory.push(id);
    if(id == '#payment_receipt' || id == '#identity_verification_form_result' || id =='#email_invoice_form_receipt'){
        searchHistory = []; //clear searHistory
    }
    
    fillDemoForm();
    if(demoAccountHash==account_hash && id=='#payment_form'){
        //fillDemoForm();
    }
    else if(id == '#account_form'){
        $('.logout').parent().css('display', 'block');
        showAccountLists();
    }
    else if(id=='#selected_account_form' || id=='#email_invoice_form' || id=='#email_invoice_form_receipt' || id=='#identity_verification_region' || id=='#verification_form_advanced'){
        $('.logout').parent().css('display', 'none');
    }
    else if(id=='#identity_verification_form'){
        $('.logout').parent().css('display', 'none');
        $('html, body').animate({
                                scrollTop: $(".form-signin-heading").offset().top
                                }, 1000);
    }
    else if(id=='#identity_verification_photo_form'){
        $('.logout').parent().css('display', 'none');
        $('html, body').animate({
                                scrollTop: $(".form-signin-heading").offset().top
                                }, 1000);
    }
    else if(id=='#identity_verification_form_result'){
        $('.logout').parent().css('display', 'none');
    }
    else{
        //$('.logout').parent().css('display', 'block');
    }
    
    //fill form data
    if(id=='#identity_verification_region'){
        $('#verification_region').val(verification_region);
    }
    return false;
}
var selected_account_hash = '';
function selectAccount(account_hash){
    
    $('.form-group').removeClass('has-error has-success has-feedback');
    $('.form-group .glyphicon').remove();
    
    selected_account_hash = account_hash;
    resetPaymentForm();
    var selected_account_details = getSelectAccountDetails();
    //console.log(selected_account_details);
    if(selected_account_details!=null){
        $('.lblAccountName').html(selected_account_details.account_name);
        
        $('.account_name').html(selected_account_details.account_name);
        $('.account_balance').html(selected_account_details.account_balance);
        
        if(empty(selected_account_details.service_message)){
            $('.service-message-row').css('display', 'none');
        }
        else{
            $('.service_message').html(selected_account_details.service_message);
            $('.service-message-row').css('display', 'block');
        }
        
        showTransactionHistory();
        
        showStepPage('#selected_account_form');
    }
    else{
        show_IOS_alert('ERROR', 'An error occured, please try again!');
    }
}
function showSubmittedAlert(){
    show_IOS_alert('ERROR', 'You have already submitted your profile.  A final activation notice will be sent to your registered email address once your payment processing account has been approved.  Now sit back, relax... and allow up to 72 hours for your account to be acivated!');
    return false;
}
function openPaymentForm(){
    showStepPage('#payment_form');
    $('#payment_form #amount').focus();
    return false;
}
function showEmailInvoiceForm(){
    show_IOS_alert('ALERT', 'Coming Soon...');
    //showStepPage('#email_invoice_form');
    return false;
}
function getSelectAccountDetails(){
    var selected_account_details = null;
    if(accountLists!=null){
        $.each(accountLists, function(index, item){
               if(item.account_hash == selected_account_hash){
               //console.log(selected_account_hash, item);
                selected_account_details = item;
               }
               });
    }
    return selected_account_details;
}
var verifyFormCountryLoaded = false;
function verifyAccount(account_hash){
    
    $('.form-group').removeClass('has-error has-success has-feedback');
    $('.form-group .glyphicon').remove();
    
    //window.location.href = SITE_SCHEMA+'://confirmAccountVerification';
    
    showVerificationForm(account_hash);
    
    return false;
}
function showVerificationForm(account_hash){
    selected_account_hash = account_hash;
    
    //show_IOS_alert('ERROR', 'ALERT: This account needs to be validated before is it able to receives money.  Please use your email address, to log into your BANGK! Account @ https://login.payyap.network, and follow the logical instructions to Verify this account.  Account validation takes about 5 minutes from your desktop, laptop or tablet.');
    
    if(!verifyFormCountryLoaded){
        fillCountryList('official_country_of_citizenship');
        //fillCountryList('residential_country');fillStateList('residential_country', 'residential_state');
        //fillCountryList('business_country');fillStateList('business_country', 'business_state');
        //fillCountryList('banking_country');fillStateList('banking_country', 'banking_state');
        
        verifyFormCountryLoaded = true;
    }
    
    showStepPage('#identity_verification_region');
    
}


function getAccountEmailAddress(){
    var url = 'https://gateway.'+API_DOMAIN+'/NSDB_account_menu.gate?gate_key=NSDBECP&member_hash=' + member_hash + '&account_hash=' + account_hash + '&action=get_emailaddress';
    $.ajax({
        type: "GET"
        ,url:url
        ,data: {  }
        ,dataType: 'json'
        ,success:function(data){
           //console.log(data);
           if(!empty(data) && !empty(data.emailaddress)){
            login_email = data.emailaddress;
           }
           
        }
        ,error:function(){
           
        }
        ,complete:function(){
           
        }
    });
    return false;
}

var accountLists = null;
function showAccountLists(){
    //getAccountEmailAddress();
    var url = 'https://gateway.'+API_DOMAIN+'/NSDB_account_menu.gate?gate_key=NSDBECP&member_hash=' + member_hash + '&account_hash=' + account_hash + '&PAYYAP_version=' + additionalParameters.PAYYAP_version;
    //console.log(url);
    $('#account_buttons').html('<img src="loading.gif" style="width:30px;" />');
    $.ajax({
        type: "GET"
        ,url:url
        ,data: {  }
        ,dataType: 'json'
        ,success:function(data){
           if(!empty(data)){
               if(!empty(data.display_TELL_A_FRIEND) && data.display_TELL_A_FRIEND != 'OFF'){
               $('#rowTellFriends').removeClass('hide_tell_friend_row');
               }
               else {
               $('#rowTellFriends').addClass('hide_tell_friend_row');
               }
               accountLists = data.account_menus;
            var account_html = '';
           var pending_account = 0;
           var setMemberHash = false;
            $.each(accountLists, function(index, item){
                if(empty(member_hash)){
                    member_hash = item.member_hash;
                    setMemberHash = true;
                }
                   
                   //item.account_status = '(verification required)';
                   
                   if(item.account_status.toUpperCase() == 'VERIFIED'){
                        account_html += '<button class="btn btn-lg btn-primary btn-block" name="PAYYAP_ACCOUUNT[]" onClick="return selectAccount(\'' + item.account_hash + '\');" >';
                        account_html += '<span id="PAYYAP_ACCOUUNT_NAME[]">' + item.account_name + '</span>';
                        account_html += '<br>';
                        account_html += '<span id="PAYYAP_ACCOUUNT_BALANCE[]">Balance: ' + item.account_balance + ' USD</span>';
                        account_html += '</button>';
                    }
                   else if(item.account_status == '(verification required)'){
                       account_html += '<button style="background-color:#cccccc;" class="btn btn-lg btn-primary btn-block" name="PAYYAP_ACCOUUNT[]" onClick="return verifyAccount(\'' + item.account_hash + '\');">';
                       account_html += '<span id="PAYYAP_ACCOUUNT_NAME[]">' + item.account_name + '</span>';
                       account_html += '<br>';
                       account_html += '<span>(Configure & Activate Account)</span>';
                       account_html += '</button>';
                   }
                   else if(item.account_status.toLowerCase().indexOf('pending') != -1 || item.account_status == 'SUBMITTED'){
                        pending_account++;
                        account_html += '<button style="background-color: #ffcc00; color:#000000;" class="btn btn-lg btn-success btn-block" name="PAYYAP_ACCOUUNT[]" onClick="return showSubmittedAlert();" >';
                       account_html += '<span id="PAYYAP_ACCOUUNT_NAME[]">' + item.account_name + '</span>';
                       account_html += '<br>';
                       account_html += '<span>(PENDING)</span>';
                       account_html += '</button>';
                   }
                   else{
                       account_html += '<button class="btn btn-lg btn-danger btn-block" type="button" name="PAYYAP_ACCOUUNT[]" >';
                       account_html += '<span id="PAYYAP_ACCOUUNT_NAME[]">' + item.account_name + '</span>';
                       account_html += '<br>';
                       account_html += '<span>(' + item.account_status + ')</span>';
                       account_html += '</button>';
                   }
                   account_html += '<br>';
            });
               if(pending_account>0){
               account_html += '<br><button class="btn btn-lg" onClick="return showAccountLists();">Check For Updates</button><br><br>';
               }
               $('#account_buttons').html(account_html);
               
               if(setMemberHash){
                window.location.href = SITE_SCHEMA+'://setMemberHash?member_hash='+member_hash;
               }
           }
        }
        ,error:function(){
           var account_html = '';
           account_html += '<h3><span style="color:red;">Failed to load Account List!</span></h3>';
           account_html += '<br><button class="btn" onClick="return showAccountLists();">Click here to reload</button><br>';
           $('#account_buttons').html(account_html);
        }
        ,complete:function(){
           
        }
    });
    return false;
}

function showTransactionHistory(){
    //selected_account_hash = '0f3c24cc0756e881b0feb984772f421f';
    var url = 'https://gateway.'+API_DOMAIN+'/vWAVE_transaction_history.gate?member_hash=' + member_hash + '&account_hash=' + selected_account_hash + '&history=25';
    //console.log(url);
    
    $('#transactionHistoryCancel').css('display', 'none');
    $('#transactionHistoryBlock').css('display', 'block');
    $('#transactionHistoryBlock').html('<img src="loading.gif" style="width:30px;" />');
    $.ajax({
           type: "GET"
           ,url:url
           ,data: {  }
           ,dataType: 'json'
           ,success:function(data){
           if(data!=null){
           var history_html = '<div style="text-align:left;"><b>Transaction History:</b></div>';
           
           history_html += '<table border="1" style="width:100%;">';
           history_html += '<tr>';
           history_html += '<th style="width:50%;padding: 0 5px;">';
           history_html += 'Name';
           history_html += '</th><th style="padding: 0 5px;text-align: right;">';
           history_html += 'AMOUNT';
           history_html += '</th>';
           history_html += '<th style="padding: 0 5px;text-align: right;">';
           history_html += 'STATUS';
           history_html += '</th>';
           history_html += '</tr>';
           $.each(data, function(index, item){
                  history_html += '<tr>';
                  history_html += '<td style="width:50%;padding: 0 5px;text-align: left;">';
                  history_html += '<div style="width:95%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">';
                  history_html += item.CUSTOMER_FULL_NAME
                  history_html += '</div>';
                  history_html += '</td><td style="padding:0 5px; text-align: right;">';
                  history_html += item.AUTHORIZATION_AMOUNT;
                  history_html += '</td>';
                  history_html += '<td style="padding: 0 5px; text-align: right;">';
                  history_html += item.AUTHORIZATION_STATUS;
                  history_html += '</td>';
                  
                  });
           if(data.length<1){
           history_html += '<tr>';
           history_html += '<td colspan="3" style="padding: 0 15px;">';
           history_html += '(no transaction history)';
           history_html += '</td>'
           history_html += '</tr>'
           }
           history_html += '</table>'
           if(data.length>0){
           $   ('#transactionHistoryCancel').css('display', 'block');
           }
           $('#transactionHistoryBlock').css('display', 'block');
           $('#transactionHistoryBlock').html(history_html);
           
           }
           }
           ,error:function(){
           var history_html = '';
           $('#transactionHistoryBlock').html(history_html);
           }
           ,complete:function(){
           
           }
           });
    return false;
}

function generateRandomNumber(){
    return Math.floor((Math.random() * 100) + 1);
}

function show_IOS_alert(type, msg){
    window.location.href = SITE_SCHEMA+'://showAlert/' + type + ':' + msg;
}

var searchHistory = [];
function goBack(){
    var lastItem = searchHistory.pop();
    lastItem = searchHistory.pop();
    //alert(lastItem);
    if(!empty(lastItem)){
        showStepPage(lastItem);
    }
    else{
        //alert("dd");
        window.location.href = SITE_SCHEMA+'://finish';
    }
}

var contactCategory = '';
function openContact(category){
    contactCategory = category;
    if(contactCategory == 'tell_friends_form'){
        $('.contactsUploadingStatus').html('<img src="loading.gif" />');
    }
    window.location.href = SITE_SCHEMA+'://openContact/' + contactCategory;
    return false;
}

function fillFormDataFromContact(email, name, phone){
    if(!empty(phone)){
        phone = phone.replace(/ /g, "");
        phone = phone.replace(/-/g, "");
        phone = phone.replace(/\+/g, "");
    }
    console.log('email, name, phone', email, name, phone);
    switch(contactCategory){
        case 'payment_form':
            $('#cardholder_email_address').val(email);
            $('#name_on_card').val(name);
            $('#telephone_number').val(phone);
            
            $('#cardholder_email_address').blur();
            $('#name_on_card').blur();
            $('#telephone_number').blur();
            break;
        case 'email_invoice':
            $('#recipient_email_address').val(email);
            $('#recipient_first_name').val(name);
            
            $('#recipient_email_address').blur();
            $('#recipient_first_name').blur();
            break;
        case 'official_identity':
            $('#official_first_name').val(name);
            $('#official_first_name').blur();
            break;
        case 'tell_friends_form':            
            break;
        case 'XXXX':
            break;
        default:
            break;
    }
    
    return false;
}

function contactUploadFinished(){
    $('.contactsUploadingStatus').html('');
}

function showRegionalVerificationForm(){

        verification_region = $('#verification_region').val();
        showStepPage('#TSYS_form');
        $('#tsys_email_address').val(email_address);
        $('#tsys_email_address').focus();
        if(verification_region == 'united_states'){
            $('.us-field').css('display', 'block');
            $('.non-us-field').css('display', 'none');
            $('#tsys_social_security_number').val('');
        }
        else{
            $('.us-field').css('display', 'none');
            $('.non-us-field').css('display', 'block');
            $('#tsys_personal_id_number').val('');
            //showStepPage('#identity_verification_form');
        }
    
        window.location.href = SITE_SCHEMA+'://verification_region/' + verification_region;

    return false;
}

function activeMerchantID(el){
    
    validateText(document.frmPayment['tsys_email_address'], 'onBlur');
    validateText(document.frmPayment['tsys_first_name'], 'onBlur');
    validateText(document.frmPayment['tsys_last_name'], 'onBlur');
    validateText(document.frmPayment['tsys_street_address'], 'onBlur');
    validateText(document.frmPayment['tsys_zip_code'], 'onBlur');
    //validateText(document.frmPayment['tsys_city_stats'], 'onBlur');
    validateText(document.frmPayment['tsys_phone_number'], 'onBlur');
    validateText(document.frmPayment['tsys_social_security_number'], 'onBlur');
    validateText(document.frmPayment['tsys_personal_id_number'], 'onBlur');
    validateTSYSDOB(document.frmPayment['tsys_birth_year']);
    validateTSYSDOB(document.frmPayment['tsys_birth_month']);
    validateTSYSDOB(document.frmPayment['tsys_birth_day']);
    //validateText(document.frmPayment['TSYS_merchant_account_id'], 'onBlur');
    
    if(verification_region == 'united_states'){
        $('#tsys_personal_id_number').parent().removeClass('has-error');
        $('#tsys_personal_id_number').val('');
    }
    else{
        $('#tsys_social_security_number').parent().removeClass('has-error');
        $('#tsys_social_security_number').val('');
    }
    
    //ERROR CHECKING
    var no_of_error = 0;
    if($('#tsys_email_address').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_first_name').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_last_name').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_street_address').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_zip_code').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_phone_number').parent().hasClass('has-error')) no_of_error++;
    if(verification_region == 'united_states'){
        if($('#tsys_social_security_number').parent().hasClass('has-error')) no_of_error++;
    }
    else{
        if($('#tsys_personal_id_number').parent().hasClass('has-error')) no_of_error++;
    }
    if($('#tsys_birth_year').parent().hasClass('has-error')) no_of_error++;
    
    //alert(no_of_error);
    //if($('.form-group.has-error').length>0){
    if(no_of_error>0){
        show_IOS_alert('ERROR', 'Please complete the form');
        return false;
    }
    else{
        var tsys_email_address = $('#tsys_email_address').val();
        var tsys_first_name = $('#tsys_first_name').val();
        var tsys_last_name = $('#tsys_last_name').val();
        var tsys_street_address = $('#tsys_street_address').val();
        var tsys_zip_code = $('#tsys_zip_code').val();
        //var tsys_city_stats = $('#tsys_city_stats').val();
        var tsys_phone_number = $('#tsys_phone_number').val();
        var tsys_social_security_number = $('#tsys_social_security_number').val();
        var tsys_birth_year = $('#tsys_birth_year').val();
        var tsys_birth_month = $('#tsys_birth_month').val();
        var tsys_birth_day = $('#tsys_birth_day').val();
        //var TSYS_merchant_account_id = $('#TSYS_merchant_account_id').val();
        
        //,url:'https://gateway.'+API_DOMAIN+'/TSYS_Merchant_Account_ID_registration.gate'
        
        $(el).parent().append('<div style="text-align:center;"><img src="loading.gif" style="width:30px;" /></div>');
        $.ajax({
               type: "POST"
               ,url:'https://gateway.'+API_DOMAIN+'/KYC_Wizard.gate'
               ,data: {member_hash: member_hash, business_account_hash: account_hash, tsys_email_address: tsys_email_address, tsys_first_name: tsys_first_name, tsys_last_name: tsys_last_name, tsys_street_address: tsys_street_address, tsys_zip_code: tsys_zip_code, tsys_phone_number: tsys_phone_number, tsys_social_security_number: tsys_social_security_number, tsys_birth_year: tsys_birth_year, tsys_birth_month: tsys_birth_month, tsys_birth_day: tsys_birth_day }
               //,dataType: 'json'
               ,success:function(data){
                    show_IOS_alert('SUCCESS', data);
                    setTimeout(function(){
                          showStepPage('#account_form');
                          }, 1000);
               
               }
               ,error:function(){
                    show_IOS_alert('ERROR', 'An error occurred, please try again.');
               }
               ,complete:function(){
                $(el).next().remove();
               }
               });
    }
    
    return false;
}

function sendGettingMerchantIDInstruction(el){
    $(el).parent().append('<div style="text-align:center;"><img src="loading.gif" style="width:30px;" /></div>');
    $.ajax({
           type: "POST"
           ,url:'https://gateway.'+API_DOMAIN+'/PAYYAP_send_merchant_account_instructions.gate'
           ,data: {member_hash: member_hash, business_account_hash: account_hash, TSYS_merchant_account_id: '' }
           //,dataType: 'json'
           ,success:function(data){
                show_IOS_alert('SUCCESS', data);
                goToTopOfPage();
                $('#TSYS_merchant_account_id').focus();
           }
           ,error:function(){
           show_IOS_alert('ERROR', 'An error occurred, please try again.');
           }
           ,complete:function(){
           $(el).next().remove();
           }
           });
    
    return false;
}


