﻿var productID_current = 0;
var productUrl_current = "";
var status = 0;
var showPersonalize = 0;
var showPersonalizeMax = 0;

$().ready(function() {
    //LoadMiniCart();
    InitSubmenu();
});

function InitSubmenu() {
    var carturl = MiniCartPath;
    $.ajax({
        type: "POST",
        url: carturl + '/GetCategoryMenu',
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            //alert(result.d);
            //location.href = cartPath;
            var myObject = eval('(' + result.d + ')');
            var count = myObject[0].Count;
            var data = myObject[1].Data;
            if (count > 0) {
                $('#sub_nav').html(data);
            }
            else {
                $('#sub_nav').html("");
            }
        },
        error: function(result) {

            return false;
        }
    });
    //$('#sub_nav').show();
}

function DisplaySubmenu() {
       $('#sub_nav').show();
}

function HideSubmenu() {
    //$('#sub_nav').html("");
    $('#sub_nav').hide();
}


function SetImage(objImg, path) {
    objImg.src = baseUrl + '/App_Themes/default/' + path;
}
//tooltip begin
        var IE = document.all?true:false 
 
        // If NS -- that is, !IE -- then set up for mouse capture 
        if (!IE) document.captureEvents(Event.MOUSEMOVE) 
 
        // Set-up to use getMouseXY function onMouseMove 
        document.onmousemove = getMouseXY; 
 
        // Temporary variables to hold mouse x-y pos.s 
        var tempX = 0 
        var tempY = 0 
 
    // Main function to retrieve mouse x-y pos.s 
 
    function getMouseXY(e) { 
      if (IE) { // grab the x-y pos.s if browser is IE 
        tempX = event.clientX + document.body.scrollLeft 
        tempY = event.clientY + document.body.scrollTop 
      } else {  // grab the x-y pos.s if browser is NS 
        tempX = e.pageX 
        tempY = e.pageY 
      }   
      // catch possible negative values in NS4 
      if (tempX < 0){tempX = 0} 
      if (tempY < 0){tempY = 0}   
    
      return true 
    } 
    function showTip(objImg, path,text,td) 
    { 
        tooltip.style.display="block"; 
        window.status=tempX; 
        tooltip.innerHTML=text; 
        tooltip.style.left=tempX; 
        tooltip.style.top=tempY; 
        SetImage(objImg, path)
    } 
    function hideTip(objImg, path) 
    { 
    tooltip.style.display="none"; 
    SetImage(objImg, path)
    } 
//tooltip end
//callback function to bring a hidden box back
function callback() {
    setTimeout(function() {
    $("#msg_1:visible").removeAttr('style').hide().fadeOut();
    $("#dialogEmail").dialog('close');
    }, 2000);
};

function checkMinLength(o, n, min, ctl) {
    if (o.val().length < min) {
        o.addClass('ui-state-error');
        updateTipsC("Field " + n + " is required!", ctl);
        return false;
    } else {
        return true;
    }

}

function checkLength(o, n, min, max) {
    if (o.val().length > max || o.val().length < min) {
        o.addClass('ui-state-error');
        updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
        return false;
    } else {
        return true;
    }

}
function updateTipsC(t, ctl) {
    ctl.text(t);
}
function checkRegularExpression(o, regexp, n, ctl) {
    if (!(regexp.test(o.val()))) {
        o.addClass('ui-state-error');
        updateTipsC(n,ctl);
        return false;
    } else {
        return true;
    }
}

function checkRegexp(o, regexp, n) {
    if (!(regexp.test(o.val()))) {
        o.removeClass('quantity');
        o.addClass('ui-state-error');
        updateTips(n);
        return false;
    } else {
        return true;
    }
}

function InitCart() {}
function LoadMiniCart() {
    var carturl = MiniCartPath;
    $.ajax({
        type: "POST",
        url: carturl + '/GetCart',
        data: "{'usrname':'" + username + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: AjaxSucceeded,
        error: AjaxFailed
    });
}

function AjaxSucceeded(result) {
    //alert(result.d);
    var myObject = eval('(' + result.d + ')');
    var count = myObject[0].Count;
    var data = myObject[1].Data;
    var templatePath = baseUrl + '/jTemplates/MiniCart.htm';
    var hlCart = count;
    $('#cart_wrap').html(hlCart);
    $('#my_cage').html(hlCart);
    if (count == 0) {
        data = "Currently, your shopping cart is empty.";
        $('#MiniCart').html(data);
    }
    else {
        //alert(data[0].ID);
        $('#MiniCart').setTemplateURL(templatePath, [], { filter_data: false });
        $('#MiniCart').processTemplate(data);
    }
}
function AjaxFailed(result) {
    alert(result.status + ' ' + result.statusText);
}

function quickLook(productID, pageName) {
    productID_current = productID;
    productUrl_current = pageName;
    var serviceUrl = QuickLookPath;
    $.ajax({
        type: "POST",
        url: serviceUrl + '/GetProduct',
        data: "{'usrname':'" + username + "', 'ProductID':'" + productID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: AjaxProductSucceeded,
        error: AjaxProductFailed
    });
}
function AjaxProductSucceeded(msg) {
    var content = msg.d;
    //alert(msg.d);
    $('#quicklook').html(content);
    quantity = $('#quantity');
    tips = $('#validateTips');
    allFields = $([]).add(quantity).add(tips);
    //var buttons = $("#dialogEmail").dialog('option', 'buttons');
    //alert(buttons);
    //var firstButton = $('#dialogEmail button:first');
    //firstButton.addClass('ui-state-disabled');
    //$(":button:contains('Add to Cart')").attr("disabled", "disabled");
    status = $('#status').attr('value');
    $(":button:contains('Add to Cart')").attr("disabled", false);
    $(":button:contains('Add to Cart')").show();
    if ((status == 1) || (status == -1)) {
        //$(":button:contains('Add to Cart')").attr("disabled", true);
    }
    if (status == 2) {
        $(":button:contains('Add to Cart')").hide();
    }
    $('#noteD').keyup(function() {
        var max = parseInt($(this).attr('maxlength'));
        if ($(this).val().length > max) {
            $(this).val($(this).val().substr(0, $(this).attr('maxlength')));
        }
        //$(this).parent().find('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
    });
    $("#dialogEmail").dialog('open');
}
function AjaxProductFailed(result) {
    alert(result.status + ' ' + result.statusText);
}


function InitDialog() {
    $("#dialogEmail").dialog({
        bgiframe: true,
        height: 500,
        width: 720,
        modal: false,
        autoOpen: false,
        buttons:
		            {
		                "Add to Cart": function() {
		                    var bValid = true;
		                    allFields.removeClass('ui-state-error');
		                    updateTipsC("", tips);
		                    bValid = bValid && checkRegularExpression(quantity, /^[-+]?[1-9]\d*.?[0]*.?$/i, "Invalid quantity!", tips);
		                    if (bValid) {
		                    
		                        AddItemToCart();
		                        
		                    }

		                },
		                "ViewDetails": function() {
		                $(this).dialog('close');
		                location.href = baseUrl + '/product/' + productUrl_current + '.aspx';
		                },
		                Cancel: function() {
		                    $(this).dialog('close');
		                }
		            },
        close: function() { allFields.val('').removeClass('ui-state-error'); }
    });
}

function AddItemToCart() {
    //alert(productID_current);
    var defaultValue = '';
    var price = 0;
    var priceClub = 0;
    var weight = 0;
    var shipping = 0;
    var handling = 0;
    var qt = 0;
    var optionGroupsCount = 0;
    var options = '';
    var required = 0;
    var note = '';
    var imageID = "0";
    optionGroupsCount = $('#1optionsQuantity').attr('value');
    if (optionGroupsCount > 0) {
        for (i = 0; i < optionGroupsCount; i++) {
            var ctl = '1idOption' + i;
            $("#" + ctl).removeClass('ui-state-error');
            var req = $("#" + ctl).attr('required');
            var option = $("#" + ctl + " option:selected").attr('value');
            if (req == 'True' && option == '') {
                required += 1;
                $("#" + ctl).addClass('ui-state-error');
            }
            options += option + ',';
        }
    }
    price = $('#price').attr('value');
    priceClub = $('#priceClub').attr('value');
    weight = $('#weight').attr('value');
    shipping = $('#shipping').attr('value');
    handling = $('#handling').attr('value');
    qt = $('#quantity').attr('value');
    note = $('#noteD').attr('value');
    imageID = $('#imageID').attr('value');
    note = note.replace("'", "&#39;");
    
    if (status == 0 || status == 1) {
        //SendToServer(defaultValue, price, qt, optionGroupsCount, options, weight);
        if (required == 0) {
            var serviceUrl = QuickLookPath;
            $.ajax({
                type: "POST",
                url: serviceUrl + '/AddToCart',
                data: "{'usrname':'" + username + "', 'productID':'" + productID_current + "', 'price':'" + price + "', 'priceClub':'" + priceClub + "', 'quantity':'" + qt + "', 'groups':'" + optionGroupsCount + "', 'options':'" + options + "', 'weight':'" + weight + "', 'shipping':'" + shipping + "', 'handling':'" + handling + "', 'note':'" + note + "', 'imageID':'" + imageID + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result) {
                    location.href = cartPath;
                    $('#msg_2').html(result.d);
                    LoadMiniCart();
                    var options = {};
                    var selectedEffect = 'blind';
                    $("#msg_1").show(selectedEffect, options, 500, callback);
                },
                error: function(result) {
                    $('#msg_2').html(result.status + ' ' + result.statusText);
                    var options = {};
                    var selectedEffect = 'blind';
                    $("#msg_1").show(selectedEffect, options, 500, callback);
                    return false;
                }
            });
        }
    }
    else {
        $('#msg_2').html("Product cannot be added to cart!");
        var options = {};
        var selectedEffect = 'blind';
        $("#msg_1").show(selectedEffect, options, 500, callback);
    }
    return false;
}

function SendToServer(defaultValue, price, qt, groups, options, weight) {
    //$('#loading').show();
   
    var serviceUrl = QuickLookPath;
    $.ajax({
    type: "POST",
        url: serviceUrl + '/AddToCart',
        data: "{'usrname':'" + username + "', 'productID':'" + productID_current + "', 'priceOption':'" + defaultValue + "', 'price':'" + price + "', 'quantity':'" + qt + "', 'groups':'" + groups + "', 'options':'" + options + "', 'weight':'" + weight + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: AjaxAddSucceeded,
        error: AjaxAddFailed
    });
}
function AjaxAddSucceeded(msg) {
    //alert(msg);
    $('#msg_2').html(msg.d);
    //$("#dialogEmail").dialog('close');
    LoadMiniCart();
    var options = {};
    var selectedEffect = 'blind';
    $("#msg_1").show(selectedEffect, options, 500, callback);
    //$('#loading').hide();
    //$("#load").html(msg);
}
function AjaxAddFailed(result) {
    //alert(result.status + ' ' + result.statusText);
    $('#msg_2').html(result.status + ' ' + result.statusText);
    var options = {};
    var selectedEffect = 'blind';
    $("#msg_1").show(selectedEffect, options, 500, callback);
}





function formatCurrency(val) {
    var num = 0;
    num = val;
    //num = num.replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    var str = '$' + num + '.' + cents;
    if (cents == "00") str = '$' + num;
    return str;
}

function ReplaceQImage() {
    var imageID = $('#imageID').attr('value');
    var imageType = 'M';
    var serviceUrl = FullCartPath;
    $.ajax({
        type: "POST",
        url: serviceUrl + '/GetImage',
        data: "{'imageID':'" + imageID + "', 'imageType':'" + imageType + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            //alert(result.d);
            var myObject = eval('(' + result.d + ')');
            var link = myObject[0].link;
            var img = myObject[0].img;
            $('#qImage1').attr('src', img);
        },
        error: function(result) {
            //alert(result.status + ' ' + result.statusText);
            return false;
        }
    });
}

function OptionQChange(selectObj, idGroup, productID) {
    var colorGroupID = 1;
    if (idGroup == colorGroupID) {
        var ctlID = selectObj.id;
        var idx = selectObj.selectedIndex;
        if (idx > 0) {
            var val = selectObj.options[idx].value;
            $('#imageID').attr('value', productID + '_' + val);
        }
        else {
            $('#imageID').attr('value', productID);
        }
        ReplaceQImage();
    }
    var price = 0;
    price = Number($('#price').attr('value'));
    optionGroupsCount = $('#1optionsQuantity').attr('value');
    if (optionGroupsCount > 0) {
        for (i = 0; i < optionGroupsCount; i++) {
            var ctl = '1idOption' + i;
            var option = $("#" + ctl + " option:selected").attr('text');
            var start = option.indexOf("(");
            if (start > -1) {
                var end = option.indexOf(")");
                var optionPrice = Number(option.substring(start + 3, end));
                price += optionPrice;
            }
        }
    }
    $('#detailPrice').html(formatCurrency(price));
}

