﻿//master JS file for whole site

/*** Globals ***/
var globalRootDir = "/"
//var globalRootDir = "/emun_b2b/"
var globalHostName = window.location.hostname;
var globalBaseURL = window.location.protocol + "//" + globalHostName + globalRootDir;
var globalAssetsPath = globalBaseURL + "assets/";
/*** end Globals ***/

/*** Console wrapper for older versions of IE ***/
if (window['console'] === undefined) {
    console = { log : function(){} };
}
/*** end console wrapper ***/

/*** Loader and lock screen ***/
var globalLockScreenTimerID = null,
    globalLockScreenStatus = false,
    globalLoaderLoaded = false;

function positionLoader(animate) {
    $newTop = (($(window).height() / 2) - ($("#loaderui").height() / 2) + $(window).scrollTop());
    $newLeft = (($(window).width() / 2) - ($("#loaderui").width() / 2) + $(window).scrollLeft());
     // console.log('Calculated loaderui top = ' + $newTop + '. Calculated loaderui left = ' + $newLeft + '.');
     $("#loaderui").stop();
    if (animate != undefined && !animate) {
        // if animate parameter is false
        $("#loaderui").css({ "top": $newTop + "px", "left": $newLeft + "px" });
    } else {
       $("#loaderui").animate({ "top": $newTop + "px", "left": $newLeft +"px" }, "fast", "linear");
    }
}

function sizeLockScreen() {
    $newHeight = $(document).height();
    $newWidth = $(document).width();
    // console.log('Calculated lockdiv height = ' + $newHeight + '. Calculated lockdiv width = ' + $newWidth + '.');
    $("#lockdiv").css({ "height": $newHeight + "px", "width": $newWidth + "px" });
}

function addLoaderToPage() {
    console.log("addLoaderToPage() called, globalLoaderLoaded = " + globalLoaderLoaded);
    if (!globalLoaderLoaded) {
        globalLoaderLoaded = true;

        $('<div class="loader" id="lockdiv"></div><div class="loader" id="loaderui"><div class="loader" id="loadercontent"><img class="loader" id="loaderimg" src="' + globalAssetsPath + 'img/loading.gif" alt="Loading..." /><br /><span class="loader" id="loaderText"></span></div></div>').prependTo('body');
        $('.loader').hide(); // to deal with IE (versions <= 8) bug where elements in a hidden div don't hide initially
        positionLoader(false);
        sizeLockScreen();
    }
}

function showLoader(text, delay) {
    console.log("showLoader() called, globalLockScreenStatus = " + globalLockScreenStatus);
    if (!globalLockScreenStatus) {
        globalLockScreenStatus = true;
        if (text === undefined) {
            text = "Loading..."; // default display message
        }
        if (delay === undefined) {
            delay = 750; // default wait period before displaying loader
        }
        // Set Loader Text
        $("#loaderText").html(text);
        // Timeout is delayed for fast AJAX queries
        globalLockScreenTimerID = setTimeout("$('.loader').show();", delay);
    }
}

function hideLoader() {
    console.log("hideLoader() called, globalLockScreenStatus = " + globalLockScreenStatus);
    if (globalLockScreenStatus) {
        globalLockScreenStatus = false;
        // Cancel Timeout if still running
        clearTimeout(globalLockScreenTimerID);
        //Hide Loader DIV
        $('.loader').hide();
    }
}

$(window).scroll(function () {
    positionLoader();
});

$(window).resize(function () {
    positionLoader();
    sizeLockScreen();
});
/*** end Loader and Lock Screen ***/


/*** Process Payments Functions ***/
/*** get payment grandTotal ***/
function getPaymentTotal() {
    var total = 0;
    var result = 0;
    var grandTotal = 0;
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            console.log($(this).val());
            total = $("#invoice-payment-value-" + $(this).val()).val();
            total = total.replace(/[$,]+/g, "");
            result = parseFloat(total);
            grandTotal = grandTotal + result;
        } else {
            $("#invoice-payment-value-" + $(this).val()).val('');
        }
    });
    console.log(result + '--' + grandTotal);
    $('#total-payment-amount').val(grandTotal).formatCurrency();
};

/*** process the payment made ***/
function processPayment(ccOnFile) {
    var ccVal = $('select[name$="ddlCardsOnFile"]').val();
    var totalAmount = $('#total-payment-amount').val().replace(/[$,]+/g, "");
    var invoices = '';
    var arrInvoices = [];
    var i = 0;
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            invoices = $(this).val();
            arrInvoices[i] = { invoiceNumber: $(this).val(), InvoicePO: $(this).data('ponumber'), OrderNumber: $(this).data('ordernumber'), invoiceAmount: $("#invoice-payment-value-" + $(this).val()).val() };
        }
        i++;
    });

    simpleLoad('PaymentProcessing.aspx/ProcessPayment', { 'ccOnFile': ccOnFile, 'ccVal': ccVal, 'totalAmount': totalAmount, 'invoices': arrInvoices }, processPayment_Success);
    return false;
};

function processPayment_Success(data) {

}
/*** End of Payment Processing functions ***/

/*** Global Functions ***/
// Gets the folder the current page resides in.
function getURLFolder() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.lastIndexOf('/'));


    if (baseURL.indexOf('http://localhost') != -1) {
        // Base Url for localhost
        url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
        alert(baseURL);
    }
}

function GetElementByIdEndsWith(tagName, endsWith) {
    var elements =
             document.getElementsByTagName(tagName);

    for (var i = 0; i < elements.length; i++) {
        if (elements[i].id.endsWith(endsWith)) {
            return elements[i];
        }
    }

    return null;
}

String.prototype.endsWith = function (txt, ignoreCase) {
    var rgx;

    if (ignoreCase) {
        rgx = new RegExp(txt + "$", "i");
    }
    else {
        rgx = new 
        RegExp(txt + "$");
    }

    return this.match(rgx) != null;
}

// Get URL parameters.
$.urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (!results) { return 0; }
    return results[1] || 0;
}

function EnableCreditRequireFields(enable) {
    if (enable == 'True') {
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCTypeRequired"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCNumberRequired"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCMonth"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCYear"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCCVV"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCName"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCAddress"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCCity"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCState"), true);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCZip"), true);
    } else {
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCTypeRequired"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCNumberRequired"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCMonth"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCYear"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCCVV"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCName"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCAddress"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCCity"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCState"), false);
        ValidatorEnable(GetElementByIdEndsWith("span", "reqCCZip"), false);
    }
}

/*** image preview ***/
this.screenshotPreview = function () {
    /* CONFIG */

    xOffset = 10;
    yOffset = 30;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result

    /* END CONFIG */
    $("a.screenshot").hover(function (e) {
        var top = e.pageY - xOffset;
        var right = e.pageX + yOffset;
        console.log('screen shot--' + e.pageY + '--' + xOffset + '--' + e.pageX + '--' + yOffset + '--' + top + '--' + right);
        this.t = this.title;
        console.log(this.rel);
        this.title = "";
        var c = (this.t != "") ? "<br/>" + this.t : "";
        $("body").append("<p id='screenshot'><img src='" + this.rel + "' alt='url preview' />" + c + "</p>");
        $("#screenshot")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function () {
	    this.title = this.t;
	    $("#screenshot").remove();
	});
    $("a.screenshot").mousemove(function (e) {
        $("#screenshot")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
    });
};

/*** end image preview ***/

 


/*** On Page Load ***/
$(document).ready(function () {
    addLoaderToPage();
    //showLoader('Hello, this is a test.');

    /*** Payment Processing ***/
    /*** when checking and invoice then populate the total and grand total ***/
    $('input[id^="invoicecheck"]').change(function () {
        var invoiceid = $(this).val();
        console.log(invoiceid + '--' + $(".invoice-amount-" + invoiceid).text() + '--' + $(this) + '--' + $("#invoicecheck-" + invoiceid).attr('checked'));
        if ($("#invoicecheck-" + invoiceid).attr('checked') == 'checked') {
            console.log("checked");
            $("#invoice-payment-value-" + invoiceid).val($(".invoice-amount-" + invoiceid).text());
        } else {
            $("#invoice-payment-value-" + invoiceid).val('');
        }
        getPaymentTotal();

    });

    /*** make all invoices checked for payment ***/
    $('#payment-select-all').click(function () {
        var invoiceid = $(this).val();
        $('input[type=checkbox]').each(function () {
            $("#invoicecheck-" + $(this).val()).attr('checked', true)
            $("#invoice-payment-value-" + $(this).val()).val($(".invoice-amount-" + $(this).val()).text());
        });
        getPaymentTotal();
        return false;
    });

    /*** clear all invoices out of payment que ***/
    $('#payment-clear-all').click(function () {
        var invoiceid = $(this).val();
        $('input[type=checkbox]').each(function () {
            $("#invoicecheck-" + $(this).val()).attr('checked', false)
            $("#invoice-payment-value-" + $(this).val()).val($(".invoice-amount-" + $(this).val()).text());
        });
        getPaymentTotal();
        return false;
    });

    /*** if selecting credit card on file then hide credit card info and vice versa ***/
    $('#creditcard-onfile').click(function () {
        $('#creditcard-info-screen').hide();
        EnableCreditRequireFields('False')

    });
    $('#new-creditcard').click(function () {
        $('#creditcard-info-screen').show();
        EnableCreditRequireFields('True')
    });

    /*** if hidden field is true then make cc on file checked ***/
    if ($('input[name$="hidCardsOnFile"]').val() == 'True') {
        $('#creditcard-onfile').attr('checked', true);
        $('#creditcard-info-screen').hide();
    } else {
        $('#new-creditcard').attr('checked', true);
        $('#creditcard-info-screen').show();
    }

    /*** if user adjusts what they want to pay then we need to update the grand total.  we do when they leave the input box ***/
    $('input[id^="invoice-payment-value"]').blur(function () {
        getPaymentTotal();
    });

    /*** this will start the payment process execution ***/
    $('#payment-apply-payment').click(function () {
        if ($('#creditcard-onfile').is(':checked')) {
            console.log('cc on file');
            var ccOnFile = true;
            processPayment(ccOnfile);
        } else {

        }

    });

    /*** End of Payment Processing ***/

    /*** image preview ***/
    screenshotPreview();
    /*** end image preview *///

    //file upload
    $('a.show-file-upload').click(function () {
        console.log('show file upload');
        $('.file-upload').show();
        return false;
    });
});
/*** end On Page Load ***/

