if (typeof attrOptionData=='undefined')
var attrOptionData = "";
if (typeof attrData=='undefined')
var attrData = "";
var appendedConditionDataID = $(".promoConditionAppended").length;
var appendedConditionRootDataID = $(".promoRoot").length;
var currentPromoRoot = '';
var currentPromoRootRel = '';
var currentPopupPicker = '';
var appendedBonusDataID = $(".promoBonusAppended").length;
var appendedBonusRootDataID = $(".promoBonusRoot").length;
var currentTab = $(".left-tab li a.active").attr("section");
var currentPromoBonusRoot = '';
var currentPromoBonusRootRel = '';
$(document).ready(function ()
{
	$(".left-tab li:first").css("border-top-width","1px");
	/* $('.date_picker_field').datepicker({showTime: false,					 
					  dateFormat:datePickerDateFormat}); */

	//- date picker only
	/*$("#fromDate").daterangepicker({
		singleDatePicker: true ,
     	startDate: new Date(), 
    	format:datePickerDateFormat,
		onSelect: function (date) {
			var dt2 = $('#toDate');
			var minDate = $(this).datepicker('getDate');
			dt2.datepicker('setDate', minDate);
			dt2.datepicker('option', 'minDate', minDate);
		}
	});*/
	//- date picker only
	/*$('#toDate').daterangepicker({
		singleDatePicker: true ,
     	startDate: new Date(), 
    	format:datePickerDateFormat,
		minDate:  $("#fromDate").datepicker('getDate')
	});*/

//To set edit picker
/* $('.enableDatePicker').daterangepicker({
                    singleDatePicker: true , 
                    startDate: new Date(),
					showTime: false,
					format:'YYYY-MM-DD'
    });
$('.enableDefaultDatePicker').daterangepicker({
                    singleDatePicker: true , 
                    startDate: new Date(),
					showTime: false,
					format:'YYYY-MM-DD'
    });	 */
 $('.enableDatePicker').datepicker({
       minDate:  new Date()
    });
   $('.enableDefaultDatePicker').datepicker({
                    singleDatePicker: true , 
                    startDate: new Date(),
					showTime: false,
					format:'YYYY-MM-DD'
    });		
	
	$(document).on('click','.promotionAddCondition', function () {	
		currentPromoRoot = $(this).closest(".promoRoot");
		currentPromoRootRel = $(this).closest(".promoRoot").attr("rel");
		setConditionSelector();
		unsetCustomText("#promoConditionRootSelector");
	});
	
	$(document).on('click','.promotionAddGroup', function () {	
		$(".promoRootConditionSelector").addClass("hide");
		currentPromoRoot = $(this).closest(".promoRoot");
		currentPromoRootRel = $(this).closest(".promoRoot").attr("rel");
		addPromoGroup();
	});
	
	$(document).on("change","#promoConditionRootSelector",function(){
		var currCondition = $(this).val();
		var selectedOptionType = $('option:selected', this).attr('datatype');
		var optiongroup = $('option:selected', this).attr('optiongroup');
		setConditionSelector();
				if(currCondition=="products"){
					if($('#store_id option:selected').val()>0){
						var productLink=	$( ".popupPicker[rel='products']").attr('href');		productLink =	productLink+"sid/"+$('#store_id option:selected').val()+"/";
						$( ".popupPicker[rel='products']").attr('href',productLink);	
					}	
				}			
		if(currCondition=="attributes")
		{			
                    
			if(attrData=='')
			{
				$.ajax({
					type: "POST",
					async: false,
					url: GLOBAL_BASE_PATH + "/promotions/ajaxLoadAttributes/",
					data: '',
					success: function (data) {
						var attr = jQuery.parseJSON(data);
						var attrForOption = '';
						if(attr.attributeArray)
						{
							$.each(attr.attributeArray, function(index, value) {
								attrForOption = attrForOption + '<option value="'+value['attributeID']+'" attrInputType="'+value['attrInputType']+'">'+value['attrName']+'</option>';
							});
						}	
						$(".promoConditionCopySource").find(".promotionCondtionElement_"+currCondition).append(attrForOption);		
						attrData = attr.attributeArray;
						attrOptionData = attr.attrOptionArray;
						appendNewCondition(currCondition);
					}
				});	
			}
			else //If already made a request
			appendNewCondition(currCondition);
		}
		else if(selectedOptionType=="select")
		{			
			if($(".promoConditionCopySource").find(".selectSelectBox_"+currCondition+" option").length==0)
			{			
				var ajaxurl = '';
				if(currCondition=="usergroup")
				ajaxurl = '/newsletter/ajaxLoadCustomerGroups/';
				else if(currCondition=="country" || currCondition=="billingcountry" )
				ajaxurl = '/promotions/ajaxLoadCountry/';
				else if(currCondition=="state" || currCondition=="billingstate" )
				ajaxurl = '/promotions/ajaxLoadState/';
				else if(currCondition=="payment_method")
				ajaxurl = '/promotions/ajaxLoadPaymentMethod/';
				else if(currCondition=="shipping_method")
				 ajaxurl = '/promotions/ajaxLoadShippingMethods/';				
				$.ajax({
					type: "POST",
					async: false,
					url: GLOBAL_BASE_PATH + ajaxurl,
					data: '',
					success: function (data) {
						var resList = jQuery.parseJSON(data);
						var resDataForOption = '';
						if(optiongroup=='Yes'){
							for(groupKey in resList.resData){
								resDataForOption+="<optgroup label='"+groupKey+"'>";
									for(optionKey in resList.resData[groupKey]){
										var optionData = resList.resData[groupKey]
										resDataForOption += '<option value="'+optionData[optionKey][0]+'">'+optionData[optionKey][1]+'</option>';
									}
							}
						}
						else{
							$.each(resList.resData, function(index, value) {
								resDataForOption = resDataForOption + '<option value="'+value[resList.fields.ID]+'">'+value[resList.fields.value]+'</option>';
							});
						}
						$(".promoConditionCopySource").find(".selectSelectBox_"+currCondition).append(resDataForOption);		
						appendNewCondition(currCondition);
					}
				});	
			}
			else{ //If already made a request
			appendNewCondition(currCondition);
			}
					
		}
		else
		appendNewCondition(currCondition,'',selectedOptionType);
	});
		$(document).on("click",'#submitRule', function () {
		parent.$.colorbox.close();


     });
	$(document).on("change",".promotionCondtionElement_attributes,.promotionBonusElement_attributes",function(){
		var option = $(this).val();		
		var selectedAttrType = $('option:selected', this).attr('attrInputType');
		$(this).nextAll(".mixedSelectBox:first").empty();
		$(this).nextAll(".mixedTextBox:first").val('');
		$(this).nextAll(".mixedTextBox:first").removeClass("enableDatePicker enableDateTimePicker enableTimePicker");
		$(this).nextAll(".mixedTextBox:first").datepicker("destroy");
		$(this).nextAll(".mixedselectors").val('');
		$(this).nextAll(".mixedselectors").addClass("hide");
		if(selectedAttrType!='')
		$(this).nextAll(".mixedselectors[mixedselector='"+selectedAttrType+"']:first").removeClass("hide");
		//Select Box Types
		if(option>0 && typeof attrOptionData[option]!='undefined')
		{
			var attrForOption = '';
			$.each(attrOptionData[option], function(index, value) {
				attrForOption = attrForOption + '<option value="'+index+'">'+value+'</option>';
			});
			$(this).nextAll(".mixedSelectBox:first").append(attrForOption);	
			$(this).nextAll(".mixedTextBox:first").addClass("hide");
			$(this).nextAll(".mixedSelectBox:first").removeClass("hide");
		}	
		else
		{
			$(this).nextAll(".mixedSelectBox:first").addClass("hide");
			$(this).nextAll(".mixedTextBox:first").removeClass("hide");	
			if(selectedAttrType=="date")
			$(this).nextAll(".mixedTextBox:first").addClass("enableDatePicker");
			else if(selectedAttrType=="datetime")
			$(this).nextAll(".mixedTextBox:first").addClass("enableDateTimePicker");
			else if(selectedAttrType=="time")
			$(this).nextAll(".mixedTextBox:first").addClass("enableTimePicker");
			
			setDateTimePickers();		
		}	
	});	
	
	$(document).on('click','.deleteConditionRow', function () {	
		deleteRow($(this));
	});
	
	$(document).on('click','.deleteGroupRow', function () {	
		deleteGroup($(this));
	});
	
	$(document).on('click','.deleteBonusGroupRow', function () {	
		deleteBonusGroup($(this));
	});
	
	$(document).on('click','.popupPicker', function (e) {	
		e.preventDefault();
		currentPromoRoot = $(this).closest(".promoRoot");
		currentPromoRootRel = $(this).closest(".promoRoot").attr("rel");
		currentPopupPicker = $(this);
		var url = currentPopupPicker.attr('href');
		var title = currentPopupPicker.attr('title');
		//$.colorbox.remove();
		//$.colorbox({iframe:true,width:"70%", height:"70%",href:url,title:title});
	});
	
	$(document).on('click','.deletePickerDataRow', function () {			
		deletePickerDataRow($(this));
	});
	
	$(document).on("change","#promoDiscountBonus",function(){
		setBonusPriceValidation();
	});	
	
	$(document).on("change","#couponType",function(){
		setCouponType();
	});	
	
	$(document).on("keydown",".isWholeNumberWithZeroClass",function(event) {		
		if ( event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 8 || event.keyCode == 9) 
		{
			
		} 
		else 
		{
			if (event.keyCode < 95) 
			{
				if (event.keyCode < 48 || event.keyCode > 57 ) 
				{
					event.preventDefault();
				}
			} 
			else 
			{
				if (event.keyCode < 96 || event.keyCode > 105) 
				{
					event.preventDefault();
				}				
			}
			if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) 
			{
				event.preventDefault(); 
			}  
		}
	});
	
	$(document).on('click','.promotionAddBonus', function () {
		currentPromoBonusRoot = $(this).closest(".promoBonusRoot");
		currentPromoBonusRootRel = $(this).closest(".promoBonusRoot").attr("rel");
		setBonusSelector();
	});
	
	$(document).on('click','.promotionAddBonusGroup', function () {	
		$(".promoRootBonusSelector").addClass("hide");
		currentPromoBonusRoot = $(this).closest(".promoBonusRoot");
		currentPromoBonusRootRel = $(this).closest(".promoBonusRoot").attr("rel");
		addPromoBonusGroup();
	});
	
	$(document).on("change","#promoBonusRootSelector",function(){
		var currBonus = $(this).val();
		var selectedOptionType = $('option:selected', this).attr('datatype');
		var optiongroup = $('option:selected', this).attr('optiongroup');
		setBonusSelector();
		if(currBonus=="attributes")
		{			
			if(attrData=='')
			{
				$.ajax({
					type: "POST",
					async: false,
					url: GLOBAL_BASE_PATH + "/promotions/ajaxLoadAttributes/",
					data: '',
					success: function (data) {
						var attr = jQuery.parseJSON(data);
						var attrForOption = '';
						if(attr.attributeArray)
						{
							$.each(attr.attributeArray, function(index, value) {
								attrForOption = attrForOption + '<option value="'+value['attributeID']+'" attrInputType="'+value['attrInputType']+'">'+value['attrName']+'</option>';
							});
						}	
						$(".promoBonusCopySource").find(".promotionBonusElement_"+currBonus).append(attrForOption);		
						attrData = attr.attributeArray;
						attrOptionData = attr.attrOptionArray;
						appendNewBonus(currBonus);
					}
				});	
			}
			else //If already made a request
			appendNewBonus(currBonus);
		}
		else if(selectedOptionType=="select")
		{			
			if($(".promoBonusCopySource").find(".selectSelectBox_"+currBonus+" option").length==0)
			{
				var ajaxurl = '';
				if(currBonus=="usergroup")
				ajaxurl = '/newsletter/ajaxLoadCustomerGroups/';
				else if(currBonus=="country" || currBonus=="billingcountry" )
				ajaxurl = '/promotions/ajaxLoadCountry/';
				else if(currBonus=="state" || currBonus=="billingstate" )
				ajaxurl = '/promotions/ajaxLoadState/';
				else if(currBonus=="payment_method")
				ajaxurl = '/promotions/ajaxLoadPaymentMethod/';
				else if(currBonus=="shipping_method")
				 ajaxurl = '/promotions/ajaxLoadShippingMethods/';				
				$.ajax({
					type: "POST",
					async: false,
					url: GLOBAL_BASE_PATH + ajaxurl,
					data: '',
					success: function (data) {
						var resList = jQuery.parseJSON(data);
						var resDataForOption = '';
						if(optiongroup=='Yes'){
							for(groupKey in resList.resData){
								resDataForOption+="<optgroup label='"+groupKey+"'>";
									for(optionKey in resList.resData[groupKey]){
										var optionData = resList.resData[groupKey]
										resDataForOption += '<option value="'+optionData[optionKey][0]+'">'+optionData[optionKey][1]+'</option>';
									}
							}
						}
						else{
							$.each(resList.resData, function(index, value) {
								resDataForOption = resDataForOption + '<option value="'+value[resList.fields.ID]+'">'+value[resList.fields.value]+'</option>';
							});
						}
						$(".promoBonusCopySource").find(".selectSelectBox_"+currBonus).append(resDataForOption);		
						appendNewBonus(currBonus);
					}
				});	
			}
			else //If already made a request
			appendNewBonus(currBonus);
		}		
		else
		appendNewBonus(currBonus,'',selectedOptionType);
	});	
	
	$(document).on('click','.deleteBonusRow', function () {	
		deleteBonusRow($(this));
	});
	
	$(document).on('click',"#submitCouponCodeDelete",function() 
	{ 
		if($(".ListAll:checked").size()==0)	{
		jAlert(lblSelectItem);
		return false;
		}   
		var changeStatus= $('#deleteCouponCode').val();
		if(changeStatus=='D')	{
		 jConfirm(msgConfirmDelete, 'Alert', function(r) {
			  if(r==true) { $("#changeCouponStatus").submit();	}
		  });
		} else if(changeStatus=='') {
		  jAlert(msgSelectAStatus);	  
		  return false;		
		} else	{
		  return true;		
		}
	  return false;	
	}); 
	
	$(document).on('click','#add_free_products', function (e) {	
		e.preventDefault();
		var url = $(this).attr('href');
		var title = $(this).attr('title');
		$.colorbox({iframe:true,width:"70%", height:"70%",href:url,title:title});
	});
	
	$(document).on('click','.deleteFreeProductsDataRow', function () {			
		deleteFreeProductDataRow($(this));
	});
	
	$(document).on("change",".promoBonusFreeProductsQuantity",function(){
		updateFreeProductsValue();
	});

});




setBonusPriceValidation();
setCouponType();
setAttributeOperators();
//To set edit picker

/*$('.enableDatePicker').datepicker({showTime: false,					 
			dateFormat:datePickerDateFormat});
$('.enableDefaultDatePicker').datepicker({showTime: false,					 
			dateFormat:'yy-mm-dd'});*/
setDateTimePickers();
setLastItemStyle();

function setConditionSelector()
{
	if($(".promoRootConditionSelector").hasClass("hide"))
	$(".promoRootConditionSelector").removeClass("hide");
	else
	$(".promoRootConditionSelector").addClass("hide");
	
	$("#promoConditionRootSelector").val('');
	unsetCustomText("#promoConditionRootSelector");
}	
function appendNewCondition(currentKey,currentHtml,currentSelectedType)
{
	appendedConditionDataID = appendedConditionDataID + 1;
	
	//Check Element Existence
	var childrenLengthCheck =parseInt($(currentPromoRoot).children('.promoConditionAppended').length) + 1;
	var reWriteVarCheck = currentPromoRootRel+'[conditions]['+childrenLengthCheck+']';
	while($("input[name='promotion_data[conditions]" + reWriteVarCheck +"[condition]']").length!=0)
	{
		appendedConditionDataID = appendedConditionDataID + 1;
		childrenLengthCheck = childrenLengthCheck  + 1;
		reWriteVarCheck = currentPromoRootRel+'[conditions]['+childrenLengthCheck+']';
	}
	
	if(currentKey)
	var currentHtml = $( ".dataCondition_"+currentKey).html();
	
	currentPromoRoot.append('<li class="clearfix promoConditionAppended" id="promoConditionAppended_'+appendedConditionDataID+'">'+currentHtml+'</li>');	
	
	//var childrenLength=$(currentPromoRoot).children('.promoConditionAppended').length;
	
	$(currentPromoRoot).children('.promoConditionAppended').removeClass("cm-last-item");
	$('#promoConditionAppended_'+appendedConditionDataID).addClass("cm-last-item");
	
	var reWriteVar = currentPromoRootRel+'[conditions]['+childrenLengthCheck+']';
	
	var promotionCondtion = $('#promoConditionAppended_'+appendedConditionDataID).find("input[name^='promotionCondtion-']");
	promotionCondtion.attr('name', 'promotion_data[conditions]' + reWriteVar +'[condition]');
	
	var promotionCondtionGroup = $('#promoConditionAppended_'+appendedConditionDataID).find("input[name^='promotionCondtionGroup-']");
	promotionCondtionGroup.attr('name', 'promotion_data[conditions]' + reWriteVar +'[condition_group]');
	
	var promotionCondtionElement = $('#promoConditionAppended_'+appendedConditionDataID).find("select[name^='promotionCondtionElement-']");
	promotionCondtionElement.attr('name', 'promotion_data[conditions]' + reWriteVar +'[condition_element]');
	
	var promotionCondtionOperator = $('#promoConditionAppended_'+appendedConditionDataID).find("select[name^='promotionCondtionOperator-']");
	promotionCondtionOperator.attr('name', 'promotion_data[conditions]' + reWriteVar +'[operator]');
	
	var promotionCondtionValue = $('#promoConditionAppended_'+appendedConditionDataID).find("input[name^='promotionCondtionValue-']");
	promotionCondtionValue.attr('name', 'promotion_data[conditions]' + reWriteVar +'[value]');
	
	var promotionCondtionValueSelect = $('#promoConditionAppended_'+appendedConditionDataID).find("select[name^='promotionCondtionValueSelect-']");
	promotionCondtionValueSelect.attr('name', 'promotion_data[conditions]' + reWriteVar +'[value_select]');
	var promotionCondtionValueNum = $('#promoConditionAppended_'+appendedConditionDataID).find("select[name^='promotionCondtionValueNum-']");
	promotionCondtionValueNum.attr('name', 'promotion_data[conditions]' + reWriteVar +'[valueNum]');	
	var promotionCondtionValueFrom = $('#promoConditionAppended_'+appendedConditionDataID).find("input[name^='promotionCondtionValueFrom-']");
	promotionCondtionValueFrom.attr('name', 'promotion_data[conditions]' + reWriteVar +'[valueFrom]');
	promotionCondtionValueFrom.attr('id', 'promotionCondtionValueFrom-' + appendedConditionDataID);
	
	var promotionCondtionValueTo = $('#promoConditionAppended_'+appendedConditionDataID).find("input[name^='promotionCondtionValueTo-']");
	promotionCondtionValueTo.attr('name', 'promotion_data[conditions]' + reWriteVar +'[valueTo]');
	promotionCondtionValueTo.attr('id', 'promotionCondtionValueTo-' + appendedConditionDataID);
	
	setNoConditions();
	if(currentSelectedType=='inputDate')
	{
		promotionCondtionValueFrom.addClass('enableDefaultDatePicker');
		promotionCondtionValueTo.addClass('enableDefaultDatePicker');		
		setDateTimePickers();
		$('.enableDefaultDatePicker').datepicker({
                    singleDatePicker: true , 
                    startDate: new Date(),
					showTime: false,
                    format:'YYYY-MM-DD'
    });
	}
	
}	
function deleteRow(thisVar)
{
	var closestPromoRoot = thisVar.closest(".promoRoot");
	thisVar.closest(".promoConditionAppended").remove();	
	closestPromoRoot.children('.promoConditionAppended').removeClass("cm-last-item");
	closestPromoRoot.children('.promoConditionAppended:last').addClass("cm-last-item");
	setNoConditions();
}
function deleteGroup(thisVar)
{
	thisVar.closest(".promoConditionAppended").remove();	
	setLastItemStyle('condition');
	setNoConditions();
}	
function deleteBonusGroup(thisVar)
{
	thisVar.closest(".promoBonusAppended").remove();	
	setLastItemStyle('bonus');
	setNoBonus();
}	
function addPromoGroup()
{
	appendedConditionRootDataID = appendedConditionRootDataID + 1;
	
	//Check Element Existence
	var childrenLengthCheck =parseInt($(currentPromoRoot).children('.promoConditionAppended').length) + 1;
	var reWriteVarCheck = currentPromoRootRel+'[conditions]['+childrenLengthCheck+']';
	while($("select[name='promotion_data[conditions]" + reWriteVarCheck +"[set]']").length!=0)
	{
		appendedConditionRootDataID = appendedConditionRootDataID + 1;
		childrenLengthCheck = childrenLengthCheck  + 1;
		reWriteVarCheck = currentPromoRootRel+'[conditions]['+childrenLengthCheck+']';
	}
	
	//var childrenLength=$(currentPromoRoot).children('.promoConditionAppended').length;
	
	//childrenLength = childrenLength + 1;
	
	var relForRoot = currentPromoRootRel+'[conditions]['+childrenLengthCheck+']';
	
	var currentHtml = '<ul class="levl-00 promoRoot" rel="'+relForRoot+'" id="promoRootConditionAppended_'+appendedConditionRootDataID+'">'+$( ".promoRootNode").html()+'</ul>';	
	appendNewCondition('',currentHtml);	
	
	var promotionCondtionSet = $('#promoRootConditionAppended_'+appendedConditionRootDataID).find("select[name^='promotionCondtionSet-']");
	promotionCondtionSet.attr('name', 'promotion_data[conditions]' + relForRoot +'[set]');
	
	var promotionCondtionSetValue = $('#promoRootConditionAppended_'+appendedConditionRootDataID).find("select[name^='promotionCondtionSetValue-']");
	promotionCondtionSetValue.attr('name', 'promotion_data[conditions]' + relForRoot +'[set_value]');
}	
function addItemFromPicker(dataObj)
{	
	var appendHtml = '';
	var ids = '';
	if(dataObj)
	{		
		var popupPickerDataValue = currentPopupPicker.nextAll().find(".popupPickerDataList .popupPickerDataValues").val();
		var popupPickerDataValues = popupPickerDataValue.split(",");
		$.each(dataObj, function( key, value ) {			
			if($.inArray(value.id, popupPickerDataValues)==-1)
			{
				var appendTitle = '';
				var appendOptions = '';
				var appendQuantity = '';
				if(typeof value.options!='undefined' && !jQuery.isEmptyObject(value.options))
				{
					if(currentTab=='conditions')
					{						
						var childrenLength=$(currentPromoRoot).children('.promoConditionAppended').length;
						var reWriteVar = currentPromoRootRel+'[conditions]['+childrenLength+']';
						$.each(value.options, function( optKey, optValue ) {
							appendTitle = appendTitle + optValue.title + ",";
							appendOptions = appendOptions + '<input type="hidden" class="popupPickerDataSubValues" name="promotion_data[conditions]' + reWriteVar +'[options][' + value.id +'][combinations][' + optValue.id +']" value="'+optValue.id+'">';
						});
						appendTitle = appendTitle.substring(0,appendTitle.length-1);
						appendTitle = value.title +' : '+ appendTitle + appendOptions;
					}	
					else if(currentTab=='bonus')
					{
						var childrenLength=$(currentPromoBonusRoot).children('.promoBonusAppended').length;
						var reWriteVar = currentPromoBonusRootRel+'[bonuses]['+childrenLength+']';	
						$.each(value.options, function( optKey, optValue ) {
							appendTitle = appendTitle + optValue.title + ",";
							appendOptions = appendOptions + '<input type="hidden" class="popupPickerDataSubValues" name="promotion_data[bonuses]' + reWriteVar +'[options][' + value.id +'][combinations][' + optValue.id +']" value="'+optValue.id+'">';
						});
						appendTitle = appendTitle.substring(0,appendTitle.length-1);
						appendTitle = value.title +' : '+ appendTitle + appendOptions;
					}
				}
				else
				{
					appendTitle = value.title;
				}	
				if(value.enableQuantity=="Yes")
				{
					appendQuantity = appendQuantity + '<td width="20%">';
					if(currentTab=='bonus')
					{
						var childrenLength=$(".promoBonusRoot").children('.promoBonusAppended').length;
						var reWriteVar = '['+childrenLength+']';
						appendQuantity = appendQuantity +'<span class="small_qty">'+lblPromoProductQuantity+'</span><input type="text" class="textbox small_txt_fld isWholeNumberWithZeroClass" name="promotion_data[bonuses]' + reWriteVar +'[quantities][' + value.id +'][quantity]" value="1">';						
					}
					appendQuantity = appendQuantity + '</td>';
					var titleTdWidth = '75%';
				}
				else
				var titleTdWidth = '95%';
				
				appendHtml = appendHtml + '<tr class="pickerDataList" rel="'+ value.id +'"><td width="'+titleTdWidth+'">' + appendTitle + '</td>'+appendQuantity+'<td align="right"><a href="Javascript:void(0);" class="deletePickerDataRow" rel="'+ value.id +'" title="'+lblDelete+'">X</a></td></tr>';
			}	
		});
	}
	var pickerDataList = currentPopupPicker.nextAll().find(".popupPickerDataList tr.pickerDataList");
	if(pickerDataList.length>0)
	{		
		if(appendHtml!='')
		currentPopupPicker.nextAll().find(".popupPickerDataList tr.pickerDataList:last").after(appendHtml);
	}
	else if(appendHtml!='')
	{
		currentPopupPicker.nextAll().find(".popupPickerDataList tr.noRecordsForPicker").addClass("hide");
		currentPopupPicker.nextAll().find(".popupPickerDataList tr.noRecordsForPicker").after(appendHtml);
	}
	var pickerDataList = currentPopupPicker.nextAll().find(".popupPickerDataList tr.pickerDataList");
	pickerDataList.each(function () { 
		ids = ids + $(this).attr("rel") +',';
	});
	updatePopupPickerDataValue(currentPopupPicker.nextAll().find(".popupPickerDataList .popupPickerDataValues"),ids);
}

function deletePickerDataRow(thisVar)
{
	var ids = '';
	var currentId = thisVar.attr("rel");
	var popupPickerDataList = thisVar.closest(".popupPickerDataList");
	var dataLength = popupPickerDataList.find(".pickerDataList").length;
	var noRecords  = popupPickerDataList.find(".noRecordsForPicker"); 	
	popupPickerDataList.find(".pickerDataList").each(function () { 
		var thisRel = $(this).attr("rel");
		if(thisRel!=currentId)
		ids = ids + thisRel +',';
	});	
	thisVar.closest(".pickerDataList").remove();	
	dataLength = dataLength - 1;
	if(dataLength==0)
	noRecords.removeClass("hide");	
	updatePopupPickerDataValue(popupPickerDataList.find(".popupPickerDataValues"),ids);	
}
function updatePopupPickerDataValue(applyObj,value)
{
	applyObj.val(value.substring(0,value.length-1));	
}	
function setBonusPriceValidation()
{
	var promoDiscountBonus = $("#promoDiscountBonus").val();
	if(promoDiscountBonus!='')
	{
		if(promoDiscountBonus=="by_percentage")
		$("#promoBonusType").val('Percentage');
		else
		$("#promoBonusType").val('Price');
		$("#promoDiscountBonusValue").attr("readonly",false);
		$("#promoDiscountBonusValue").removeClass("disabled");
	}
	else	
	{
		$("#promoBonusType").val('');
		$("#promoDiscountBonusValue").val('');
		$("#promoDiscountBonusValue").attr("readonly",true);
		$("#promoDiscountBonusValue").addClass("disabled");
	}	
}
function setDateTimePickers()
{
	/*$('.enableDatePicker').datepicker({showTime: false,					 
			dateFormat:datePickerDateFormat});
		$('.enableDateTimePicker').datetimepicker({dateFormat:datePickerDateFormat});
	$('.enableTimePicker').timepicker({ampm: false,stepMinute: 15});
			*/
			//  - date picker only
	/*   $('.enableDatePicker').daterangepicker({
		  	singleDatePicker: true , 
            startDate: new Date(),
			format:datePickerDateFormat
			});
			//  - date time picker only
		$('.enableDateTimePicker').daterangepicker({
		  	singleDatePicker: true , 
            startDate: new Date(),
		  	timePicker: true,
			timePickerIncrement: 1,
			timePicker12Hour: false,
            format:'YYYY-MM-DD HH:mm:SS'			 
			}); */
			//  - time picker only	
		$('.enableTimePicker').datepicker({
			singleDatePicker: true ,
			timePicker:true,
			timePicker12Hour: false,  
			datePicker:false, 
			format:'HH:mm:SS'
			});	
 $('.enableDateTimePicker').datepicker({
       		  	singleDatePicker: true , 
            startDate: new Date(),
		  	timePicker: true,
			timePickerIncrement: 1,
			timePicker12Hour: false,
            format:'YYYY-MM-DD HH:mm:SS'	
    });
   $('.enableTimePicker').datepicker({
			singleDatePicker: true ,
			timePicker:true,
			timePicker12Hour: false,  
			datePicker:false, 
			format:'HH:mm:SS'
    });				
	
}
function setCouponType()
{
	if($("#couponType"))
	{
		var couponType = $("#couponType").val();
		$("#currentCouponType").val(couponType);
		if(couponType=="2")
		$(".specificCouponSelect").removeClass("hide");
		else
		$(".specificCouponSelect").addClass("hide");			
		
		if(couponType!="3")
		{
			$(".generateCouponCodesListing :input").prop("disabled","disabled");
			$(".generateCouponCodesListing :input[type!='submit']").addClass("disabled");
			$(".generateCouponCodesListing .message_validation").addClass("hide");
			$(".generateCouponCodesListing .pagination-layout").addClass("hide");
		}
		else
		{
			$(".generateCouponCodesListing :input").removeAttr("disabled");
			$(".generateCouponCodesListing :input[type!='submit']").removeClass("disabled");
			$(".generateCouponCodesListing .pagination-layout").removeClass("hide");
		}
	}	
}	
function setBonusSelector()
{
	if($(".promoRootBonusSelector").hasClass("hide"))
	$(".promoRootBonusSelector").removeClass("hide");
	else
	$(".promoRootBonusSelector").addClass("hide");
	
	$("#promoBonusRootSelector").val('');
	unsetCustomText("#promoBonusRootSelector");
}
function appendNewBonus(currentKey,currentHtml,currentSelectedType)
{
	appendedBonusDataID = appendedBonusDataID + 1;
	//Check Element Existence
	var childrenLengthCheck =parseInt($(currentPromoBonusRoot).children('.promoBonusAppended').length) + 1;
	var reWriteVarCheck = currentPromoBonusRootRel+'[bonuses]['+childrenLengthCheck+']';
	while($("input[name='promotion_data[bonuses]" + reWriteVarCheck +"[bonus]']").length!=0)
	{
		appendedBonusDataID = appendedBonusDataID + 1;
		childrenLengthCheck = childrenLengthCheck  + 1;
		reWriteVarCheck = currentPromoBonusRootRel+'[bonuses]['+childrenLengthCheck+']';
	}
	
	if(currentKey)
	var currentHtml = $( ".promoBonus_"+currentKey).html();
	currentPromoBonusRoot.append('<li class="clearfix promoBonusAppended" id="promoBonusAppended_'+appendedBonusDataID+'">'+currentHtml+'</li>');	

	$(currentPromoBonusRoot).children('.promoBonusAppended').removeClass("cm-last-item");
	$('#promoBonusAppended_'+appendedBonusDataID).addClass("cm-last-item");
	
	var reWriteVar = currentPromoBonusRootRel+'[bonuses]['+childrenLengthCheck+']';

	var promoBonus = $('#promoBonusAppended_'+appendedBonusDataID).find("input[name^='promotionBonus-']");
	promoBonus.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[bonus]');
	
	var promoBonusGroup = $('#promoBonusAppended_'+appendedBonusDataID).find("input[name^='promotionBonusGroup-']");
	promoBonusGroup.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[bonus_group]');
	
	var promotionBonusElement = $('#promoBonusAppended_'+appendedBonusDataID).find("select[name^='promotionBonusElement-']");
	promotionBonusElement.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[condition_element]');
	
	var promotionBonusOperator = $('#promoBonusAppended_'+appendedBonusDataID).find("select[name^='promotionBonusOperator-']");
	promotionBonusOperator.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[operator]');
	
	var promotionBonusDataValue = $('#promoBonusAppended_'+appendedBonusDataID).find("input[name^='promotionBonusValue-']");
	promotionBonusDataValue.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[value]');	
	var promotionBonusValueSelect = $('#promoBonusAppended_'+appendedBonusDataID).find("select[name^='promotionBonusValueSelect-']");
	promotionBonusValueSelect.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[value_select]');
	var promotionBonusValueFrom = $('#promoBonusAppended_'+appendedBonusDataID).find("input[name^='promotionBonusValueFrom-']");
	promotionBonusValueFrom.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[valueFrom]');
	promotionBonusValueFrom.attr('id', 'promotionBonusValueFrom-' + appendedBonusDataID);		
	var promotionBonusValueTo = $('#promoBonusAppended_'+appendedBonusDataID).find("input[name^='promotionBonusValueTo-']");
	promotionBonusValueTo.attr('name', 'promotion_data[bonuses]' + reWriteVar +'[valueTo]');
	promotionBonusValueTo.attr('id', 'promotionBonusValueTo-' + appendedBonusDataID);
	setNoBonus();	
	if(currentSelectedType=='inputDate')
	{
		promotionBonusValueFrom.addClass('enableDefaultDatePicker');
		promotionBonusValueTo.addClass('enableDefaultDatePicker');		
		setDateTimePickers();
/* 		$('.enableDefaultDatePicker').daterangepicker({
                    singleDatePicker: true , 
                    startDate: new Date(),
					showTime: false,
                    format:'YYYY-MM-DD'
    }); */

   $('.enableDefaultDatePicker').datepicker({
                    singleDatePicker: true , 
                    startDate: new Date(),
					showTime: false,
					format:'YYYY-MM-DD'
    });		
	}	
}	
function deleteBonusRow(thisVar)
{	
	var closestPromoBonusRoot = thisVar.closest(".promoBonusRoot");
	thisVar.closest(".promoBonusAppended").remove();	
	closestPromoBonusRoot.children('.promoBonusAppended').removeClass("cm-last-item");
	closestPromoBonusRoot.children('.promoBonusAppended:last').addClass("cm-last-item");
	setNoBonus();
}
function checkPromoCouponExists()
{
	return true;	
}
//Set No Conditions
function setNoConditions()
{
	if($('.promoConditionAppended').length>0)
	$("#noConditionData").addClass("hide");
	else
	$("#noConditionData").removeClass("hide");	
}
//Set No Bonus
function setNoBonus()
{
	if($('.promoBonusAppended').length>0)
	$("#noBonusData").addClass("hide");
	else
	$("#noBonusData").removeClass("hide");	
}	
//Check Condition fields : Validation of empty conditions
function checkConditionFields()
{
        
	var errorsFound = 0;
	if(($('#listingType option:selected').val()=='custom'))
	{
	$(".promoRoot").find(".requiredData").each(function () { 
		if($.trim($(this).val())=="" && !$(this).hasClass("hide"))
		{
			errorsFound++;	
		}	
	});
	if($('select[name="promotion_data[conditions][orderBy]"] option:selected').val()=='none' && $(".conditionInd:visible").length==0 && (!$("#promotion_data_conditions_isFeatured").is(":checked")))
	{
		errorsFound++;
	}
	}
	if(errorsFound==0)
	{
		$("#validateConditionValues").val("0");
		return true;
	}
	else
	{
		$("#validateConditionValues").val("1");
		return false;
	}
}	
function setAttributeOperators()
{
	$(".promotionCondtionElement_attributes").each(function () { 
		var selectedAttrType = $('option:selected', this).attr('attrInputType');
		if(selectedAttrType!='')
		{
			$(this).nextAll(".mixedselectors[mixedselector='"+selectedAttrType+"']:first").removeClass("hide");
			if(selectedAttrType=="date")
			$(this).nextAll(".mixedTextBox:first").addClass("enableDatePicker");
			else if(selectedAttrType=="datetime")
			$(this).nextAll(".mixedTextBox:first").addClass("enableDateTimePicker");
			else if(selectedAttrType=="time")
			$(this).nextAll(".mixedTextBox:first").addClass("enableTimePicker");
		}	
	});
	$(".promotionBonusElement_attributes").each(function () { 
		var selectedAttrType = $('option:selected', this).attr('attrInputType');
		if(selectedAttrType!='')
		{
			$(this).nextAll(".mixedselectors[mixedselector='"+selectedAttrType+"']:first").removeClass("hide");
			if(selectedAttrType=="date")
			$(this).nextAll(".mixedTextBox:first").addClass("enableDatePicker");
			else if(selectedAttrType=="datetime")
			$(this).nextAll(".mixedTextBox:first").addClass("enableDateTimePicker");
			else if(selectedAttrType=="time")
			$(this).nextAll(".mixedTextBox:first").addClass("enableTimePicker");
		}	
	});
}
function setLastItemStyle(section)
{
	if(!section || section=='condition')
	{
		$(".promoRoot").each(function(){
			$(this).children('.promoConditionAppended:last').addClass("cm-last-item");
		});
	}
	if(!section || section=='bonus')	
	{
		$(".promoBonusRoot").each(function(){
			$(this).children('.promoBonusAppended:last').addClass("cm-last-item");
		});
	}
}

//============== Common Tabs=======//

function checkViewMoreLink() {
	
var typArray = [ "brands", "categories", "attributes" ];
var condArray=[];
var type;

$(".promoConditionAppended").each(function ()
	{
		type=$(this).find('.promotionCondtion').val();
		if($.inArray(type, typArray)==-1)
		return false;
		else
		{
			condArray.push(type);
			if ((type=='brands' || type=='categories') && (($(this).find('.promotionCondtionOperator').val()!='in')||($(this).find(".pickerDataList").length>1))) {
				return false;
			}
			else if (type=='attributes')
			{
				var attrInputType=$(this).find('.promotionCondtionElement_attributes option:selected').attr('attrInputType');
			
				if($(this).find('.mixedselectors').val()!='eq')			
				return false;
			
				else if((attrInputType!='multiselect') && (attrInputType!='select'))
				return false;
			
			}
		}


	});

if (($.inArray('brands', condArray)==-1) && ($.inArray('categories', condArray)==-1)) 
	return false;
return true;
}
/* Mass Update Features*/ 
 
 function addItemFromPickerMassUpdate(dataObj,type)
{
	var appendHtml = '';
	var loc;
	
	//$("#contentList").empty();
	if (type=='up') {
		var holder="Up";
	}
	else if(type=='cross')
	{
		var holder="Cross";
	}
	
if(dataObj)
	{
		var postItemIds    =$.trim($("#postItemIds"+holder).val());
		var dataValues=[];
		if(postItemIds!='')
		dataValues= postItemIds.split(',');		
		$.each(dataObj, function( key, value ) {
			var image;
			if($.inArray(value.id, dataValues)==-1)
			{
			$("#hidItem").val("0");			
			appendHtml = appendHtml + '<li class="clearfix pickerDataListCommon'+ holder+'" id="'+ value.id +'" rel="'+ value.id +'"><a href="Javascript:void(0);" type="'+holder+'" class="deletePickerDataRowMass delete03 delete  sprite icon  pull-right" rel="'+ value.id
			+'" title="'+lblDelete+'"></a>'+value.title+'</li>' ;
			dataValues.push(value.id);
			}
			
		});
		var itemIds=dataValues.join(',');
		if(appendHtml!='')
		{			
			$("#contentList"+holder).append(appendHtml);
			$("#contentList"+holder).show();
			$("#postItemIds"+holder).val(itemIds);
		}
		//update function.
		//based on type append(already exist
	}
}


$(document).on('click','.deletePickerDataRowMass', function () {			
		deletePickerDataRowMass($(this));
	});
function deletePickerDataRowMass(thisVar)
{
var type=thisVar.attr('type');
$("#"+thisVar.attr('rel')).remove();
var result = $(".item"+type).sortable('toArray');
$("#postItemIds"+type).val(result);
}

 