//var groupPriceControl={
//	addItem:function(optionID,group,prefix){
//		var template = $("#groupPricetemplate").html();
//		var elm= $("#group_price_container_"+optionID);
//		var currentlength = elm.find('.parent').length;
//		elm.append(_.template(template,{'index':currentlength,'productOptionCount':optionID,'group':group,'prefix':prefix}));
//
//	},
//	deleteItem:function(obj){
//		obj.closest('.parent').remove();
//	}
//};
//
var tierPriceControl={
	addItem:function(optionID,group,prefix){
		var template = $("#tierPriceRowTemplate").html();
		var elm= $("#tier_price_container_"+optionID);
		var currentlength = elm.find('.parent').length;
		elm.append(_.template(template,{'index':currentlength,'productOptionCount':optionID,'group':group,'prefix':prefix}));

	},
	deleteItem:function(obj){
		obj.closest('.parent').remove();
	}
};

function setProductDealMandatory(){
            if ($("#setAsProductDeal").is(':checked')) {
                $('.stdtcls').addClass('mandatory');
                $('.endtcls').addClass('mandatory');
                $(".dealPrice-Sec").removeClass("hide");
                $("#hiddenSetProductDeal").val(1);
            }else{
                $('.stdtcls').removeClass('mandatory');
                $('.endtcls').removeClass('mandatory');
                $(".dealPrice-Sec").addClass("hide");
                $("#hiddenSetProductDeal").val(0);
            }
        }



$(document).ready(function () { 
        
//	if ($("#isProductDeal").is(':checked')) {
//        $('#showCountTimer').prop('checked',true);
//        $("#showCountTimer").prop("disabled", true);
//        productDealCheck();
//    }
        setProductDealMandatory();
        $(document).on('click','#setAsProductDeal',function(){
            setProductDealMandatory();
        })
	
	$(".choosen").chosen();
	$("#product_drop_right_idUp").sortable();
	$("#product_drop_right_idCross").sortable();
	$("#product_drop_right_id").sortable();
        checkBusinessQuantity();
        $("#product_drop_right_idFree").sortable();
/* START : Product group Price and Tier Price */
	$('#Product').submit(function(){
		var validate=true;
                
                var checkGroupPrice = groupPriceCheck('');
                if(checkGroupPrice>0){
                    validate = false;
                }
                
		$(".required-entry").each(function(){
                    if($(this).is(":visible")==true){
			if((!$(this).val()>0) || isNaN($(this).val()) || $.trim($(this).val())==''){
				validate=false;
				if($.trim($(this).val())=='' || isNaN($(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');
			}
                    }else{
                        $(this).siblings('.message_validation').addClass('hide');
                    }
		});
                
                var duplicateValidate = 0;
                var enableBoyBoxSel   = $('#enableBoyBoxSel').val();
                
                if(enableBoyBoxSel=="Yes"){
                    $('ul#moptions li ul.levl-00').each(function(){
                        var duplicationEle = [];
                        $(this).find('.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($.in_array(thisValue,duplicationEle)){
                                duplicateValidate = duplicateValidate+1;
                                //$('#validate_business_value_'+productoptioncount+'_'+sellerIncr).removeClass('hide').html(errDuplicateMerchant);
                                $('#businessOptionsID_'+productoptioncount+' .optionBusiness option:selected[value='+thisValue+']').each(function(e){
                                    var selID       =  $(this).parent('.optionBusiness').attr('id');
                                    var splitSelID  =  selID.split('_');
                                    $('#validate_business_value_'+splitSelID[1]+'_'+splitSelID[2]).removeClass('hide').html(errDuplicateMerchant);
                                });
                            }else{
                                $('#validate_business_value_'+productoptioncount+'_'+sellerIncr).addClass('hide').html("");
                                duplicationEle.push(thisValue);
                            }
                        });
                    });
                }
                
                if(duplicateValidate>0){
                    validate=false;
                }
                
                $(".required-entry-text").each(function(){
                    if($(this).is(":visible")==true){
			if($.trim($(this).val())==""){
				validate=false;
				$(this).siblings('.message_validation').html(errRequired).removeClass('hide');
			}
			else{
				$(this).siblings('.message_validation').html("").addClass('hide');
			}
                    }else{
                        $(this).siblings('.message_validation').html("").addClass('hide');
                    }
		});
                
                $(".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');
			}
		});
		
		
//		var combination =[];
//		$(".option_group_price_user_group").each(function(){
//			var productoptioncount= $(this).attr('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 =[];
//		$(".option_tier_price_user_group").each(function(){
//			var rel= $(this).attr('rel');
//			var productoptioncount= $(this).attr('productoptioncount');  
//			var key = productoptioncount +"_"+ $(this).val()+"_"+$(".option_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){
			setErrortab();
			return false;
		}else{
			return true;
		}
	});

/* END : Product group Price and Tier Price */




//To add auto suggest functionaltiy to Search Tags
	$("#autosuggesttags").find("input[type=text]").autoSuggest(
		GLOBAL_BASE_PATH + "/catalogtags/ajaxlistTags/"
		, { selectedItemProp: "tagName", selectedValuesProp: "tagName", asHtmlID: "searchTags", searchObjProps: "tagName", minChars: 2, preFill: "," + data  }
	);	
	
    $(document).on('click','#showCountTimer',function(){
        showTimerCheck();
    });
    
    $(document).on('click','#isProductDeal',function(){
        productDealCheck();
    });
	$(".sale_price").each(function () {
		var id=$(this).attr('rel');
		var regPrice = parseFloat(jQuery.trim($("#productOptionsGroup_"+id+"_productOptionRegularPrice").val()));
                
                if($("#productOptionsGroup_"+id+"_productOptionProductPrice").val()!='') {
                    var productPrice = parseFloat(jQuery.trim($("#productOptionsGroup_"+id+"_productOptionProductPrice").val()));
                } else {
                    var productPrice = '';
                }                
		 if(regPrice==productPrice)
		 {
			$("#productOptionsGroup_"+id+"_productOptionProductPrice").val('')
		 }
});
$('input[type="submit"]').removeAttr('disabled');
equalHeight($(".AjaxAutoHeight"));
  $('#categoryVisible  input[name="productCategory[]"]:checked').each(function () {
                $(this).attr("checked", false);
            });  
$('.form_listing #FreeshippingShow').each(function () {
        $(this).nextUntil('#FreeshippingQuantity').andSelf().wrapAll("<div class='selectionProduct' />")
});
var loadCommissionStatus = changeCommissionStatus();
    var setQuantityValidation = setProductQuantityValidation();   
    $('.delete').attr('title', 'Delete');    
    /* Related Products search */
    $(document).on('click','#submitProductSearch',function(){
        var values = "";
        if ($.trim($('#searchKeyword').val()) != $.trim(lblProductIDTitle))
            values = $('#searchKeyword').val();
        $('#categoryVisible input[name="productCategoryID[]"]:checked').each(function () {
            values = values + "|" + $(this).val();
        });
		
        if ($('#categoryVisible input[name="productCategoryID[]"]:checked').length < 1 && $('#searchKeyword').val() == lblProductIDTitle) {
          
		 	jAlert(msgSearchWarning);
           return false;
        }  $("#Ajax_loader").html('<img src="' + GLOBAL_ROOT_PATH + '/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"  />');
		
		$("#Ajax_loader").show()
       loadAllProductProducts(values);
        return false;
    });
    /* Related Product search */      
    $("#productUseGlobalCommision").click(function () {
        $("#productCommissionRate").val("")
		if($("#productUseGlobalCommision").is(':checked') && $(".categoryTree:checked").length<1){
			jAlert("Please select any category");
			return false;
		}
        var loadCommissionStatus = changeCommissionStatus();
    })
    
    $("form").bind("submit", function () {
        var productID = $("#productID").val();
        var productRequestID = $("#productRequestID").val();
          if($("#hid_err_Product_productMaxBuyLimit").val()==1 && $("#hid_err_Product_hidmaxcertificate").val()==1)
        $("#div_err_Product_hidmaxcertificate").addClass("hide");
       if ($("#enableMultipleOptions").is(':checked')) {	
        var setNameValidation = setProductNameValidation();
        if (!setNameValidation) {
            return false;
        } 
        }
        //return setNameValidation;      
	           
    })
  
$(document).click(function (e)
{
	var type='';
	if($("#maintab").find('.active').attr('rel')=='related-save')	{
		type='';
	}else 	if($("#maintab").find('.active').attr('rel')=='crosssell-save')	{
		type='Cross';
	}	else if($("#maintab").find('.active').attr('rel')=='upsell-save')	{
		type='Up';
	} else if($("#maintab").find('.active').attr('rel')=='freeproducts-save')	{
		type='Free';
	}
    if ($("#categoryLabel"+type).is(e.target) ||  $('#categoryLabel'+type).find(e.target).length>0 ) 
    {

        $('#categoryVisible'+type).toggle();
    }else if ( $('#categoryVisible'+type).find(e.target).length>0) 
    {

        $('#categoryVisible'+type).show();
    }
	else{

		 $('#categoryVisible'+type).hide();
	}
});	
    $(document).on('click','#submitProductDetails',function(event){
        var setStartEndDateValidation = setProductStartEndDateValidation();
        var setDealStartEndDateValidation = setProductDealStartEndDateValidation();
        var CertifiacateValidation = setMaxCertifiacateValidation();      
        var setLayoutDateValidation = setLayoutEndDateValidation();
                
    });
    $(document).on('click','#productrelatedProductSubmit',function(event){
        saveRelatedProducts();
    })

    $("#productMinBuyLimit,#productOptionQuantity").change(function () {
        var setQuantityValidation = setProductQuantityValidation();
    })
    $("#productMinBuyLimit,#productOptionQuantity").click(function () {
        var setQuantityValidation = setProductQuantityValidation();
    })      
    $("#productMinBuyLimit,#productMaxBuyLimit").change(function () {
       // var CertifiacateValidation = setMaxCertifiacateValidation();
    })
$("#productMinBuyLimit,#productMaxBuyLimit").change(function () {
       // var CertifiacateValidation = setMaxCertifiacateValidation();
            if($("#hid_err_Product_productMaxBuyLimit").val()==1 && $("#hid_err_Product_hidmaxcertificate").val()==1)
            $("#div_err_Product_hidmaxcertificate").addClass("hide");

    })
$("#productMinBuyLimit,#productMaxBuyLimit").blur(function () {
       // var CertifiacateValidation = setMaxCertifiacateValidation();
 if($("#hid_err_Product_productMaxBuyLimit").val()==1 && $("#hid_err_Product_hidmaxcertificate").val()==1)           
            $("#div_err_Product_hidmaxcertificate").addClass("hide");

    })
    $("#productStartTime,#productEndTime").change(function () {
      var startDate= jQuery.trim($("#productStartTime").val());
       var endDate=  jQuery.trim($("#productEndTime").val());
       if (startDate=='' || endDate=='') {
           $("#div_err_" + productType + "_StartEndDatecheck").addClass("hide");          
       }
    });
	 $("#dealStartTime,#dealEndTime").change(function () {
      var startDate= jQuery.trim($("#dealStartTime").val());
       var endDate=  jQuery.trim($("#dealEndTime").val());
       if (startDate=='' || endDate=='') {
           $("#div_err_" + productType + "_StartEndDatecheck").addClass("hide");          
       }
    });
    var productID = $("#productID").val();
    var productRequestID = $("#productRequestID").val();
    var currDate = new Date;
    currDate.setDate(currDate.getDate() - 1);
    currDate.setHours(00);
    currDate.setMinutes(00);
    var tpStart;
    var tpEnd;
    var tpExpiry;
    if (productID && !productRequestID) {
    } else {
        tpStart = currDate;
        tpEnd = currDate;
        tpExpiry = currDate;
    }
    $('#productStartTime').datepicker({
       minDate: tpStart,
        onSelect: function (dateText, inst) {
            $("#div_err_" + productType + "_productStartTime").addClass("hide");
        }
    });
    $('#productEndTime').datepicker({
        minDate: tpEnd,
        onSelect: function (dateText, inst) {
            $("#div_err_" + productType + "_productEndTime").addClass("hide");
        }
    });   
	$('#dealStartTime').datepicker({
       minDate: tpStart,
        onSelect: function (dateText, inst) {
            $("#div_err_" + productType + "_dealStartTime").addClass("hide");
        }
    });
    $('#dealEndTime').datepicker({
        minDate: tpEnd,
        onSelect: function (dateText, inst) {
            $("#div_err_" + productType + "_dealEndTime").addClass("hide");
        }
    });   
    $(".ui-datepicker-current").css("display", "none");   
    $(".option_quantity").change(function () {
        var setOptionQuantityValidation = setProductOptionQuantityValidation($(this).attr('rel'));
    })
    $(".option_quantity").click(function () {
        var setOptionQuantityValidation = setProductOptionQuantityValidation($(this).attr('rel'));
    })  
    $(document).on('change','.option_quantity_new',function(){
        var setOptionQuantityNewValidation = setProductOptionQuantityNewValidation($(this).attr('rel'));
    })  
     
    $(document).on('click','.option_quantity_new',function(){
        var setOptionQuantityNewValidation = setProductOptionQuantityNewValidation($(this).attr('rel'));
    })
    $("#productImagesul .delete").remove();   
    // NOW DEAL BEGIN	
    setCategorySelected();
    $(".categoryTree").change(function () {
	
        setCategorySelected();
    })
    // NOW DEAL END	
    var productID = $("#productID").val();
    if (productID > 0) {
      //  $(".fileuploader_field .delete").css("display", "none");
    }
	
	   $("#businessID").change(function () {
		 if ($("#businessID").val()>0) 
		 {
		  $('#taxpayable').show();
		 }
    })
	
	 if ($("#businessID").val()>0) 
		 {
		  $('#taxpayable').show();
		 }
	
		if($('#productReturnable').is(':Checked')){ 
			$('#returnPeriod').attr('readonly',false);
		}	
		else
		{
			$('#returnPeriod').attr('readonly',true);
		}


        $(document).on('change','.categoryTree',function(){
		if($(this).is(':checked')){
                        $('.categoryTree').prop('checked',false);	
                        $(this).prop('checked',true);			
		}
    });
	
		$(".expand").click(function(){
		if($(this).hasClass('colapse')){
			$(this).removeClass('colapse');
			$(this).closest('li').find('ul:first').addClass('hide');
		}
		else{
			$(this).addClass('colapse'); 
			$(this).closest('li').find('ul:first').removeClass('hide');
		}
	});
	
    $(document).on('click', ".expandable", function () {
        var id = $(this).attr("id");
        $("#div" + id).fadeIn();
        $(this).removeClass("expandable").addClass("collapsable");
    });
    $(document).on('click','.collapsable',function(){
        var id = $(this).attr("id");
        $("#div" + id).fadeOut();
        $(this).removeClass("collapsable").addClass("expandable");
    });	
	
		$(document).on('keyup',"#filterCategories",function(){
		
		var val = $(this).val();
		$(".li_catIDs").each(function() {
		//console.log($(this).attr('catname').toLowerCase().indexOf(val));
		if ($(this).attr('catname').toLowerCase().indexOf(val) > -1) {
			if($(this).attr('data-level') == 0){
				$(this).removeClass("hide").addClass("show");
			}
		}else{
			if($(this).attr('data-level') == 0){
				$(this).removeClass("show").addClass("hide");
			}
		}			
		});
	});
        
        $(document).on('click','#setAsProductDealVal', function () {
        if($(this).prop("checked")==true){
            checkDealPriceValues();
        }else{
            $("#dealStartTime").val("");
            $("#dealEndTime").val("");
            $("#dealDiscountType").val("");
            $("#dealDiscount").val("");  
            //$(".option-dealprice").val("");
            $("#dealMaxBuyLimit").val("");
        }
    });
	
    $(document).on('blur','#dealDiscount', function () {
        if($("#setAsProductDealVal").prop("checked")==true){
          checkDealPriceValues();
        }
    });
	
    $(document).on('change','#dealDiscountType', function () {
        if($("#setAsProductDealVal").prop("checked")==true){
          checkDealPriceValues();
        }
    });
	
   });
   
   function checkDealPriceValues(){
         var dealDiscountType  =       $("#dealDiscountType").val();
         var dealDiscount      =       $("#dealDiscount").val();
         //dealPriceCalc(dealDiscount,dealDiscountType);
         var discValue         =       0;
         if(dealDiscountType == "Percentage" && (dealDiscount>100 || dealDiscount<=0)){
             $("#hiddenValidateDealDiscount").val("0");
             discValue         =       0;
         }else{
             $("#hiddenValidateDealDiscount").val("1");
             discValue         =       1;
         }
         if(discValue==0){
             return false;
         }else{
             return true;
         }
     }

    function dealPriceCalc(dealDiscount,dealDiscountType){
        if(dealDiscount>0 && dealDiscountType!=""){
            $('li#optionTab ul#moptions li.productOptionRow').each(function(){
                var prodPrice   =   parseInt($(this).find('.sale_price').val()) || 0;
                if(prodPrice<=0){
                    prodPrice   =   parseInt($(this).find('.option-itemprice').val());
                }
                var dealPrice;
                if(dealDiscountType=="Fixed"){
                    dealPrice   =   Math.round(prodPrice-dealDiscount);
                }else{
                    dealPrice   =   Math.round((prodPrice-((dealDiscount/100)*prodPrice)));
                }
                if(dealPrice<0){
                    dealPrice = 0;
                }
                //$(this).find('.option-dealprice').val(dealPrice);
            });
        }
    }
   
   function checkBusinessQuantity(){
       if($('#InventoryTrackLevel').val()=="Product"){
           $('.busQuantitySec').removeClass('hide');
           $('.businessQuantity').addClass('required-entry');
       }else{
           $('.busQuantitySec').addClass('hide');
           $('.businessQuantity').removeClass('required-entry');
       }
   }
   
    function setCategorySelected() {
        var categorySelected = 0;
        $(".categoryTree").each(function () {
            if ($(this).is(':checked')){ categorySelected = 1;
		//	var item = $(this).val();
//var lastItem = item.split(",").pop(-1);
			//alert(lastItem);
			}
        })
        if (categorySelected == 1) $("#categorySelected").val('1');
        else $("#categorySelected").val('');
    }  	

    function striptag(optname) {
        var tmp = document.createElement("DIV");
        tmp.innerHTML = optname;
        return tmp.textContent || tmp.innerText;
    }   
    function setProductNameValidation() {
        var text = new Array();
        var text1 = new Array();
        text.push($("#productTitle").val());
        $(".productName:visible").each(function () {            
            if ($(this).val() != '') {
                var productName = $(this).val();
                productName = $.trim(productName);
                productName = striptag(productName);
                text.push(productName);
                text1.push(productName);
            }
        });
        var arrayLength = text.length;
        var arrayLength1 = text1.length;
        if ($.unique(text1).length != arrayLength1) {
            jAlert(msgSelectDifferentNamesoption);
            return false;
        } else if ($.unique(text).length != arrayLength) {
            jAlert(msgSelectDifferentNames);
            return false
        } else return true;
    }

    function setMaxCertifiacateValidation() {
        var maxCertificate = jQuery.trim($("#productMaxBuyLimit").val());
        var minCertificate = jQuery.trim($("#productMinBuyLimit").val());
        if (parseInt(maxCertificate) < parseInt(minCertificate) && (maxCertificate != "") && (maxCertificate > 0)) {
            $("#hiddenmaxcertificate").val(0);
        } else {;
            $("#hiddenmaxcertificate").val(1);
        }
    }
  
    function setProductOptionQuantityValidation(id) {
        var Quantity = $("#productMinBuyLimit").val();
        var productOptionQuantity = $("#productOptionQuantity" + id).val();
        if (parseInt(productOptionQuantity) >= parseInt(Quantity) || Quantity == "" || productOptionQuantity == "") {
            $("#hiddenProductQuantity" + id).val(0);
        } else {
            $("#hiddenProductQuantity" + id).val(1);
        }
    }
     function setProductOptionQuantityNewValidation(id) {
        var Quantity = $("#productMinBuyLimit").val();
        var productOptionQuantity = $("#productOptionQuantityNew" + id).val();
        if (parseInt(productOptionQuantity) >= parseInt(Quantity) || Quantity == "" || productOptionQuantity == "") {
            $("#hiddenProductQuantityNew" + id).val(0);
        } else {
            $("#hiddenProductQuantityNew" + id).val(1);
        }
    }
    function setProductStartEndDateValidation() {
        var startDate = convertDate($("#productStartTime").val(), datePickerDateFormat);
        var endDate = convertDate($("#productEndTime").val(), datePickerDateFormat);	
        if ((startDate >= endDate) && (startDate != "") && (endDate != "")) {		
            $("#hiddenStartEndDate").val(0);	    
        } else {		
            $("#hiddenStartEndDate").val(1);
        }
    }
    
    function setProductDealStartEndDateValidation() {
        var startDate = convertDate($("#dealStartTime").val(), datePickerDateFormat);
        var endDate = convertDate($("#dealEndTime").val(), datePickerDateFormat);	
        if ((startDate >= endDate) && (startDate != "") && (endDate != "")) {		
            $("#hiddenDealStartEndDate").val(0);	    
        } else {		
            $("#hiddenDealStartEndDate").val(1);
        }
    }


    function setProductQuantityValidation() {
        var Qunatity = $("#productOptionQuantity").val();
        var maxlimit = $("#productMinBuyLimit").val();
        if ((parseInt(Qunatity) >= parseInt(maxlimit)) || (maxlimit == "") || (Qunatity == "")) {
            $("#hiddenProductQuantity").val(0);
        } else {
            $("#hiddenProductQuantity").val(1);
        }
    }
	
	function setLayoutEndDateValidation() {
        var startDate = convertDate($("#layoutActiveFrom").val(), datePickerDateFormat);
        var endDate = convertDate($("#layoutActiveTo").val(), datePickerDateFormat);	
        if ((startDate >= endDate) && (startDate != "") && (endDate != "")) {		
            $("#hiddenLayoutEndDate").val(0);	    
        } else {		
            $("#hiddenLayoutEndDate").val(1);
        }
    }
	
   function deleteRowImages(opid,imagecount) {
	
        jConfirm(msgDeleteItem, 'Delete', function (r) {
            if (r == true) {
		$("#isdelete_" + opid+"_" + imagecount).val(1);
		$("#productImagesul" + opid+" .productImageInlineli" + imagecount).hide();		
                if ($(".productImageLi"+opid+":visible").size() == 1) {			
                    $(".delete02").hide();
                }
		else
		{
		$(".delete02").show();	
		}
            };
        });
   
}      
    function changeCommissionStatus() {
        if ($("#productUseGlobalCommision").is(':checked')) {
			var item =$(".categoryTree:checked").val();				
			   var catParent=item.split(",").pop(-1);
   	$.ajax({
	        type: "POST",
	        url: GLOBAL_BASE_PATH+"/productcategory/ajaxparentadmincommission/",
	        data: "productCategoryParent="+catParent,
	        success: function(msg){
			   
	            if(msg){
				$("#productCommissionRate").val(msg);
	            }else{
	                  $("#productCommissionRate").val($("#productCommisionhidden").val());                                   
	            }
	    	}
  		});	
		
          //  $("#productCommissionRate").val($("#productCommisionhidden").val())
            $("#productCommissionRate").attr("readonly", "readonly")
            $("#productCommissionRate").addClass("disabled")
            $("#div_err_" + productType + "_productCommissionRate").addClass("hide");
            $("#hid_err_" + productType + "_productCommissionRate").val(0);
        } else {
            $("#productCommissionRate").removeAttr("readonly")
            $("#productCommissionRate").removeClass("disabled")
        }
    }

    function ismaxlength(obj) {
        var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
        if (obj.getAttribute && obj.value.length > mlength) obj.value = obj.value.substring(0, mlength)
				}
	function ResetProducts(type)
	{
		$(".Ajax_loader").show();	
		if (!type)
		type='';
        $('#searchKeyword'+type).val(lblProductIDTitle);
		  $('#categoryVisible'+type+' input[name="productCategoryID'+type+'[]"]:checked').attr("checked", false);
		$("#selectedText"+type).html(lblSelectCategory)
		$('#attrSetID'+type).prop('selectedIndex',0);
		$('#product_drop_left_id'+type).empty();
		$(".Ajax_loader").hide()	
	}
    function loadAllProductProducts(searchItem) {
        /* Related Product search */
        // + '&searchItem=' + searchItem appended and search item function parameter added
        /* Related Product search */
        $.ajax({
            type: "POST",
            data: 'productID=' + $("#productID").val() + '&selectedProductProductIDs=' + $("#selectedProductProductIDs").val() + '&searchItem=' + searchItem,
            url: GLOBAL_BASE_PATH + "/product/ajaxListProducts/",
            success: function (data) {
				$("#Ajax_loader").hide()
                $("#divExceptAll").show();
                $("#divExceptAll").html(data);  
		$("#selectedText").html($('#categoryVisible input[name="productCategoryID[]"]:checked').length+' Selected')
		$("ul#product_drop_left_id li" ).draggable({
		connectToSortable: ".connect",
		helper:'clone'
		});
		 $("#product_drop_right_id").sortable({
		connectWith: ".connect",
		//cancel: ".product_drop_right",
		dropOnEmpty: true,
		beforeStop:function(event,ui){
                      // console.log(ui);
			var objDup=$("#product_drop_right_id").find("."+ui.helper[0]['classList']['0']+" :visible");                        
			if(objDup.length>1 && ($.inArray("ui-draggable-dragging", ui.helper[0]['classList'])!=-1))
			{				
			objDup.first().parent().remove();	
			}
			var sortclass=	ui.helper[0]['classList']['0'];
			objDup.parent().attr('id',sortclass.replace('sort',''));
			},
			stop: function (event, ui)
			{
			$(".sort-label").addClass('hide');
			$("ul.product_drop_right").removeClass("outer-border");
                        $("ul#product_drop_right_id li .product_drop_delete").show();
						
			}
		
		});		
            }
        });
    }
$(document).on('click','ul#product_drop_right_id li .product_drop_delete',function(){
                    $(this).closest("li").remove();
if ($('#product_drop_right_id li').length == 0){
$(".sort-label").removeClass('hide');
$(".top-label").addClass("hide");
$(".product_drop_right").addClass("outer-border");
} 
                });	 
		
    function setDraggedProducts(type) {
            if(!type)
            type='';
        var droppedProducts = "";
        $('ul#product_drop_right_id'+type+' li').each(function (index) {		
            droppedProducts = droppedProducts + $(this).attr("id")+"~*";
        });
        var dataArray = new Array();
        dataArray[0] = droppedProducts;
        $("#selectedProductProductIDs"+type).val(droppedProducts);
		
    }

    function saveRelatedProducts() {
	setDraggedProducts();
        $.ajax({
            type: "POST",
            async: false,
            url: GLOBAL_BASE_PATH + '/product/ajaxsaveRelatedProducts/',
            data: 'droppedProducts=' + $("#selectedProductProductIDs").val() + '&productID=' + $("#productID").val(),
            success: function (data) {
                jAlert(msgRelatedProductsSaved);
            }
        });
    }
    // Auto Height
    function equalHeight(group) {
        tallest = 0;
        group.each(function () {
            thisHeight = $(this).height();
            if (thisHeight > tallest) {
                tallest = thisHeight;
            }
        });

        group.height(tallest);

    }
   
    /*Firefox 11 editor issue*/
    $(window).load(function () {
        $(".mceEditor .mceLayout").each(function (i, ele) {
            $("#" + ele.id).css('width', $("#" + ele.id).width() + 10)
        });
    });
    $.extend({
        arrMax: function (arr) {
            var max = arr[0];
            var len = arr.length;
            for (var i = 1; i < len; i++) if (arr[i] > max) max = arr[i];
            return max;
        },
        arrMin: function (arr) {
            var min = arr[0];
            var len = arr.length;
            for (var i = 1; i < len; i++) if (arr[i] < min) min = arr[i];
            return min;
        }

    });
    function callback_checkKeyExist()
    {
	return true;
    } 
$(document).on('blur','#productTitle',function(){
if(settingsRedirectUrl == '' ) {
	var formattedInput = $.formatUrl($(this).val());	
	$("#productUrl").val(formattedInput);
	$("#productUrl").trigger('change');
}
});
 // Permanent Redirect
$("#productUrl").change(function() {
    if(settingsRedirectUrl == 'Yes') {	
       $("#redirectOption").removeAttr('disabled');		
   }
   $("#productUrl").val($.formatUrl($(this).val()));
 });

$(document).ready(function (){
            
            if($("#thumbPreview").val()!='Yes')
            {
            $("#preview_main").hide();	
            }
            else
            {
            $("#preview-main").show();		
            }
                        
            if($("#InventoryTrackLevel").val()=='No')
            {
             $('.stock').hide();
             $('.combbus-quantity').addClass('hide');
             $('.comboBusQuant').removeClass('required-entry-combo');
            }
            else{
             if($("#InventoryTrackLevel").val()=='Product')           
                $(".optionQty").addClass('mandatory');
            else
                $(".comboQty").addClass('mandatory');
             $('.stock').show();
             $('.combbus-quantity').removeClass('hide');
             $('.comboBusQuant').addClass('required-entry-combo');
            }
 $("#productCategoryID").multiselectCustom({
        noneSelectedText: lblSelectCategory,
        selected: 'categories'
    });
 $("#productCategoryIDUp").multiselectCustom({
        noneSelectedText: lblSelectCategory,
        selected: 'categories'
    });
 $("#productCategoryIDCross").multiselectCustom({
        noneSelectedText: lblSelectCategory,
        selected: 'categories'
    });
$("#productCategoryIDFree").multiselectCustom({
        noneSelectedText: lblSelectCategory,
        selected: 'categories'
});
});

 $(document).on("change","#InventoryTrackLevel",function () {
$(".comboQty").removeClass('mandatory');
$(".optionQty").removeClass('mandatory');
if(($(this)).val()=='No')  
    {
        $('.stock').hide();
        $('.combbus-quantity').addClass('hide');
        $('.comboBusQuant').removeClass('required-entry-combo');
    }
    else
    {
        checkBusinessQuantity();
 if($(this).val()=='Product')           
    $(".optionQty").addClass('mandatory');
else
    $(".comboQty").addClass('mandatory');
 $('.stock').show();
 $('.combbus-quantity').removeClass('hide');
 $('.comboBusQuant').addClass('required-entry-combo');
    }
    })

$('#preview_hide').click(function(){
  $('#preview_main').toggle();
  return false; // should return false to prevent page loading
})

 function checkUrlExist()
    {
	return true;
    }
    
function checkOptSKUexist()
    {
	return true;
    } 
 function enableReturn()
	{
	
		if($('#productReturnable').is(':Checked')){
			$('#returnPeriod').attr('readonly',false);
			
		}	
		else
		{
			$('#returnPeriod').attr('readonly',true);
		}
	}
        
        
//Upsell Cross sell    
    $(document).on('click','#submitUpSellSearch',function () {
        var values = "";
        if ($.trim($('#searchKeywordUp').val()) != $.trim(lblProductIDTitle))
            values = $('#searchKeywordUp').val();
        $('#categoryVisibleUp input[name="productCategoryIDUp[]"]:checked').each(function () {
            values = values + "|" + $(this).val();
        });
        if ($.trim($('#attrSetIDUp').val()) !='')
         values = values +"&searchSetID="+$.trim($('#attrSetIDUp').val());
        if ( $('#categoryVisibleUp input[name="productCategoryIDUp[]"]:checked').length < 1 && $('#searchKeywordUp').val() == lblProductIDTitle && $('#attrSetIDUp').val()=='') {
            jAlert(msgSearchWarning);
            return false;
        }
		$(".Ajax_loader").html('<img src="' + GLOBAL_ROOT_PATH + '/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"  />');
		$(".Ajax_loader").show()	
        loadAllUpSells(values);
        return false;
    });
    
    
    function loadAllUpSells(searchItem) {
        /* Related Product search */
        // + '&searchItem=' + searchItem appended and search item function parameter added
        /* Related Product search */
        var type='Up';
        $.ajax({
            type: "POST",
            data: 'productID=' + $("#productID").val() + '&selectedUpProductProductIDs=' + $("#selectedUpProductProductIDs").val() + '&searchItem=' + searchItem+'&type='+type,
            url: GLOBAL_BASE_PATH + "/product/ajaxListProducts/",
            success: function (data) {
				$("#selectedTextUp").html($('#categoryVisibleUp input[name="productCategoryIDUp[]"]:checked').length+' Selected')
				$(".Ajax_loader").hide()	
                $("#divExceptAllUp").show();
                $("#divExceptAllUp").html(data);
				
                /* Related Product search */               
		$("ul#product_drop_left_idUp li" ).draggable({
		connectToSortable: ".connect",
		helper:'clone'
		});
		 $("#product_drop_right_idUp").sortable({
		connectWith: ".connect",
		//cancel: ".product_drop_right",
		dropOnEmpty: true,
		beforeStop:function(event,ui){
                      // console.log(ui);
			var objDup=$("#product_drop_right_idUp").find("."+ui.helper[0]['classList']['0']+" :visible");                        
			if(objDup.length>1 && ($.inArray("ui-draggable-dragging", ui.helper[0]['classList'])!=-1))
			{				
			objDup.first().parent().remove();	
			}
			var sortclass=	ui.helper[0]['classList']['0'];
			objDup.parent().attr('id',sortclass.replace('sort',''));
			},
			stop: function (event, ui)
			{
			$(".sort-labelUp").addClass('hide');
                        $("ul#product_drop_right_idUp li .product_drop_delete").show();
						
			}
		
		});		
            }
        });
    }
     $(document).on('click',"#productUpsellProductSubmit",function (event) {
        saveSellProducts('Up');
    })
     function saveSellProducts(type) {	
	var msg;
	if (type=='Up')
	msg=msgUpsellProductsSaved;	
	else if (type=='Free')
	msg=msgFreeProductsSaved
	else
	msg=msgCrosssellProductsSaved
	setDraggedProducts(type);
        $.ajax({
            type: "POST",
            async: false,
            url: GLOBAL_BASE_PATH + '/product/ajaxsaveSellProducts/',
            data: 'droppedProducts=' + $("#selectedProductProductIDs"+type).val() + '&productID=' + $("#productID").val(),
            success: function (data) {
                jAlert(msg);
            }
        });
    }
    $('ul#product_drop_right_idUp li .product_drop_delete').on('click', function () {
                    $(this).closest("li").remove();
if ($('#product_drop_right_idUp li').length == 0){
$(".sort-labelUp").removeClass('hide');
$(".top-labelUp").addClass("hide");
$(".product_drop_rightUp").addClass("outer-border");
} 
                });
    
//Cross sell    
    $(document).on('click','#submitCrossSellSearch',function () {
        var values = "";
        if ($.trim($('#searchKeywordCross').val()) != $.trim(lblProductIDTitle))
            values = $('#searchKeywordCross').val();
        $('#categoryVisibleCross input[name="productCategoryIDCross[]"]:checked').each(function () {
            values = values + "|" + $(this).val();
        });
        if ($.trim($('#attrSetIDCross').val()) !='')
         values = values +"&searchSetID="+$.trim($('#attrSetIDCross').val());
        if ( $('#categoryVisibleCross input[name="productCategoryIDCross[]"]:checked').length < 1 && $('#searchKeywordCross').val() == lblProductIDTitle && $('#attrSetIDCross').val()=='') {
            jAlert(msgSearchWarning);
            return false;
        }
		$(".Ajax_loader").html('<img src="' + GLOBAL_ROOT_PATH + '/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"  />');
		$(".Ajax_loader").show()			
        loadAllCrossSells(values);
        return false;
    });
    //Free products    
    $(document).on('click','#submitFreeSearch',function () {
        var values = "";
        if ($.trim($('#searchKeywordFree').val()) != $.trim(lblProductIDTitle))
            values = $('#searchKeywordFree').val();
        $('#categoryVisibleFree input[name="productCategoryIDFree[]"]:checked').each(function () {
            values = values + "|" + $(this).val();
        });
        if ($.trim($('#attrSetIDFree').val()) !='')
         values = values +"&searchSetID="+$.trim($('#attrSetIDFree').val());
        if ($.trim($('#hidBusinessID').val()) !='')
         values = values +"&searchBusiness="+$.trim($('#hidBusinessID').val());
        if ( $('#categoryVisibleFree input[name="productCategoryIDFree[]"]:checked').length < 1 && $('#searchKeywordFree').val() == lblProductIDTitle && $('#attrSetIDFree').val()=='' && $('#hidBusinessID').val()=='') {
            jAlert(msgSearchWarning);
            return false;
        }
		$(".Ajax_loader").html('<img src="' + GLOBAL_ROOT_PATH + '/public/default/manage/standard/images/ajax-loader.gif" id="loading_gif2"  />');
		$(".Ajax_loader").show()			
        loadAllFreeProducts(values);
        return false;
    });
    
    function loadAllFreeProducts(searchItem) {
        /* Free Product search */
        // + '&searchItem=' + searchItem appended and search item function parameter added
        /* Related Product search */
        var type='Free';
        $.ajax({
            type: "POST",
            data: 'productID=' + $("#productID").val() + '&selectedFreeProductProductIDs=' + $("#selectedFreeProductProductIDs").val() + '&searchItem=' + searchItem+'&type='+type,
            url: GLOBAL_BASE_PATH + "/product/ajaxListProducts/",
            success: function (data) {
				$("#selectedTextFree").html($('#categoryVisibleFree input[name="productCategoryIDFree[]"]:checked').length+' Selected')
				$(".Ajax_loader").hide()					
                $("#divExceptAllFree").show();
                $("#divExceptAllFree").html(data);
                /* Related Product search */               
		$("ul#product_drop_left_idFree li" ).draggable({
		connectToSortable: ".connect",
		helper:'clone'
		});
		 $("#product_drop_right_idFree").sortable({
		connectWith: ".connect",
		//cancel: ".product_drop_right",
		dropOnEmpty: true,
		beforeStop:function(event,ui){
                      // console.log(ui);
			var objDup=$("#product_drop_right_idFree").find("."+ui.helper[0]['classList']['0']+" :visible");                        
			if(objDup.length>1 && ($.inArray("ui-draggable-dragging", ui.helper[0]['classList'])!=-1))
			{				
			objDup.first().parent().remove();	
			}
			var sortclass=	ui.helper[0]['classList']['0'];
			objDup.parent().attr('id',sortclass.replace('sort',''));
			},
			stop: function (event, ui)
			{
                        $(".product_drop_delete_all").removeClass('hide');                            
			$(".sort-labelFree").addClass('hide');
                        $("ul#product_drop_right_idFree li .product_drop_delete").show();
    
			}
		
		});		
            }
        });
    }
    function loadAllCrossSells(searchItem) {
        /* Related Product search */
        // + '&searchItem=' + searchItem appended and search item function parameter added
        /* Related Product search */
        var type='Cross';
        $.ajax({
            type: "POST",
            data: 'productID=' + $("#productID").val() + '&selectedCrossProductProductIDs=' + $("#selectedCrossProductProductIDs").val() + '&searchItem=' + searchItem+'&type='+type,
            url: GLOBAL_BASE_PATH + "/product/ajaxListProducts/",
            success: function (data) {
				$("#selectedTextCross").html($('#categoryVisibleCross input[name="productCategoryIDCross[]"]:checked').length+' Selected')
				$(".Ajax_loader").hide()					
                $("#divExceptAllCross").show();
                $("#divExceptAllCross").html(data);
                /* Related Product search */               
		$("ul#product_drop_left_idCross li" ).draggable({
		connectToSortable: ".connect",
		helper:'clone'
		});
		 $("#product_drop_right_idCross").sortable({
		connectWith: ".connect",
		//cancel: ".product_drop_right",
		dropOnEmpty: true,
		beforeStop:function(event,ui){
                      // console.log(ui);
			var objDup=$("#product_drop_right_idCross").find("."+ui.helper[0]['classList']['0']+" :visible");                        
			if(objDup.length>1 && ($.inArray("ui-draggable-dragging", ui.helper[0]['classList'])!=-1))
			{				
			objDup.first().parent().remove();	
			}
			var sortclass=	ui.helper[0]['classList']['0'];
			objDup.parent().attr('id',sortclass.replace('sort',''));
			},
			stop: function (event, ui)
			{
			$(".sort-labelCross").addClass('hide');
                        $("ul#product_drop_right_idCross li .product_drop_delete").show();
						
			}
		
		});		
            }
        });
    }
     $(document).on('click',"#productCrosssellProductSubmit",function (event) {
        saveSellProducts('Cross');
    })
      $(document).on('click',"#productFreeproductsProductSubmit",function (event) {
          if($("#freeProductsCount").val()>$('#product_drop_right_idFree li').length && $('#product_drop_right_idFree li').length>0){
              jAlert(lblFreeProductErr1);
              return false;
          } else{
              saveSellProducts('Free');
          }
         // saveSellProducts('Free');
    })
     function saveSellProducts(type) {
	var msg;
	if (type=="Up")
	msg=msgUpsellProductsSaved;
        else if (type=='Free')
	msg=msgFreeProductsSaved
	else
	msg=msgCrosssellProductsSaved
	setDraggedProducts(type);
        $.ajax({
            type: "POST",
            async: false,
            url: GLOBAL_BASE_PATH + '/product/ajaxsaveSellProducts/',
            data: 'droppedProducts=' + $("#selectedProductProductIDs"+type).val() + '&productID=' + $("#productID").val()+ '&type=' +type+ '&freecnt=' +$("#freeProductsCount").val(),
            success: function (data) {
                jAlert(msg);
            }
        });
    }
   
    $(document).on('click',".product_drop_delete_all", function () {
        $('ul#product_drop_right_idFree li').remove();
        $(".product_drop_delete_all").addClass('hide');
    });
    $(document).on('click','ul#product_drop_right_idCross li .product_drop_delete',function () {
                    $(this).closest("li").remove();
	if ($('#product_drop_right_idCross li').length == 0){
	$(".sort-labelCross").removeClass('hide');
	$(".top-labelCross").addClass("hide");
	$(".product_drop_rightCross").addClass("outer-border");
	} 
                });
                   $(document).on('click','ul#product_drop_right_idFree li .product_drop_delete',function () {
                    $(this).closest("li").remove();
	if ($('#product_drop_right_idFree li').length == 0){
        $(".product_drop_delete_all").removeClass('hide');    
        $(".product_drop_delete_all").addClass('hide');         
	$(".sort-labelFree").removeClass('hide');
	$(".top-labelFree").addClass("hide");
	$(".product_drop_rightFree").addClass("outer-border");
                    }
                });
//                if($("#baseProduct").is(':checked')) {
//                   if($("#isProductDeal").is(':checked')) {
//                        $("#isProductDeal").prop('checked',false);
//                        $("#isProductDeal").prop('disabled',true);
//                        productDealCheck();
//
//                    }
//                   
//                }
//                 $(document).on('change','#baseProduct',function() {
//        
//                    if($("#isProductDeal").is(':checked')) {
//                        $("#isProductDeal").prop('checked',false);
//                        productDealCheck();
//
//                    }
//                });
	function productDealCheck() {
//		if ($("#isProductDeal").is(':checked')) {
//			$('#showCountTimer').prop('checked',true);
//			$('#showCountTimer').val('Yes');
//			$('#showCountTimer').prop('disabled',true);
//			$('#isProductDealCheck').val('checked');
//			$(".stdtcls").addClass('mandatory');
//			$(".endtcls").addClass('mandatory');
//		} else {
//			$('#showCountTimer').prop('disabled',false);
//			$('#showCountTimer').prop('checked',false);
//			$(".stdtcls").removeClass('mandatory');
//			$(".endtcls").removeClass('mandatory');
//			if ($("#showCountTimer").is(':checked')) {
//				$('#isProductDealCheck').val('checked');
//			} else {
//				$('#isProductDealCheck').val('');
//			}
//		}
			}

	function showTimerCheck() {
//		if ($("#showCountTimer").is(':checked')) {
//			$('#timerCheck').val('checked');
//			$('#isProductDealCheck').val('checked');
//		} else {
//			$('#timerCheck').val('');
//			if ($("#isProductDeal").is(':checked')) {
//				$('#isProductDealCheck').val('checked');
//			} else {
//				$('#isProductDealCheck').val('');
//			}
//		}
			}

	
     