var globalErrorMessage = 'Temporary network communication issues prevented us from reaching your contact. Please try again...';

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 {
                showValidImg(field);
                return;
            }
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONCHANGE") {
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) ) {
                showErrorImg(field);
                return;
            } else {
                showValidImg(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 validateTSYSUSDirectDOB(field) {
    // validateBirthdate(this,'');
    var prefix = "tsys_us_direct_";
    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 if(id == '#tsys_us_direct_business_name'){
        //if(empty($('#tsys_us_direct_business_name').val())){
            //var full_name = $.trim($('#tsys_us_direct_first_name').val() + ' ' + $('#tsys_us_direct_last_name').val());
            //$('#tsys_us_direct_business_name').val(full_name);
        //}
    }    
    else if(id == '#tsys_us_direct_business_website'){
        if(empty($('#tsys_us_direct_business_website').val())){
            document.frmPayment['is_advertise_website'].checked = false;
        }
    }
    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');
       if(viewport.height>0){
        $('#mainContainer').css('height', (viewport.height - 75) + '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', '');
      //getTermsAndConditionsAggreementText();
       
       $(window).scroll(function(){
               //alert($(document).scrollTop());
                //$('#headerBar').css('top', $(document).scrollTop() + 'px');
        });
                     
});

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(msg){
    var processingMessage = '';
    if(!empty(msg)) processingMessage = msg;
    window.location.href = SITE_SCHEMA+'://showProgressDialog?processingMessage=' + processingMessage;
}
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_device_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_device_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_device_alert('ERROR', 'Failed to send Email Invoice! Please try again!' );
                                     }
                                     }
                                     else{
                                     show_device_alert('ERROR', globalErrorMessage );
                                     }
                                     }, 1000);
                          }
                          ,error:function(){
                          console.log('error');
                          hideProgressDialog();
                          setTimeout(function(){
                                     show_device_alert('ERROR', globalErrorMessage );
                                     }, 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_device_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_device_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_device_alert('ERROR', 'Account verification failed! Please try again!');
               }
//           }
//           else{
//            show_device_alert('ERROR', globalErrorMessage);
//           }
        }
        ,error:function(){
           console.log('error');
           hideProgressDialog();
           show_device_alert('ERROR', globalErrorMessage);
        }
        ,complete:function(){
           hideProgressDialog();
        }
    });
    return false;
}

function autoCompletePaymentInBackground(){
    window.location.href = SITE_SCHEMA+'://confirmAutoCompletePaymentInBackground?msg=Backgrounding will not cancel the payment.  The payment will continue in the background, and you will be notified when the payment process has completed.';
    return false;
}
var intervalRefreshTransactionHistory;
function confirmAutoCompletePaymentInBackground(){
    is_payment_in_background = true;
    if(!empty(paymentStatusAnimationTimer)) clearTimeout(paymentStatusAnimationTimer);
    showStepPage('#selected_account_form');
    intervalRefreshTransactionHistory = setInterval(function(){ showTransactionHistory(false); }, 1000);
    return false;
}

function processPayment1(){
    validateText(document.frmPayment['amount'], 'onBlur');
    validateText(document.frmPayment['name_on_card'], 'onBlur');
    validateText(document.frmPayment['telephone_country_iso3'], 'onBlur');
    validateText(document.frmPayment['telephone_number'], 'onBlur');
    
    if($('.form-group.has-error').length>0){
        show_device_alert('ERROR', 'Please complete payment form');
        return false;
    }
    
    var enable_high_security_chargeback_protection = document.frmPayment['enable_high_security_chargeback_protection'].checked;
    if(enable_high_security_chargeback_protection){
        showStepPage('#enable_high_security_chargeback_protection_page1');
    }
    else processPayment2();
    return false;
}
function chargebackProtection(step){
    showStepPage('#enable_high_security_chargeback_protection_page' + (step + 1));
    return false
}

var freeeswitch_uuid = '';
function processPayment2(){
    clearPaymentMessages();
    var selected_account_details = getSelectAccountDetails();
    
    is_payment_cancelled = false;
    is_payment_in_background = false;
    $('.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_device_alert('ERROR', 'Please complete payment form');
    }
    else{
        console.log('additionalParameters', additionalParameters);
        var devicePhone = additionalParameters.PAYYAP_device_telephone_number;
        var customerPhone = $('#telephone_number').val();
        console.log('devicePhone, customerPhone', devicePhone , customerPhone);
        if(!empty(devicePhone) && !empty(customerPhone)){
            if(devicePhone.length>7) devicePhone = devicePhone.substr(devicePhone.length - 7);
            if(customerPhone.length>7) customerPhone = customerPhone.substr(customerPhone.length - 7);
            console.log('devicePhone, customerPhone', devicePhone , customerPhone);
            if(devicePhone == customerPhone){
                show_device_alert('ERROR', "Do not bill yourself. (Do not use your own telephone number.) Please provide the card holder's telephone number.");
                return false;
            }
        }
        
        showProgressDialog();
        
        //show_device_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.payyap.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;
        
        var isCustomerExpectingCall = $('input[name=isCustomerExpectingCall]:checked').val();
        if(isCustomerExpectingCall == 'Yes' && !empty(selected_account_details.merchant_telephone_number)){
            post_data += '&PAYYAP_precall_number=' + selected_account_details.merchant_telephone_number;
        }
        else post_data += '&PAYYAP_precall_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_device_alert('ERROR', globalErrorMessage );
                    }, 500);
               }
            }
            ,error:function(){
               console.log('error');
               hideProgressDialog();
               setTimeout(function(){
                          show_device_alert('ERROR', globalErrorMessage );
                          }, 500);
            }
            ,complete:function(){
               hideProgressDialog();
            }
        });
    }
    
    return false;
}

var paymentStatusAnimationTimer = null;
function paymentStatusAnimation(){
    if(is_payment_cancelled){ paymentStatusAnimationTimer = null; return false; }
    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() {
        if(is_payment_in_background) return false;
        //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(){
               
            }
        });
    }
}	

var is_payment_in_background = false;
var is_payment_cancelled = false;
function cancel_hangup() {
    if(!empty(xhr_status)) xhr_status.abort();
    is_payment_cancelled = true;
    showStepPage('#payment_form');
    $('#payment_form #amount').focus();
    $('.form-group').removeClass('has-error has-success has-feedback');
    $('.form-group .glyphicon').remove();
    if(!empty(freeeswitch_uuid)){
        //freeeswitch_uuid = '';
       
        $.ajax({
            type: "GET"
            ,url:'https://authorizations.'+API_DOMAIN+'/freeswitch.auth'
            ,data: { command: 'kill', uuid: freeeswitch_uuid }
            //,dataType: 'json'
            ,success:function(data){
               console.log('FreeSwitch Hangup', freeeswitch_uuid, data);
            }
            ,error:function(){
            }
            ,complete:function(){
            }
        });
    }
    clearPaymentMessages();
    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(){
    freeeswitch_uuid = '';
    if(!empty(paymentStatusAnimationTimer)) clearTimeout(paymentStatusAnimationTimer);
    clearStatusIcons();
    
    $('#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(email_address);
    //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.<br><br><button class="btn" style="color:#000;" onClick="return openDownloadPage();">Click here to Update!</button>');
                    show_device_alert('ALERT', 'openDownloadPage', 'openDownloadPage');
                }
           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 openDownloadPage(){
    window.location.href = 'https://itunes.apple.com/us/app/payyap/id1135281260?mt=8';
    return 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;}
    
    additionalParameters.emailaddress = email;
    
    if(email == 'demo@corp.nsdb.com' || email == 'demo@payyap.network' || email == 'shahid@corp.nsdb.com'){
        if(email == 'demo@corp.nsdb.com') demoAccountHash = '97d1ea8d7fb372558954fc6554e15215';
        else 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>");
                    setTimeout(function(){
                               window.location.href = SITE_SCHEMA+'://setMemberHash?member_hash='+member_hash;
                      }, 1000);
               }
//               else if(data.toUpperCase().indexOf('SUCCESS')!=-1){
//                   show_device_alert('SUCCESS', data);
//               }
               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;
           
                       if(!empty(data.login_message)){
                           show_device_alert('SUCCESS', data.login_message);
                           setTimeout(function(){
                                window.location.href = SITE_SCHEMA+'://setMemberHash?member_hash='+member_hash;
                            }, 1000);
                       }
                       else{
                            goLogin('account_hash=' + account_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();
}

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

function selectPhoto(imageNo){
    gImageNo = 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 + '" upload-status="uploading" >';
    //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);
    $('.proof' + imageNo + ' .selectedImage').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'));
    
    setUploadProgress(value);
}

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');
    openUploadProgressPopup();
    setTimeout(function(){ uploadPhoto(); }, 1000);
    
}

function uploadPhoto(){
    var url = SITE_SCHEMA+'://uploadPhoto';
    var enable_high_security_chargeback_protection = document.frmPayment['enable_high_security_chargeback_protection'].checked;
    if(enable_high_security_chargeback_protection){
        url += '?transaction_session_hash=' + transaction_session_hash;
    }
    window.location.href = url;
}

function uploadFinished(data){    
    closeUploadProgressPopup();
    try {
        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>');
            $('.photo' + data.imageNo ).attr('upload-status', 'failed');
            
            clearSelectedPhoto(data.imageNo);
            
            var imageUploaderName = 'personal_document_type';
            if(data.imageNo==1) imageUploaderName = 'personal_document_type';
            else if(data.imageNo==2) imageUploaderName = 'business_document_type';
            else if(data.imageNo==3) imageUploaderName = 'pricing_document_type';
            else if(data.imageNo>=91 && data.imageNo<=96){
                $('#btnChargebackPretection' + data.imageNo).attr('disabled', 'disabled');
            }
            
            showErrorImg($('.photo' + data.imageNo ).parent().parent().prev().find('#' + imageUploaderName));
            //$('.photo' + data.imageNo ).parent().parent().prev().find('.help-block').html('Please upload document');
            $('.photo' + data.imageNo ).parent().parent().prev().find('.help-block').html('');
        }
        else {
            $('.photo' + data.imageNo ).find('.progress').css('display' , 'none');
            $('.photo' + data.imageNo ).find('.upload-no').html('<span style="color:green;">Uploaded</span>');
            $('.photo' + data.imageNo ).attr('upload-status', 'uploaded');
            
            var imageUploaderName = 'personal_document_type';
            if(data.imageNo==1) imageUploaderName = 'personal_document_type';
            else if(data.imageNo==2) imageUploaderName = 'business_document_type';
            else if(data.imageNo==3) imageUploaderName = 'pricing_document_type';
            else if(data.imageNo>=91 && data.imageNo<=96){
                $('#btnChargebackPretection' + data.imageNo).removeAttr('disabled');
            }
            
            showValidImg($('.photo' + data.imageNo ).parent().parent().prev().find('#' + imageUploaderName));
            $('.photo' + data.imageNo ).parent().parent().prev().find('.help-block').html('');
            
            //if(data.imageNo==1) $('#btnActivateUSDirectAccount').removeAttr('disabled');
            //else if(data.imageNo==2) $('#btnActivateUSDirectFinalAccount').removeAttr('disabled');
        }
    }
    catch(err) {
        $('.photo' + gImageNo ).find('.progress').css('display' , 'none');
        $('.photo' + gImageNo ).find('.upload-no').html('<span style="color:red;">Failed</span>');
        $('.photo' + gImageNo ).attr('upload-status', 'failed');
        
        clearSelectedPhoto(gImageNo);
    }
    
}

function clearSelectedPhoto(imageNo, noAlert){
    console.log('clearSelectedPhoto > imageNo', imageNo);
    if(!noAlert) show_device_alert('ERROR', 'Upload Failed! Please try again.');
    $('.proof' + imageNo + ' .selectedImage').html('<div style="color:gray; padding: 50px 10px; text-align: left;">With your device camera, you may now please take a photo of your Proof of Additional Business Identity — Simply click on the button (below): "Take a Photo"! — or if you have a file/scan/or photo (of your Additional Business ID) already "in" your device gallery/storage, then: "Upload a File"!</div>');
}

function goToTopOfPage(){
    $('#mainContainer').animate({
                            scrollTop: $("#mainContainer").offset().top - 75
                            }, 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);
        
        if(empty($('#verification_region').val())){
           verification_region = $("#verification_region").find("option").eq(0).val();
           $("#verification_region").val(verification_region);
        }
        
//        if(email_address == 'demo@corp.nsdb.com' || email_address == 'demo@payyap.network' || email_address == 'shahid@corp.nsdb.com'){
//            //
//        }
//        else{
//            //REMOVE UNITED_STATES_DIRECT OPTION FOR NOT DEMO ACCOUNTS
//            if($("#verification_region").find("option").eq(0).val() == 'united_states_direct'){
//                $("#verification_region").find("option").eq(0).remove();
//                $("#verification_region").val($("#verification_region").find("option").eq(0).val());
//                verification_region = $("#verification_region").find("option").eq(0).val();
//            }
//        }
                
    }
    goToTopOfPage();
    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_device_alert('ERROR', 'An error occured, please try again!');
    }
}
function showSubmittedAlert(){
    show_device_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;
}

var transaction_session_hash = '';
function openPaymentForm(){
    transaction_session_hash = rand();
    showStepPage('#payment_form');
    $('#payment_form #amount').focus();
    return false;
}
function showEmailInvoiceForm(){
    show_device_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_device_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;
    }
    
    var selected_account_details = getSelectAccountDetails();
    if(!empty(selected_account_details.activate_business_document_3) && selected_account_details.activate_business_document_3 == "YES"){
        //fillSelectOptions('#additional_business_document_type', selected_account_details.activate_business_document_3_pulldown_option);
        //showStepPage('#TSYS_US_Direct_form_proof_of_additional_identity');
        buildDocument3Uploader(1);
    }
    else if(startPage == 3){
        showStepPage('#TSYS_US_Direct_form_final');
        $('#tsys_us_direct_business_name').focus();
    }
    else{
        //var selected_account_details = getSelectAccountDetails();
        fillSelectOptions('#business_description', selected_account_details.KYC_business_description_pulldown_options);
        fillSelectOptions('#personal_document_type', selected_account_details.KYC_option_text_proof_of_person);
        fillSelectOptions('#business_document_type', selected_account_details.KYC_option_text_proof_of_business);
        fillSelectOptions('#pricing_document_type', selected_account_details.KYC_option_text_proof_of_pricing);
        
        showStepPage('#identity_verification_region');
    }
    
    //set form
    if(!empty(selected_account_details.KYC_option_request_business_url_required) && selected_account_details.KYC_option_request_business_url_required == 'TRUE'){
        $('#tsys_us_direct_business_website').addClass('required');
        $('#tsys_us_direct_business_website').prev().find('.field-optional').addClass('hide-filed');
    }
    else{
        $('#tsys_us_direct_business_website').removeClass('required');
        $('#tsys_us_direct_business_website').prev().find('.field-optional').removeClass('hide-filed');
    }
    
    KYC_getSESSION();
}

function confirmTakePhoto1(n){
    confirmTakePhoto(n + $('.additional_business_document_number').val());
    return false;
}
function confirmSelectPhoto1(n){
    confirmSelectPhoto(n + $('.additional_business_document_number').val());
    return false;
}
function buildDocument3Uploader(n){
    var selected_account_details = getSelectAccountDetails();
    //selected_account_details.activate_business_document_3;
    //RESET UPLOADER
    $('#additional_business_document_type').parent().removeClass('has-success has-feedback has-error').find('.glyphicon').remove();
    $('.proof6' + n + ' .selectedImage').html('<div style="color:gray; padding: 50px 10px; text-align: left;">With your mobile device camera, you may now please take a photo of your Proof of Additional Business Identity — Simply click on the button (below): "Take a Photo"! — or if you have a file/scan/or photo (of your Additional Business ID) already "in" your mobile device gallery/storage, then: "Upload a File"!</div>');
    $('.proof6' + n).addClass('hide-row');
    
    $('#btnSkipProofOfAdditonalBusinessIdentity, #btnCompleteProofOfAdditonalBusinessIdentity').parent().removeClass('hide-row');
    //RESET UPLOADER
    var titlePrefix = 'OPTIONAL: ';
    $('.additional_business_document_number').val(n);
    //, #btnCompleteProofOfAdditonalBusinessIdentity
    if(selected_account_details.additional_business_document_3_required || selected_account_details.additional_business_document_2_required || selected_account_details.additional_business_document_3_required || selected_account_details.additional_business_document_4_required || selected_account_details.additional_business_document_5_required){
        $('#btnSkipProofOfAdditonalBusinessIdentity').parent().addClass('hide-row');
        titlePrefix = 'REQUIRED: ';
    }
    
    if(n == 1){
        var options = selected_account_details.activate_business_document_3_pulldown_option;
    }
    else if(n == 2){
        var options = selected_account_details.activate_business_document_4_pulldown_option;
    }
    else if(n == 3){
        var options = selected_account_details.activate_business_document_5_pulldown_option;
    }
    else if(n == 4){
        var options = selected_account_details.activate_business_document_6_pulldown_option;
    }
    else if(n == 5){
        var options = selected_account_details.activate_business_document_7_pulldown_option;
    }
    fillSelectOptions('#additional_business_document_type', options);
    $('#additional_business_document_type').attr('name', 'business_document_' + (2+n) + '_type' );
    $('.proof6 .photo6').attr('upload-status', 'ready');
    $('#TSYS_US_Direct_form_proof_of_additional_identity .page-title').html(titlePrefix + 'Additional Proof of Business #' + n);
    
    if(!empty(kyc_session)){
        //console.log('kyc_session', 'business_document_' + (2+n) + '_type', kyc_session['business_document_' + (2+n) + '_type']);
        if ( $("#additional_business_document_type option[value='" + (kyc_session['business_document_' + (2+n) + '_type']) + "']").length > 0 ){
            $('#additional_business_document_type').val(kyc_session['business_document_' + (2+n) + '_type']);
            $('.proof6').removeClass('hide-row');
        }
        else{
            $('#additional_business_document_type').val('');
            $('.proof6').addClass('hide-row');
        }
        
        if(!empty(kyc_session['business_document_' + (2+n) + '_url'])){
            var html = '<div class="photo-container photo6' + n + '" upload-status="uploaded" >';
            html += '<div class="upload-no"></div>';
            
            html += '<div class="photo"><img src="" /></div>';
            html += '<div class="editForm"></div>';
            html += '</div>';
            //$('#selectedImage' + imageNo).html(html);
            $('.proof6' + n + ' .selectedImage').html(html);
            
            setTimeout(function(){
               //$('#selectedImage' + imageNo + ' .photo img').attr('src', value);
               $('.proof6' + n + ' .selectedImage .photo img').attr('src', kyc_session['business_document_' + (2+n) + '_url'] + '?' + generateRandomNumber());
            }, 100);
        }
        
    }
    
    showStepPage('#TSYS_US_Direct_form_proof_of_additional_identity');
}
function fillSelectOptions(id, options){
    $(id).html('<option value="">Please select (1) one to upload...</option>');
    $.each(options, function(i, val){
        if(!empty(val)) $(id).append('<option value=' + escape(val) + '>' + val + '</option>');
   });
}

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 tell_a_friend_info_button = '';
var YOUTUBE_Services_Video_ID = '';
var accountLists = null;
function showAccountLists(){
    YOUTUBE_Services_Video_ID = '';
    $('#rowTellFriends').addClass('hide_tell_friend_row');
    //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 + '&PAYYAP_device_type=' + additionalParameters.PAYYAP_device_type ;
    //console.log(url);
    $('#account_buttons').html('<img src="loading.gif" style="width:30px;" />');
    $('#rowTellFriends').addClass('hide_tell_friend_row');
    $('#demoVideo #demoVideoImage').attr('src', '');
    $('#youtubeImage').attr('src', 'loading.gif');
    $('.service-vedo-row').addClass('hide-row');
    
    $.ajax({
        type: "GET"
        ,url:url
        ,data: {  }
        ,dataType: 'json'
        ,success:function(data){
           $('.service-vedo-row').removeClass('hide-row');
           
           if(!empty(data)){
           
               if(!empty(data.force_update) && data.force_update.toUpperCase() == 'YES'){
                   logout();
                   return false;
               }
           
               YOUTUBE_Services_Video_ID = data.YOUTUBE_Services_Video_ID;
               //$('#demoVideo').removeClass('hide_tell_friend_row');
               //$('#demoVideo #demoVideoImage').attr('src', 'http://img.youtube.com/vi/' + YOUTUBE_Services_Video_ID + '/0.jpg?rnd=' + generateRandomNumber());
               
               var url = 'http://img.youtube.com/vi/' + YOUTUBE_Services_Video_ID + '/0.jpg';
               
               setTimeout(function(){
                      //$('#youtubeImage').attr('src', 'youtube-512.png');
                      $('#demoVideo #demoVideoImage').attr('src', url);
               }, 100);
           
               if(!empty(data.display_TELL_A_FRIEND) && data.display_TELL_A_FRIEND != 'OFF'){
           tell_a_friend_info_button = data.tell_a_friend_info_button;
                    $('.btn-tell-a-friend').html(data.tell_a_friend_button_text);
                    $('#rowTellFriends').removeClass('hide_tell_friend_row');
               }
               else {
                $('#rowTellFriends').addClass('hide_tell_friend_row');
               }
               $('#enable_high_security_chargeback_protection').removeAttr('checked');
               if(data.enable_high_security_chargeback_protection == 'YES'){
                    $('#enable_high_security_chargeback_protection').parent().parent().removeClass('hide-row');
               }
               else {
                    $('#enable_high_security_chargeback_protection').parent().parent().addClass('hide-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;
                }
                   
                   //alert(startPage, account_hash);
                   if(startPage == 3){
                       //back from web
                       verifyAccount(item.account_hash);
                        startPage = 0;
                       return false;
                   }
                   
                   //item.account_status = '(verification required)';
                   //item.account_status = 'VERIFIED';
                   
                   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(doRefresh){
    //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');
    if(empty(doRefresh) || doRefresh){
        $('#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:5px;">';
           history_html += 'Name';
           history_html += '</th><th style="padding:5px;text-align: right;">';
           history_html += 'AMOUNT';
           history_html += '</th>';
           history_html += '<th style="padding:5px;text-align: right;">';
           history_html += 'STATUS';
           history_html += '</th>';
           history_html += '</tr>';
           $.each(data, function(index, item){
                  history_html += '<tr data-history-hash="' + item.hash + '">';
                  history_html += '<td style="width:50%;padding:10px 5px;text-align: left;">';
                  history_html += '<a >';
                  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 += '</a>';
                  history_html += '</td><td style="padding:10px 5px; text-align: right;">';
                  history_html += item.AUTHORIZATION_AMOUNT;
                  history_html += '</td>';
                  history_html += '<td style="padding:10px 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);
           $('#transactionHistoryBlock table tr').unbind('click');
           $('#transactionHistoryBlock table tr').click(function(event){
                                                        var history_hash = $(this).attr('data-history-hash');
                                                        if(empty(history_hash)) return false;
                                                        openTransactionDetailsPopup(history_hash);
                                                        });
           
           }
           }
           ,error:function(){
           var history_html = '';
           $('#transactionHistoryBlock').html(history_html);
           }
           ,complete:function(){
                $('#transactionHistoryCancel').css('display', 'block');
           }
           });
    return false;
}

function openTransactionDetailsPopup(hash){
    if(empty(hash)) return false;
    
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    
    if($('body').height() < windowHeight){
        $('body').css('height', windowHeight);
    }
    $('#transactionDetails').css('max-height', (windowHeight - 150));
    $('#transactionDetails').css('overflow', 'auto');
    
    $('#transactionDetailsModal').modal({
                                        backdrop: 'static',
                                        keyboard: false
                                        });
    
    $('#transaction_hash').val(hash);
    //https://gateway.payyap.network/PAYYAP_transaction_details.gate?transaction_hash=10487abc06bac1c2853f6547bd55ff34
    $.ajax({
           type: "GET"
           ,url:'https://gateway.'+API_DOMAIN+'/PAYYAP_transaction_details.gate'
           ,data: {transaction_hash: hash}
           //,dataType: 'json'
           ,success:function(data){
            if(data == 'INVALID'){
                show_device_alert('ERROR', 'Details are not available for this transaction.');
                closeTransactionDetailsPopup();
            }
           else {
            $('#transactionDetails').html(data);
            //$('#transactionDetails').css('max-height', (windowHeight - $('.modal-footer').height()));
           }
           }
           ,error:function(){
           show_device_alert('ERROR', 'An error occurred, please try again.');
           closeTransactionDetailsPopup();
           }
           ,complete:function(){
           
           }
           });
    return false;
}

function retryThisTransaction(){
    var hash = $('#transaction_hash').val();
    if(empty(hash)) return false;
    
    showProgressDialog();
    setTimeout(function(){
               //https://gateway.payyap.network/PAYYAP_retry.gate?api_session_hash=10487abc06bac1c2853f6547bd55ff34
               $.ajax({
                      type: "GET"
                      ,url:'https://gateway.'+API_DOMAIN+'/PAYYAP_retry.gate'
                      ,data: {api_session_hash: hash}
                      ,dataType: 'json'
                      ,success:function(data){
                      hideProgressDialog();
                      
                          setTimeout(function(){
                                     
                             try {
                                 //data = $.parseJSON(data);
                                 if(!empty(data)){
                                 var AUTHORIZATION_AMOUNT = 0.0;
                                 if(!empty(data.AUTHORIZATION_AMOUNT)) AUTHORIZATION_AMOUNT = parseFloat(data.AUTHORIZATION_AMOUNT);
                                 var CUSTOMER_FULL_NAME = '';
                                 if(!empty(data.CUSTOMER_FULL_NAME)) CUSTOMER_FULL_NAME = data.CUSTOMER_FULL_NAME;
                                 var CUSTOMER_TELEPHONE_COUNTRY_CODE = '';
                                 if(!empty(data.CUSTOMER_TELEPHONE_COUNTRY_CODE)) CUSTOMER_TELEPHONE_COUNTRY_CODE = data.CUSTOMER_TELEPHONE_COUNTRY_CODE;
                                 var CUSTOMER_TELEPHONE_NUMBER = '';
                                 if(!empty(data.CUSTOMER_TELEPHONE_NUMBER)) CUSTOMER_TELEPHONE_NUMBER = data.CUSTOMER_TELEPHONE_NUMBER;
                                 
                                 $('#amount').val(AUTHORIZATION_AMOUNT);
                                 $('#name_on_card').val(CUSTOMER_FULL_NAME);
                                 $('#telephone_country_iso3').val(CUSTOMER_TELEPHONE_COUNTRY_CODE);
                                 $('#telephone_number').val(CUSTOMER_TELEPHONE_NUMBER);
                                 
                                 showStepPage('#payment_form');
                                 $('#payment_form #amount').focus();
                                 
                                 closeTransactionDetailsPopup();
                                 }
                                 else show_device_alert('ERROR', data);
                             }
                             catch(err) {
                                //console.log(err.message);
                                show_device_alert('ERROR', 'An error occurred, please try again.');
                             }
                        }, 500);
                      }
                      ,error:function(){
                        show_device_alert('ERROR', 'An error occurred, please try again.');
                      }
                      ,complete:function(){
                        hideProgressDialog();
                      }
                      });
               }, 500);
    return false;
}

function refundThisTransaction(){
    window.location.href = SITE_SCHEMA+'://confirmRefundThisTransaction';
    return false;
}
function confirmRefundThisTransaction(){
    var hash = $('#transaction_hash').val();
    if(empty(hash)) return false;
    
    showProgressDialog();
    setTimeout(function(){
               //https://gateway.payyap.network/PAYYAP_refund.gate?api_session_hash=10487abc06bac1c2853f6547bd55ff34
               $.ajax({
                      type: "GET"
                      ,url:'https://gateway.'+API_DOMAIN+'/PAYYAP_refund.gate'
                      ,data: {api_session_hash: hash}
                      //,dataType: 'json'
                      ,success:function(data){
                      hideProgressDialog();
                      
                      setTimeout(function(){
                                 if(data == 'SUCCESS') show_device_alert('SUCCESS', data);
                                 else show_device_alert('ERROR', data);
                                 
                                 setTimeout(function(){
                                            closeTransactionDetailsPopup()
                                            showTransactionHistory();
                                            }, 500);
                                 
                                 }, 500);
                      }
                      ,error:function(){
                      show_device_alert('ERROR', 'An error occurred, please try again.');
                      }
                      ,complete:function(){
                      hideProgressDialog();
                      }
                      });
               }, 500);
    return false;
}

function closeTransactionDetailsPopup(){
    $('#transactionDetailsModal').modal('hide');
}

function generateRandomNumber(){
    //return Math.floor((Math.random() * 100) + 1);
    return  new Date().valueOf() + Math.random().toFixed(16).substring(2);
}

function show_device_alert(type, msg, callback){
    if(empty(callback)) callback = '';
    window.location.href = SITE_SCHEMA+'://showAlert?type=' + type + '&msg=' + escape(msg) + '&callback=' + callback;
}

function show_device_confirm(type, msg, callback){
    if(empty(callback)) callback = '';
    window.location.href = SITE_SCHEMA+'://showConfirm?type=' + type + '&msg=' + encodeURIComponent(msg) + '&callback=' + callback;
}

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'){
         openContactsCallLogsForm();
        //$('.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 tell_friends_cancel(){
    //window.location.href = SITE_SCHEMA+'://closeCalllogCursor';
    return false;
}

function tell_friends_ok(){
    window.location.href = SITE_SCHEMA+'://confirmInviteToPAYYAPNow?msg=' + tell_a_friend_info_button;
    return false;
}

function confirmInviteToPAYYAP(){
    var len = $("#contacts_call_logs_form input[name='checked_contacts_index[]']:checked").length;
    if(len<1){
        show_device_alert('ERROR', 'Please select at least one (1) associate to invite.');
        return false;
    }
    $('#member_hash').val(member_hash);
    $('#hash').val(account_hash);
    
    $('#myModal .modal-footer').addClass('hideContactUploadModalButtons');
    $('#myModal .modal-footer').parent().append('<div style="text-align:center; padding-bottom:30px;"><img src="loading.gif" style="width:30px;" /></div>');
    $.ajax({
           type: "POST"
           ,url:'https://gateway.'+API_DOMAIN+'/payyap_member_referral.gate'
           //,data: { member_hash: member_hash, hash: account_hash, contacts: $('#contacts_call_logs_form').serialize() }
           ,data: $('#contacts_call_logs_form').serialize()
           //,dataType: 'json'
           ,success:function(data){
           show_device_alert('SUCCESS', "InviteToPAYYAPNowSuccessMessage");
           
           setTimeout(function(){
                      showAccountLists();
                      $('#checkUncheckAllContacts').prop('checked', true);
                      toggle(document.getElementById('checkUncheckAllContacts'));
                      closeContactsCallLogsForm();
                      }, 500);
           }
           ,error:function(){
           show_device_alert('ERROR', 'An error occurred, please try again.');
           }
           ,complete:function(){
           $('#myModal .modal-footer').removeClass('hideContactUploadModalButtons');
           $('#myModal .modal-footer').next().remove();
           }
           });
    
    return false;
}

function fillContactsCallLogsForm(callDetails){
    var windowWidth = $(window).width();
    var windowHeight = $(window).height();
    
    if($('body').height() < windowHeight){
        $('body').css('height', windowHeight);
    }
    //$('#contacts_n_call_logs').css('height',viewport.height);
    $('#contacts_n_call_logs').css('max-height', (windowHeight - 300));
    $('#contacts_n_call_logs').css('overflow', 'auto');
    
    callDetails = $.parseJSON(callDetails);
    console.log('callDetails', callDetails);
    var totalCallLogs = 0;
    var totalContacts = 0;
    var total = 0;
    if(!empty(callDetails.callLogs.length)) totalCallLogs = callDetails.callLogs.length;
    if(!empty(callDetails.contacts.length)) totalContacts = callDetails.contacts.length;
    total = totalCallLogs+totalContacts;
    console.log("total", total);
    if(total>0){
        var html = "";
        html += '<div class="contact-log"><input type="checkbox" id="checkUncheckAllContacts" onClick="toggle(this)" /> Check/Uncheck All</div><br>';
        html += '<div id="callLogList"><h6 style="font-weight: bold; padding-bottom: 5px;">Call Logs:</h6>';
        if(totalCallLogs<1) html += '<span style="color:#ff0000;">We cannot find any contacts in your call log.</span>';
        $.each(callDetails.callLogs, function(key, value) {
               //console.log(key, value);
               //for(k=0;k<20;k++){
               value.cachedName = value.firstName + ' ' + value.lastName;
               html += '<div class="contact-log">';
               html += '<hr style="margin-top:10px; margin-bottom:10px;"/>';
               html += '<input type="hidden" name="contacts_name[]" value="' + value.cachedName + '" />';
               html += '<input type="hidden" name="contacts_phone[]" value="' + value.phone + '" />';
               
               html += '<span class="" ><input type="checkbox" name="checked_contacts_index[]" value="' + key + '" /> </span>';
               html += '<span class="" style="font-weight:bold;">' + value.cachedName + '</span></br>';
               html += '<span class="" style="font-weight:normal;">' + value.phone + '</span>';
               html += '</div>';
               //}
               });
        html += '</div>';
        
        //        html += '</br><div id="contactList"><h6 style="border-bottom: 1px solid #ccc; font-weight: bold; padding-bottom: 5px;">Contacts:</h6>';
        //        if(totalContacts<1) html += '<span style="color:#ff0000;">No contacts were found!</span>';
        //        $.each(callDetails.contacts, function(key, value) {
        //            //console.log(key, value);
        //            var name = $.trim($.trim(value.firstname + ' ' + value.middlename) + value.lastname);
        //            html += '<div class="contact-log">';
        //            html += '<span class="" ><input type="checkbox" name="contacts[]" value="' + value.phone + '" /> </span>';
        //            html += '<span class="" style="font-weight:bold;">' + value.name + '</span></br>';
        //            html += '<span class="" style="font-weight:normal;">' + value.phone + '</span>';
        //            html += '</div>';
        //        });
        //        html += '</div>';
        
        $('#contacts_n_call_logs').html(html);
        
        
        $('.contact-log').click(function(event){
                                //alert('function runs twice');
                                if(event.target.type !== 'checkbox'){
                                $(':checkbox', this).trigger('click');
                                // Change property instead
                                //$(':checkbox', this).prop('checked', true);
                                }
                                });
    }
    else{
        $('#contacts_n_call_logs').html('<span style="color:#ff0000;">We cannot find any contacts in your call log.</span>');
    }
}

function openContactsCallLogsForm(){
    $('#myModal').modal({
                        backdrop: 'static',
                        keyboard: false
                        });
}
function closeContactsCallLogsForm(){
    $('#myModal').modal('hide');
}

$('#myModal').on('show.bs.modal', function (e) {
                 var modal = $(this);
                 modal.find('.modal-title').text('New message to ')
                 //modal.find('.modal-body input').val(recipient)
                 $('.btn-close').click(function(){
                                       alert('Closed');
                                       $('#myModal').modal('hide');
                                       });
                 });

function toggle(source) {
    checkboxes = document.getElementsByName('checked_contacts_index[]');
    for(var i=0, n=checkboxes.length;i<n;i++) {
        checkboxes[i].checked = source.checked;
    }
}

function showRegionalVerificationForm(){
    var no_of_error = 0;
    validateText(document.frmPayment['verification_region'], 'onBlur');
    validateText(document.frmPayment['business_category'], 'onBlur');
    validateText(document.frmPayment['business_description'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_sell_what'], 'onBlur');
    validateText(document.frmPayment['year_doing_business'], 'onBlur');
    validateText(document.frmPayment['estimated_average_transaction_value'], 'onBlur');
    
    if($('#estimated_average_transaction_value').parent().hasClass('has-error')) {
        no_of_error++;
        $('#estimated_average_transaction_value').focus();
    }
    
    if($('#year_doing_business').parent().hasClass('has-error')) {
        no_of_error++;
        $('#year_doing_business').focus();
    }
    
    if($('#tsys_us_direct_sell_what').parent().hasClass('has-error')) {
        no_of_error++;
        $('#tsys_us_direct_sell_what').focus();
    }
    
    if($('#business_description').parent().hasClass('has-error')){
        no_of_error++;
        //show_device_alert('ERROR', 'Please select Business Category');
        $('#business_description').focus();
        //return false;
    }
    
    if($('#business_category').parent().hasClass('has-error')){
        no_of_error++;
        //show_device_alert('ERROR', 'Please select Business Category');
        $('#business_category').focus();
        //return false;
    }
    
    if($('#verification_region').parent().hasClass('has-error')){
        no_of_error++;
        //show_device_alert('ERROR', 'Select Your Region');
        $('#verification_region').focus();
        //return false;
    }
    
    
    
    if(no_of_error>0){
        show_device_alert('ERROR', 'Please complete the form');
        //$('#verification_region').focus();
        return false;
    }
    
    else{
        //showStepPage('#identity_verification_form');
        
        verification_region = $('#verification_region').val();
        
        $('.sell_product_type').html($('#business_category').val());
        
        if(verification_region == 'united_states_direct'){
            //if(empty($('#tsys_us_direct_personal_email_address').val())) $('#tsys_us_direct_personal_email_address').removeAttr('readonly');
            //if(empty($('#tsys_us_direct_personal_telephone_number').val())) $('#tsys_us_direct_personal_telephone_number').removeAttr('readonly');
            
            showStepPage('#TSYS_US_Direct_form');
            
            $('#tsys_us_direct_first_name').focus();
        }
        else{
            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');
            }
        }
        
        setTimeout(function(){
                   window.location.href = SITE_SCHEMA+'://verification_region/' + verification_region;
                   }, 1000);
        
    }
    return false;
}

function TSYS_US_Direct_Form_Validate(){
    var no_of_error = 0;
    
    validateText(document.frmPayment['tsys_us_direct_first_name'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_last_name'], 'onBlur');
    //validateText(document.frmPayment['tsys_us_direct_personal_email_address'], 'onBlur');
    validateText(document.frmPayment['personal_telephone_country_code'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_personal_telephone_number'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_street_address'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_postal_code'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_social_security_number'], 'onBlur');
    
    validateTSYSUSDirectDOB(document.frmPayment['tsys_us_direct_birth_year']);
    validateTSYSUSDirectDOB(document.frmPayment['tsys_us_direct_birth_month']);
    validateTSYSUSDirectDOB(document.frmPayment['tsys_us_direct_birth_day']);
    
    //ERROR CHECKING
    if($('#tsys_us_direct_first_name').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_last_name').parent().hasClass('has-error')) no_of_error++;
    //if($('#tsys_us_direct_personal_email_address').parent().hasClass('has-error')) no_of_error++;
    if($('#personal_telephone_country_code').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_personal_telephone_number').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_street_address').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_postal_code').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_social_security_number').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_birth_year').parent().hasClass('has-error')) no_of_error++;
    
    
    validateSocialSecurityNumber('#tsys_us_direct_social_security_number', function(){
        if(no_of_error>0){
            show_device_alert('ERROR', 'Please complete the form');
            return false;
        }
        else{
            showStepPage('#TSYS_US_Direct_form_final');
            $('#tsys_us_direct_business_name').focus();
            //getTermsAndConditionsAggreementText();
        }
    });
    return false;
}

function validateBusinessIdentity(el){
    var no_of_error = 0;
    
    validateText(document.frmPayment['tsys_us_direct_business_type'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_business_tax_id'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_business_name'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_business_email_address'], 'onBlur');
    validateText(document.frmPayment['business_telephone_country_code'], 'onBlur');
    validateText(document.frmPayment['tsys_us_direct_business_telephone'], 'onBlur');
    
    var selected_account_details = getSelectAccountDetails();
    if(!empty(selected_account_details.KYC_option_request_business_url_required) && selected_account_details.KYC_option_request_business_url_required == 'TRUE'){
        validateText(document.frmPayment['tsys_us_direct_business_website'], 'onBlur');
    }
    
    //ERROR CHECKING
    if($('#tsys_us_direct_business_type').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_business_type').val() == 'unregistered' ){
        
        //document.frmPayment['authorization_to_email_EIN_FAQ'].checked
        //
        show_device_alert('ERROR', 'You must have a Certified DBA or Registered EIN to continue. If you have neither, we suggest that you please follow our SUPER EASY guide to registering an EIN in 5 MINUTES or LESS!');
        return false;
    }
    else if($('#tsys_us_direct_business_type').val() == 'Certified DBA'){
        //
    }
    else{
        if($('#tsys_us_direct_business_tax_id').parent().hasClass('has-error')) no_of_error++;
    }
    if($('#tsys_us_direct_business_name').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_business_email_address').parent().hasClass('has-error')) no_of_error++;
    if($('#business_telephone_country_code').parent().hasClass('has-error')) no_of_error++;
    if($('#tsys_us_direct_business_telephone').parent().hasClass('has-error')) no_of_error++;
    
    if(!empty(selected_account_details.KYC_option_request_business_url_required) && selected_account_details.KYC_option_request_business_url_required == 'TRUE'){
        if($('#tsys_us_direct_business_website').parent().hasClass('has-error')) no_of_error++;
    }
    
    if(no_of_error>0){
        show_device_alert('ERROR', 'Please complete the form');
        return false;
    }
    else{
        showStepPage('#TSYS_US_Direct_form_proof_of_identity');
        
        //reset images
        if(!empty(kyc_session)){
            resetSelectedImages('personal_document_url', kyc_session['personal_document_url']);
            resetSelectedImages('business_document_url', kyc_session['business_document_url']);
            resetSelectedImages('pricing_document_url', kyc_session['pricing_document_url']);
            
            resetSelectedImages('business_document_3_url', kyc_session['business_document_3_url']);
            resetSelectedImages('business_document_4_url', kyc_session['business_document_4_url']);
            resetSelectedImages('business_document_5_url', kyc_session['business_document_5_url']);
            resetSelectedImages('business_document_6_url', kyc_session['business_document_6_url']);
            resetSelectedImages('business_document_7_url', kyc_session['business_document_7_url']);
        }
        
        getTermsAndConditionsAggreementText();
    }
    return false;
}

//reset images
function resetSelectedImages(key, value){
    var imageNo = 1;
    if(key == 'personal_document_url'){
        imageNo = 1;
    }
    else if(key == 'business_document_url'){
        imageNo = 2;
    }
    else if(key == 'pricing_document_url'){
        imageNo = 3;
    }
    else if(key == 'business_document_3_url'){
        imageNo = 61;
    }
    else if(key == 'business_document_4_url'){
        imageNo = 62;
    }
    else if(key == 'business_document_5_url'){
        imageNo = 63;
    }
    else if(key == 'business_document_6_url'){
        imageNo = 64;
    }
    else if(key == 'business_document_7_url'){
        imageNo = 65;
    }
    clearSelectedPhoto(imageNo, true);
    
    if( !empty(value) && (key == 'business_document_3_url' || key == 'business_document_4_url' || key == 'business_document_5_url' || key == 'business_document_6_url' || key == 'business_document_7_url' || key == 'personal_document_url' || key == 'business_document_url' || key == 'pricing_document_url') ){
        var imageExt = value.split(".").pop();
        if(imageExt == 'png' || imageExt == 'jpg'){
            var html = '<div class="photo-container photo' + imageNo + '" upload-status="uploaded" >';
            html += '<div class="upload-no"></div>';
            
            html += '<div class="photo"><img src="" /></div>';
            html += '<div class="editForm"></div>';
            html += '</div>';
            //$('#selectedImage' + imageNo).html(html);
            $('.proof' + imageNo + ' .selectedImage').html(html);
            
            //setTimeout(function(){
            //$('#selectedImage' + imageNo + ' .photo img').attr('src', value);
            $('.proof' + imageNo + ' .selectedImage .photo img').attr('src', value + '?' + generateRandomNumber());
            //}, 500);
        }
    }
}

function validateProofOfIdentity(el){
    var no_of_error = 0;
    
    validateText(document.frmPayment['personal_document_type'], 'onBlur');
    validateText(document.frmPayment['business_document_type'], 'onBlur');
    
    if($('#personal_document_type').parent().hasClass('has-error')){
        no_of_error++;
    }
    else{
        if($('.proof1 .photo1').attr('upload-status') == 'uploaded'){
            showValidImg($('#personal_document_type'));
            $('#personal_document_type').parent().find('.help-block').html('');
        }
        else{
            showErrorImg($('#personal_document_type'));
            //$('#personal_document_type').parent().find('.help-block').html('Please upload document');
            $('#personal_document_type').parent().find('.help-block').html('');
        }
        
        if($('#personal_document_type').parent().hasClass('has-error')) no_of_error++;
    }
    
    if($('#tsys_us_direct_business_type').val() == 'unregistered' && document.frmPayment['authorization_to_email_EIN_FAQ'].checked){
        //
    }
    else{
        if($('#business_document_type').parent().hasClass('has-error')){
            no_of_error++;
        }
        else{
            if($('.proof2 .photo2').attr('upload-status') == 'uploaded'){
                showValidImg($('#business_document_type'));
                $('#business_document_type').parent().find('.help-block').html('');
            }
            else{
                showErrorImg($('#business_document_type'));
                //$('#business_document_type').parent().find('.help-block').html('Please upload document');
                $('#business_document_type').parent().find('.help-block').html('');
            }
            
            if($('#business_document_type').parent().hasClass('has-error')) no_of_error++;
        }
    }
    
    if($('#pricing_document_type').parent().hasClass('has-error')){
        no_of_error++;
    }
    else{
        if($('.proof3 .photo3').attr('upload-status') == 'uploaded'){
            showValidImg($('#pricing_document_type'));
            $('#pricing_document_type').parent().find('.help-block').html('');
        }
        else{
            showErrorImg($('#pricing_document_type'));
            //$('#pricing_document_type').parent().find('.help-block').html('Please upload document');
            $('#pricing_document_type').parent().find('.help-block').html('');
        }
        
        if($('#pricing_document_type').parent().hasClass('has-error')) no_of_error++;
    }
    
    if(no_of_error>0){
        show_device_alert('ERROR', 'Please complete the form');
        return false;
    }
    else{
        displayConfirmValues();
        showStepPage('#TSYS_US_Direct_form_confirm_and_active');
    }
    return false;
}

function confirmAdditionalProofOfIdentity(el){
    var additional_business_document_number = $('.additional_business_document_number').val();
    var no_of_error = 0;
    //console.log('business_document_', 'business_document_' + (2+additional_business_document_number) + '_type');
    validateText(document.frmPayment['business_document_' + (2+parseInt(additional_business_document_number)) + '_type'], 'onBlur');
    
    if($('#additional_business_document_type').parent().hasClass('has-error')){
        no_of_error++;
    }
    else{
        
        if($('.proof6' + additional_business_document_number + ' .photo6' + additional_business_document_number).attr('upload-status') == 'uploaded'){
            showValidImg($('#additional_business_document_type'));
            $('#additional_business_document_type').parent().find('.help-block').html('');
        }
        else{
            showErrorImg($('#additional_business_document_type'));
            //$('#personal_document_type').parent().find('.help-block').html('Please upload document');
            $('#additional_business_document_type').parent().find('.help-block').html('');
        }
        if($('#additional_business_document_type').parent().hasClass('has-error')) no_of_error++;
    }
    
    if(no_of_error>0){
        show_device_alert('ERROR', 'Please complete the form');
        return false;
    }
    else{
        if(additional_business_document_number < 5){
            buildDocument3Uploader(++additional_business_document_number);
            return false;
        }
        
        completeAdditionalProofOfBusinessIdentity();
    }
    return false;
}

function completeAdditionalProofOfBusinessIdentity(){
    //http://gateway.payyap.network/KYC_Wizard_followup.gate?member_hash=_XXXXX_&business_account_hash=_XXXXX_&business_document_3_action=confirmed
    //var apiData = { member_hash: member_hash, business_account_hash: account_hash, business_document_3_action: "confirmed"};
    var apiData = { member_hash: member_hash, business_account_hash: account_hash, additional_document_status: "complete"};
    
    showProgressDialog();
    setTimeout(function(){
       $.ajax({
              type: "POST"
              ,url:'https://gateway.'+API_DOMAIN+'/KYC_Wizard_followup.gate'
              ,data: apiData
              //,dataType: 'json'
              ,success:function(data){
              
              setTimeout(function(){
                         hideProgressDialog();
                         show_device_alert('SUCCESS', data);
                         
                         setTimeout(function(){
                                    showStepPage('#account_form');
                                    }, 500);
                         
                         }, 500);
              }
              ,error:function(){
              setTimeout(function(){
                         hideProgressDialog();
                         show_device_alert('ERROR', 'An error occurred, please try again.');
                         }, 500);
              }
              ,complete:function(){
              //$(el).next().remove();
              }
              });
       }, 500);
    return false;
}

function activeMerchantID(el){
    var no_of_error = 0;
    if(verification_region == 'united_states_direct'){
        
    }
    else{
        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
        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_device_alert('ERROR', 'Please complete the form');
        //$('.form-group.has-error').css('display', 'block');
        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_personal_id_number = $('#tsys_personal_id_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'
        
        //var isBusinessMoreThanOneYearOld = $('input[name=isBusinessMoreThanOneYear]:checked').val();
        var isBusinessAcceptCreditCard = $('input[name=isBusinessAcceptCreditCard]:checked').val();
        
        var year_doing_business = $('#year_doing_business').val();
        
        //US DIRECT form data
        var tsys_us_direct_first_name = $('#tsys_us_direct_first_name').val();
        var tsys_us_direct_last_name = $('#tsys_us_direct_last_name').val();
        var tsys_us_direct_business_type = $('#tsys_us_direct_business_type').val();
        var tsys_us_direct_business_name = $('#tsys_us_direct_business_name').val();
        //var tsys_us_direct_personal_email_address = $('#tsys_us_direct_personal_email_address').val();
        var tsys_us_direct_business_email_address = $('#tsys_us_direct_business_email_address').val();
        var personal_telephone_country_code = $('#personal_telephone_country_code').val();
        var tsys_us_direct_personal_telephone_number = $('#tsys_us_direct_personal_telephone_number').val();
        var business_telephone_country_code = $('#business_telephone_country_code').val();
        var tsys_us_direct_business_telephone = $('#tsys_us_direct_business_telephone').val();
        var tsys_us_direct_sell_what = $('#tsys_us_direct_sell_what').val();
        var tsys_us_direct_business_tax_id = $('#tsys_us_direct_business_tax_id').val();
        var tsys_us_direct_business_website = $('#tsys_us_direct_business_website').val();
        var is_advertise_website = document.frmPayment['is_advertise_website'].checked;
        
        var tsys_us_direct_street_address = $('#tsys_us_direct_street_address').val();
        var tsys_us_direct_postal_code = $('#tsys_us_direct_postal_code').val();
        var tsys_us_direct_social_security_number = $('#tsys_us_direct_social_security_number').val();
        
        var tsys_us_direct_birth_year = $('#tsys_us_direct_birth_year').val();
        var tsys_us_direct_birth_month = $('#tsys_us_direct_birth_month').val();
        var tsys_us_direct_birth_day = $('#tsys_us_direct_birth_day').val();
        
        var personal_document_type = $('#personal_document_type').val();
        var business_document_type = $('#business_document_type').val();
        //
        
        var business_category = $('#business_category').val();
        var business_description = $('#business_description').val();
        var authorization_to_email_EIN_FAQ = document.frmPayment['authorization_to_email_EIN_FAQ'].checked;
        
        var apiData = { member_hash: member_hash, business_account_hash: account_hash, region: verification_region, business_category:business_category, year_doing_business: year_doing_business, business_accept_credit_card: isBusinessAcceptCreditCard, 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_personal_id_number: tsys_personal_id_number, tsys_birth_year: tsys_birth_year, tsys_birth_month: tsys_birth_month, tsys_birth_day: tsys_birth_day};
        if(verification_region == 'united_states_direct'){
            apiData = { member_hash: member_hash, business_account_hash: account_hash, region: verification_region, business_category:business_category, business_description: business_description, year_doing_business: year_doing_business, business_accept_credit_card: isBusinessAcceptCreditCard, tsys_us_direct_first_name: tsys_us_direct_first_name , tsys_us_direct_last_name: tsys_us_direct_last_name, personal_telephone_country_code: personal_telephone_country_code, tsys_us_direct_personal_telephone_number: tsys_us_direct_personal_telephone_number, tsys_us_direct_business_type: tsys_us_direct_business_type , tsys_us_direct_business_name: tsys_us_direct_business_name, tsys_us_direct_business_email_address: tsys_us_direct_business_email_address, business_telephone_country_code: business_telephone_country_code, tsys_us_direct_business_telephone: tsys_us_direct_business_telephone, tsys_us_direct_street_address: tsys_us_direct_street_address, tsys_us_direct_postal_code: tsys_us_direct_postal_code, tsys_us_direct_social_security_number: tsys_us_direct_social_security_number, tsys_us_direct_sell_what: tsys_us_direct_sell_what, tsys_us_direct_business_tax_id: tsys_us_direct_business_tax_id, tsys_us_direct_business_website:tsys_us_direct_business_website, is_advertise_website: is_advertise_website, tsys_us_direct_birth_year: tsys_us_direct_birth_year, tsys_us_direct_birth_month: tsys_us_direct_birth_month, tsys_us_direct_birth_day: tsys_us_direct_birth_day, personal_document_type: personal_document_type, business_document_type: business_document_type, authorization_to_email_EIN_FAQ: authorization_to_email_EIN_FAQ};
        }
        //$(el).parent().append('<div style="text-align:center;"><img src="loading.gif" style="width:30px;" /></div>');
        showProgressDialog();
        setTimeout(function(){
                   $.ajax({
                          type: "POST"
                          ,url:'https://gateway.'+API_DOMAIN+'/KYC_Wizard.gate'
                          ,data: apiData
                          //,dataType: 'json'
                          ,success:function(data){
                          
                          setTimeout(function(){
                                     hideProgressDialog();
                                     show_device_alert('SUCCESS', data);
                                     
                                     setTimeout(function(){
                                                showStepPage('#account_form');
                                                }, 500);
                                     
                                     }, 500);
                          }
                          ,error:function(){
                          setTimeout(function(){
                                     hideProgressDialog();
                                     show_device_alert('ERROR', 'An error occurred, please try again.');
                                     }, 500);
                          }
                          ,complete:function(){
                          //$(el).next().remove();
                          }
                          });
                   }, 500);
    }
    
    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_device_alert('SUCCESS', data);
                goToTopOfPage();
                $('#TSYS_merchant_account_id').focus();
           }
           ,error:function(){
           show_device_alert('ERROR', 'An error occurred, please try again.');
           }
           ,complete:function(){
           $(el).next().remove();
           }
           });
    
    return false;
}

function playDemoVideo(){
    if(empty(YOUTUBE_Services_Video_ID)) return false;
    else if($('#youtubeImage').attr('src') == 'loading.gif') return false;
    window.location.href = SITE_SCHEMA+'://openLink/youtube?vid=' + YOUTUBE_Services_Video_ID;
    return false;
}

function youtubeDemoVideoLoaded(){
    $('#youtubeImage').attr('src', 'youtube-512.png');
}

function checkBusinessWebsiteIsNotEmpty(el){
    if(document.frmPayment['is_advertise_website'].checked){
        if(empty($('#tsys_us_direct_business_website').val())){
            show_device_alert('ERROR', 'To qualify for free advertising, and a listing on the PAYYAP.network Business Directory, you must please set your business webpage / URL.');
            document.frmPayment['is_advertise_website'].checked = false;
            //return false;
        }
    }
}

function validateSocialSecurityNumber(id, callback){
    //'#tsys_us_direct_social_security_number'
    //$(id).val()
    var ssn = $(id).val();
    if(empty(ssn)){
        if(!empty(callback)) callback();
        return false;
    }
    else if($(id).attr('data-validation-status') == 'valid'){
        if(!empty(callback)) callback();
        return false;
    }
    else if($(id).attr('data-validation-status') == 'invalid'){
        if(!empty(callback)) callback();
        return false;
    }
    
    showProgressDialog('Checking ' + escape($(id).attr('placeholder')) + '...');
    setTimeout(function(){
               var url = 'https://gateway.payyap.network/social_security_checker.gate';
               $.ajax({
                      type: "GET"
                      ,url: url
                      ,data: {tsys_us_direct_social_security_number: ssn}
                      ,dataType: 'json'
                      ,success:function(data){
                      hideProgressDialog();
                      setTimeout(function(){
                         console.log(data);
                         
                            if(data.status == 'VALID'){
                                 //$(id).val(data.ssn);
                                 //$('#btnActivateUSDirectAccount').removeAttr('disabled');
                                 if(!empty(callback)) callback();
                            }
                            else{
                                 showErrorImg($(id));
                                 //$('#btnActivateUSDirectAccount').attr('disabled', 'disabled');
                                 show_device_alert('ERROR', 'INVALID ' + escape($(id).attr('placeholder')) );
                            }
                         
                        }, 1);
                      }
                      ,error:function(){
                      hideProgressDialog();
                      setTimeout(function(){
                                 show_device_alert('ERROR', globalErrorMessage );
                                 }, 1);
                      }
                      ,complete:function(){
                      //hideProgressDialog();
                      }
                      });
               }, 1);
}


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

function getTermsAndConditionsAggreementText(){
    if(empty($('#tsys_service_agreement').html())){
        $('#tsys_service_agreement').html('<div style="text-align:center; padding-top:20px;"><img src="loading.gif" /></div>');
        $.ajax({
               type: "GET"
               ,url:'https://gateway.'+API_DOMAIN+'/PROPAY_terms_of_service.gate?link_from_payyap=yes'
               ,data: {}
               //,dataType: 'json'
               ,success:function(data){
               $('#tsys_service_agreement').html(data);
               }
               ,error:function(){
               
               }
               ,complete:function(){
               
               }
               });
    }
    
    return false;
}

function showProofOfBusinessUploader(el, uploader){
    if(empty($(el).val())){
        $('.' + uploader).addClass('hide-row');
    }
    else{
        $('.' + uploader).removeClass('hide-row');
        //window.location.href = SITE_SCHEMA+'://setProofOfBusiness?uploader_name=' + uploader + 'option=' + escape($(el).find('option:selected').text());
        //alert($(el).find('option:selected').text());
    }
    return false;
}

var proofOfBusinessUploaderAction = '';
var proofOfBusinessUploaderNo = '';
function confirmTakePhoto(n){
    proofOfBusinessUploaderAction = 'takePhoto';
    confirmTakeOrSelectPhoto(n);
    return false;
}
function confirmSelectPhoto(n){
    proofOfBusinessUploaderAction = 'selectPhoto';
    confirmTakeOrSelectPhoto(n);
    return false;
}
function confirmTakeOrSelectPhoto(n){
    proofOfBusinessUploaderNo = n;
    var selected_account_details = getSelectAccountDetails();
    var selectedIndex = $('.proof' + n).prev().find(":selected").index() - 1;
    var confirmationText = '';
    if(n == '1'){
        if(!empty(selected_account_details.KYC_confirmation_text_proof_of_person))
            confirmationText = selected_account_details.KYC_confirmation_text_proof_of_person[selectedIndex];
    }
    else if(n == '2'){
        if(!empty(selected_account_details.KYC_confirmation_text_proof_of_business))
            confirmationText = selected_account_details.KYC_confirmation_text_proof_of_business[selectedIndex];
    }
    else if(n == '3'){
        if(!empty(selected_account_details.KYC_confirmation_text_proof_of_pricing))
            confirmationText = selected_account_details.KYC_confirmation_text_proof_of_pricing[selectedIndex];
    }
    else if(n == '61'){
        if(!empty(selected_account_details.activate_business_document_3_pulldown_option_confirmation_text))
            confirmationText = selected_account_details.activate_business_document_3_pulldown_option_confirmation_text[selectedIndex];
    }
    else if(n == '62'){
        if(!empty(selected_account_details.activate_business_document_4_pulldown_option_confirmation_text))
            confirmationText = selected_account_details.activate_business_document_4_pulldown_option_confirmation_text[selectedIndex];
    }
    else if(n == '63'){
        if(!empty(selected_account_details.activate_business_document_5_pulldown_option_confirmation_text))
            confirmationText = selected_account_details.activate_business_document_5_pulldown_option_confirmation_text[selectedIndex];
    }
    else if(n == '64'){
        if(!empty(selected_account_details.activate_business_document_6_pulldown_option_confirmation_text))
            confirmationText = selected_account_details.activate_business_document_6_pulldown_option_confirmation_text[selectedIndex];
    }
    else if(n == '65'){
        if(!empty(selected_account_details.activate_business_document_7_pulldown_option_confirmation_text))
            confirmationText = selected_account_details.activate_business_document_7_pulldown_option_confirmation_text[selectedIndex];
    }
    
    if(!empty(confirmationText)){
        //var c = confirm(confirmationText, "Confirm");
        //if(!c) return false;
        //setTimeout(function(){
        show_device_confirm("confirmSelectOption", confirmationText);
        //},1000);
    }
    //takePhoto(n);
    return false;
}
function setSelectOption(el){
    console.log("Previous val > ", $(el).val());
    proofOfBusinessUploaderPreviousOption = $(el).val();
}
function confirmSelectOption(r){
    //console.log('confirmSelectOption', r);
    //console.log('proofOfBusinessUploaderAction', proofOfBusinessUploaderAction);
    //console.log('proofOfBusinessUploaderPreviousOption', proofOfBusinessUploaderPreviousOption);
    if(r == 'yes'){
        //$('.' + proofOfBusinessUploaderAction).removeClass('hide-row');
        eval(''+proofOfBusinessUploaderAction+'('+proofOfBusinessUploaderNo+')');
    }
    else{
        //$('.' + proofOfBusinessUploaderAction).prev().find("select").val(proofOfBusinessUploaderPreviousOption);
    }
}

function saveText(field, callerEvent) {
    var url = 'http://gateway.payyap.network/KYC_onBLUR.gate';
    var fieldName = $(field).attr('name');
    var fieldValue = $(field).val();
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONCHANGE") {
            url = 'http://gateway.payyap.network/KYC_onCHANGE.gate';
        }
    }
    
    if(fieldName == 'tsys_us_direct_social_security_number'){
        $(field).attr('data-validation-status', '');
    }
    else if(fieldName == 'authorization_to_email_EIN_FAQ'){
        fieldValue = 'no';
        if($('#authorization_to_email_EIN_FAQ').prop("checked")) fieldValue = 'yes';
        
        if(fieldValue == 'yes'){
            //$('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
            $('#authorization_to_email_EIN_FAQ').attr('disabled', 'disabled');
            $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
            
            //$('#btnActivateUSDirectFinalAccount').parent().addClass('hide-row');
            
            show_device_alert('ALERT', 'An email has been sent! Please check your INBOX (or SPAM folder).');
        }
        else{
            //$('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
            $('#tsys_us_direct_business_tax_id').parent().removeClass('hide-row');
            
            $('#btnActivateUSDirectFinalAccount').parent().removeClass('hide-row');
        }
    }
    else if(fieldName == 'tsys_us_direct_business_type'){
        if(fieldValue == 'unregistered'){
            //openEINConfirmationPopup();
            $('#authorization_to_email_EIN_FAQ').prop("checked", false);
            $('#authorization_to_email_EIN_FAQ').parent().parent().removeClass('hide-row');
            $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
            
            //$('#btnActivateUSDirectFinalAccount').parent().addClass('hide-row');
        }
        else if(fieldValue == 'Certified DBA'){
            $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
            $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
            if(empty($('#business_document_type').val())){
                $('#business_document_type').val('DBA Certificate');
                $('.proof2').removeClass('hide-row');
            }
            
            //$('#btnActivateUSDirectFinalAccount').parent().removeClass('hide-row');
        }
        else{
            $('#authorization_to_email_EIN_FAQ').prop("checked", false);
            $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
            $('#tsys_us_direct_business_tax_id').parent().removeClass('hide-row');
            
            //$('#btnActivateUSDirectFinalAccount').parent().removeClass('hide-row');
        }
    }
    
    //console.log('url, fieldName,fieldValue', url, fieldName, fieldValue);
    $.ajax({
           type: "GET"
           ,url: url
           ,data: {member_hash: member_hash, business_account_hash: account_hash, fieldName: fieldName, fieldValue: fieldValue}
           //,dataType: 'json'
           ,success:function(data){
               if( (fieldName == 'tsys_us_direct_business_type' && fieldValue == 'unregistered' ) || (fieldName == 'authorization_to_email_EIN_FAQ' && fieldValue == 'yes') ){
                   //show_device_alert('ALERT', 'An email has been sent! Please check your INBOX (or SPAM folder).');
               }
           }
           ,error:function(){
           }
           ,complete:function(){
           }
           });
}

var kyc_session = null;
function KYC_getSESSION() {
    showProgressDialog();
    setTimeout(function(){
               var url = 'http://gateway.payyap.network/KYC_getSESSION.gate';
               $.ajax({
                      type: "GET"
                      ,url: url
                      ,data: {member_hash: member_hash, business_account_hash: account_hash}
                      ,dataType: 'json'
                      ,success:function(data){
                      kyc_session = data;
                      //console.log(data);
                      $.each(data, function(key, value) {
                             //console.log(key, value);
                             var el = $('#' + key);
                             if(el.is('input')) { //we are dealing with an input
                             var type = el.attr('type'); //will either be 'text', 'radio', or 'checkbox
                             if(type == 'radio'){
                             if(key == 'business_accept_credit_card'){
                             //$("input[name=background][value='some value']").prop("checked",true);
                             if(value.toLowerCase() == 'yes'){
                             $('#isBusinessAcceptCreditCardYes').prop("checked",true);
                             }
                             else{
                             $('#isBusinessAcceptCreditCardNo').prop("checked",false);
                             }
                             }
                             }
                             else if(type == 'checkbox' ){
                             if(key == 'is_advertise_website'){
                             if(value.toLowerCase() == 'true' || value.toLowerCase() == 'yes'){
                             $('#is_advertise_website').prop("checked", true);
                             }
                             else{
                             $('#is_advertise_website').prop("checked", false);
                             }
                             }
                             else if(key == 'authorization_to_email_EIN_FAQ'){
                                 if(value.toLowerCase() == 'true' || value.toLowerCase() == 'yes'){
                                     if($('#tsys_us_direct_business_type').val() == 'unregistered'){
                                         $('#authorization_to_email_EIN_FAQ').prop("checked",false);
                                         $('#authorization_to_email_EIN_FAQ').parent().parent().removeClass('hide-row');
                                         $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
                                         
                                         //$('#btnActivateUSDirectFinalAccount').parent().addClass('hide-row');
                                     }
                                     else if($('#tsys_us_direct_business_type').val() == 'Certified DBA'){
                                         $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
                                         $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
                                     }
                                     else{
                                         $('#authorization_to_email_EIN_FAQ').prop("checked",false);
                                         $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
                                         $('#tsys_us_direct_business_tax_id').parent().removeClass('hide-row');
                                         
                                         //$('#btnActivateUSDirectFinalAccount').parent().removeClass('hide-row');
                                     }
                                 }
                                 else{
                                     if($('#tsys_us_direct_business_type').val() == 'unregistered'){
                                         $('#authorization_to_email_EIN_FAQ').prop("checked",false);
                                         $('#authorization_to_email_EIN_FAQ').parent().parent().removeClass('hide-row');
                                         $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
                                         
                                         //$('#btnActivateUSDirectFinalAccount').parent().addClass('hide-row');
                                     }
                                     else if($('#tsys_us_direct_business_type').val() == 'Certified DBA'){
                                         $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
                                         $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
                                     }
                                     else{
                                         $('#authorization_to_email_EIN_FAQ').prop("checked",false);
                                         $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
                                         $('#tsys_us_direct_business_tax_id').parent().removeClass('hide-row');
                                         
                                         //$('#btnActivateUSDirectFinalAccount').parent().removeClass('hide-row');
                                     }
                                 }
                            }
                             }
                             else{
                                if(key == 'tsys_us_direct_social_security_number'){
                                //value = '';
                                }
                                $('#' + key).val(value);
                             }
                             } else if(el.is('select')) { //we are dealing with a select
                             if(key == 'verification_region'){
                                if(empty(value)) value = 'united_states_direct';
                             }
                             else if(key == 'tsys_us_direct_business_type'){
                                 if(value == 'Certified DBA'){
                                    $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
                                    $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
                                    if(empty($('#business_document_type').val())){
                                        $('#business_document_type').val('DBA Certificate (State-Issued)');
                                        $('.proof2').removeClass('hide-row');
                                    }
                                 }
                             }
                             else if(key == 'personal_document_type'){
                                if(empty(value)) $('.proof1').addClass('hide-row');
                                else $('.proof1').removeClass('hide-row');
                             }
                             else if(key == 'business_document_type'){
                                if(empty(value)) $('.proof2').addClass('hide-row');
                                else $('.proof2').removeClass('hide-row');
                             }
                             else if(key == 'pricing_document_type'){
                                 if(empty(value)) $('.proof3').addClass('hide-row');
                                 else $('.proof3').removeClass('hide-row');
                             }
                             else if(key == 'additional_business_document_type'){
                                 if(empty(value)) $('.proof6').addClass('hide-row');
                                 else $('.proof6').removeClass('hide-row');
                             }
                             
                             try{
                                 if ( $("#" + key + " option[value='" + escape(value) + "']").length > 0 ){
                                    $('#' + key).val(escape(value));
                                 }
                                 else if ( $("#" + key + " option[value='" + value + "']").length > 0 ){
                                    $('#' + key).val(value);
                                 }
                                 else{
                                    //$('#' + key).val('');
                                    if(!empty(value)) $('#' + key).prepend('<option value=' + escape(value) + ' selected>' + value + '</option>');
                                 }
                             }
                             catch(e){
                             
                             }
                             
                             }else { //we are dealing with a textarea
                                //code here
                                 if(key == 'business_document_3_type'){
                                     var n = 1;
                                     if ( $("#additional_business_document_type option[value='" + escape(value) + "']").length > 0 ){
                                        $('#additional_business_document_type').val(escape(value));
                                        $('.proof6').removeClass('hide-row');
                                     }
                                     else if ( $("#additional_business_document_type option[value='" + value + "']").length > 0 ){
                                        $('#additional_business_document_type').val(value);
                                        $('.proof6').removeClass('hide-row');
                                     }
                                     else{
                                        if(!empty(value)) $('#additional_business_document_type').prepend('<option value=' + escape(value) + ' selected>' + value + '</option>');
                                        $('.proof6').addClass('hide-row');
                                     }
                                 }
                             
                             }
                        });
                      }
                      ,error:function(){
                      }
                      ,complete:function(){
                      hideProgressDialog();
                      }
                      });
               }, 500);
    return false;
}

function popForceUpdate(){
    window.location.href = SITE_SCHEMA+'://actionBarItem?action=force_update';
    return false;
}

function openUploadProgressPopup(){
    setUploadProgress(0);
    $('#uploadingProgress .modal-title').html('Uploading...');
    
    var progress_html = '';
    
    progress_html += '<div class="progress">';
    progress_html += '<div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">';
    progress_html += '0%';
    progress_html += '</div>';
    progress_html += '</div>';
    
    $('#uploadingProgress .modal-body').html(progress_html);
    $('#uploadingProgress .modal-footer').addClass('hide-row');
    
    $('#uploadingProgress').modal({
                                  backdrop: 'static',
                                  keyboard: false
                                  });
}

function setUploadProgress(value){
    var el = $('#uploadingProgress .progress-bar');
    el.attr('aria-valuenow', value);
    el.css('width', value + '%');
    el.html(value + '%');
}

function closeUploadProgressPopup(){
    $('#uploadingProgress').modal('hide');
}

function openEINConfirmationPopup(){
    var buttons_html = '';
    buttons_html += '<button class="btn btn-lg btn-success btn-block" name="EIN_YES" onClick="return registerEIN(\'Yes\');" >';
    buttons_html += '<span>Yes please!</span>';
    buttons_html += '<br>';
    buttons_html += '<span>I authorize PAYYAP (as a third party) to safely and securely apply for an EIN on my behalf.</span>';
    buttons_html += '</button>';
    
    buttons_html += '<br>';
    buttons_html += '<br>';
    buttons_html += '<br>';
    
    buttons_html += '<button class="btn btn-lg btn-danger btn-block" name="EIN_NO" onClick="return registerEIN(\'No\');" >';
    buttons_html += '<span>No thanks!</span>';
    buttons_html += '<br>';
    buttons_html += '<span>I prefer to apply for an EIN myself.</span>';
    buttons_html += '</button>';
    
    buttons_html += '<br>';
    buttons_html += '<br>';
    buttons_html += '<br>';
    
    buttons_html += '<a onclick="return openEIN_FAQ_Page()";>';
    buttons_html += 'CLICK HERE TO VISIT OUR EIN FAQ PAGE';
    buttons_html += '</a>';
    
    $('#uploadingProgress .modal-title').html('Not a registered company (no EIN, yet)');
    $('#uploadingProgress .modal-body').html(buttons_html);
    $('#uploadingProgress .modal-footer').addClass('hide-row');
    
    $('#uploadingProgress').modal({
                                  backdrop: 'static',
                                  keyboard: false
                                  });
}

function closeEINConfirmationPopup(){
    $('#uploadingProgress').modal('hide');
}

function openEIN_FAQ_Page(){
    closeEINConfirmationPopup();
    window.location.href = SITE_SCHEMA+'://actionBarItem?action=registerEIN';
    return false;
}

function registerEIN(option){
    closeEINConfirmationPopup();
    //console.log('option', option);
    if(option.toLowerCase() == 'yes'){
        $('#authorization_to_email_EIN_FAQ').prop("checked", true);
        $('#authorization_to_email_EIN_FAQ').parent().parent().removeClass('hide-row');
        $('#tsys_us_direct_business_tax_id').parent().addClass('hide-row');
    }
    else {
        $('#authorization_to_email_EIN_FAQ').prop("checked", false);
        $('#authorization_to_email_EIN_FAQ').parent().parent().addClass('hide-row');
        $('#tsys_us_direct_business_tax_id').parent().removeClass('hide-row');
    }
    return false;
}

function displayConfirmValues(){
    var isBusinessAcceptCreditCard = $('input[name=isBusinessAcceptCreditCard]:checked').val();
    
    var year_doing_business = $('#year_doing_business').find('option:selected').text();
    var estimated_average_transaction_value = $('#estimated_average_transaction_value').find('option:selected').text();
    
    //US DIRECT form data
    var tsys_us_direct_first_name = $('#tsys_us_direct_first_name').val();
    var tsys_us_direct_last_name = $('#tsys_us_direct_last_name').val();
    var tsys_us_direct_business_type = $('#tsys_us_direct_business_type').find('option:selected').text();
    var tsys_us_direct_business_name = $('#tsys_us_direct_business_name').val();
    //var tsys_us_direct_personal_email_address = $('#tsys_us_direct_personal_email_address').val();
    var tsys_us_direct_business_email_address = $('#tsys_us_direct_business_email_address').val();
    var personal_telephone_country_code = $('#personal_telephone_country_code').find('option:selected').text();
    var tsys_us_direct_personal_telephone_number = $('#tsys_us_direct_personal_telephone_number').val();
    var business_telephone_country_code = $('#business_telephone_country_code').find('option:selected').text();
    var tsys_us_direct_business_telephone = $('#tsys_us_direct_business_telephone').val();
    var tsys_us_direct_sell_what = $('#tsys_us_direct_sell_what').val();
    var tsys_us_direct_business_tax_id = $('#tsys_us_direct_business_tax_id').val();
    var tsys_us_direct_business_website = $('#tsys_us_direct_business_website').val();
    var is_advertise_website = document.frmPayment['is_advertise_website'].checked;
    
    var tsys_us_direct_street_address = $('#tsys_us_direct_street_address').val();
    var tsys_us_direct_postal_code = $('#tsys_us_direct_postal_code').val();
    var tsys_us_direct_social_security_number = $('#tsys_us_direct_social_security_number').val();
    
    var tsys_us_direct_birth_year = $('#tsys_us_direct_birth_year').find('option:selected').text();
    var tsys_us_direct_birth_month = $('#tsys_us_direct_birth_month').find('option:selected').text();
    var tsys_us_direct_birth_day = $('#tsys_us_direct_birth_day').find('option:selected').text();
    
    var personal_document_type = $('#personal_document_type').find('option:selected').text();
    var business_document_type = $('#business_document_type').find('option:selected').text();
    //
    
    var region = $('#verification_region').find('option:selected').text();
    var business_category = $('#business_category').find('option:selected').text();
    var business_description = $('#business_description').find('option:selected').text();
    
    var authorization_to_email_EIN_FAQ = document.frmPayment['authorization_to_email_EIN_FAQ'].checked?'Yes':'No';
    
    $('#lbl_verification_region').html(region);
    $('#lbl_business_category').html(business_category);
    $('#lbl_business_description').html(business_description);
    $('#lbl_keywords').html(tsys_us_direct_sell_what);
    $('#lbl_years_doing_business').html(year_doing_business);
    $('#lbl_first_time_card_processing').html(isBusinessAcceptCreditCard);
    $('#lbl_estimated_average_transaction_value').html(estimated_average_transaction_value);
    $('#lbl_first_name').html(tsys_us_direct_first_name);
    $('#lbl_last_name').html(tsys_us_direct_last_name);
    $('#lbl_street_address').html(tsys_us_direct_street_address);
    $('#lbl_zip_code').html(tsys_us_direct_postal_code);
    $('#lbl_personal_telephone_number').html(personal_telephone_country_code + ' ' + tsys_us_direct_personal_telephone_number);
    $('#lbl_birthdate').html(tsys_us_direct_birth_year + ' ' + tsys_us_direct_birth_month + ' ' + tsys_us_direct_birth_day);
    $('#lbl_personal_social_security_number').html(tsys_us_direct_social_security_number);
    $('#lbl_business_name').html(tsys_us_direct_business_name);
    $('#lbl_business_telephone_number').html(business_telephone_country_code + ' ' + tsys_us_direct_business_telephone);
    $('#lbl_business_email_address').html(tsys_us_direct_business_email_address);
    $('#lbl_business_url').html(tsys_us_direct_business_website);
    $('#lbl_business_type').html(tsys_us_direct_business_type);
    $('#lbl_business_tax_ein_id').html(tsys_us_direct_business_tax_id);
    //$('#lbl_authorization_to_email_EIN_FAQ').html(authorization_to_email_EIN_FAQ);
    $('#lbl_proof_of_person_preview').html('<div class="selectedImage photoIdentityImage"><img src="' + $('#selectedImage1 .photo img').attr('src') + '" /></div>');
    $('#lbl_proof_of_business_preview').html('<div class="selectedImage photoIdentityImage"><img src="' + $('#selectedImage2 .photo img').attr('src') + '" /></div>');
    $('#lbl_proof_of_pricing_preview').html('<div class="selectedImage photoIdentityImage"><img src="' + $('#selectedImage3 .photo img').attr('src') + '" /></div>');
    
}

