var attributeMode = $("#attributeMode").val();
$(document).ready(function(){
$(document).on("change","#inputType",function() {
	setInputTypeConstraints();	
	vaidateMessageValidation();
	
});
setInputTypeConstraints();
vaidateMessageValidation();
$(document).on("click","#add_new_options",function ()
{
	$("#optionGrid").removeClass("hide");
	loadOptions();
});
$(document).on("click",".deleteRow",function () 
{
	$("#variant_message").css("display","none");
	if ($(".attributeOptionRow").not('.hide').size() > 1 && !$(this).hasClass('delete-inactive'))
	{
		var element = $(this).parent().parent();
		var row_is_delete_id	= $(this).attr('rel');
		var variant_id	= $(this).attr('id');		
		jConfirm(msgSelectAtleastOne, 'Delete', function (deletedConfirm) 
		{
			if (deletedConfirm == true) 
			{
				if(($("#inputType").val()=='select')&&(variant_id>0))
				{
				var data=new Object();
				var ajaxUrl = "/productoption/AjaxDestroyProVariant/";
				data.productID= $("#productID").val();
				data.productRequestID= $("#productRequestID").val();
				data.variantID = variant_id;
				data.productRequestID=$("#productRequestID").val();
				$.ajax({
				   type: "POST",
				   url: GLOBAL_BASE_PATH+ajaxUrl,
				   data:data,
				   success: function(data){
					if(data==3) {						
					jNotifyShow(msgdeleteComboVariant, "variant_message","message_error");
					}
					else
					{
					$("#"+row_is_delete_id).val('1');
					element.addClass("hide");
					element.addClass("nodrag");
					element.addClass("nodrop");
					element.find('.hid_err_formAttributeAdd_validations').val(0);
					if ($(".attributeOptionRow").not('.hide').size() == 0)
					{
					$("#optionGrid").addClass("hide");
					}	
					hideDeleteButton();	
					setTabelDrag();	
					}
					
				}
				});
			
				}
				else
					{
					$("#"+row_is_delete_id).val('1');
					element.addClass("hide");
					element.addClass("nodrag");
					element.addClass("nodrop");
					element.find('.hid_err_formAttributeAdd_validations').val(0);
					if ($(".attributeOptionRow").not('.hide').size() == 0)
					{
					$("#optionGrid").addClass("hide");
					}	
					hideDeleteButton();	
					setTabelDrag();	
					}
				}
		});
	}
});
$(document).on("click",".isDefaultCheckbox",function(){
var inputType = $("#inputType").val();	
if(inputType=='select')
{
	if($(this).prop("checked"))
	{
	if ($(".attributeOptionRow").not('.hide').size() > 1)
	{
	$(".isDefaultCheckbox").prop('checked',false);
	$(this).prop("checked",true);
	}
	}
}
else if(inputType=='textbox' || inputType=='textarea' || inputType=='date' || inputType=='datetime')
{
	$(this).prop('checked',true);	
}
});


$('form[name="formAttributeAdd"]').bind('submit',function() {
  var chk = checkAttributeOptions();
  if(!chk)
  return false;
});

$(document).on("click","#validateRuleRequired",function(){
	if($("#includeInCombination").prop('checked', true) && !$(this).is(":checked"))		
	return false;
vaidateMessageValidation();	
});
$(document).on("change","#validateRule",function(){
	if($("#includeInCombination").prop('checked', true) && !$(this).is(":checked"))		
	return false;
vaidateMessageValidation();	
});
$(document).on("blur","#validationMessage",function(){
	if($("#includeInCombination").prop('checked', true) && !$(this).is(":checked"))		
	return false;
vaidateMessageValidation();	
});
$(document).on("change","#validationMessage",function(){
	if($("#includeInCombination").prop('checked', true) && !$(this).is(":checked"))		
	return false;
vaidateMessageValidation();	
});
$(document).on('change', 'select[fieldname="priceDiffType"]', function () {
var thisVal = $(this).val();
if(thisVal=="N")
{
	var thisID = $(this).attr("id");
	var priceResetID = thisID.split("_");
	$("#attrOptionsGroup_"+priceResetID[1]+"_priceDiff").val("0");
}
}); 
$(document).on('blur', 'input[fieldname="priceDiff"]', function () {
var thisID = $(this).attr("id");
var priceResetID = thisID.split("_");
if($("#attrOptionsGroup_"+priceResetID[1]+"_priceDiffType").val()=="N")
{
	$(this).val("0");
}
}); 
});

function setInputTypeConstraints()
{
	var inputType = $("#inputType").val();
	$(".comboInclude").hide();
	if(inputType=='textbox' || inputType=='time' || inputType=='textarea' || inputType=='date' || inputType=='datetime')
	{
		$(".attributeOptionsSections").hide();	
		$("#optionGrid").removeClass("hide");
		$(".forSelectType").hide();	
		if(attributeMode=='new')
		{
			setRowDelete();	
			//loadOptions();			
		removeDisabled(".forCommonTypeSection");
		$(".forCommonType").show();
		}
		else
		{
			hideDeleteButton();	
		}
		$("#includeInCombination").prop('checked',false);
	}
	else if(inputType=='multiselect' || inputType=='select')
	{
		$(".attributeOptionsSections").show();					
		$(".forSelectType").show();	
		$("#optionGrid").removeClass("hide");
		if(attributeMode=='new')
		{
			$(".isDefaultCheckbox").prop('checked',false);
			setRowDelete();	
			loadOptions(); 
		}
		else
		{
			setTabelDrag();
			hideDeleteButton();	
		}
		if(inputType=='select')
		{
		$(".comboInclude").show();
		if ($("#includeInCombination").is(":checked")) 
		$(".priceSect").hide();
		}
		else
		$("#includeInCombination").prop("checked",false);
					
	}
	else if(inputType=='file')
	{		
		
		$(".attributeOptionsSections").hide();	
		postCallback = '';
		setRowDelete();
		$("#includeInCombination").prop("checked",false);	
	}
	else
	{
		$(".attributeOptionsSections").hide();	
		postCallback = '';	
		setRowDelete();
		$("#includeInCombination").prop("checked",false);	
	}
	setFileTypeFields();
	setCommonTypeFields();
	if(inputType=='textbox' || inputType=='textarea')
	{
		removeDisabled("#validateRule");
		removeDisabled("#value");
		$(".attributeOptionsSections").hide();	
	}
	else
	{
		setDisabled("#validateRule");
		$("#validateRule").val('');		
	}
}
function setDisabled(domField)
{
	$(domField).attr("disabled","disabled");
	$(domField).addClass("disabled");		
}
function removeDisabled(domField)
{
	$(domField).removeAttr("disabled");
	$(domField).removeClass("disabled");		
}
function setReadonly(domField)
{
	$(domField).attr("readonly","readonly");
			
}
function removeReadonly(domField)
{
	$(domField).removeAttr("readonly");
			
}



function loadOptions() 
{
	
	if(postCallback=="1")
	{
		postCallback = '';
		setTabelDrag();
		hideDeleteButton();		
		return false;
	}	
	var inputType = $("#inputType").val();	
	if(inputType=='textbox' || inputType=='textarea')
	{
		if ($(".attributeOptionRow").not('.hide').size() == 1)
		return false;	
	}
	$(".attributeOptionsSections").show();	
	$("#attroptions_loader").removeClass("hide");
    var attrOptionCount = $("#attrOptionAddCount").val();
    $.ajax({
        type: "POST",
		async:false,
        url: GLOBAL_BASE_PATH + '/productoption/ajaxLoadOptionsVariantTpl/',
        data: {
            "attrOptionCount": attrOptionCount,
			"inputType":inputType,
			"optionType":optionType
			
        },
        success: function (data) {		
            $("#attroptions_loader").addClass("hide");
            attrOptionCount = parseInt(attrOptionCount) + 1;
            $("#attrOptionAddCount").val(attrOptionCount)
            $('#attroptions_loader').before(data)
            $("#attroptions_loader").addClass("hide");
	    
	    if(inputType=='multiselect')
	{		
		$(".variant_image").hide();	
	}
	else if (inputType=='select') {
		$(".variant_image").show();
		if ($("#includeInCombination").is(":checked")) 
		$(".priceSect").hide();

	}
			setTabelDrag();
			hideDeleteButton();
			
        }
    });
}

function setRowDelete()
{
	if(postCallback=="1")
	return false;
	$(".attributeOptionsRows").val('1');	
	$(".attributeOptionRow").addClass("hide");
	$(".attributeOptionRow").addClass("nodrag");
	$(".attributeOptionRow").addClass("nodrop");
}

function setTabelDrag()
{
	setPriority();
	if ($(".attributeOptionRow").not('.hide').size() > 1)
	{		
		$("#tableElm").tableDnD({
		onDragClass: "myDragClass",
		onDrop: function(table, row) {
		var	Order	=	escape($.tableDnD.serialize());		
		Order	=	Order.replace(/tableElm%5B%5D%3D/g,'');
		Order	=	Order.replace(/%26/g,'|');
		saveListOrder(Order);
		}		
		});			
	}
	else
	{
		$(".attributeOptionRow").not('.hide').css("cursor","default");	
	}
}

function saveListOrder(order)
{
	if(order)
	{
		var orderList=order.split("|");	
		var priority = 1;		
		for (var i=0;i<orderList.length;i++)
		{ 
			if(orderList[i]!='' && orderList[i]!='attroptions_loader')
			{
				if(!$("#"+orderList[i]).hasClass('hide'))
				{
					var currentID = orderList[i].split("_");
					$("#attrOptionsGroup_"+currentID[1]+"_sortOrder").val(priority);									
					priority++;	
				}				
			}
		}
	}
}

function hideDeleteButton()
{	
	if ($(".attributeOptionRow").not('.hide').size() > 1)
	{
		$(".attributeOptionRow").not('.hide').find(".deleteRow").removeClass('delete03-inactive');
		$(".attributeOptionRow").not('.hide').find(".deleteRow").addClass('delete03');		
		$(".attributeOptionRow").not('.hide').find(".deleteRow").show();	
	}
	else
	{
		$(".attributeOptionRow").not('.hide').find(".deleteRow").removeClass('delete03');
		$(".attributeOptionRow").not('.hide').find(".deleteRow").addClass('delete03-inactive');		
	}
}
function setPriority()
{
	var priority = 1;
	$(".attributeOptionRow").each(function(index, element) {
        if(!$(this).hasClass('hide'))
		{
			var currentID = $(this).attr("id");
			var currentRow = currentID.split("_");
			$("#attrOptionsGroup_"+currentRow[1]+"_sortOrder").val(priority);
			priority++;			
		}
    });	
}
function setFileTypeFields()
{
	var inputType = $("#inputType").val();
	if(inputType=='file')
	{
		$(".forFileType").show();	
		removeDisabled(".forFileTypeSection");	
	}
	else
	{
		$(".forFileType").hide();
		$(".forFileTypeSection").val('');
		setDisabled(".forFileTypeSection");	
	}
}
function checkAttributeOptions()
{
	var optionTitle = new Array();
	$('input[fieldname="valueTitle"]').each(function(index, element) {
      if(!$(this).parent(".attributeOptionRow").hasClass('.hide'))
	  {
			var optionName = $(this).val();
			optionName = $.trim(optionName);
			if(optionName!='')
			optionTitle.push(optionName);
	  }
    });
	var arrayLength = optionTitle.length;	
	if($.unique(optionTitle).length!=arrayLength && arrayLength>0)
	{
		jAlert(msgSelectDifferentNamesoption);
		return false;
	}
	return true;
}
function vaidateMessageValidation()
{
	if(($("#validateRuleRequired").prop('checked', true) || $("#validateRule").val()!='') && ($.trim($("#validationMessage").val())==''))
	{
		$("#checkValidationMessage").val('0');	
	}
	else
	{
		$("#checkValidationMessage").val('1');	
	}
	if($("#validateRuleRequired").prop('checked',true) || $("#validateRule").val()!='')
	{
		removeDisabled("#validationMessage");	
	}
	else
	{
		$("#validationMessage").val('');
		setDisabled("#validationMessage");
		$("#div_err_formAttributeAdd_validationMessage").addClass("hide");
	}
	if($("#validateRuleRequired").prop('checked', true))
	{	
	$("#msgReq").addClass("mandatory");
	}
	else
	{
	$("#msgReq").removeClass("mandatory");	
	}
}

function setCommonTypeFields()
{
	var inputType = $("#inputType").val();
	if(inputType=='textbox' || inputType=='textarea' || inputType=='date' || inputType=='datetime' || inputType=='time')
	{
		$(".forCommonType").show();	
		removeDisabled(".forCommonTypeSection");		
		$(".attributeOptionsSections").hide();
	}
	
	else
	{
		$(".forCommonType").hide();
		$(".forCommonTypeSection").val('');
		setDisabled(".forCommonTypeSection");	
	}
}

 function deletevariantImages(opid,imageType) {
	var curr_id = Math.random();
var fileName = $("#OptionVariant"+imageType+"_"+opid+"_temp").val();
var nofile = $("#no_image_path").val();
        jConfirm(msgimageDelConfirm, 'Delete', function (r) {
            if (r == true) {
$.ajax({
type: "GET",
url: GLOBAL_BASE_PATH+"/AjaxUploadImage/uploads/",
data: "fileFieldName="+encodeURIComponent(fileName)+"&method=delete&curr_id="+opid+"/",
success: function (data) {
$("#div_upload_sub_OptionVariant"+imageType+"_"+opid).html("<img style=\"padding-top:2px;cursor:pointer;\" src=\""+nofile+"\" width=\"77\" id=\"imageFileOptionVariant"+imageType+"_"+opid+"\" />");
$("#imageEditboxOptionVariant"+imageType+"_"+opid).css("display","none");
$("#noImageCheckbox").css("display","none");
$("#OptionVariant"+imageType+"_"+opid+"").val("");
$("#OptionVariant"+imageType+"_"+opid+"").val("");
$("#OptionVariant"+imageType+"_"+opid+"Url").val("");
}
});

	    }	    
	    
        });  
}
$(document).on("click","#includeInCombination",function () {
		if ($("#includeInCombination").is(":checked")) 
		{
		$(".priceSect").hide();		
		if(!$("#validateRuleRequired").is(":checked"))
		$('#validateRuleRequired').trigger('click');
		}
		else
		$(".priceSect").show();		
	});
