
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)
{
    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)
{
    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
    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;

    // 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) {
    
    if(field.value) {
        var fieldValue = field.value.trim();
    }
    
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONFOCUS") {
            showEmptyImg(field);
            return;
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONKEYUP") {
            
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) ) {
                showErrorImg(field);
                return;
            } else {
                showEmptyImg(field);
                return;
            }
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONCHANGE") {
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) ) {
                showErrorImg(field);
                return;
            } else {
                showEmptyImg(field);
                return;
            }
        }
    }
    
    if(typeof(callerEvent) != 'undefined') {
        if(callerEvent.toUpperCase() == "ONBLUR") {
            if( (fieldValue == "") || (fieldValue == null) || (!fieldValue) || (fieldValue=='Select a country...') || (fieldValue=='Select One...') ) {
                showErrorImg(field);
                return;
            } else {
                showValidImg(field);
                return;
            }
        }
    }
    
    //	if(callerEvent.toUpperCase() == "ONLOAD") {
    //		if((fieldValue == "") || (fieldValue == null)) {
    //			showErrorImg(field);
    //			return;
    //		} else {
    //			showValidImg(field);
    //			return;
    //		}
    //	}
    //	
}
function 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 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 = "official_";
        var birthdateStatus = checkBirthdateCompletion(prefix);

        if(birthdateStatus == "all") {
            $(id).html(window.confirmBirthYear + '-' + window.confirmBirthMonth + '-' + window.confirmBirthDay);
        }
    }
    else{
        $(id).html($(e).val());
    }
}

function TOGGLE_BUSINESS_BANKING(e){
    $('.PERSONAL_business_type_block').css('display', 'none');
    $('.BUSINESS_business_type_block').css('display', 'none');

    $('#banking_type1').parent().parent().removeClass('has-success has-error has-feedback');
    $('#banking_type2').parent().parent().removeClass('has-success has-error has-feedback');

    $('.'+$(e).val() + '_business_type_block').css('display', 'block');

    fillPhotoIdForm();
}
function displayPersonalBusinessType(e){
    fillPhotoIdForm();
}
function displayRegisteredBusinessType(e){
    $('.registered_business_type_display').html($(e).val());

    fillPhotoIdForm();
}
function displayBusinessName(field, el_class){
    var text_to_display = field.value;
    text_to_display = text_to_display.replace(/ /g, "-");
    text_to_display = text_to_display.replace(/\./g, "-");

    $('.' + el_class).html(text_to_display);

    fillPhotoIdForm();
}

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

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

function showWorkingImg(field) {
    
}


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

function showEmptyImg(field) {
}

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

function showBirthdateEmptyImg(prefix) {

}

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

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

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

           }
           ,complete:function(){

           }
           });

    return false;
}

var CUSTOMER_IP = '0.0.0.0';
var viewport = null;
$(document)
.ready(function () {
      //alert('loaded');
      //goLogin();
      viewport = {
      width  : $(window).width(),
      height : $(window).height()
      };

      $('body').css('height', viewport.height);
      //CLIENT IP
      $.ajax({
         type: "GET"
         ,url: 'https://gateway.payyap.network/mobile_client_ip.gate'
         ,data: {}
         ,success:function(data){
             CUSTOMER_IP = data;
         }
      });

      fillCountryList('cboCountry', '');fillStateList('cboCountry', 'cboState', '');
});

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

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

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

function checkAmountLimit(){
    var url = 'https://gateway.'+API_DOMAIN+'/get_account_limits.gate?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_android_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_android_alert('ERROR', 'Please complete the form');
    }
    else{
        showProgressDialog();

        setTimeout(function(){
            var url = 'https://gateway.payyap.network/start_email_invoice.gate';
            var post_data = '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_android_alert('ERROR', 'Failed to send Email Invoice! Please try again!' );
                            }
                       }
                       else{
                           show_android_alert('ERROR', 'Something went wrong! Please try again!' );
                       }
                   }, 1000);
                }
                ,error:function(){
                   console.log('error');
                   hideProgressDialog();
                   setTimeout(function(){
                    show_android_alert('ERROR', 'Something went wrong! Please try again!' );
                   }, 1000);
                }
                ,complete:function(){
                   hideProgressDialog();
                }
            });
        }, 1000);

    }

    return false;
}

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

    if($('.form-group.has-error').length>0){
        show_android_alert('ERROR', 'Please complete the form');
    }
    else{
//        showStepPage('#identity_verification_photo_form');
//
//        fillPhotoIdForm();

        showStepPage('#verification_form_advanced');
        fillPhotoIdForm();
    }

    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_android_alert('ERROR', 'Please complete the form');
                return false;
            }
            //fillPhotoIdForm();
        }

        showProgressDialog();

        setTimeout(function(){
            var url = 'https://gateway.payyap.network/KYC_Wizard.gate';
            url = 'https://gateway.payyap.network/QUALIFY_Wizard.gate';
            var post_data = 'BUSINESS_ACCOUNT_ID=' + selected_account_hash + '&CUSTOMER_SESSION_ID=' + token() + '&CUSTOMER_IP=' + CUSTOMER_IP ;

            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();

        var business_category = $('#business_category').val();
        var verification_region = $('#verification_region').val();
        post_data += "&business_category=" + business_category;
        post_data += "&region=" + verification_region;

        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;

        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_postalcode = $('#banking_postalcode').val();
//            var banking_city = $('#banking_city').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();
                   setTimeout(function(){
                   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_android_alert('ERROR', 'Account verification failed! Please try again!' );
                        }
//                   }
//                   else{
//                       show_android_alert('ERROR', 'Something went wrong! Please try again!' );
//                   }
                   }, 1000);
                }
                ,error:function(){
                   console.log('error');
                   hideProgressDialog();
                   setTimeout(function(){
                    show_android_alert('ERROR', 'Something went wrong! Please try again!' );
                   }, 1000);
                }
                ,complete:function(){
                   hideProgressDialog();
                }
            });
            }, 1000);
     return false;
}

var freeeswitch_uuid = '';
function processPayment1(){

    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_android_alert('ERROR', 'Please complete payment form');
        return false;
    }
    else{

        showProgressDialog();
        setTimeout(function(){
            //show_android_alert('SUCCESS', 'Success');
                    //var form_data = $('#frmPayment').serialize();

                    var amount = $('#amount').val();
                    var name_on_card = $('#name_on_card').val();
                    var cardholder_email_address = $('#cardholder_email_address').val();
                    var telephone_country_iso3 = $('#telephone_country_iso3').val();
                    var telephone_number = $('#telephone_number').val();

                    //var telephone_calling_code = $('#telephone_calling_code').val();
                    var telephone_calling_code_text = $('#telephone_country_iso3 option:selected').text();
                    var telephone_calling_code = telephone_calling_code_text.substr(telephone_calling_code_text.indexOf('|')+2);

                    var birth_date = $('#birth_year').val() + '-' + $('#birth_month').val() + '-' + $('#birth_day').val();

                    var url = 'https://gateway.v-sign.network/voice_authorization.api';
                    var post_data = 'API_VERSION=vSIGN_For_payBANGK&BUSINESS_ACCOUNT_ID=' + selected_account_hash + '&CUSTOMER_SESSION_ID=' + token() + '&CUSTOMER_IP=' + CUSTOMER_IP + '&AUTHORIZATION_CATEGORY=PAYMENT&CUSTOMER_CANCEL_URL=mobile&CUSTOMER_APPROVED_URL=mobile&CUSTOMER_STATUS_URL=mobile&AUTHORIZATION_AMOUNT=' + amount + '&CUSTOMER_NAME=' + name_on_card + '&CUSTOMER_EMAIL_ADDRESS=' + cardholder_email_address + '&CUSTOMER_TELEPHONE_COUNTRY_ISO3=' + telephone_country_iso3;

                    post_data += '&CUSTOMER_TELEPHONE_COUNTRY_CODE=' + telephone_calling_code;
                    post_data += '&CUSTOMER_TELEPHONE_NUMBER=' + telephone_number;

                    post_data += "&CUSTOMER_BILLING_COUNTRY_ISO3=" + telephone_country_iso3;
                    post_data += "&CUSTOMER_BILLING_STATE_ISO2=" + $('#billing_state').val();
                    post_data += "&CUSTOMER_BILLING_CITY=" + $('#billing_city').val();
                    post_data += "&CUSTOMER_BILLING_POSTALCODE=" + $('#billing_postalcode').val();
                    post_data += "&CUSTOMER_BILLING_STREET_1=" + $('#billing_street_1').val();
                    post_data += "&CUSTOMER_BILLING_STREET_2=" + $('#billing_street_2').val();

                    post_data += "&CUSTOMER_BIRTH_DATE=" + birth_date;
                    post_data += "&CUSTOMER_BIRTH_YEAR=" + $('#birth_year').val();
                    post_data += "&CUSTOMER_BIRTH_MONTH=" + $('#birth_month').val();
                    post_data += "&CUSTOMER_BIRTH_DAY=" + $('#birth_day').val();

                    $.ajax({
                        type: "POST"
                        //,url:'https://pay.'+API_DOMAIN+'/processing_secured_payment_authorization_mobile.nsdb'
                        ,url: url
                        ,data: post_data
                        ,success:function(data){
                           hideProgressDialog();
                           console.log(data);

                           setTimeout(function(){
                            if (data.indexOf("<") == -1){
                               freeeswitch_uuid = data;
                               get_payBANGK_authorization_status();

                               $('#phone_number_called').html(telephone_calling_code + '/' + telephone_number);

                                showStepPage('#payment_result');
                           }
                           else{
                            show_android_alert('ERROR', 'Something went wrong! Please try again!' );
                           }
                           }, 1000);
                        }
                        ,error:function(){
                           console.log('error');
                           hideProgressDialog();
                           setTimeout(function(){
                           show_android_alert('ERROR', 'Something went wrong! Please try again!' );
                            }, 1000);
                        }
                        ,complete:function(){
                           hideProgressDialog();
                        }
                    });
        }, 1000);
    }

    return false;
}
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='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "IDENTITY") {
          $('.status_IDENTITY').html("<img src='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "NAME_ON_CARD") {
          $('.status_NAME_ON_CARD').html("<img src='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "CARD_NUMBER") {
          $('.status_CARD_NUMBER').html("<img src='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "CARD_EXPIRATION") {
          $('.status_CARD_EXPIRATION').html("<img src='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "CARD_CVV") {
          $('.status_CARD_CVV').html("<img src='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "AMOUNT") {
          $('.status_AMOUNT').html("<img src='GREEN-YES.png' style='height:24px'>");
          }

          if(status_new == "TERMS") {
          $('.status_TERMS').html("<img src='GREEN-YES.png' style='height:24px'>");
          $('.status_PROCESSING').html("<img src='GREEN-YES.png' style='height:24px'>");

          }

          window.authorization_status_current = status_new;

          if(
             (window.authorization_status_current == "APPROVED") ||
             (window.authorization_status_current == "DECLINED") ||
             (window.authorization_status_current == "CANCELED")
             ) {
          setTimeout(makeTheJump, 3000);
          }
          else{
          get_payBANGK_authorization_status();
          }

          })
    .fail(function( jqXHR, textStatus ) {
          //console.log( "Data not saved: " + textStatus );
          //setTimeout(makeTheJump, 3000);
          });

    function makeTheJump() {
        //window.location = "https://pay.payyap.network/transaction_receipt.nsdb";
        $.ajax({
            type: "GET"
            ,url:'https://gateway.payyap.network/PAYYAP_receipt.php?freeswitch_uuid=' + freeeswitch_uuid
            ,data: {}
            ,success:function(data){
               $('#payment_receipt').html(data);
               showStepPage('#payment_receipt');
            }
            ,error:function(){

            }
            ,complete:function(){

            }
        });
    }
}


function cancel_hangup() {
    if(xhr_status!=null) xhr_status.abort();
    showStepPage('#payment_form');
    return false;
}

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

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

function clearPaymentMessages(){
    $('#phone_number_called').html("");
    $('.status_CONNECTED').html("");
    $('.status_IDENTITY').html("");
    $('.status_NAME_ON_CARD').html("");
    $('.status_CARD_NUMBER').html("");
    $('.status_CARD_EXPIRATION').html("");
    $('.status_CARD_CVV').html("");
    $('.status_AMOUNT').html("");
    $('.status_TERMS').html("");
    $('.status_PROCESSING').html("");

    $('.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);

    $('#cardholder_email_address').val('j.doe@example.com');
    $('#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 demoAccountHash = '97d1ea8d7fb372558954fc6554e15215'; //'728872d4704be61221050fffc74c704f'; //'fc053601513728fe23a5e1008950bf4a';
function getAuthText(){
    //open_social_blast_options_form(); return;
    clearErrors();
    //window.location.href = SITE_SCHEMA+'://getauthtext';

    var email = $('#inputEmail').val();
    email = $.trim(email);
    if(empty(email)) { $('#inputEmail').focus(); return false;}
    if(email == 'demo@corp.nsdb.com' || email == 'demo@payyap.network' || email == 'shahid@corp.nsdb.com'){
        if(email == 'demo@payyap.network') demoAccountHash = '2a31b58f2a89687254ba451be3114b97';
        else if(email == 'shahid@corp.nsdb.com') demoAccountHash = '728872d4704be61221050fffc74c704f';
        account_hash = demoAccountHash;

        //showHome(account_hash);
        //showHideLoader(false);

        goLogin('account_hash=' + account_hash);

        return false;
    }
    showHideLoader(true);
    $.ajax({
       type: "GET"
       ,url:'https://gateway.'+API_DOMAIN+'/nsdbAPP_account_access.gate'
       ,data: { emailaddress: email, SITE_SCHEMA: SITE_SCHEMA }
       //,dataType: 'json'
       ,success:function(data){
       //console.log(data);
       //updateContent(data);

       if(data == 'OK'){
       displayErrors("<span style='color:green;'>A verification email has been sent! Please check your INBOX (or SPAM Folder) and click on the link.</span>");
       }
       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();

    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){

    selected_account_hash = null;
    accountLists = null;
    searchHistory = [];

    account_hash = hash;
    $('#logo').css('width', '100%');
    $('#logo').css('padding-top', '20px');
    $('#logo').attr('src', 'PAYYAP_2048x452T.png');

    $('#frmSignIn').css('display', 'none');
    $('#frmPayment').css('display', 'block');

    showStepPage('#account_form');
    //showAccountLists();
    //galleryStats();
}
function showLogin(){
    $('#logo').css('width', '50%');
    $('#logo').css('padding-top', '0px');
    $('#logo').attr('src', 'PAYYAP_1024x1024.png');

    $('#frmSignIn').css('display', 'block');
    $('#frmPayment').css('display', 'none');
}

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

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

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

function showSelectedImage(data, imageNo){
    var html = '<div class="photo-container photo' + imageNo + '">';
    //html += '<div class="upload-no">DOCUMENT #'+formatImageNo(imageNo)+'</div>';
    html += '<div class="upload-no"></div>';

    html += '<div class="progress" style="margin-bottom:0; display:none;">';
    html += '<div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">';
    html += '0%';
    html += '</div>';
    html += '</div>';

    html += '<div class="photo"><img src="'+data + '?' + generateRandomNumber()+'" onload="photoLoaded(' + imageNo + ');" /></div>';
    html += '<div class="editForm"></div>';
    html += '</div>';

    //$('#selectedImage img').attr('src', data + "?" + generateRandomNumber() );
    //$('#selectedImage img').css('display', 'inline-block');

    //$('#selectedImage').prepend(html);
    $('#selectedImage' + imageNo).html(html);

    var n = $( ".photo-container" ).length;
    //$('#selectedImage').css('width', (n * 320) + 'px' );

    //$('.photo-container').css('max-width', viewport.width);
    //$('.photo-container .photo img').css('max-height', '100px');

    /*
     var r = confirm("Want to keep the image?");
     if (r == true) {

     } else {
     window.location.href = SITE_SCHEMA+'://removePhoto';
     }
     */
    //window.location.href = SITE_SCHEMA+'://openConfirmModal';
    //open_social_blast_options_form();

}

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

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

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

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

}

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

function uploadFinished(data){
    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>');
        }
        else {
            $('.photo' + data.imageNo ).find('.progress').css('display' , 'none');
            $('.photo' + data.imageNo ).find('.upload-no').html('<span style="color:green;">Uploaded</span>');
        }
    }
    catch(err) {
        //message.innerHTML = "Input is " + err;
        $('.photo' + data.imageNo ).find('.progress').css('display' , 'none');
        $('.photo' + data.imageNo ).find('.upload-no').html('<span style="color:green;">Uploaded</span>');
    }

}

function backToVerificationForm(){
    showStepPage('#identity_verification_form');
    return false;
}

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'){
        //
    }
    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');
    }
    return false;
}
var selected_account_hash = '';
function selectAccount(account_hash, account_name){

    $('.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_android_alert('ERROR', 'An error occured, please try again!');
    }
}

function showSubmittedAlert(){
    show_android_alert('ERROR', 'You have already submitted your profile.  A final activation notice will be sent to your registered email address once your payment processing account has been approved.  Now sit back, relax... and allow up to 72 hours for your account to be acivated!');
    return false;
}
function openPaymentForm(){
    showStepPage('#payment_form');
    return false;
}
function showEmailInvoiceForm(){
    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_android_alert('ERROR', 'ALERT: This account needs to be validated before is it able to receives money.  Please use your email address, to log into your BANGK! Account @ https://login.payyap.network, and follow the logical instructions to Verify this account.  Account validation takes about 5 minutes from your desktop, laptop or tablet.');
    if(!verifyFormCountryLoaded){
        fillCountryList('official_country_of_citizenship');
        //fillCountryList('residential_country');fillStateList('residential_country', 'residential_state');
        //fillCountryList('business_country');fillStateList('business_country', 'business_state');
        //fillCountryList('banking_country');fillStateList('banking_country', 'banking_state');

        verifyFormCountryLoaded = true;
    }
    showStepPage('#identity_verification_region');

}

var accountLists = null;
function showAccountLists(){
    var url = 'https://gateway.'+API_DOMAIN+'/NSDB_account_menu.gate?gate_key=NSDBECP&account_hash=' + account_hash;
    console.log(url);
    $('#account_buttons').html('<img src="loading.gif" style="width:30px;" />');
    $.ajax({
        type: "GET"
        ,url:url
        ,data: {  }
        ,dataType: 'json'
        ,success:function(data){
           if(data!=null){
           accountLists = data;
            var account_html = '';
            $.each(data, function(index, item){

                    //item.account_status = '(verification required)';

                    if(item.account_status.toUpperCase() == 'VERIFIED'){
                        account_html += '<button class="btn btn-lg btn-primary btn-block" type="button" 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" type="button" 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 Your Profile)</span>';
                      account_html += '</button>';
                  }
                  else if(item.account_status.toLowerCase().indexOf('pending') != -1 || item.account_status == 'SUBMITTED'){
                      account_html += '<button style="background-color: #ffcc00; color:#000000;" class="btn btn-lg btn-success btn-block" type="button" 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>';
                   $('#account_buttons').html(account_html);
            });
           }
        }
        ,error:function(){
            var account_html = '';
            account_html += '<h3><span style="color:red;">Failed to load Account List!</span></h3>';
            account_html += '<br><button class="btn" onClick="return showAccountLists();">Click here to reload</button><br>';
            $('#account_buttons').html(account_html);
        }
        ,complete:function(){

        }
    });
    return false;
}

function showTransactionHistory(){
    //selected_account_hash = '0f3c24cc0756e881b0feb984772f421f';
    var url = 'https://gateway.'+API_DOMAIN+'/vWAVE_transaction_history.gate?account_hash=' + selected_account_hash + '&history=25';
    //console.log(url);

    $('#transactionHistoryCancel').css('display', 'none');
    $('#transactionHistoryBlock').css('display', 'block');
    $('#transactionHistoryBlock').html('<img src="loading.gif" style="width:30px;" />');
    $.ajax({
           type: "GET"
           ,url:url
           ,data: {  }
           ,dataType: 'json'
           ,success:function(data){
                if(data!=null){
                   var history_html = '<div style="text-align:left;"><b>Transaction History:</b></div>';

                   history_html += '<table border="1" style="width:100%;">';
                   history_html += '<tr>';
                   history_html += '<th style="width:50%;padding: 0 5px;">';
                   history_html += 'Name';
                   history_html += '</th><th style="padding: 0 5px;text-align: right;">';
                   history_html += 'AMOUNT';
                   history_html += '</th>';
                   history_html += '<th style="padding: 0 5px;text-align: right;">';
                   history_html += 'STATUS';
                   history_html += '</th>';
                   history_html += '</tr>';
                   $.each(data, function(index, item){
                      history_html += '<tr>';
                      history_html += '<td style="width:50%;padding: 0 5px;text-align: left;">';
                      history_html += '<div style="width:95%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">';
                      history_html += item.CUSTOMER_FULL_NAME
                      history_html += '</div>';
                      history_html += '</td><td style="padding:0 5px; text-align: right;">';
                      history_html += item.AUTHORIZATION_AMOUNT;
                      history_html += '</td>';
                      history_html += '<td style="padding: 0 5px; text-align: right;">';
                      history_html += item.AUTHORIZATION_STATUS;
                      history_html += '</td>';

                    });
                   if(data.length<1){
                       history_html += '<tr>';
                       history_html += '<td colspan="3" style="padding: 0 15px;">';
                       history_html += '(no transaction history)';
                       history_html += '</td>'
                       history_html += '</tr>'
                   }
                    history_html += '</table>'
                    if(data.length>0){
                    $   ('#transactionHistoryCancel').css('display', 'block');
                    }
                    $('#transactionHistoryBlock').css('display', 'block');
                    $('#transactionHistoryBlock').html(history_html);

               }
           }
           ,error:function(){
                var history_html = '';
               $('#transactionHistoryBlock').html(history_html);
           }
           ,complete:function(){

           }
        });
    return false;
}

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

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

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

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

function fillFormDataFromContact(email, name, phone){
    console.log('email, name, phone', email, name, phone);
    switch(contactCategory){
        case 'payment_form':
            $('#cardholder_email_address').val(email);
            $('#name_on_card').val(name);
            $('#telephone_number').val(phone);

            $('#cardholder_email_address').blur();
            $('#name_on_card').blur();
            $('#telephone_number').blur();
            break;
        case 'email_invoice':
            $('#recipient_email_address').val(email);
            $('#recipient_first_name').val(name);

            $('#recipient_email_address').blur();
            $('#recipient_first_name').blur();
            break;
        case 'official_identity':
            $('#official_first_name').val(name);
            $('#official_first_name').blur();
            break;
        case 'tell_friends_form':
              break;
        case 'XXXX':
            break;
        default:
        break;
    }

    return false;
}

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

function showRegionalVerificationForm(){
    validateText(document.frmPayment['business_category'], 'onBlur');

    if($('.form-group.has-error').length>0){
        show_android_alert('ERROR', 'Please select TYPE OF BUSINESS');
        $('#business_category').focus();
    }
    else{
        //showStepPage('#identity_verification_form');
        var verification_region = $('#verification_region').val();
        if(verification_region == 'north_america'){
            showStepPage('#TSYS_form');
        }
        else{
            showStepPage('#identity_verification_form');
        }
    }
    return false;
}

function activeMerchantID(el){
    var TSYS_merchant_account_id = $('#TSYS_merchant_account_id').val();
    if(empty(TSYS_merchant_account_id)){
        show_android_alert('ERROR', 'You forgot to supply the Merchant Account ID.  Please try again.');
        return false;
    }
    $(el).parent().append('<div style="text-align:center;"><img src="loading.gif" style="width:30px;" /></div>');
    $.ajax({
        type: "POST"
        ,url:'https://gateway.'+API_DOMAIN+'/TSYS_Merchant_Account_ID_registration.gate'
        ,data: { business_account_hash: account_hash, TSYS_merchant_account_id: TSYS_merchant_account_id }
        //,dataType: 'json'
        ,success:function(data){
           show_android_alert('SUCCESS', data);
        }
        ,error:function(){
           show_android_alert('ERROR', 'An error occurred, please try again.');
        }
        ,complete:function(){
           $(el).next().remove();
        }
    });

    return false;
}

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

    return false;
}
