﻿$(document).ready(function () {

    initalizeLoginArea();

    $("#loginBtn").click(function () {
        loginUser();
        $(this).blur();
    });

    $("#lnkLogout").click(function () {
        logoutUser();
    });

    //script for numbers only fields
    $('input.number').keypress(function (e) {
        var keychar;
        var e = e || window.event;
        var key = e.which || e.keyCode;
        keychar = String.fromCharCode(key);
        if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27)) {
            return true; // control keys
        }
        else if (("0123456789").indexOf(keychar) >= 0) {
            return true; // numbers
        }
        else {
            return false;
        }
    });

    //back to top feature
    $('.backtotop').click(function () {
        $('html, body').animate({ scrollTop: 0 }, 'slow');
    });

    $('.auctionScheduleBtn').click(function () {
        window.location = "../my_schedviewer.aspx"
    });

    $('.prepurchasedStockBtn').click(function () {
        window.location = "../my_prepurchased.aspx"
    });

    $('.todaysAuctionOnlineBtn').click(function () {
        window.location = "../my_auctiononline.aspx"
    });

    $('.shoppingListReportBtn').click(function () {
        window.location = "../my_reportaddedlist.aspx"
    });

    $('.customerLogReportBtn').click(function () {
        window.location = "../my_reportcustomerlog.aspx"
    });
});       //end document ready


//lightbox object
var lightbox = {
    showLightBox: function(selector, height, width) {
        var lightbox = '<div id="lightbox" style="height:' + height + '; width:' + width + ';"></div>'
        $(selector).append(lightbox);
    },
    hideLightBox: function() {
        $("#lightbox").remove();
    }
}

//error message object
var errorMsg = {
    showErrorMsg: function (selector, strMessage) {
        var errHTML = '<div id="errorMsg">';
        errHTML = errHTML + '<p>' + strMessage + '</p>';
        errHTML = errHTML + '<input type="button" value="Close" onclick="javascript:lightbox.hideLightBox(); errorMsg.closeErrorMsg();" />';
        errHTML = errHTML + '</div>';
        $(selector).append(errHTML);
    },
    closeErrorMsg: function () {
        $("#errorMsg").remove();
    }
}

/*==================================================================================
Functon: loginUser()
Author:  Enrique Jingco
Description: Logs in user
====================================================================================*/
function loginUser() {
    $("#frmLogin").submit(function () {
        if ($("#username").val() == "" && $("#password").val() == "") {
            var selector = "body";
            var lightboxHeight = $(selector).height() + 'px';
            var lightboxWidth = $(selector).width() + 'px';

            lightbox.showLightBox(selector, lightboxHeight, lightboxWidth);
            errorMsg.showErrorMsg(selector, 'Invalid User ID and Password. Please try again.');
        }
        else {
            var params = $("#frmLogin").serialize();
            $.ajax({
                type: "POST",
                url: "handlers/customerHandler.ashx",
                data: params, //action 1
                cache: false,
                beforeSend: function () {
                    var selector = "body";
                    var lightboxHeight = $(selector).height() + 'px';
                    var lightboxWidth = $(selector).width() + 'px';

                    lightbox.showLightBox(selector, lightboxHeight, lightboxWidth);
                    $('body').append("<img id='ajaxloader' src='/images/nonlog/common/ajax-loader.gif' style='position:absolute; top:10%; left:50%; z-index:9999;'/>")
                },
                success: function (html) {
                    if (html == "Error") {
                        $('#ajaxloader').remove();
                        errorMsg.showErrorMsg('body', 'Invalid User ID and Password. Please try again.');
                    }
                    else {
                        window.location = html;
                    }
                }
            });
        }
        $("#frmLogin").unbind();
        return false;
    });
}

/*==================================================================================
Functon: logoutUser()
Author:  Enrique Jingco
Description: Logs out user
====================================================================================*/
function logoutUser() {
    $.ajax({
        type: "POST",
        url: "handlers/customerHandler.ashx",
        data: "action=3",
        cache: false,
        success: function(html) {
            window.location = html;
        }
    });

    return false;
}

/*==================================================================================
 Functon: initalizeLoginArea()
 Author:  Enrique Jingco
 Created: 06/09/2011
 Description: This function is called everytime the a page is opened or refreshed.
              This function will check and see if there are values in the login
              area and if the username or password textbox is focused or blurred.
====================================================================================*/
function initalizeLoginArea() {
    var username = $('input.username');
    var password = $('input.password');

    if (username.val() != '') {
        hideUsername();
    }
    else {
        showUsername();
    }

    if (password.val() != '') {
        hidePassword();
    }
    else {
        showPassword();
    }

    username.keypress(function(event) {
        hideUsername();
    });

    password.keypress(function(event) {
        hidePassword();
    });

    username.focus(function() {
        hideUsername();
    });

    password.focus(function() {
        hidePassword();
    });

    $('span.uname').click(function() {
        hideUsername();
        username.focus();
    });
    
    $('span.pass').click(function() {
        hidePassword();
        password.focus();
    });
    
    username.blur(function() {
        if ($(this).val() == '') {
            showUsername();
        }
    });

    password.blur(function() {
        if ($(this).val() == '') {
            showPassword();
        }
    });
}

function hideUsername() {
    $('#login-area span.uname').css('z-index', '-100');
}

function hidePassword() {
    $('#login-area span.pass').css('z-index', '-100');
}

function showUsername() {
    $('#login-area span.uname').css('z-index', '100');
}

function showPassword() {
    $('#login-area span.pass').css('z-index', '100');
}


/*==================================================================================
Functon: resetForm(id, strClass)
Parameters: id - ID of the form being reset
Author:  Enrique Jingco
Created: 07/07/2011
Description: Clears the form fields back to empty and removes the "error" class 
             given during validation. Removes error class for inputs of type
             text and password (add more types if necessary).
====================================================================================*/
function resetForm(id) {
    $('#' + id).each(function () {
        this.reset();
        $("#errorBox").css("display", "none");
        $('input[type="text"], input[type="password"]').removeClass("error");
    });
}


/*==================================================================================
Functon: conversionCalculator()
Author:  Enrique Jingco
Created: 07/05/2011
Description: Converts JPY to NZD given the ForexRate and rounded off to the nearest
             hundreds.
====================================================================================*/
function conversionCalculator() {
    var ForexRate = $('.ForexRate').val();
    var JPY = $('#yen').val();
    var NZD = ForexRate * JPY;
    NZD = Math.round(NZD * 100) / 100;
    $('#nzdollars').attr('value', NZD);
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

// FUNCTION TO DELETE A COOKIE
function deleteCookie(name) {
    var expdate = new Date();
    expdate.setTime(expdate.getTime() - 1);
    document.cookie = name += "=; expires=" + expdate.toGMTString();
}

 function openNewWindow(url) {
 popupWin = window.open(url,
 'open_window',
 'menubar, toolbar, location, directories, status, scrollbars, resizable, dependent, width=640, height=480, left=0, top=0')
}

 /*==================================================================================
 Functon: ()
 Author:  
 Created: 07/05/2011
 Description: Converts JPY to NZD given the ForexRate and rounded off to the nearest
 hundreds.
 ====================================================================================*/
function conversionCalculator() {


}
