$(document).ready(function() {
    groupPriceAdded = "No";
    checkBuybox();
    $(document).on('click','#enableBuybox',function(){
        checkBuybox();
    });
    
    $('.optionBusiness').each(function(){
        var selBusinessID   =   $(this).val();
        if(selBusinessID>0){
            var selectedIDVal   =   $(this).attr('id');
            var expSring        =   selectedIDVal.split('_');
            var productOptCount =   expSring[1];
            var sellerIncr      =   expSring[2]; 
            getWareHouse(selBusinessID,sellerIncr,productOptCount);
            }            
    })
            
    $(document).on('change','.optionBusiness',function(){
        var selBusinessID   =   $(this).val();
        var selectedIDVal   =   $(this).attr('id');
        var expSring        =   selectedIDVal.split('_');
        var productOptCount =   expSring[1];
        var sellerIncr      =   expSring[2];
        getWareHouse(selBusinessID,sellerIncr,productOptCount);
    });
            
    $(document).on('click','.addMerchant',function(){
        addMerchants($(this).attr("rel"));
    });
    
    $(document).on('click','.businessDefOption',function(){
        var thisID      =       $(this).attr('id');
        var splitIDVal  =       thisID.split('_');
        var productOptCount =   splitIDVal[1];
        var sellerCount     =   splitIDVal[2];
        setDefOption($(this),productOptCount,sellerCount);
    });
    
//    $(document).on('click','.editMerchant',function(){
//        var sellerIncr              =   $(this).attr('rel');
//        var productoptioncount      =   $(this).attr('productoptioncount');
//        editMerchant(sellerIncr,productoptioncount);
//    });
    
    if($('.editMerchant').length>0){
        $(".editMerchant").colorbox({iframe:true, innerWidth:"60%", innerHeight:400, arrowkey:false, loop:false
        });
        }
    
    $(document).on('click','.deleteMerchant',function(){
        var sellerIncr              =   $(this).attr('rel');
        var productoptioncount      =   $(this).attr('productoptioncount');
        deleteMerchant(sellerIncr,productoptioncount);
    });

    $(document).on('click','.deleteMerchantRow',function(){
        var sellerIncr              =   $(this).attr('rel');
        var productoptioncount      =   $(this).attr('productoptioncount');
        var productOptionBusinessID =   $(this).attr('optionbusinessid');
        var productOptionID         =   $(this).attr('productoptionid');
        deleteMerchantRow(sellerIncr,productoptioncount,productOptionBusinessID,productOptionID);
    });
    
    $(document).on('click','.busAddGroupPrice',function(){
        var sellerIncr         =   $(this).attr('rel');
        var productOptionCount =   $(this).attr('productoptioncount');
        addGroupPrice(sellerIncr,productOptionCount);
    });
    
    $(document).on('click','.deleteGroupPrice',function(){
        var sellerIncr      =   $(this).attr('sellerIncr');
        var groupIncr       =   $(this).attr('groupIncr');
        var productOptionCount =   $(this).attr('productoptioncount');
        deleteGroupPrice(sellerIncr,groupIncr,productOptionCount);
    });
    
    $(document).on('submit','#formSellerEditSubmit',function(){
        var currProdOptCount = $('#currProdOptCount').val();
        var currSellerIncr   = $('#currSellerIncr').val();
        var validate = sellerSubmit(currProdOptCount,currSellerIncr);
        if(!validate){
                return false;
        }else{
                return true;
        }
    });
    
    
});

function checkBuybox(){
    if($('#enableBuybox').prop('checked')==true){
        //$('.newMerchant').removeClass('hide');
        $('.addMerchant').removeClass('hide');
        $('.not-for-buybox').addClass('hide');
        $('.yes-for-buybox').removeClass('hide');
        $('#enableBoyBoxSel').val("Yes");
     }else{
         if($('.newMerchant').length>1){
            $('.newMerchant').each(function(){
                if($(this).attr('rel')>0){
                    $(this).addClass('hide');
    }
            });
         }
         $('.addMerchant').addClass('hide');
         $('.not-for-buybox').removeClass('hide');
         $('.yes-for-buybox').addClass('hide');
         $('#enableBoyBoxSel').val("No");
     }
}

function getWareHouse(selBusinessID,sellerIncr,productOptionCount){
        $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH+"/product/ajaxBusinessLocations/",
            data: "businessID="+selBusinessID+"&sellerIncr="+sellerIncr+"&productOptionCount="+productOptionCount,
            success: function(msg){
                if(msg){
                    $("#busWareHouse_"+productOptionCount+"_"+sellerIncr).html(msg);
                    var hiddenWareHouse  =  $('#hiddenWareHouse_'+productOptionCount+'_'+sellerIncr).val();
                    if(hiddenWareHouse>0){
                        $('#productOptionsGroup_'+productOptionCount+'_businessOptionsGroup_'+sellerIncr+'_businessWareHouse').val(hiddenWareHouse);
            }
                }
            }
        });
    }
    
function addMerchants(productOptionCount){
    var currSellerCount      = $('#sellerIncrCount_'+productOptionCount).val();
    var sellerIncrCount      = parseInt(currSellerCount)+1;
    var productID            = $("#hiddenProductID").val();
    var invLevel             = $("#InventoryTrackLevel").val();
    var setAsProductDeal     = $("#setAsProductDeal:checked").val();
    if(setAsProductDeal=="undefined"){
        setAsProductDeal     = "";
    }
       $.ajax({
            type: "POST",
            url: GLOBAL_BASE_PATH+"/product/ajaxAddMerchant/",
            data: "sellerIncrCount="+sellerIncrCount+"&productOptionCount="+productOptionCount+"&pdid="+productID+"&invLevel="+invLevel+"&setAsProductDeal="+setAsProductDeal,
            success: function(msg){
                if(msg){
                    $("#businessOptionsID_"+productOptionCount).append(msg);
                    $('#sellerIncrCount_'+productOptionCount).val(sellerIncrCount);
                    $('#newMerchant_'+productOptionCount+'_'+sellerIncrCount).removeClass('hide');
                }
            }
        });
}

function setDefOption(thisVal,productOptCount,sellerCount){
    $('#businessOptionsID_'+productOptCount+' .businessDefOption').prop('checked',false);
    thisVal.attr('checked',true);
    $('#businessOptionsID_'+productOptCount+' .businessOptStatus').prop('disabled',false);
    $("#businessOptStatus_"+productOptCount+"_"+sellerCount+ "[value='Active']").prop("checked",true);
    $("#businessOptStatus_"+productOptCount+"_"+sellerCount+ "[value='Inactive']").prop("disabled",true);
//    if($('#businessOptionsGroup_'+sellerIncr+'_busProductStatus:checked').val()=="Active"){
//        $('#businessOptionsGroup_'+sellerIncr+'_businessOptionDefault').attr('disabled',false);
//        $('#businessOptionsGroup_'+sellerIncr+'_businessOptionDefault').prop('checked',true);
//    }else{
//        $('#businessOptionsGroup_'+sellerIncr+'_businessOptionDefault').prop('checked',false);
//        $('#businessOptionsGroup_'+sellerIncr+'_businessOptionDefault').attr('disabled',true);
//    }
}

//function editMerchant(sellerIncr,productoptioncount){
//    $('.newMerchant').addClass('hide');
//    $('#newMerchant_'+productoptioncount+'_'+sellerIncr).removeClass('hide');
//}

function deleteMerchant(sellerIncr,productoptioncount){
    jConfirm(msgDeleteItem, 'Alert', function (r) {
        if (r == true) {
            $('#newMerchant_'+productoptioncount+'_'+sellerIncr).remove();
        }
    });
}

function deleteMerchantRow(sellerIncr,productoptioncount,productOptionBusinessID,productOptionID){
    jConfirm(msgDeleteItem, 'Alert', function (r) {
        if (r == true) {
            $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH+"/product/ajaxdeleteMerchant/",
                data: "productOptionBusinessID="+productOptionBusinessID+"&productOptionID="+productOptionID,
                success: function(msg){
                    if(msg=='1'){
                        $('#newMerchantrow_'+productoptioncount+'_'+sellerIncr).remove();
                        $('#newMerchant_'+productoptioncount+'_'+sellerIncr).remove();
                    }
                }
            });
        }
    });
}

function addGroupPrice(sellerIncr,productOptionCount){
    if(groupPriceAdded=="No"){
        groupPriceAdded     =   "Yes";
        var currGroupCount  = $('#groupIncrCount_'+productOptionCount+'_'+sellerIncr).val();
        var groupIncrCount  = parseInt(currGroupCount)+1;
           $.ajax({
                type: "POST",
                url: GLOBAL_BASE_PATH+"/product/ajaxAddGroupPrice/",
                data: "groupIncr="+groupIncrCount+"&sellerIncr="+sellerIncr+"&productOptionCount="+productOptionCount,
                success: function(msg){
                    if(msg){
                        $("#business_group_price_container_"+productOptionCount+'_'+sellerIncr).append(msg);
                        $('#groupIncrCount_'+productOptionCount+'_'+sellerIncr).val(groupIncrCount);
                        customerGroupFilter(sellerIncr,productOptionCount);
                        groupPriceAdded     =   "No";
                    }
                }
            });
    }
}

function deleteGroupPrice(sellerIncr,groupIncr,productOptionCount){
    jConfirm(msgDeleteItem, 'Alert', function (r) {
        if (r == true) {
            $('#groupContainer_'+productOptionCount+'_'+sellerIncr+'_'+groupIncr).remove();
            checkGroupAvail(sellerIncr,groupIncr,productOptionCount);
        }
    });
}

//function validateGroupPrice(sellerIncr){
//    var groupArr        =   new Array();
//    var duplicateVal    =   0;
//    $('.groupContainerClass select.option_group_price_user_group,input[type=text].option_group_price_sp_price').each(function(){
//        if($.inArray($(this).val(), groupArr )){
//            duplicateVal = duplicateVal+1;
//        }else{
//            groupArr.push($(this).val());
//        }
//    });
//    
//}
    
function customerGroupFilter(sellerIncr,productOptionCount){
    var groupIncr   =   $('#groupIncrCount_'+productOptionCount+'_'+sellerIncr).val();

//    var groupSelCount  =  $('#business_group_price_container_'+sellerIncr+' select.option_group_price_user_group').length; 
//    if(groupSelCount>0){
//        $.each($("#business_group_price_container_"+sellerIncr+" [fieldname='userGroupID']").not('#businessOptionsGroup_'+sellerIncr+'_group_price_'+groupIncr+'_userGroupID'), function( index, value ) {
//            $("#businessOptionsGroup_"+sellerIncr+"_group_price_"+groupIncr+"_userGroupID option[value='" + $(this).val() + "']").remove();
//        });	
//    }
//    
//    var currValue   =   $('#businessOptionsGroup_'+sellerIncr+'_group_price_'+groupIncr+'_userGroupID').val();
//    $("#business_group_price_container_"+sellerIncr+" [fieldname='userGroupID']").not("#businessOptionsGroup_"+sellerIncr+"_group_price_"+groupIncr+"_userGroupID").find("option[value='"+currValue+"']").remove();
    
    checkGroupAvail(sellerIncr,groupIncr,productOptionCount);
	
}

function checkGroupAvail(sellerIncr,groupIncr,productOptionCount){
    if($("#productOptionsGroup_"+productOptionCount+"_businessOptionsGroup_"+sellerIncr+"_group_price_"+groupIncr+"_userGroupID > option").length==1){
        $('#grpPrice_'+productOptionCount+'_'+sellerIncr+'_'+groupIncr).addClass("hide");
                }else{
        $('#grpPrice_'+productOptionCount+'_'+sellerIncr+'_'+groupIncr).removeClass("hide");
                }
}

function groupPriceCheck(section){
    if(section=='edit'){
        var merchantSec = "#editMerchantSec";
                }else{
        var merchantSec = "ul.businessOptionsID";
                }
    var groupPriceValidate  =    0;
    $(merchantSec+' li.newMerchant').each(function(){
        var sellerIncr          =    $(this).attr('rel');
        var productoptioncount  =    $(this).attr('productoptioncount');
        $(this).find('.option_group_price_sp_price').each(function(){
            var groupPriceID    =    $(this).attr('id');
            var priceIDSplit    =    groupPriceID.split('_');
            var groupIncr       =    priceIDSplit[3];
            var selValue        =    $(this).val();
            if(selValue<=0 || selValue==""){
                groupPriceValidate = groupPriceValidate+1;
                $('#validate_group_price_'+productoptioncount+'_'+sellerIncr+'_'+groupIncr).removeClass('hide').html(errRequired);
            }else{
                $('#validate_group_price_'+productoptioncount+'_'+sellerIncr+'_'+groupIncr).addClass('hide').html("");
                
                var validPrice  =  /^\d{0,4}(\.\d{0,2})?$/.test(selValue);
                if(validPrice==false){
                    groupPriceValidate = groupPriceValidate+1;
                    $('#validate_group_price_'+productoptioncount+'_'+sellerIncr+'_'+groupIncr).removeClass('hide').html(errValidNumber);
                }else{
                    $('#validate_group_price_'+productoptioncount+'_'+sellerIncr+'_'+groupIncr).addClass('hide').html("");
            }
        }
    });

        var duplicationEle = [];
        $(this).find('.option_group_price_user_group').each(function(){
            var thisValue = $(this).val();
            if($.in_array(thisValue,duplicationEle)){
                groupPriceValidate = groupPriceValidate+1;
            }else{
                duplicationEle.push(thisValue);
            }
});

        if(groupPriceValidate>0){
            $('#validate_usergroup_'+productoptioncount+'_'+sellerIncr).removeClass('hide').html(errDuplicateCombination);
        }else{
            $('#validate_usergroup_'+productoptioncount+'_'+sellerIncr).addClass('hide').html("");
                }
        
    });
    return groupPriceValidate;
                }

function sellerSubmit(prodOptCount,sellIncr){
    var validate=true;
    
    var checkGroupPrice = groupPriceCheck('edit');
    if(checkGroupPrice>0){
        validate = false;
            }
    
    $("#editMerchantSec .required-entry").each(function(){
            if((!$(this).val()>0) || isNaN($(this).val()) || $.trim($(this).val())==''){
                validate=false;
                if($.trim($(this).val())=='' || isNaN($.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');
            }
});

        var duplicateValidate = 0;
        var enableBoyBoxSel   = parent.$('#enableBoyBoxSel').val();

        if(enableBoyBoxSel=="Yes"){
            var duplicationEle = [];
            parent.$('ul#businessOptionsID_'+prodOptCount+' .newMerchant .optionBusiness').each(function(){
                var thisValue = $(this).val();
                var thisIDVal = $(this).attr('id');
                var splitStr  = thisIDVal.split('_');
                var productoptioncount = splitStr[1];
                var sellerIncr         = splitStr[2];
                
                if(productoptioncount!=prodOptCount || sellerIncr!=sellIncr){
                    duplicationEle.push(thisValue);
        }
    });
            
            var selValue  = $('#business_'+prodOptCount+'_'+sellIncr).val();
            if($.in_array(selValue,duplicationEle)){
                duplicateValidate = duplicateValidate+1;
}
        }
    
        if(duplicateValidate>0){
            $('#validate_business_value_'+prodOptCount+'_'+sellIncr).removeClass('hide').html(errDuplicateMerchant);
            validate=false;
        }else{
            $('#validate_business_value_'+prodOptCount+'_'+sellIncr).addClass('hide').html("");
           }

        $("#editMerchantSec .required-entry-text").each(function(){
                if($.trim($(this).val())==''){
                        validate=false;
                        $(this).siblings('.message_validation').html(errRequired).removeClass('hide');
    }
                else{
                        $(this).siblings('.message_validation').html("").addClass('hide');
}
        });

        $("#editMerchantSec .required-busOptSalePrice").each(function(){
                var saleprice   =   $(this).val();
                var thisID      =   $(this).attr('id');
                if(saleprice!=""){
                    if((!$(this).val()>0) || isNaN($(this).val())){
                        validate=false;
                        $(this).siblings('.message_validation').html(errValidNumber).removeClass('hide');
                    }else{
                        var regprice    =   $('#'+thisID+'_busOptReqPrice').val();
                        if(parseInt(saleprice)>parseInt(regprice)){
                            validate=false;
                            $(this).siblings('.message_validation').html(errProductRegularPrice).removeClass('hide');
                        }else{
                            $(this).siblings('.message_validation').html("").addClass('hide');
                        }
                    }
                }else{
                        $(this).siblings('.message_validation').html("").addClass('hide');
                }
        });
        return validate;
        
}