//Off2Shop Configuration Variables
var MerchantId = 28;
var Off2ShopMainURL = "https://www.off2shop.com/JSONService.ashx?jsonp=?&";
var Off2ShopEmbCartURL = "https://www.off2shop.com/MerchantPage/";
var Off2ShopImagesURL = "https://www.off2shop.com/";

//Shopping cart code
if (xread() == null) xset();
function xset() {
    var date = new Date();
    var expires = "";
    document.cookie = "xcart=" + date.getTime() + expires + "; path=/";
}
function xread() {
    var nameEQ = "xcart=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
    }
    return null;
}

//QueryString Parser
function QueryStringParse(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

//Used for formatting currency output
function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if (isNaN(i)) { i = 0.00; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}
// end of function CurrencyFormatted()

function IsNumeric(sText) {
    var ValidChars = "0123456789.";
    var IsNumber = true;
    var Char;


    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function IsQuantity(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;

    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }

    //We don't allow negative quantity
    if (IsNumber && sText < 1)
        IsNumber = false;
    
    return IsNumber;
}

function ResizedImagePath(imageURL, width, height) {
    var s = Off2ShopImagesURL;
    return s + "Image.aspx?Height=" + height + "&Width=" + width + "&Path=" + imageURL;
}

var lightboxPreferences = {
    imageLoading: 'images/lightbox-ico-loading.gif',
    imageBtnClose: 'images/lightbox-btn-close.gif',
    imageBtnPrev: 'images/lightbox-prevlabel.gif',
    imageBtnNext: 'images/lightbox-nextlabel.gif',
    overlayOpacity: 0.9
};    

//Delegate for showing large image
function LightboxDelegate(path) { // pass in the correct path to the function so we only need one <a> for infinite amount of calls from  flash                
    $('a#lightbox').remove();
    // if the lightbox does not exist we will make it                 
    $("body").append('<a id="lightbox" style="visibility: hidden; position: absolute; left: -9999px;" href="' + path + '">&nbsp;</a>');
    $('a#lightbox').lightBox(lightboxPreferences);
    // now we will simulate the click here.
    $('a#lightbox').trigger("click");
}

//Image preloader
function Off2ShopPreloadImage(img, url, container, callback) {
    // create loader image
    var _loader = new Image();

    // begin loader
    $(_loader).load(function() {

        img.attr('src', url);

        // scaled tumbnails!
        var w = this.width;
        var h = this.height;
        var wDiff = Math.ceil(w / h * container.height());
        var hDiff = Math.ceil(h / w * container.width());
//        if (wDiff < hDiff) {
//            img.css({ height: 'auto', width: container.width(), marginTop: -(hDiff - container.height()) / 2 });
//        } else {
//            img.css({ width: 'auto', height: container.height(), marginLeft: -(wDiff - container.width()) / 2 });
//        }
        if (wDiff < hDiff) {
            img.css({ width: 'auto', height: container.height(), marginLeft: -(wDiff - container.width()) / 2 });
        } else {
            img.css({ height: 'auto', width: container.width(), marginTop: -(hDiff - container.height()) / 2 });
        }

        //container.prepend("w:" + this.width + " h:" + h + "cw:" + container.width() + "ch:" + container.height() + "wdiff:" + wDiff + "hdiff:" + hDiff);

        // call the itemCreatedCallback function
        if (callback != null)
            callback(img);

    }).error(function() {

        // Error handling
        container.html('<span class="error">Error loading image: ' + url + '</span>');

    }).attr('src', url);
}

function getCartProducts_Callback(data) {

    // This is generated:
    if (data == null) {
        $('#cartoverlay #cart-checkout').attr("disabled", "true");
        $('#overlay-cart-products-table tr:last').after(
                    '<tr><td align="right" colspan="3">The shopping cart is empty</td></tr>'
                    );
    }
    else {
        $('#cartoverlay #cart-checkout').attr("disabled", "");
        var totalValue = 0;
        $.each(data.Rows, function(i, val) {
            // This is generated:
            // <tr><td class="tLeft">Sumo</td><td class="tRight">1</td><td class="tRight">$199</td></tr>
            // <tr><td align="right" colspan="3"><input class="butsubmit_red" type="button" value="Remove" /></td></tr>
            $('#overlay-cart-products-table tr:last').after(
                        '<tr><td class="tLeft">' + val.Title + '</td><td class="tRight">' +
                        val.Quantity +
                        '</td><td class="tRight">$' +
                        CurrencyFormatted(val.Price) +
                        '</td></tr>'
            //'<tr><td align="right" colspan="3">' +
            //'<input class="butsubmit_red" type="button" value="Remove" /></td></tr>'
                        );
            totalValue = totalValue + (CurrencyFormatted(val.Price) * val.Quantity);
        });
        $('#overlay-cart-products-table tr:last').after(
            '<tr>' +
            '<th colspan="2">Cart Sub-Total:</th>' +
            '<td align="right" style="border:0px;">$' + CurrencyFormatted(totalValue) + '</td>' +
            '</tr>'
        );
    }

    $("#saveStatus").hide();
}

//Load the overlaid cart
function loadOverlayCart(element) {
    //Check if the overlay is already displayed
    if ($("#cartoverlay").length > 0)
        return;

    //Generate the overlay
    //    <div id="cartoverlay">
    //        <div class="rel">
    //            <a href="javascript:void();" class="cart-close-button">Close
    //                <img align="absmiddle" src="images/close16.png" /></a>
    //            <div>
    //                <img id="cart-loading" src="images/loading.gif" style="display: none;" />
    //                <span class="bluetitle">&nbsp;Your Items</span>
    //                <br />
    //                <br />
    //                <table cellpadding="0" cellspacing="0" id="overlay-cart-products-table">
    //                    <tr>
    //                        <th class="tLeft">
    //                            Product
    //                        </th>
    //                        <th class="tRight">
    //                            Qty
    //                        </th>
    //                        <th class="tRight">
    //                            Price
    //                        </th>
    //                    </tr>
    //                </table>
    //                <br />
    //                <input class="butsubmit_red" id="cart-checkout" type="button" value="Checkout" />
    //            </div>
    //        </div>
    //    </div>
    $("body").prepend(
            '<div id="cartoverlay">' +
                '<div class="rel">' +
                    '<a href="javascript:void();" class="cart-close-button">Close' +
                        '<img align="absmiddle" src="/images/close16.png" /></a>' +
                    '<div>' +
                        '<img id="cart-loading" src="/images/loading.gif" style="display: none;" />' +
                        '<span class="bluetitle">&nbsp;Your Items</span>' +
                        '<br />' +
                        '<br />' +
                        '<table cellpadding="0" cellspacing="0" id="overlay-cart-products-table">' +
                            '<tr>' +
                                '<th class="tLeft">' +
                                    'Product' +
                                '</th>' +
                                '<th class="tRight">' +
                                    'Qty' +
                                '</th>' +
                                '<th class="tRight">' +
                                    'Price' +
                                '</th>' +
                            '</tr>' +
                        '</table>' +
                        '<br />' +
                        '<input class="butsubmit_red" id="cart-checkout" type="button" value="Checkout" />' +
                    '</div>' +
                '</div>' +
            '</div>'
            );

    //Show the overlay ... slowly
    var position = element.offset();
    position.top += 50;
    position.left -= 30;
    $("#cartoverlay").css(position);
    $("#cartoverlay").show("slow");

    //Bind the buttons
    $('#cartoverlay a.cart-close-button')
			    .click(
				    function() {
				        $("#cartoverlay").hide("slow", function() {
				            $(this).remove();
				        });
				    }
			    );

    $('#cartoverlay #cart-checkout')
			    .click(
				    function() {
				        document.location.href = "/cart.aspx"; 
				    }
			    );

    //Make ajax call to get the contents
    $.jsonp({
        url: Off2ShopMainURL + "methodName=getCartProducts",
        data: {
            "CartUniqueId": xread(),
            "max": 5
        },
        timeout: 5000,
        beforeSend: function() {
            $("#saveStatus").html("<div class='text'>Loading ...</div>").css({ top: $(window).scrollTop() + "px" }).show();
        },
        success: getCartProducts_Callback,
        error: function(xOptions, textStatus) {
            var msg = textStatus.slice(0, 1).toUpperCase() + textStatus.slice(1) + " accessing " + xOptions.url;
            $("#saveStatus").html("<div class='error'>" + msg + "</div>").show();
            setTimeout(function() {
                $('#saveStatus').fadeOut('fast', function() {
                    //$("#saveStatus").html("Loading ...");
                });
            }, 5000); // <-- time in milliseconds

        }
    });

}


//Load the current user
function getCurrentUser_Callback(data) {
    if (data.ID != 0) 
    {
        var myStr = data.Name;
       if (myStr.match(/^[^\s]+$/gi) == null)
       {
            if (myStr.length-1 != 0)
                {
                    $("#login").html('<div class="text"><span>Welcome, ' + data.Name + '</span><a href="Page.aspx">My account</a> | <a href="Page.aspx?op=edit">Profile</a> | <a href="Page.aspx?op=history">History</a> | <a href="Page.aspx?op=reffer">Refer a Friend</a> | <a href="Logout.aspx">Logout</a></div>');
                }
            else
                {
                    $("#login").html('<div class="text"><span>Welcome</span><a href="Page.aspx">My account</a> | <a href="Page.aspx?op=edit">Profile</a> | <a href="Page.aspx?op=history">History</a> | <a href="Page.aspx?op=reffer">Refer a Friend</a> | <a href="Logout.aspx">Logout</a></div>');
                }
        }
    }
    else {
        //              This is generated:
        //            	<img src="images/log_in_start_saving.jpg" alt="Log in and start saving!" title="Log in and start saving" id="log_in_start_saving" />
        //                <div id="login_fields">
        //                <form action="http://localhost:4000/MerchantPage/Emb/login.aspx" method="post">
        //                    Username:
        //                    <input type="text" maxlength="30" size="16" tabindex="1" name="login_username" />
        //                    Password:
        //                    <input type="password" maxlength="30" size="16" tabindex="2" name="login_password" />
        //                    <input type="submit" name="submit" value="Login" tabindex="3" class="butsubmit" />
        //                    <div>
        //                        New to LW ? <a href="Signup.aspx" title="">Register Here</a></div>
        //                </form>
        //                </div>
        //            	<img src="images/log_in_start_saving.jpg" alt="Log in and start saving!" title="Log in and start saving" id="log_in_start_saving" />
        $("#login").html(
                '<div id="login_fields">' +
                '<form action="' + Off2ShopEmbCartURL + 'Emb/login.aspx" method="post">' +
                '    Email:' +
                '    <input type="text" maxlength="30" size="16" tabindex="1" name="login_username" />' +
                '    Password:' +
                '    <input type="password" maxlength="30" size="16" tabindex="2" name="login_password" />' +
                '    <input type="hidden" name="MerchantId" value="' + MerchantId + '" />' +
                '    <input type="submit" name="submit" value="Login" tabindex="3" class="butsubmit" />' +
                '    <div>' +
                '        New to LW ? <a href="/Signup.aspx" title="">Register Here</a></div>' +
                '</form>' +
                '</div>' +
                '<img src="/images/log_in_start_saving.jpg" alt="Log in and start saving!" title="Log in and start saving" id="log_in_start_saving" />'
                );
    }

    $("#saveStatus").hide();
}

$(document).ready(function() {
    //Is current user logged in ?
	
	// Replace the menu html
	<!--var menu = '<div style="font-size:10px"><a href="/index.html">Home</a> | <a href="/maps/FindStore.aspx">Store Finder</a> | <a href="/flyer.aspx">Weekly Ad</a> | <a href="/html/vip/vip.aspx">Be A V.I.P.</a> | <a href="/html/services/dealhunter.html">Deal Hunter</a> | <a href="/html/services/whatwedo.html">LW Services</a> | <a href="/html/community/index.html">LW In Your Community</a> | <a href="/html/stores/stores.html">Our Stores</a> | <a href="/html/story/story.html">Our Story</a> | <a href="/html/products/employment.html">Careers</a> | <a href="/html/investors/index.html">Investors</a> | <a href="/html/contact/contact.html">Contact</a> | <a href="/html/faq/faq.html">F.A.Q.</a> | <a href="/html/policy/privacy.html">Privacy Policy</a> | <a href="http://www.liquidationworld.com/html/employees/employees.aspx">Employees</a> | <a href="http://liquidationworld.com/html/products/beourlandlord.aspx">Be Our Landlord</a></div>';-->
	
	var menu = '<div style="font-size:10px"><a href="/index.html">Home</a> | <a href="/maps/FindStore.aspx">Store Finder</a> | <a href="/flyer.aspx">Weekly Ad</a> | <a href="/html/vip/vip.aspx">Be A V.I.P.</a> | <a href="/html/services/whatwedo.html">LW Services</a> | <a href="/html/story/story.html">Our Story</a> | <a href="/html/products/employment.html">Careers</a> |  <a href="/html/contact/contact.html">Contact</a> | <a href="/html/faq/faq.html">F.A.Q.</a> | <a href="/html/policy/privacy.html">Privacy Policy</a></div>';

	var menubottom = '<div style="font-size:10px"><a href="/index.html">Home</a> | <a href="/maps/FindStore.aspx">Store Finder</a> | <a href="/flyer.aspx">Weekly Ad</a> | <a href="/html/vip/vip.aspx">Be A V.I.P.</a> | <a href="/html/services/whatwedo.html">LW Services</a> |  <a href="/html/story/story.html">Our Story</a> | <a href="/html/products/employment.html">Careers</a> | <a href="/html/contact/contact.html">Contact</a> | <a href="/html/faq/faq.html">F.A.Q.</a> | <a href="/html/policy/privacy.html">Privacy Policy</a></div>';

	$(".menu").html(menu);
	
	
	// Set the left column contents on each page
	var leftColumn =  "<img src=\"/images/newspapers.gif\" border=\"0\" alt=\"LW Ad\" title=\"LW Ad\" /><div class=\"vipsignupbox\" style=\"margin-top:20px;\">\n<form action=\"/html/vip/vip.aspx\" method=\"post\">\n\t\t\t\t\t<div class=\"vipsignupbox_inner\">\n\t\t\t\t\t\t<br /><br /><br /><br /><div class=\"inputsright\">\n\t\t\t\t\t\t\t\t<input type=\"text\" maxlength=\"30\" size=\"24\" name=\"entered_email\" style=\"width: 178px;\" />\n\t\t\t\t\t\t\t\t<input type=\"submit\" name=\"register\" value=\"Register\" class=\"butsubmit\" />\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</form>\t\t\t\t</div>\n\n<div style=\"height:20px\"></div>\n\n\t\t\t<div class=\"findstorebox\">\n\t\t\t\t<form name=\"form1\" method=\"post\" action=\"/maps/FindStore.aspx\" id=\"form1\">\n\t\t\t\t\t<div class=\"findstorebox_inner\">\n\t\t\t\t\t<br /><br /><br /><br /><br /><br /><div class=\"inputsright\" style=\"margin-right: 15px;\">\n\t\t\t\t\t\t\n<input type=\"text\" maxlength=\"30\" size=\"24\" name=\"address\" style=\"width: 178px;\" />\n\t\t\t\t\t\t<input type=\"submit\" name=\"findstore\" value=\"Find a Store\" class=\"butsubmit_orange\" />\n\t\t\t\t\t</div>\n\t\t\t\t</form>\n\t\t\t\t</div>\n\t\t\t</div>\n\n";
			
	$("#left_column").html(leftColumn);
	$("td.right").html(leftColumn);
	
	var leftColumnInvestors = "\t\t<h1 style=\"background: transparent url('/images/sidenav_top.jpg') bottom left no-repeat;padding: 10px 0px 0px 10px;color:#ffffff;margin-bottom:0px;\">Investor Information</h1>\n\t\t<ul id=\"sidenav\">\n\t\t\t<li><a href=\"index.html\">Company Profile</a></li>\n\t\t\t<li><a href=\"StockPrice.aspx\">Stock Information</a></li>\n\t\t\t<li><a href=\"comp_adv.html\">Competitive Advantage</a></li>\n\t\t\t<li><a href=\"executives.html\">Company Executives</a></li>\n\t\t\t<li><a href=\"board.html\">Board of Directors</a></li>\n\t\t\t<li><a href=\"reports.html\">Financial Reports</a></li>\n\t\t\t<li><a href=\"news.html\">News Releases</a></li>\n\t\t</ul>\n\n";
	
	$("#left_column_inv").html(leftColumnInvestors);
	
    $.jsonp({
        url: Off2ShopMainURL + "methodName=getCurrentUser",
        data: { "MerchantId": MerchantId },
        timeout: 5000,
        beforeSend: function() {
            $("#saveStatus").html("<div class='text'>Loading ...</div>").css({ top: $(window).scrollTop() + "px" }).show();
        },
        success: getCurrentUser_Callback,
        error: function(xOptions, textStatus) {
            var msg = textStatus.slice(0, 1).toUpperCase() + textStatus.slice(1) + " accessing " + xOptions.url;
            $("#saveStatus").html("<div class='error'>" + msg + "</div>").show();
            setTimeout(function() {
                $('#saveStatus').fadeOut('fast', function() {
                    //$("#saveStatus").html("Loading ...");
                });
            }, 5000); // <-- time in milliseconds

        }
    });
});

