 $(document).ready(function(){
	$(document).on('click','.mailTemplates',function(){ 
			 CKEDITOR.instances["newsLetterContentHtml"].setData( $(this).next().val());
	  });

if( $.trim($("#templateType:checked").val())=='product'){
	   $('.hideProductRule').removeClass('hide');
	   $("[task=product]").removeClass('hide');
	   $("[task=static]").addClass('hide');
	   
	  }else{
		$('.hideProductRule').addClass('hide');
	   $("[task=product]").addClass('hide');
	   $("[task=static]").removeClass('hide');		

	  }
	
$(document).on("click",'#templateType', function () {
	  if($(this).val()=='product'){
	   $('.hideProductRule').removeClass('hide');
	   $("[task=product]").removeClass('hide');	   
	   $("input:radio[task=product]:first").trigger("click");
	   $("[task=static]").addClass('hide');	   
	  }else{
		$('.hideProductRule').addClass('hide');
	   $("[task=product]").addClass('hide');
	   $("[task=static]").removeClass('hide');
		$("input:radio[task=static]:first").trigger("click");  
	  }
	    //listCartPromotionOnTemplate();
	});	
	otherSubscribers();
 $(function(){
    $("a.fancylink").colorbox({iframe:true, innerWidth:"80%", innerHeight:"80%"});
})
 var othersPresent = false;
 displayNewsletterGroup();

	$(document).on('change','#newsletterGroup',function(){
	   displayNewsletterGroup();
	   otherSubscribers();
          
	  $("#validateHiddenType").trigger("change");
  });
	if($("#newsletterGroup").val() =='savedgroup'){
		displayEditSavedGroup();
	}  
        if($("#newsletterGroup").val() =='businessFollowers'){
		displayEditbusinessFollowers();
	} 
   $(document).on("change",'#customerRuleID', function () {
		 displayEditSavedGroup();


     });  
      $(document).on("change",'#customerFollowID', function () {
		 displayEditbusinessFollowers();


     });  
  
	 $(document).on("click",'#editSavedGroup', function () {
 		 var href='';
		 var ruleID =$("#customerRuleID").val();
		// href= GLOBAL_BASE_PATH +'/newsletter/editrule/id/'+ruleID+'/enableSavedGroup/1/';		 
		 $.colorbox({href:GLOBAL_BASE_PATH+'/newsletter/editrule/id/'+ruleID+'/enableSavedGroup/1/',iframe:true, innerWidth:"80%", innerHeight:"80%"});


     });
 $(document).on("change",'#testEmailId', function () {	
 parent.$('#testEmailId').val($(this).val());
	
}); 
    $(document).on("click",'#sendTest', function () { 
            $('#previewBtn').val(0); 
	  var sendData = new Array();
        sendData[0] = $('#newsletterFromName').val();
        sendData[1] = $('#newsletterFromEmail').val();
        sendData[2] = $('#newsLetterSubject').val();
		sendData[3] = $('#popup_body').html();
		sendData[5] = $('#newsletterReplyEmail').val();
        if($.trim(sendData[0])==''){
            jAlert(errFromName);
            return false;
        }
        if($.trim(sendData[1])==''){
            jAlert(errFromEmail);
            return false;
        }
        if($.trim(sendData[2])==''){
            jAlert(errSubject);
            return false;        }
        if($.trim(sendData[3])==''){
                jAlert(errEmailBody);
                return false;
        }
        if($.trim(sendData[5])==''){
           // jAlert(errSubject);
            return false;
		}

		if(!validate($('#testEmailId').val())) {
			jAlert(errEnterValidEmail);
          /*  $('#popup_message_err').removeAttr("style")
           jNotify(errEnterValidEmail, 'popup_message_err','message_error');
		   $('#sendTestScroll').click();	 */
		   
           return false;
        }
        sendData[4] = $('#testEmailId').val();
        $.ajax({
        type : 'POST',
        data : {mail:sendData},
        url : GLOBAL_BASE_PATH+'/newsletter/ajaxsendTestEmail/',
        success : function(data){
			 if (data.indexOf("success")!=-1){
                                $.colorbox.close();
				 $('#popup_message_err').removeAttr("style")
                  jAlert(msgTestMailSent);
                }
              else {
                 jAlert(errTestMailSendingFailed);
              }
        }
     });
    })
    $('#previewNews').click(function(){
                $('#previewBtn').val(1); 
            //    alert($('#previewBtn').val());
		$('#popup_message_err').removeClass('message_success');
		$('#popup_message_err').removeClass('message_error');
        var content = '';
        var fromName = $.trim($('#newsletterFromName').val());
        var fromEmail  = $('#newsletterFromEmail').val();
		var replyEmail  = $('#newsletterReplyEmail').val();
        var subject    = $.trim($('#newsLetterSubject').val());
        var templateType = $.trim($("#templateType:checked").val());
        var txtContent = CKEDITOR.instances["newsLetterContentHtml"].getData();
        if(fromName == ''){
            jAlert(errFromName); 
            return false;
        }
        if(!validate(fromEmail)) {
            jAlert(errEnterValidEmail);
            return false;
        }
        if(!validate(replyEmail)) {
            jAlert(errEnterValidReplyEmail);
            return false;
        }		
        if(subject == '') {
            jAlert(errSubject);
            return false;
        }
		if(templateType=='product'){
			var productListingLimit  = $('#productListingLimit').val();
			if(productListingLimit == '') {
            jAlert("product Listing Limit");
            return false;
        }
			var formData = $("#formNewsletter").serializeArray();
			formData.push({ name: "submit", value: 1 });
			formData.push({ name: "newsLetterContentHtml", value: txtContent });
		$.ajax({
			type:"POST",
			async: false,
			url: GLOBAL_BASE_PATH + "/newsletter/ajaxProductTemplate/",
			data:formData,
			success:function(msg){
			if(msg){
                            
                                $('#previewBtn').val(0);   
				 txtContent =msg;
                            
                                
			}else{
			return false;
			}
		}		
		});
					
		}
        if(content=='' && txtContent == '' )
       {
            jAlert(errEmailBody);return false;
       }
       if(content=='') {
           content = txtContent;
       }
        $('#popup_body').html(content);
        $('#popup').show();
	
       $.colorbox({
            'width' : '70%',
            'height' :'80%',
            'href' : '#popup',
			'inline':true,
			'title':preview,
            'onClosed' : function(){
                
               $('#testEmailId').val('');
               $('#popup').hide();
                $('.message_success').html("");
				$('.message_error').html("");
            },
            'onComplete' : function(){ 
                
             // $('#fancybox-overlay').height($(document).height());
            }
        });
		
        })
      $('#cancelTestMail').click(function(){
        $('#popup').hide();
        $('#testEmailId').val('');
            $.colorbox.close();
      })
   var d = new Date();
   nd = new Date(d.getFullYear(),d.getMonth(),d.getDate());
	  $('#scheduleDate').datetimepicker({
        minDate: nd,dateFormat: datePickerDateFormat
     });
        var sendingTime = $(':radio[name=sendingTime]:checked').val();
 		newsLetterStatusShow(sendingTime);
     $(':radio[name=sendingTime]').change(function(){
		 var sendingTime =$(this).val();
		 newsLetterStatusShow(sendingTime);
		 })
    })
function validate(email) {
	var reg = /^([A-Za-z0-9\'_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;  
	if(reg.test(email) == false) {
		return false;
	}
    else{
        return true;
    }
}
function newsLetterStatusShow(sendingTime) {
     if(sendingTime=='Scheduled') {
          $('#submitNewsletter').attr('value',lblSave);
          $('.newsletterScheduler').show();
     }else if(sendingTime=='Drafted'){
		   $('#submitNewsletter').attr('value',lblSave);
		   $('.newsletterScheduler').hide();
	 }else {
		// $('#scheduleDate').val('');
         $('#submitNewsletter').attr('value',lblSend);
         $('.newsletterScheduler').hide();
      }
     }
function otherSubscribers() {
		var subscriberType='';
		 subscriberType	=$("#newsletterGroup").val();
			if(subscriberType=='customgroup'){
				$("#hidOtherType").val(1);
				$("#otherSubType").removeClass("hide");
			}else{
				$("#otherSubType").addClass("hide");
				$("#hidOtherType").val(0);
			}
	  if(subscriberType){
		  $("#hiddenValidate").val(0);
	  }else{
		  $("#hiddenValidate").val(1);
	  }	
 	  
	}

function displayNewsletterGroup(){
		if($("#newsletterGroup").val() =='savedgroup'){
		 $('#hideSavedGroup').removeClass('hide');		 
		}else{
		 $('#hideSavedGroup').addClass('hide'); 
		}
		if($("#newsletterGroup").val() =='newgroup'){
		 $('#hideNewGroup').removeClass('hide');		 
		}else{
		 $('#hideNewGroup').addClass('hide'); 
		}if($("#newsletterGroup").val() =='businessFollowers'){
		 $('#hideBusinessFollowers').removeClass('hide');		 
		}else{
		 $('#hideBusinessFollowers').addClass('hide'); 
		}
                

}
function displayEditSavedGroup(){
		
 		 var href='';
		 var ruleID =$("#customerRuleID").val();
		// href= GLOBAL_BASE_PATH +'/newsletter/editrule/id/'+ruleID+'/enableSavedGroup/1/';
		//$("#editSavedGroup").attr("href",href);		
		$("#editSavedGroup").show();

}