$(document).ready(function(){
    //$(".choosen").chosen();        
	$('#formProductCategorySubmit').submit(function(){
		setErrortab();
	});
if ($("#productCommissionType").val()=='new') {
	$("#productCommissionRate").removeAttr("readonly")
	$("#productCommissionRate").removeClass("disabled")	
}	

function setErrortab()
{
	$('.left-tab-a').removeClass("error");
	$("form").each(function(){
	var formName = $(this).attr("name");	
	//var invalidPanels = $(this).find('.hid_err_'+formName+'_validations[value=1]').closest('.tabpane');
	var invalidPanels = $(this).find(".message_validation:not(.hide),.message_inline_validation:not(.hide)").closest('.tabpane');
	if (invalidPanels.size() > 0) 
	{
		$.each($.unique(invalidPanels.get()), function () {
			var index = $(this).index('.tabpane');					
			$('#maintab').find('.left-tab-a:eq(' + index + ')').addClass("error");
		});
	}
	});
}
$('#brandID').change(function(){
	if($("#brandID").val()>0) {
		$.ajax({
	        type: "POST",
	        url: GLOBAL_BASE_PATH+"/productcategory/ajaxGetParents/",
	        data: "brandID="+$("#brandID").val(),
	        success: function(msg){
				if(msg!=0)
					$("#ajax-parents").html(msg);
				}
  		});
				
	}
});	
$('#productCategoryKey').change(function(){
	// Permanent Redirect
	if(settingsRedirectUrl == 'Yes') {
		if($("#productCategoryKey").val()!=$("#oldCatagoryKey").val()) 
			$("#redirectOption").removeAttr('disabled');
		else {
			$("#redirectOption").attr("disabled", "true");
		}
	}
         $("#productCategoryKey").val($.formatUrl($(this).val()));       
         keycheck();
    });	
    $(document).on('blur','#productCategoryName', function () {	
		if($.trim($("#productCategoryKey").val())=="")
                {
                        $("#productCategoryKey").val($.formatUrl($("#productCategoryName").val()));	
                }
    });
});


function limitText(limitField, limitNum){
	if (limitField.value.length > limitNum){
    	limitField.value	=	limitField.value.substring(0, limitNum);
	} 
}

function checkExists(){
	var productCategoryParent	=   $('#productCategoryParent').val();
	var productCategoryName  	=   $.trim($("#productCategoryName").val());
	productCategoryName		=	$.URLEncode(productCategoryName);
        productCategoryID   	 	=   $("#productCategoryID").val();  	
  	if(productCategoryName!=''){
    	$.ajax({
	        type: "POST",
	        url: GLOBAL_BASE_PATH+"/productcategory/productCategoryExits/",
	        data: "productCategoryParent="+productCategoryParent+"&productCategoryName="+productCategoryName+"&productCategoryID="+productCategoryID,
	        success: function(msg){
			    $('#validateKeyValue').val(msg);
	            if(msg=="1"){
					$("#div_err_formProductCategorySubmit_productCategoryName").css("display","");
					$("#div_err_formProductCategorySubmit_productCategoryName").addClass("hide");  
					
	                $("#div_err_formProductCategorySubmit_validateKey").css("display","");
	                $("#div_err_formProductCategorySubmit_validateKey").removeClass("hide");  
	            }else{
	                 $("#div_err_formProductCategorySubmit_validateKey").css("display","none");
	                 $("#div_err_formProductCategorySubmit_validateKey").addClass("hide");	
                         if(!productCategoryID)
			getUrlKey(); 
			 		                                       
	            }
	    	}
  		});
	}
}

function getUrlKey(){
	$("#productCategoryKey").val($.formatUrl($("#productCategoryName").val()));	
        keycheck();
}
function keycheck(){	
	var deayKey			=	$('#productCategoryKey').val();
	var productCategoryID  =   $("#productCategoryID").val();
	var exceptions		=	new Array("other","category","city");
	if($.inArray(deayKey, exceptions) != -1)
	{
		$("#div_err_formProductCategorySubmit_productCategoryKey").css("display","");
		$("#div_err_formProductCategorySubmit_productCategoryKey").addClass("hide");
		
		$("#div_err_formProductCategorySubmit_validateKey").css("display","");
		$("#div_err_formProductCategorySubmit_validateKey").addClass("hide");
					
        $("#div_err_formProductCategorySubmit_validateEceptions").css("display","");
        $("#div_err_formProductCategorySubmit_validateEceptions").removeClass("hide");
		
		$('#validateKeyexceptions').val(1);	
		$('#validateKeyValue').val(0);
	}
	else
	{
	$('#validateKeyexceptions').val(0);	
	if(deayKey!=''){
		$.ajax({
			type: "POST",
			url: GLOBAL_BASE_PATH+"/productcategory/productCatKeyExists/",
			data: "productKey="+deayKey+"&productCategoryID="+productCategoryID,
			success: function(msg){
				$('#validateKeyValue').val(msg);
				if(msg=="1"){
					$("#div_err_formProductCategorySubmit_productCategoryKey").css("display","");
					$("#div_err_formProductCategorySubmit_productCategoryKey").addClass("hide");
					
					$("#div_err_formProductCategorySubmit_validateEceptions").css("display","");
					$("#div_err_formProductCategorySubmit_validateEceptions").addClass("hide");
					
               		$("#div_err_formProductCategorySubmit_validateKey").css("display","");
               		$("#div_err_formProductCategorySubmit_validateKey").removeClass("hide");
            	}else{
					$("#div_err_formProductCategorySubmit_validateKey").css("display","none");
                 	$("#div_err_formProductCategorySubmit_validateKey").addClass("hide");
					
					$("#div_err_formProductCategorySubmit_validateEceptions").css("display","");
					$("#div_err_formProductCategorySubmit_validateEceptions").addClass("hide");
            	}
			}
		});
	}
}
}
	//         drag widget 
	
	$(document).ready(function () {
    var transferred = false;
	var adsArray = [];
    var transferredItem = {};
    $("#product_drop_right_id").sortable({
		beforeStop:function(){
			$("#dragSection_info").addClass('hide');
		},
        receive: function (event, ui) {
            transferred = true;
        },
        update: function () {
            $(".saveController").removeClass('hide');
			assignWidgetToHidden();
		//	resetNumbers();
        }
    }); //.disableSelection();
	function dragfunc(){
	$("#product_drop_left_id").find('li').draggable({
		connectToSortable: "#product_drop_right_id",
		helper: 'clone',
		cursor: "move",
		start: function (event, ui) {
			$(this).hide();
		},
		stop: function (event, ui) {
			if (!transferred){
				$(this).show();
				
			}else {
			//	$(this).remove();
				transferred = false;
				var selectedWidgetID	=	 $(this).attr('ad_id');
				var hiddenSelectedWidgetID	=	$('#selectedWidgetIDs').val();
				if(hiddenSelectedWidgetID != '' && hiddenSelectedWidgetID != 'undefined'){ hiddenSelectedWidgetID += '~*' + selectedWidgetID;}
				else{hiddenSelectedWidgetID = selectedWidgetID;}
				assignWidgetToHidden();
			}
			$("ul#product_drop_right_id li a").removeClass('hide');
			$(".sort-label").addClass('hide');
            
		}
	});
	}
	dragfunc();
   	$(document).on('click',"#product_drop_right_id .product_drop_delete",function(){
		var objElement= $(this);
		jConfirm(msgConfirmDelete,lblMessage,function(r){
			if(r){
				var WidgetID =objElement.closest('li').attr('ad_id');
				var checkwidgetisThere	=	0;
				$("#product_drop_left_id").find('li').each(function(){
					if($(this).attr('ad_id') == objElement.closest('li').attr('ad_id')){
						$(this).show();
						checkwidgetisThere = 1;
					}
					
				});
				if(checkwidgetisThere == 0){
						objElement.closest('li').find('a').addClass('hide');
						$("#product_drop_left_id").append('<li id="'+WidgetID+'" ad_id="'+WidgetID+'" class="sort'+WidgetID+' ui-draggable" style="display:list-item">'+objElement.closest('li').html()+'</li>')	
						dragfunc();
				}
				objElement.closest('li').find('a').css('display','none');
				var deletedWidgetID	=	objElement.closest('li').removeAttr('ad_id'); 
				assignWidgetToHidden();
				objElement.closest('li').css('display','none');
				$('#widgetNotAvailable').addClass('hide');
			}
		})
		
	});
	
	function assignWidgetToHidden(){
		var elements = [];
		$("#product_drop_right_id li").each(function(){
			if(typeof $(this).attr('ad_id') !='undefined' && $(this).attr('ad_id') > 0 ){
				elements.push($(this).attr('ad_id'));
			}
		});
		$('#selectedWidgetIDs').val(elements.join("~*"));
	}
	$(document).on('change',"#productCategoryParent",function(){
        
		 if ($("#productCommissionType").val()=='parent') {
			 $("#productCommissionRate").val("")
			var loadCommissionStatus = changeCommissionStatus();
		 }
	});	
	$(document).on('change',"#productCommissionType",function(){
        $("#productCommissionRate").val("")
        var loadCommissionStatus = changeCommissionStatus();
	});
	$("#search").click(function () {
		
		var data = new Object();
        data.widgetName = $("#widgetName").val();
        data.widgetDisplayedOn = 'category';
		data.selectedCategoryID	=	$('#selectedWidgetIDs').val();
		if (data.widgetName == '') {
            return;
        }
		var ads = [];
        $("#playlist_default li").each(function () {
            ads.push($(this).attr('ad_id'));
        });
		data.ads = ads;
		$.ajax({
            method: "POST",
            url: GLOBAL_BASE_PATH + '/productcategory/ajaxgetwidget/',
            data: data,
            success: function (data) {
				$('#product_drop_left_id').html(data);
				var transferred = false;
				var adsArray = [];
				var transferredItem = {};
				$("#product_drop_right_id").sortable({
					beforeStop:function(){
						$("#dragSection_info").addClass('hide');
					},
					receive: function (event, ui) {
						transferred = true;
					},
					update: function () {
						$(".saveController").removeClass('hide');
					}
				})
				$("#product_drop_left_id").find('li').draggable({
					connectToSortable: "#product_drop_right_id",
					helper: 'clone',
					cursor: "move",
					start: function (event, ui) {
						$(this).hide();
					},
					stop: function (event, ui) {
						if (!transferred)
							$(this).show();
						else {
							$(this).remove();
							transferred = false;
							var selectedWidgetID	=	 $(this).attr('ad_id');
							var hiddenSelectedWidgetID	=	$('#selectedWidgetIDs').val();
							if(hiddenSelectedWidgetID != '' && hiddenSelectedWidgetID != 'undefined'){ hiddenSelectedWidgetID += '~*' + selectedWidgetID;}
							else{hiddenSelectedWidgetID = selectedWidgetID;}
							$('#selectedWidgetIDs').val(hiddenSelectedWidgetID);
							$(".sort-label").addClass('hide'); 
							$("ul#product_drop_right_id li a").removeClass('hide');
						}
					}
				});
				//resetNumbers();
            }
        });
    });
});
$('#reset').click(function(){
	$('#categoryID').val('');
	$('#widgetName').val('');
	var data = new Object();
        data.widgetName = $("#widgetName").val();
        data.categoryID = $("#categoryID").val();
		data.productCategoryID	=	$('#productCategoryID').val();
		data.selectedCategoryID	=	$('#selectedWidgetIDs').val();
		data.widgetDisplayedOn = 'category';
		var ads = [];
        $("#product_drop_right_id li").each(function () {
            ads.push($(this).attr('ad_id'));
        });
		data.ads = ads;
		$.ajax({
            method: "POST",
            url: GLOBAL_BASE_PATH + '/productcategory/ajaxgetwidget/',
            data: data,
            success: function (data) {
				$('#product_drop_left_id').html(data);
				var transferred = false;
				var adsArray = [];
				var transferredItem = {};
				$("#product_drop_right_id").sortable({
					beforeStop:function(){
						$("#dragSection_info").addClass('hide');
					},
					receive: function (event, ui) {
						transferred = true;
					},
					update: function () {
						$(".saveController").removeClass('hide');
					}
				})
				$("#product_drop_left_id").find('li').draggable({
					connectToSortable: ".product_drop_right",
					helper: 'clone',
					cursor: "move",
					start: function (event, ui) {
						$(this).hide();
					},
					stop: function (event, ui) {
						if (!transferred)
							$(this).show();
						else {
							$(this).remove();
							transferred = false;
							var selectedWidgetID	=	 $(this).attr('ad_id');  
							var hiddenSelectedWidgetID	=	$('#selectedWidgetIDs').val();
							if(hiddenSelectedWidgetID != '' && hiddenSelectedWidgetID != 'undefined'){ hiddenSelectedWidgetID += '~*' + selectedWidgetID;}
							else{hiddenSelectedWidgetID = selectedWidgetID;}
							$('#selectedWidgetIDs').val(hiddenSelectedWidgetID)
							$(".sort-label").addClass('hide'); 
							$("ul#product_drop_right_id li a").removeClass('hide');
						}
						
					}
				})
			}
        });
});
	
	$('#parentCategorySettings').click(function(){
			if($('#parentCategorySettings').prop('checked')){
				var productCategoryID = $('#productCategoryParent').val();
				if(productCategoryID !='' && productCategoryID != '0'){
			$.ajax({
				method:'POST',
				dataType : 'json',
				data : 'productCategoryID='+productCategoryID,
				url : GLOBAL_BASE_PATH + '/productcategory/ajaxgetcategorydetails/',
				success:function(msg){
					if(msg){
						
					$('#productThumbWidth').val(msg.productThumbWidth).attr('readonly','readonly');
						$('#productThumbHeight').val(msg.productThumbHeight).attr('readonly','readonly');
						if(msg.layoutActiveFrom != '0000-00-00'){
							$('#layoutActiveFrom').val(msg.layoutActiveFrom.replace(/%/g, '')).attr('readonly','readonly');
						}
						if(msg.layoutActiveTo != '0000-00-00'){
							$('#layoutActiveTo').val(msg.layoutActiveTo.replace(/%/g, '')).attr('readonly','readonly');
						}
						$('#pageDefaultView').val(msg.pageDefaultView).attr('disabled','disabled');
						$('#hiddenPageDefaultView').val(msg.pageDefaultView);
						$('#numberOfProductCount').val(msg.numberOfProductCount).attr('readonly','readonly');
						$('#productGridListLayoutID').val(msg.productGridListLayoutID).attr('disabled','disabled');
						$('#hiddenProductGridListLayoutID').val(msg.productGridListLayoutID);
						$('#productDetailsLayoutID').val(msg.productDetailsLayoutID).attr('disabled','disabled');
						$('#hiddenProductDetailsLayoutID').val(msg.productDetailsLayoutID);
						if(msg.showRatingCountInGrid =='Yes'){
							$('#showRatingCountInGrid').prop('checked',true).attr('readonly','readonly');
						}
					}
				}
			});
		}
	}
	else{
			$('#productThumbWidth').removeAttr('readonly');
			$('#productThumbHeight').removeAttr('readonly');
			$('#layoutActiveFrom').removeAttr('readonly');
			$('#layoutActiveTo').removeAttr('readonly');
			$('#pageDefaultView').removeAttr('disabled');
			$('#hiddenPageDefaultView').val('');
			$('#numberOfProductCount').removeAttr('readonly');
			$('#productGridListLayoutID').removeAttr('disabled');
			$('#hiddenProductGridListLayoutID').val('');
			$('#productDetailsLayoutID').removeAttr('disabled');
			$('#hiddenProductDetailsLayoutID').val('');
			$('#showRatingCountInGrid').removeAttr('readonly');
		}
});
///// ////////// CUSTOM ATTRIBUTES /////////////
$(document).ready(function ()
	{	
		
		$(document).on("click",".left-tab-a",function(){		
			var thisVar = $(this);
			var thisRel = $(this).attr("rel");
			var cmButtonsFloating = $("#"+thisRel+"-section").children(".cm-buttons-floating");
			var cmButtons = $("#"+thisRel+"-section").children(".cm-buttons");
			$.scrollPane({
					floating: cmButtonsFloating,
					fixed: cmButtons,
					padding: 71
				});
			toggleSaveButton(thisRel);
			var editedForms = 0;
			var editedForm = '';
			$("form").each(function(){
			if($(this).attr("changed")=="true")
			{
				editedForm = $(this).attr("rel");
				editedForms++;
			}	
			});
			if (editedForm!='' && thisRel!=editedForm) {
				jAlert(lblPageLeaveAlert);
				jConfirm(lblPageLeaveAlert, 'Alert',function (r) {
					if (r == true) 
					{
						setSelectedTab(thisVar,cmButtonsFloating,cmButtons,thisRel);
					}
					else 
					{
						return false;
					}
				},okText,cancelText);	  
		
			}
			else
			{
				setSelectedTab(thisVar,cmButtonsFloating,cmButtons,thisRel);
			}
		});
	
		$(window).scroll(function()
		{
			var thisRel =   $(".left-tab li a.active").attr("rel");
			toggleSaveButton(thisRel);
		})
		setActiveTabSaveButton();
	
		$("form").attr("changed",false);
		
		$("form :input").change(function() {
			$(this).parents("form").attr("changed",true);
		});
	
		$(document).on("click","input[type=submit]",function() {
			$("form").attr("changed",false); 
		});
	
		$('form').bind("submit",function ()
		{	
			setErrortab();
		});		
	});
function setActiveTabSaveButton()
{
	var thisRel =   $(".left-tab li a.active").attr("rel");
	var cmButtonsFloating = $("#"+thisRel+"-section").children(".cm-buttons-floating");
	var cmButtons = $("#"+thisRel+"-section").children(".cm-buttons");
	$.scrollPane({
			floating: cmButtonsFloating,
			fixed: cmButtons,
			padding: 71
			});
	$.fn.hasScrollBar = function()
	{
		var thisRel =   $(".left-tab li a.active").attr("rel");
		toggleSaveButton(thisRel);
	}
	var thisRel =   $(".left-tab li a.active").attr("rel");
	toggleSaveButton(thisRel);
}

window.onbeforeunload = confirmExit;

function setSelectedTab(thisVar,cmButtonsFloating,cmButtons,thisRel)
{
	$("ul.left-tab>li>a").removeClass("active");	
	thisVar.addClass("active");	
	var thisIndex = $("ul.left-tab>li>a").index(thisVar);
	$(".tabpane").hide();
	$(".tabpane:eq("+thisIndex+")").show();
	if(thisVar.hasClass('inventoryLink'))
	{
		inventoryUpdate();
	}
	$.scrollPane({
				floating: cmButtonsFloating,
				fixed: cmButtons,
				padding: 71
			});
	toggleSaveButton(thisRel);
}

function confirmExit()
{
	var editedForms = 0;
	var returnData = ''
	$("form").each(function(){
	if($(this).attr("changed")=="true")
	editedForms++;
	});
	if (editedForms>0) {
	  return lblPageLeaveAlert;
	}
	return null;
}

setErrortab();

function setErrortab()
{
	$('.left-tab-a').removeClass("error");
	$("form").each(function(){
	var formName = $(this).attr("name");	
	//var invalidPanels = $(this).find('.hid_err_'+formName+'_validations[value=1]').closest('.tabpane');
	var invalidPanels = $(this).find(".message_validation:not(.hide),.message_inline_validation:not(.hide)").closest('.tabpane');
	if (invalidPanels.size() > 0) 
	{
		
		$.each($.unique(invalidPanels.get()), function () {
			var index = $(this).index('.tabpane');					
			$('#maintab').find('.left-tab-a:eq(' + index + ')').addClass("error");
		});
	}
	});
}

function toggleSaveButton(thisRel)
{
	$(".save-floating-section").hide();
	$("#"+thisRel+"-section").show();
}

// CUSTOM ATTRIBUTES ENDS//

function setAjaxErrortab(formtab,show)
{	
	if (show==1) 
	$('.left-tab-a[rel=' + formtab + ']').addClass('error');
	else
	$('.left-tab-a[rel=' + formtab + ']').removeClass('error');
	
}
  $(document).on('click',"#submit",function (event) {
        setProductStartEndDateValidation();
	   })
 function setProductStartEndDateValidation() {
        var startDate = convertDate($("#layoutActiveFrom").val(), datePickerDateFormat);
        var endDate = convertDate($("#layoutActiveTo").val(), datePickerDateFormat);	
        if ((startDate >= endDate) && (startDate != "") && (endDate != "")) {		
            $("#hiddenStartEndDate").val(0);	    
        } else {		
            $("#hiddenStartEndDate").val(1);
        }
    }

   function changeCommissionStatus() {
	   
	   if ($("#productCommissionType").val()=='global') {
		   $("#productCommissionRate").val($("#productCommisionhidden").val());
            $("#productCommissionRate").attr("readonly", "readonly")
            $("#productCommissionRate").addClass("disabled")		   
	   } if ($("#productCommissionType").val()=='parent') {
		   if ($("#productCategoryParent").val()==0) {
			     $("#productCommissionRate").val($("#productCommisionhidden").val());
		   }else{
			  
			   var catParent=$("#productCategoryParent").val();
   	$.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").attr("readonly", "readonly")
            $("#productCommissionRate").addClass("disabled")		   
	   }
       else {
            $("#productCommissionRate").removeAttr("readonly")
            $("#productCommissionRate").removeClass("disabled")
        }
    }	 
		