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");
	setNoConditions();
	$(document).on('click','.left-tab-a', function () {
		var thisVar = $(this);
		var thisRel = thisVar.attr("rel");
		currentTab	= thisVar.attr("section");
		var cmButtonsFloating = $("#"+thisRel+"-section").children(".cm-buttons-floating");
		var cmButtons = $("#"+thisRel+"-section").children(".cm-buttons");
		$.scrollPane({
				floating: cmButtonsFloating,
				fixed: cmButtons,
				padding: 71
			});
		toggleSaveButton(thisRel);
		setSelectedTab(thisVar,cmButtonsFloating,cmButtons,thisRel);
		setPaginationLinks();
	});
        
        $('#ruleName').blur(function(){
		var formattedInput = $.formatUrl($(this).val());
		$("#ruleKey").val(formattedInput);
        });

	$(window).scroll(function()
	{
		var thisRel =   $(".left-tab li a.active").attr("rel");
		toggleSaveButton(thisRel);
	});
	
	$(window).resize(function()
	{
		var thisRel =   $(".left-tab li a.active").attr("rel");
		toggleSaveButton(thisRel);
	})
	
	setActiveTabSaveButton();

	$('form').bind("submit",function (e)
	{	
		$(".mixedselectors.hide").remove();
		setErrortab();
	});	
	
	$(document).on('click','.promotionAddCondition', function () {	
		currentPromoRoot = $(this).closest(".promoRoot");
		currentPromoRootRel = $(this).closest(".promoRoot").attr("rel");
		setConditionSelector($(this));
	});
	
	$(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=="attributes")
		{			
			if(attrData=='')
			{
				$.ajax({
					type: "POST",
					async: false,
					url: GLOBAL_BASE_PATH + "/bundle/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 = '/bundle/ajaxLoadUserGroup/';
				else if(currCondition=="country")
				ajaxurl = '/bundle/ajaxLoadCountry/';
				else if(currCondition=="state")
				ajaxurl = '/bundle/ajaxLoadState/';
				else if(currCondition=="payment_method")
				ajaxurl = '/bundle/ajaxLoadPaymentMethod/';
				else if(currCondition=="merchant_subtotal")
				ajaxurl = '/bundle/ajaxLoadMerchants/';
				
				$.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);
	});
	
	$(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(".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");		
		}	
	});	
	
	$(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($(this));
	});
	
	$(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');
		setBonusSelector();
		if(currBonus=="attributes")
		{			
			if(attrData=='')
			{
				$.ajax({
					type: "POST",
					async: false,
					url: GLOBAL_BASE_PATH + "/bundle/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
		appendNewBonus(currBonus);
	});	
	
	$(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();
	});
	
	$(document).on("change",".freeProdfreeShipping",function(){
		updateFreeProductsValue();
	});
});
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);
}

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();
	$.scrollPane({
				floating: cmButtonsFloating,
				fixed: cmButtons,
				padding: 71
			});
	toggleSaveButton(thisRel);
}
setErrortab();
setBonusPriceValidation();
setCouponType();
setPaginationLinks();
setAttributeOperators();
setLastItemStyle();

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');	
	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();
}

function setConditionSelector(thisVar)
{
	$("#promoConditionRootSelectorContainer").removeClass("hide");
	if($.type(thisVar) == 'object')
	{
		var deleteGroupRowWidth = 0;
		var deleteGroupRowLength = thisVar.prev(".deleteGroupRow").length;
		if(deleteGroupRowLength>0)
		{
			deleteGroupRowWidth = thisVar.prev(".deleteGroupRow").outerWidth(true);
		}
		var right = (($(window).width() - (thisVar.outerWidth(true) + thisVar.offset().left))/2)+deleteGroupRowWidth;
		$("#promoConditionRootSelectorContainer").css({"right": right+"px","top":thisVar.position().top+10});
	}	
	else
	{
		$("#promoConditionRootSelectorContainer").addClass("hide");
	}
	$("#promoConditionRootSelector").val('');
}	
function appendNewCondition(currentKey,currentHtml)
{
	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]');
	$('html,body').animate({
        scrollTop: $("#promoConditionAppended_"+appendedConditionDataID).position().top},
        'slow');
	setNoConditions();
}	
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]');
	$('html,body').animate({
        scrollTop: $("#promoRootConditionAppended_"+appendedConditionRootDataID).position().top},
        'slow');
}	
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 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(thisVar)
{
	$("#promoBonusRootSelectorContainer").removeClass("hide");
	if($.type(thisVar) == 'object')
	{
		var deleteGroupRowWidth = 0;
		var deleteGroupRowLength = thisVar.prev(".deleteBonusGroupRow").length;
		if(deleteGroupRowLength>0)
		{
			deleteGroupRowWidth = thisVar.prev(".deleteBonusGroupRow").outerWidth(true);
		}
		var right = (($(window).width() - (thisVar.outerWidth(true) + thisVar.offset().left))/2)+deleteGroupRowWidth;
		$("#promoBonusRootSelectorContainer").css({"right": right+"px","top":thisVar.position().top+10});
	}	
	else
	{
		$("#promoBonusRootSelectorContainer").addClass("hide");
	}
	$("#promoBonusRootSelector").val('');
	
	
}
function appendNewBonus(currentKey,currentHtml)
{
	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^='promoBonus-']");
	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^='promotionBonusDataValue-']");
	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]');
	$('html,body').animate({
        scrollTop: $("#promoBonusAppended_"+appendedBonusDataID).position().top},
        'slow');	
	setNoBonus();	
}	
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;	
}
function setPaginationLinks()
{
	if(currentTab=="coupons")
	{
		$(".pagination-layout a").each(function () { 
			var thisHref = $(this).attr("href");
			if (thisHref.indexOf("section/coupons/") == -1)
			{
				var slash= thisHref.charAt(thisHref.length-1);
				if(slash!='/')
				slash = '/';
				else
				slash = '';
				$(this).attr("href",thisHref+slash+'section/coupons/');
			}	
		});	
	}	
}		
//Set No Conditions
function setNoConditions()
{
	if($('.promoConditionAppended').length>0)
	{
	$("#noConditionData").addClass("hide");
	$(".promotionAddCondition").addClass("hide");
	}
	else
	{
	$("#noConditionData").removeClass("hide");	
	$(".promotionAddCondition").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;
	$(".promoRoot").find(".requiredData").each(function () { 
		if($.trim($(this).val())=="" && !$(this).hasClass("hide"))
		{
			errorsFound++;	
		}	
	});
	if($(".promoRoot").find(".conditionInd").length==0)
       {
               errorsFound++;
       }
	if($(".conditionInd:visible").length>0 && $(".promoRoot").find(".requiredData").length==0)
	{
		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");
		}	
	});
	$(".promotionBonusElement_attributes").each(function () { 
		var selectedAttrType = $('option:selected', this).attr('attrInputType');
		if(selectedAttrType!='')
		{
			$(this).nextAll(".mixedselectors[mixedselector='"+selectedAttrType+"']:first").removeClass("hide");
		}	
	});
}
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");
		});
	}
}
function addfreeproducts(dataObj)
{
	var appendHtml = '';
	var ids = '';
	if(dataObj)
	{		
		var freeproductsValue = $.parseJSON($("#promobonusfreeproducts").val());
		var freeproductsValues = [];
		if(freeproductsValue)
		{
			$.each(freeproductsValue, function( key, value ) {
				freeproductsValues.push(value.productID);
			});
		}	
		$.each(dataObj, function( key, value ) {
			if($.inArray(value.id, freeproductsValues)==-1)
			{
				var appendTitle = '';
				var appendCustomOptTitle = '';
				var appendOptions = '';
				var appendOptionsHtml = '';
				var appendCustomOptionsHtml = '';
				var appendQuantity = '';
				var appendQuantityVar = '';
				var optionsType = '';
				var titleFlag = 0;
				var shippingCostHtml = '';
				if(typeof value.options!='undefined' && !jQuery.isEmptyObject(value.options))
				{
					$.each(value.options, function( optKey, optValue ) {
						appendTitle = appendTitle + optValue.title + ",";
						appendOptionsHtml = appendOptionsHtml + '<input type="hidden" class="freeProductsSubValues" name="freeProductsSubValues" optiontype="'+optValue.optiontype+'" value="'+optValue.id+'">';
						appendOptions = appendOptions + optValue.id + ',';
					});
					appendTitle = appendTitle.substring(0,appendTitle.length-1);
					if(value.optionsType=="combinations")
					{
						optionsType = lblCombinations;
					}
					else if(value.optionsType=="variants")
					{
						optionsType = lblVariants;
					}	
					appendTitle = value.title +'<br/><br/>'+ optionsType + '<br/><br/>' +appendTitle+appendOptionsHtml;
					titleFlag = 1;
				}
				if(typeof value.customOptions!='undefined' && !jQuery.isEmptyObject(value.customOptions))
				{
					$.each(value.customOptions, function( optKey, customOptionsValue ) {
						if(customOptionsValue.inputType == "multiselect" || customOptionsValue.inputType == "select")
						{
							var valueText = customOptionsValue.valueText;
							appendCustomOptTitle = appendCustomOptTitle + customOptionsValue.title +' : '+ valueText.join()+ ",";
						}	
						else
						{
							appendCustomOptTitle = appendCustomOptTitle + customOptionsValue.title +' : '+ customOptionsValue.value + ",";
						}
						appendCustomOptionsHtml = appendCustomOptionsHtml + '<input type="hidden" class="freeProductsCustomOptionValues" id="freeProductsCustomOptionValues_'+customOptionsValue.id+'" rel="'+customOptionsValue.id+'" inputtype="'+customOptionsValue.inputType+'" name="freeProductsCustomOptionValues" value="'+customOptionsValue.value+'">';
						appendOptions = appendOptions + customOptionsValue.id + ',';
					});
					appendCustomOptTitle = appendCustomOptTitle.substring(0,appendCustomOptTitle.length-1);
					if(titleFlag == 0)
					{
						appendCustomOptTitle = value.title +'<br/><br/>'+ lblCustomOptions + '<br/><br/>' +appendCustomOptTitle+appendCustomOptionsHtml;
					}	
					else
					{
						appendCustomOptTitle = '<br/><br/>'+ lblCustomOptions + '<br/><br/>' +appendCustomOptTitle+appendCustomOptionsHtml;
					}	
					titleFlag = 1;
				}				
				if(titleFlag == 0)
				{
					appendTitle = value.title;
				}	
				appendQuantity = appendQuantity + '<td width="18%">';
				appendQuantity = appendQuantity +'<span class="small_qty">'+lblPromoProductQuantity+'</span><input type="text" class="textbox small_txt_fld isWholeNumberWithZeroClass promoBonusFreeProductsQuantity" name="promoBonusFreeProductsQuantity" value="1">';
				appendQuantity = appendQuantity + '</td>';
				
				shippingCostHtml = shippingCostHtml + '<td width="15%">';
				shippingCostHtml = shippingCostHtml +'<input type="checkbox" class="checkbox01 freeProdfreeShipping" value="Yes" name="freeProdfreeShipping" checked="checked"><span class="small_qty">'+lblFreeshipping+'</span>';
				shippingCostHtml = shippingCostHtml + '</td>';
				
				var titleTdWidth = '65%';
				
				appendHtml = appendHtml + '<tr class="freeproductList" rel="'+ value.id +'" optionsType="'+ value.optionsType +'"><td width="'+titleTdWidth+'">' + appendTitle + appendCustomOptTitle +'</td>'+appendQuantity+shippingCostHtml+'<td align="right"><a href="Javascript:void(0);" class="deleteFreeProductsDataRow" rel="'+ value.id +'" title="'+lblDelete+'">X</a></td></tr>';
			}
		});
		var pickerDataList = $(".freeProductDataList tr.freeproductList");
		if(pickerDataList.length>0)
		{		
			if(appendHtml!='')
			$(".freeProductDataList tr.freeproductList:last").after(appendHtml);
		}
		else if(appendHtml!='')
		{
			$(".freeProductDataList tr.noRecordsForPicker").addClass("hide");
			$(".freeProductDataList tr.noRecordsForPicker").after(appendHtml);
		}
		updateFreeProductsValue();
	}
}
function deleteFreeProductDataRow(thisVar)
{
	var ids = '';
	var currentId = thisVar.attr("rel");
	var freeProductDataList = thisVar.closest(".freeProductDataList");
	var dataLength = freeProductDataList.find(".freeproductList").length;
	var noRecords  = freeProductDataList.find(".noRecordsForPicker"); 	
	freeProductDataList.find(".freeproductList").each(function () { 
		var thisRel = $(this).attr("rel");
		if(thisRel!=currentId)
		ids = ids + thisRel +',';
	});	
	thisVar.closest(".freeproductList").remove();	
	dataLength = dataLength - 1;
	if(dataLength==0)
	noRecords.removeClass("hide");	
	updateFreeProductsValue();
}
function updateFreeProductsValue()
{
	var freeProductsDataObj = [];
	$('.freeproductList').each(function (index){
		var appendOptions = '';
		var appendCustomOptions = [];
		$(this).find(".freeProductsCustomOptionValues").each(function () { 
			appendCustomOptions.push({
				id: $(this).attr("rel"),
				inputtype: $(this).attr("inputtype"),
				value: $(this).val()
			});
		});
		$(this).find(".freeProductsSubValues").each(function () { 
			appendOptions = appendOptions + $(this).val() + ',';
		});
		if(appendOptions!='')
		appendOptions = appendOptions.substring(0,appendOptions.length-1);
		var optionsType = $(this).attr("optionsType");
		var variants = '';
		var combinations = '';
		if(optionsType == "combinations")
		{
			combinations = appendOptions;
		}
		else
		{
			variants = appendOptions;
		}	
		var freeShipping = "";
		var freeShippingStatus = 	$(this).find(".freeProdfreeShipping").prop( "checked" );
		if(freeShippingStatus)
		freeShipping = "Yes";
		freeProductsDataObj.push({
			productID: $(this).attr("rel"),
			combinations: combinations,
			variants: variants,
			customOptions: appendCustomOptions,
			quantity : $(this).find(".promoBonusFreeProductsQuantity").val(),
			freeShipping : freeShipping
		});	
	});
	$("#promobonusfreeproducts").val(JSON.stringify(freeProductsDataObj));
}
function addPromoBonusGroup()
{
	appendedBonusRootDataID = appendedBonusRootDataID + 1;
	
	//Check Element Existence
	var childrenLengthCheck =parseInt($(currentPromoBonusRoot).children('.promoBonusAppended').length) + 1;
	var reWriteVarCheck = currentPromoBonusRootRel+'[bonuses]['+childrenLengthCheck+']';
	while($("select[name='promotion_data[bonuses]" + reWriteVarCheck +"[set]']").length!=0)
	{
		appendedBonusRootDataID = appendedBonusRootDataID + 1;
		childrenLengthCheck = childrenLengthCheck  + 1;
		reWriteVarCheck = currentPromoBonusRootRel+'[bonuses]['+childrenLengthCheck+']';
	}
	
	var relForRoot = currentPromoBonusRootRel+'[bonuses]['+childrenLengthCheck+']';
	
	var currentHtml = '<ul class="levl-00 promoBonusRoot" rel="'+relForRoot+'" id="promoRootBonusAppended_'+appendedBonusRootDataID+'">'+$( ".promoBonusRootNode").html()+'</ul>';	
	appendNewBonus('',currentHtml);	
	
	var promotionBonusSet = $('#promoRootBonusAppended_'+appendedBonusRootDataID).find("select[name^='promotionBonusSet-']");
	promotionBonusSet.attr('name', 'promotion_data[bonuses]' + relForRoot +'[set]');
	
	var promotionBonusSetValue = $('#promoRootBonusAppended_'+appendedBonusRootDataID).find("select[name^='promotionBonusSetValue-']");
	promotionBonusSetValue.attr('name', 'promotion_data[bonuses]' + relForRoot +'[set_value]');
	
	$('html,body').animate({
        scrollTop: $("#promoRootBonusAppended_"+appendedBonusRootDataID).position().top},
        'slow');
}
//Check Bonus fields : Validation of empty conditions
function checkBonusFields()
{
	var errorsFound = 0;
	$(".promoBonusRoot").find(".requiredData").each(function () { 
		if($.trim($(this).val())=="" && !$(this).hasClass("hide"))
		{
			errorsFound++;	
		}	
	});
	if($(".bonusInd:visible").length>0 && $(".promoBonusRoot").find(".requiredData").length==0)
	{
		errorsFound++;
	}
	if(errorsFound==0)
	{
		$("#validateBonusValues").val("0");
		return true;
	}
	else
	{
		$("#validateBonusValues").val("1");
		return false;
	}
}
//Check empty Bonus
function checkBonusEntered()
{
	var errorsFound = 0;
	$(".bonusEntered").each(function () { 
		var thisVal = $.trim($(this).val());
		if(($(this).attr("id")=="promobonusfreeproducts" && thisVal=="[]") || thisVal=="")
		{
			errorsFound++;	
		}	
	});
	if(errorsFound!=$(".bonusEntered").length)
	{
		$("#validateBonusEnteredValues").val("0");
		return true;
	}
	else
	{
		$("#validateBonusEnteredValues").val("1");
		return false;
	}
}
//Check Gift coupon Amount
function checkGiftCoupon()
{
	var couponAmnt = parseFloat($.trim($("#promoDiscountGiftCoupon").val()));
	if(couponAmnt<=0)
	{				
		return false;	
	}
	return true;
}
$(document).mouseup(function (e)
{
	var condnContainer= $(".promoRootConditionSelector");
    if (condnContainer.has(e.target).length === 0)
    {
       $(".promoRootConditionSelector").addClass("hide");
    }
	var bonusContainer= $(".promoRootBonusSelector");
    if (bonusContainer.has(e.target).length === 0)
    {
       $(".promoRootBonusSelector").addClass("hide");
    }
});