/*
 * Functions
 */
function checkEmail(email)
{
    var queryType       = "checkEmail";
    var customeremail   = email;
    var emailOk         = "";
    $.ajax
    ({
        async: false,
        url: 'handlers/buyer_data_handler.php',
        type: 'POST',
        data: 'customeremail=' + customeremail + '&queryType=' + queryType,
        success: function(result)
        {
           emailOk = result;
        }
    });
    return emailOk;
}
function userNameOk(userName)
{
    var queryType   = "checkUsrName";
    var usrName     = userName;
    var usrNameOk   = false;
    $.ajax
    ({
        async: false,
        url: 'handlers/buyer_data_handler.php',
        type: 'POST',
        data: 'usrName=' + usrName + '&queryType=' + queryType,

        success: function(result)
        {
            if (result == "Available")
            {
                usrNameOk = true;
            }
            else
            {
                usrNameOk = false;
            }
        }
    });
    return usrNameOk;
}

function validatePurchase(formID)
{
  // All the form's fields
    var merchantid;
    var lang;
    var productdetail;
    var cc;
    var affID;
    var refererPage;
    var alreadyLoggedIn = $('#alreadyLoggedIn').val();

    var lastName          = "";
    var firstName         = "";
    var customeremail     = "";
    var usrName           = "";
    var usrPass           = "";
    var confirmPass       = "";
    var nbLicEBook        = "";
    var eBookTotal        = "";
    var upgradePtagPro    = "";
    var upgradeTotal      = "";
    var nbLicPtagPro      = "";
    var PrepTagsPro_total = "";
    var total     = "";

    var errorArray        = new Array();
    var formArray         = new Array(19);
    var i                 = 0;
  // Loop through the form and load values in variables
  $(':input', formID).each(function() {
    var elemId  = this.id;
    formArray[i] = this.value;
    i++;

    if (elemId      == 'lastName')          { lastName = this.value;            }
    else if (elemId == 'firstName')         { firstName = this.value;           }
    else if (elemId == 'customeremail')     { customeremail = this.value;       }
    else if (elemId == 'usrName')           { usrName = this.value;             }
    else if (elemId == 'usrPass')           { usrPass = this.value;             }
    else if (elemId == 'confirmPass')       { confirmPass = this.value;         }
    else if (elemId == 'nbLicEBook')        { nbLicEBook = this.value;          }
    else if (elemId == 'eBookTotal')        { eBookTotal = this.value;          }
    else if (elemId == 'upgradePtagPro')    { upgradePtagPro = this.value;      }
    else if (elemId == 'upgradeTotal')      { upgradeTotal = this.value;        }
    else if (elemId == 'nbLicPtagPro')      { nbLicPtagPro = this.value;        }
    else if (elemId == 'PrepTagsPro_total') { PrepTagsPro_total = this.value;   }
    else if (elemId == 'total')             { total = this.value;               }

    else if (elemId == 'merchantid')        { merchantid = this.value;          }
    else if (elemId == 'lang')              { lang = this.value;                }
    else if (elemId == 'productdetail')     { productdetail = this.value;       }
    else if (elemId == 'cc')                { cc = this.value;                  }
    else if (elemId == 'affID')             { affID = this.value;               }
    else if (elemId == 'refererPage')       { refererPage = this.value;         }
  });
  if (lastName.length < 2)
  {
    errorArray.push("lastName");
  }
  if (firstName.length < 2)
  {
    errorArray.push("firstName");
  }
  var emailVal = checkEmail(customeremail);
  if (emailVal != "ok")
  {
    errorArray.push("customeremail");
  }
  if (alreadyLoggedIn != "loggedIn")
  {
    if (userNameOk(usrName) != true)
    {
        errorArray.push("userName");
    }
    if (usrPass != confirmPass || usrPass == "")
    {
        errorArray.push("password");
    }
  }
  if (total == 0)
  {
    errorArray.push('totalZero');
  }
  /* Recompute the total */
  var checkTotal = (nbLicEBook * 15) + (upgradePtagPro * 24) + (nbLicPtagPro *39);
  if (total != checkTotal)
  {
    errorArray("totalMismatch");
  }

  /* Decide if the form was properly filled out */
  if (errorArray.length > 0)
  {
    return errorArray;
  }
  else
  {
    return true;
  }
}

function editProductDetail()
{
    var nbLicEBook        = $('#nbLicEBook').val();
    var eBookTotal        = $('#eBookTotal').val();
    var upgradePtagPro    = $('#upgradePtagPro').val();
    var upgradeTotal      = $('#upgradeTotal').val();
    var nbLicPtagPro      = $('#nbLicPtagPro').val();
    var PrepTagsPro_total = $('#PrepTagsPro_total').val();

    var productDetail = "";
    if (nbLicEBook > 0)
    {
        productDetail += nbLicEBook + " eBook (" + eBookTotal + ").# ";
    }
    if (upgradePtagPro > 0)
    {
        productDetail += upgradePtagPro + " upgrade to PrepTags Pro (" + upgradeTotal + ").# ";
    }
    if (nbLicPtagPro > 0)
    {
        productDetail += nbLicPtagPro + " PrepTags Pro licenses (" + PrepTagsPro_total + ").# ";
    }
    $('#productdetail').val(productDetail);
}

function saveFormDataInDB(formID)
{
    var queryType = "loadInDatabases";
    var postData = 'queryType=' + queryType;

    $(':input', formID).each(function()
    {
        postData += "&" + this.id + "=" + this.value;
    });
    var queryOk;
    $.ajax
    ({
        async: false,
        url: 'handlers/buyer_data_handler.php',
        type: 'POST',
        data: postData,

        success: function(result)
        {
            if (result == "OK")
            {
                queryOk = true;
            }
            else
            {
                queryOk = false;
            }
        }
    });
    return queryOk;
}

function resetFormBackgroundColor()
{
    $('#lastName').css('background-color', '#5FF78D');
    $('#firstName').css('background-color', '#5FF78D');
    $('#customeremail').css('background-color', '#5FF78D');
    $('#usrName').css('background-color', '#5FF78D');
    $('#usrPass').css('background-color', '#5FF78D');
    $('#confirmPass').css('background-color', '#5FF78D');
    $('#lastName').css('background-color', '#5FF78D');


}
/* 
 * Ajax routines
 */

$(function()
{
// Generate PrepTags Lite license
    $('#GenPtagsLite').click(function()
    {
    $('#GenPtagsLite').append('<img src="imgages/loading.gif" alt="Currently Loading" id="loading" />');
        var PtagLiteCompID  = $('#PtagLiteCompID').val();
        var SoftVersion     = "PrepTagsLite";

        $.ajax
        ({
            url: 'handlers/licenseGen.php',
            type: 'POST',
            data: 'PtagCompID=' + PtagLiteCompID + '&SoftVersion=' + SoftVersion,

            success: function(result)
            {
                $('#GenPtagsLite').empty();
                $('#GenPtagsLite').append(result);
                $('#loading').fadeOut(500, function()
                {
                    $(this).remove();
                });
            }
        });
        return false;
    });
        
    $('#GenPtagsEBook').click(function()
    {
    $('#GenPtagsEBook').append('<img src="imgages/loading.gif" alt="Currently Loading" id="loading" />');
        var PtagEbookCompID  = $('#PtagEbookCompID').val();
        var SoftVersion      = "PrepTagsEBook";

        $.ajax
        ({
            url: 'handlers/licenseGen.php',
            type: 'POST',
            data: 'PtagCompID=' + PtagEbookCompID + '&SoftVersion=' + SoftVersion,

            success: function(result)
            {
                $('#GenPtagsEBook').empty();
                $('#GenPtagsEBook').append(result);
                $('#loading').fadeOut(500, function()
                {
                    $(this).remove();
                });
            }
        });
        return false;
    });

    $('#GenPtagsPro').click(function()
    {
    $('#GenPtagsPro').append('<img src="imgages/loading.gif" alt="Currently Loading" id="loading" />');
        var PtagProCompID  = $('#PtagProCompID').val();
        var SoftVersion     = "PrepTagsPro";

        $.ajax
        ({
            url: 'handlers/licenseGen.php',
            type: 'POST',
            data: 'PtagCompID=' + PtagProCompID + '&SoftVersion=' + SoftVersion,

            success: function(result)
            {
                $('#GenPtagsPro').empty();
                $('#GenPtagsPro').append(result);
                $('#loading').fadeOut(500, function()
                {
                    $(this).remove();
                });
            }
        });
        return false;
    });

    $('#usrName').change(function(){
        $('#usrNameCell').append('<img src="images/loading.gif" alt="Currently Loading" id="loading" />');
        $('#usrNameCell').append('<span id="availability"></div>');
        var queryType   = "checkUsrName";
        var usrName     = $('#usrName').val();
        $.ajax
        ({
            url: 'handlers/buyer_data_handler.php',
            type: 'POST',
            data: 'usrName=' + usrName + '&queryType=' + queryType,

            success: function(result)
            {
                if (result == "Available")
                {
                    $('#usrName').css('background-color', '#5FF78D');
                    $('#loading').remove();
                    $('#availability').empty().append(" Ok");
                }
                else if (result == "tooShort")
                {
                    $('#usrName').css('background-color', 'orange');
                    $('#usrName').select();
                    $('#loading').remove();
                    $('#availability').empty().append(" > 4 chars");
                }
                else if (result == "NotAvailable")
                {
                    $('#usrName').css('background-color', 'orange');
                    $('#usrName').select();
                    $('#loading').remove();
                    $('#availability').empty().append(" Not available<script>alert('This username is taken. Are you trying to login? \nIf so, please use the Login Icon (top right).')</script>");
                }
            }
        });
        return false;
    });

    // Selects the content of an input field on focus
    $('input').bind("focus", function()
    {
        this.select();
    });

    /* Validate payment form */
    $('#customeremail').change(function()
    {
        $('#emailCell').append('<img src="images/loading.gif" alt="Currently Loading" id="loading" />');
        $('#emailCell').append('<span id="emailCheck"></div>');
        var queryType   = "checkEmail";
        var customeremail     = $('#customeremail').val();
        $.ajax
        ({
            url: 'handlers/buyer_data_handler.php',
            type: 'POST',
            data: 'customeremail=' + customeremail + '&queryType=' + queryType,

            success: function(result)
            {
                if (result == "ok")
                {
                    $('#customeremail').css('background-color', '#5FF78D');
                    $('#loading').remove();
                    $('#emailCheck').empty().append(" Ok");
                }
                else if (result == "notOk")
                {
                    $('#customeremail').css('background-color', 'orange');
                    $('#customeremail').select();
                    $('#loading').remove();
                    $('#emailCheck').empty().append(" Invalid email");
                }
            }
        });
    });
    /* Name check */
    $('#lastName').change(function(){
        $('#lastNameCell').append('<span id="lastNameCheck"></div>');
        var lastName     = $('#lastName').val();
        if (lastName.length > 1)
        {
            $('#lastName').css('background-color', '#5FF78D');
            $('#lastNameCheck').empty().append(" Ok");
        }
        else
        {
            $('#lastName').css('background-color', 'orange');
            $('#lastNameCheck').empty().append(" Error");
            $('#lastName').select();
        }
    });
    $('#firstName').change(function()
    {
        $('#firstNameCell').append('<span id="firstNameCheck"></div>');
        var firstName     = $('#firstName').val();
        if (firstName.length > 1)
        {
            $('#firstName').css('background-color', '#5FF78D');
            $('#firstNameCheck').empty().append(" Ok");
        }
        else
        {
            $('#firstName').css('background-color', 'orange');
            $('#firstNameCheck').empty().append(" Error");
            $('#firstName').select();
        }
    });

    $('#usrPass').change(function(){
        $('#usrPassCell').append('<span id="usrPassCheck"></div>');
        var usrPass     = $('#usrPass').val();
        if (usrPass.length > 5)
        {
            $('#usrPass').css('background-color', '#5FF78D');
            $('#usrPassCheck').empty().append(" Ok");
        }
        else
        {
            $('#usrPass').css('background-color', 'orange');
            $('#usrPassCheck').empty().append(" 6 chars or more");
            $('#usrPass').select();
        }
    });
    $('#confirmPass').change(function()
    {
        $('#confirmPassCell').append('<span id="confirmPassCheck"></div>');
        var usrPass     = $('#usrPass').val();
        var confirmPass = $('#confirmPass').val();
        if (usrPass.length > 5 && usrPass == confirmPass)
        {
            $('#confirmPass').css('background-color', '#5FF78D');
            $('#confirmPassCheck').empty().append(" Ok");
        }
        else
        {
            $('#confirmPass').css('background-color', 'orange');
            $('#confirmPassCheck').empty().append(" Error");
            $('#confirmPass').select();
        }
    });

    $('#purchaseForm').submit(function()
    {
        /* Check the form's content */
        var validated = validatePurchase('#purchaseForm');
        if (validated === true)
        {
            // Update the productdetails
            editProductDetail();
            // log all the data in the various database tables.
            saveFormDataInDB('#purchaseForm');
            return true;
        }
        else
        {
            var errorMsg = "";
            $.each(validated, function(intIndex, arrValue){
                if (arrValue == "totalMismatch")
                {
                    $('#total').css('background-color', 'orange');
                    errorMsg += " - Sorry, it looks like the total was miscalculated. Please contact us to process your purchase manually.\n";
                }
                if (arrValue == "totalZero")
                {
                    $('#total').css('background-color', 'orange');
                    errorMsg += "- You have to select at least one product.\n";
                }
                if (arrValue == "password")
                {
                    $('#usrPass').val("");
                    $('#usrPass').css('background-color', 'orange');
                    $('#usrPass').select();
                    $('#confirmPass').val("");
                    $('#confirmPass').css('background-color', 'orange');
                    errorMsg += "- Password error.\n";
                }
                if (arrValue == "userName")
                {
                    $('#usrName').css('background-color', 'orange');
                    $('#usrName').select();
                    errorMsg += "- This user name is not available.\n";
                }
                if (arrValue == "customeremail")
                {
                    $('#customeremail').css('background-color', 'orange');
                    $('#customeremail').select();
                    errorMsg += "- The email address must be valid.\n";
                }
                if (arrValue == "firstName")
                {
                    $('#firstName').css('background-color', 'orange');
                    $('#firstName').select();
                    errorMsg += "- Invalid first name\n";
                }
                if (arrValue == "lastName")
                {
                    $('#lastName').css('background-color', 'orange');
                    $('#lastName').select();
                    errorMsg += "- Invalid last name\n";
                }                
            });
            var arr2str = validated.toString();
            if (arr2str.search('lastName') == -1)       { $('#lastName').css('background-color', '#5FF78D'); }
            if (arr2str.search('firstName') == -1)      { $('#firstName').css('background-color', '#5FF78D'); }
            if (arr2str.search('customeremail') == -1)  { $('#customeremail').css('background-color', '#5FF78D'); }
            if (arr2str.search('userName') == -1)       { $('#usrName').css('background-color', '#5FF78D'); }
            if (arr2str.search('password') == -1)
            {
                $('#usrPass').css('background-color', '#5FF78D');
                $('#confirmPass').css('background-color', '#5FF78D');
            }
            if (arr2str.search('totalZero') == -1 && arr2str.search('totalMismatch') == -1)
            {
                $('#total').css('background-color', '#5FF78D');
            }
            alert(validated.length + ' errors found:\n' + errorMsg);
            return false;
        }
    });

});


