$(document).ready(function() {
    $(document).on('click','.addComboBusiness',function(){
        var combocount      =       $(this).attr('combocount');
        var comboBusIncr    =       $(this).attr('rel');
        addComboMerchants(combocount,comboBusIncr);
    });
    
     $(document).on('click','.deleteComboMerchant',function(){
        var comboBusIncr            =   $(this).attr('rel');
        var combinationcount        =   $(this).attr('combinationcount');
        deleteComboMerchant(comboBusIncr,combinationcount);
    });
});

//Selected Combo
function setComboProducts() {
    var droppedAttrs = "";
    $("#selectedSortedAttrIDs").val('');
    $('.comboselect').each(function () {
        if ($(this).prop('checked')) {
            droppedAttrs = droppedAttrs + $(this).attr("value") + "~*";
        }
    });
    $("#selectedAttrIDs").val(droppedAttrs);
}
$(document).ready(function () {
    if ($("#OptionCount").val() == 1) {
        $("#AddComboLink").show();
    }
    //Add Combo
    $(document).on('click','#submitCombo',function(event){
        setComboProducts();
        var productID = $("#productID").val();
        $('#combinationSKU,#combinationQty,#combinationPrice,#combinationWeight,#combinationLength,#combinationWidth,#combinationHeight,#combinationHeight').trigger('blur');
        var selectedAttrIDs = jQuery.trim($("#selectedAttrIDs").val());
        if (selectedAttrIDs == '') {
            $("#validateSelected").val('');
            $("#div_err_formComboAdd_validateSelected").removeClass("hide");
            $("#hid_err_formComboAdd_validateSelected").val(1);
        } else if (selectedAttrIDs != '') {
            $("#div_err_formComboAdd_validateSelected").addClass("hide");
            $("#hid_err_formComboAdd_validateSelected").val(0);
            $("#validateSelected").val('1');
        }
        ApplyComboRule();
        if (!$(this).validateForm({
            form: "formComboAdd"
        })) {
            setAjaxErrortab('inventory-save', '1');
            return false;
        }
        var validate = true;
        $(".required-entry-combo").each(function () { 
            if((!$(this).val()>0) || isNaN($(this).val()) || $.trim($(this).val())==''){
                validate = false;
                if (isNaN($(this).val()) || $.trim($(this).val())=='') {
                    $(this).siblings('.message_validation').html(errValidNumber).removeClass('hide');
                } else if ((!$(this).val() > 0)) {
                    $(this).siblings('.message_validation').html(errRequired).removeClass('hide');
                }
            } else {
                $(this).siblings('.message_validation').addClass('hide');
            }
        });
        $(".required-entry-text-combo").each(function(){
                if($.trim($(this).val())==""){
                        validate=false;
                        $(this).siblings('.message_validation').html(errRequired).removeClass('hide');
                }
                else{
                        $(this).siblings('.message_validation').html("").addClass('hide');
                }
        });
        var combination = [];
        $(".combination_group_price_user_group").each(function () {
            var productoptioncount = $(this).attr('productoptioncount');
            productoptioncount = _.isUndefined(productoptioncount) ? 0 : productoptioncount;
            var key = productoptioncount + "_" + $(this).val();
            if ($.in_array(key, combination)) {
                validate = false;
                var rel = $(this).attr('rel');
                $(".message_validation.grp_" + rel).removeClass('hide');
            } else {
                $(".message_validation.grp_" + rel).addClass('hide');
                combination.push(key);
            }
        });
        var combination = [];
        $(".combination_tier_price_user_group").each(function () {
            var rel = $(this).attr('rel');
            var productoptioncount = $(this).attr('productoptioncount');
            productoptioncount = _.isUndefined(productoptioncount) ? 0 : productoptioncount;
            var key = productoptioncount + "_" + $(this).val() + "_" + $(".combination_tier_price_qty." + rel).val();
            if ($.in_array(key, combination)) {
                validate = false;
                var rel = $(this).attr('rel');
                $(".message_validation.tier_" + rel).removeClass('hide');
            } else {
                $(".message_validation.tier_" + rel).addClass('hide');
                combination.push(key);
            }
        });
        if (!validate) {
            return false;
        }
        $.ajax({
            type: "POST",
            async: false,
            url: GLOBAL_BASE_PATH + "/product/ajaxAddCombination/",
            data: $("form#formComboAdd").serialize() + "&action=OP&productID=" + productID,
            success: function (data) {
                var x = jQuery.parseJSON(data);
                if (x.validationError == 'No') {
                    if (x.message == 3) {
                        jNotifyShow(msgComboExist, "common_error", "message_error");
                        setAjaxErrortab('inventory-save', '1');
                        event.preventDefault();
                    } else if (x.message == 4) {
                        jNotifyShow(msgComboSkuExist, "common_error", "message_error");
                        setAjaxErrortab('inventory-save', '1');
                        event.preventDefault();
                    } else {
                        $("#ajaxListBlock").html(x.html);
                        if (x.action = 'DB') {
                            if (x.message == 1) {
                                jNotifyShow(msgComboAdd, "common_message", "message_success");
                                $('#ajaxAddBlock').hide();
                                $("#formComboAdd").attr("changed", false);
                            } else if (x.message == 2) {
                                jNotifyShow(msgComboUpdate, "common_message", "message_success");
                                $('#ajaxAddBlock').hide();
                                $("#formComboAdd").attr("changed", false);
                            }
                            setAjaxErrortab('inventory-save', '0');
                        }
                        // Clear Combo
                        clearCombination();
                        $("#submitCombo").attr('value', 'Add Combination');
                    }
                }
            }
        });
    });
    //Edit Combo

});

$(document).on('click','.editCombo',function(){
    // $('html,body').animate({ scrollTop: $('#ajaxAddBlock').offset().top}, 600);
    $("#submitCombo").attr('value', lblCombo);
    var combinationID = $(this).attr('id');
    var productID = $("#productID").val();
    $.ajax({
        type: "POST",
        async: false,
        url: GLOBAL_BASE_PATH + "/product/ajaxAddCombination/",
        data: "combinationID=" + combinationID + "&productID=" + productID,
        success: function (data) {
            var x = jQuery.parseJSON(data);
            if (x.action == 'Show') {
                $("#ajaxAddBlock").html(x.html);
                $("#submitCombo").attr('value', lblCombo);
                if ($("#combothumbPreview").val() != 'Yes')
                    $("#combopreview_main").hide();
                else
                    $("#combopreview-main").show();
                $('#ajaxAddBlock').show();
                
                if($("#InventoryTrackLevel").val()=='No'){
                    $('.combbus-quantity').addClass('hide');
                    $('.comboBusQuant').removeClass('required-entry-combo');
                }else{
                    $('.combbus-quantity').removeClass('hide');
                    $('.comboBusQuant').addClass('required-entry-combo');
                }
                setAjaxErrortab('inventory-save', '0');
            }
        }
    });
});
//Delete Combo
$(document).on('click','.comboDelete',function(){
    var obj = $(this);
    var cId = obj.attr('id');
    jConfirm(msgConfirmDelete, 'Alert', function (r) {
        if (r == true) {
            var data = new Object();
            var ajaxUrl = "/product/AjaxDestroyCombo/";
            data.comboID = obj.attr('id');
            data.status = 'D';
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH + ajaxUrl,
                data: data,
                success: function (data) {
                    if (data) {
                        $("#row_" + cId).remove();
                        if (cId == $("#combinationID").val()) {
                            clearCombination();
                        }
                        if ($('[id^=row_]').length == 0) {
                            $("#combohead").hide();
                            $("#comboNorecords").show();
                        } else {
                            $("#combohead").show();
                            $("#comboNorecords").hide();
                        }
                        jNotifyShow(msgComboDeleted, "common_message", "message_success");
						setAjaxErrortab('inventory-save', '0');
                    }
                }
            });
        } else {
            return false;
        }
    }, okText, cancelText);
});
$(document).on('click','.comboStatus',function(){
    var obj = $(this);
    var data = new Object();
    var ajaxUrl = "/product/AjaxDestroyCombo/";
    data.comboID = obj.attr('id');
    data.productRequestID = $("#productRequestID").val();
    if ($(this).hasClass('status-active')) {
        data.status = 'I';
        data.newClass = 'status-inactive hide-txt icon-set comboStatus';
    } else if ($(this).hasClass('status-inactive')) {
        data.status = 'A';
        data.newClass = 'status-active hide-txt icon-set comboStatus';
    }
    $.ajax({
        type: "POST",
        url: GLOBAL_BASE_PATH + ajaxUrl,
        data: data,
        success: function (msg) {
            setActiveTabSaveButton();
            jNotifyShow(OptionStatusChange, "common_message", "message_success");
            obj.attr('class', data.newClass);
        }
    });
});
//Cancel Combo
$(document).on('click','#ComboCancel',function(){
    clearCombination();
    $("#ajaxAddBlock").hide();
});

function clearCombination() {
    $(':input', '#formComboAdd').not(':button, :submit,#productOptionID,.comboselect,[name="status"]').val('').removeAttr('checked').removeAttr('selected');
    $("#imageFilecombo_image").attr('src', $("#no_image_path").val());
     $("#imageFilecombo_thumbImage").attr('src', $("#no_image_path").val());
    $(":input[type='radio'][value='A'][name='status']").prop('checked', 'checked');
}

function ApplyComboRule() {
    var ruleIDs = new Array();
    if (ruleApplyJs != '')
        var ruleIDs = $.trim(ruleApplyJs).split(',');
    $.each(ruleIDs, function (key, val) {
        if ($("input:radio[name='variantselect_" + val + "[]'].comboselect:checked").length > 0) {
            $("#validateOptionRule" + val).val('1');
            $("#div_err_formComboAdd_validateOptionRule" + val).addClass("hide");
            $("#hid_err_formComboAdd_validateOptionRule" + val).val(0);
        } else {
            $("#validateOptionRule" + val).val('');
            $("#div_err_formComboAdd_validateOptionRule" + val).removeClass("hide");
            $("#hid_err_formComboAdd_validateOptionRule" + val).val(1);
        }
    });
}
$(document).on('click','#comboPreview_hide',function(){
    $('#combopreview_main').toggle();
    return false; // should return false to prevent page loading
});

function addComboMerchants(combocount,comboBusIncr){
    var productID           =       $("#productID").val();
    //var currComboCount      =       parseInt(combocount)+1;
    var currComboBusIncr    =       parseInt(comboBusIncr)+1;
       $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH+"/product/ajaxAddComboMerchant/",
            data: "combocount="+combocount+"&comboBusIncr="+currComboBusIncr+"&productID="+productID,
            success: function(msg){
                if(msg){
                    $("#combinationBusinessSec").append(msg);
                    $("#hiddenComboBusCount").val(currComboBusIncr);
                    $(".addComboBusiness").attr("combocount",combocount);
                    $(".addComboBusiness").attr("rel",currComboBusIncr);
                    var InvLevel    =  $('#InventoryTrackLevel').val();
                    if(InvLevel=="No"){
                        $('.combbus-quantity').addClass('hide');
                        $('.comboBusQuant').removeClass('required-entry-combo');
                    }else{
                        $('.combbus-quantity').removeClass('hide');
                        $('.comboBusQuant').addClass('required-entry-combo');
                    }
                }
            }
        });
}

function deleteComboMerchant(comboBusIncr,combinationcount){
    jConfirm(msgDeleteItem, 'Alert', function (r) {
        if (r == true) {
            $('#newComboMerchant_'+combinationcount+'_'+comboBusIncr).remove();
        }
    });
}