jQuery(document).ready(function(){
	document.location.hash = "";
	jQuery(".add_protected_content").click(function(){
		var post_status = jQuery("#post_status").val();
		if(post_status =="publish"){
			jQuery("select.productall_ids").attr('disabled', '');
			jQuery("select.productall_ids").prop('disabled', false);
			jQuery(".pro_contentoverlay").removeClass("clickedpopup");
			var getpopID = jQuery(this).attr("href");
			jQuery(getpopID).addClass("clickedpopup");
		}else{
			alert("You can only protect published posts/pages.");
			return false;
		}
	});
	
	/** ADD Protected Content**/
	jQuery(document).on('click', '.protect_content_cls', function() {
		addResourceToProduct();
	});	

	jQuery(document).on('click', '.action_buttons .edit-btn', function() {
		jQuery(".pro_contentoverlay").removeClass("clickedpopup");
		var getpopID = jQuery(this).attr("href");
		jQuery(getpopID).addClass("clickedpopup");
		jQuery("select.productall_ids").attr('disabled', 'disabled');
		jQuery("select.productall_ids").prop('disabled', true);
		getdatepicker();
	});

	/** Delete Protected Content Product **/
	jQuery(document).on('click', '.each_prod_row .del-btn', function() {
		
		var getproductId = jQuery(this).closest(".each_prod_row").children('.prod_class').prop("id");
		getproductId = getproductId.split("pro_");
		var productId = getproductId[1];
		var resourceId = jQuery(this).attr("data-id");
		var delId = jQuery(this).attr("id");
		delId = delId.split("del_");
		if(confirm("WARNING: Are you sure you want to delete this protected content from this Product?")) {
			this.click;
			hideProduct(delId);
			deleteProduct(productId,resourceId);
	   } else {   }  
	});
	
	/** Delete All Protected Content Product **/
	jQuery(document).on('click', '.delete_protected_content', function(event) {
	   event.stopPropagation();
	   if(confirm("WARNING: Are you sure you want to completely unprotect this content? It'll be removed from all products where it's protected.")) {
			this.click;
			deleteAllProduct();
			hideProducts();
	   } else {   }       
	});
	/** Drip settings **/
	jQuery(document).on('click', '.update-btn', function() {
		var dripval = jQuery(this).closest(".each_prod_row").find(".editablecls").val();
		var get_id_row = jQuery(this).closest(".each_prod_row").prop("id");
		getrowId = get_id_row.split("row_");
		var getrowId = getrowId[1];
		editdripsetting(dripval, getrowId);
	});
	
	/** Datepicker **/
	getdatepicker();
	jQuery(document).on('input', '.clickedpopup #fileName', function() {
		var fileName = jQuery(this).val();
		jQuery("#postnameid").val(fileName);
	}); 
});

function getdatepicker(){
	jQuery("input[name='start_date']").datepicker({
		dateFormat: "mm-dd-yy"
	}).datepicker();
	jQuery('.get_datepicker').click(function () {
		jQuery("input[name='start_date']").datepicker('show');
	});
	jQuery("input[name='end_date']").datepicker({
		dateFormat: "mm-dd-yy"
	}).datepicker();
	jQuery('.get_datepicker1').click(function () {
		jQuery("input[name='end_date']").datepicker('show');
	});
}

function editdripsetting(dripval, getrowId){
	jQuery.post(ajaxurl, {
		action: 'drip_day_settings_edit',
		rowId: getrowId,
		dripval: dripval
	}, function(response) {
		console.log(response);
		jQuery(".success_drip_msg").show();
		jQuery("#pro_contentpopup"+getrowId+" .start_day_input" ).val(dripval);
		setTimeout(function(){ jQuery(".success_drip_msg").hide(); }, 3000);
	}); 
}

function addResourceToProduct(){
	
	var p_id = jQuery("#p_id").val();
	var productId = jQuery(".clickedpopup #product_all").val();
	var url = jQuery("#p_url").val();
	var pageurl = jQuery("#url").val();
	var name = jQuery("#postnameid").val();
	if(name=="" || name=="undefined" || name=="null"){
		var name = jQuery(".clickedpopup #fileName").val();
	}
	var display_in_list = jQuery(".clickedpopup .display_in_list_val:checked").val();
	var start_day = jQuery(".clickedpopup input[name='start_day']").val();
	var end_day = jQuery(".clickedpopup  input[name='end_day']").val();
	var start_date = jQuery(".clickedpopup  input[name='start_date']").val();
	var end_date = jQuery(".clickedpopup  input[name='end_date']").val();
	var img_calc = jQuery(".plainLink img").attr('src');
	var dap_prod_url = jQuery("#dap_prod_url").val();
	
	if((start_day != "" || end_day != "" ) && ( start_date != "" ||  end_date != "" )){
		alert('Cannot select both "Day" and "Date" drip options. Please select "Day" or Date" based dripping.');
		return false;
	}else if(start_day =="" && end_day !=""){
		alert("Missing start day");
		return false;
	}else if(end_day =="" && start_day !=""){
		alert("Missing end day");
		return false;
	}else if(start_date =="" && end_date !=""){
		alert("Missing start date");
		return false;
	}else if(end_date =="" && start_date !=""){
		alert("Missing end date");
		return false;
	}else if((start_day == "" || end_day  == "" ) && (start_date == "" || end_date  == "" )){
		alert('Please select "Day" and "Date" drip options.');
		return false;
	}else{
	}
	if(productId == 0 || productId =="" || productId =="null" || productId =="undefined" || productId == null || productId == undefined){
		alert("Please select atleast one Product");
		return false;
	}else{    
		jQuery.post(ajaxurl, {
			action: 'live_links_protected_content',
			dataType: "json",
			productId: productId,
			url: url,
			name: name,
			display_in_list: display_in_list,
			start_day: start_day,
			end_day: end_day,
			start_date: start_date,
			end_date: end_date
		}, function(response) {
			var responsejson = jQuery.parseJSON(response);
			var total_rows = responsejson.total_rows;
			var productname = responsejson.productname;
			var product_name_short = responsejson.product_name_short;
			var product_ids = responsejson.product_ids;
			var productList = responsejson.productList;
			var product_names = responsejson.product_names;
			var lengthofObject = total_rows.length; 
			var pc_product_ids = product_ids;
			var pc_product_names = product_names;
			var all_products_ids = [];
	
			if(lengthofObject > 0){
				jQuery( ".protected_product_table_page_select tbody" ).html('');
				jQuery( ".pro_contentoverlay_outer" ).html('');
				jQuery(".protected_product_content_table").show();
				jQuery(".delete_protected_content").show();
				jQuery(".protected_product_head").removeClass('hide_div');
			}
			
			 for(i=0; i<lengthofObject; i++){
				var pc_id = total_rows[i].id;
				var	pc_display_in_list = total_rows[i].display_in_list;
				var pc_product_id = total_rows[i].product_id;
				var pc_fileName = total_rows[i].fileName;
				var pc_url_perm = total_rows[i].url;
				var pc_start_day = total_rows[i].start_day;
				var pc_end_day = total_rows[i].end_day;
				var pc_start_date = total_rows[i].start_date;
				var pc_end_date = total_rows[i].end_date;

				all_products_ids.push(pc_product_id);
				
				if(pc_start_day =="null" || pc_start_day =="undefined" || pc_start_day == null || pc_start_day == undefined || pc_start_day ==0 ){
					pc_start_day="";
				}
				if(pc_end_day =="null" || pc_end_day =="undefined" || pc_end_day == null || pc_end_day == undefined || pc_end_day ==0){
					pc_end_day="";
				}
				if(pc_start_date =="null" || pc_start_date =="undefined" || pc_start_date == null || pc_start_date == undefined || pc_start_date ==0){
					pc_start_date="";
				}
				if(pc_end_date =="null" || pc_end_date =="undefined" || pc_end_date == null || pc_end_date == undefined || pc_end_date ==0){
					pc_end_date="";
				}
				if(pc_start_day !=""){
					var dripday = '<input value="'+pc_start_day+'" contenteditable="true" class="editablecls"><a class="update-btn btn btn-xs" title="Click to update drip settings." onclick="" href="javascript:void(0)"><i aria-hidden="true" class="fa fa-refresh"></i></a>';
				}
				if(pc_start_date !=""){
					var dripday = pc_start_date.split('-');
					var dripday = dripday[1] + '-' + dripday[2] + '-' + dripday[0];
				}
				if(pc_start_date !=""){
					var pc_start_date = pc_start_date.split('-');
					var pc_start_date = pc_start_date[1] + '-' + pc_start_date[2] + '-' + pc_start_date[0];
				}
				if(pc_end_date !=""){
					var pc_end_date = pc_end_date.split('-');
					var pc_end_date = pc_end_date[1] + '-' + pc_end_date[2] + '-' + pc_end_date[0];
				}
				
				var tooltip_text ='Select YES if you want this link to be displayed in the "available content" area of DAP MyContent page.';
				var pc_resource_id = total_rows[i].resource_id;
				var pc_product_name_short = product_name_short[i];
				var pc_prd_name = productname[i];
				var selectedHtml = "";
				var radioCheckedYes = "";
				if(pc_display_in_list == 'Y'){
					radioCheckedYes =  "checked = 'checked'";
				} 
				var radioCheckedNo = "";
				if(pc_display_in_list == 'N'){
					radioCheckedNo =  "checked = 'checked'";
				} 
				
				jQuery.each(productList, function(key, value) { 
					var selectedField = "";
					if(value.id == pc_product_id){
						selectedField =  "selected = 'selected'";
					} 
					selectedHtml = selectedHtml+'<option value="'+value.id+'" '+selectedField+'>'+value.name+'</option>';
				});  

				jQuery( ".protected_product_content_table" ).addClass('protected_table_border');
				jQuery( ".protected_product_content" ).append('<a class="delete_protected_content" title="Delete this protected content from all products." data-id="'+pc_resource_id+'" href="javascript:void(0)"><i class="fa fa-trash" aria-hidden="true"></i></a>');
				
				jQuery( ".protected_product_table_page_select tbody" ).append('<tr id="row_'+pc_id+'" class="each_prod_row"><td valign="top" class="prod_class" id="pro_'+pc_product_id+'"><div class="tool-tip"><div class="tool-tip-outer"><a href="'+dap_prod_url+pc_product_id+'" target="_blank">'+pc_product_name_short+'</a><div class="toll-tip-desc"><a href="javascript:void(0)">'+pc_prd_name+'</a></div></div></div></td><td valign="top">'+dripday+'</td><td class="editable-button text-right action_buttons"><div id="" name="select_action"><a class="edit-btn btn btn-primary btn-xs" title="Click to edit drip settings." id="edit_'+pc_id+'" href="#pro_contentpopup'+pc_id+'"><i class="fa fa-pencil" aria-hidden="true"></i></a><a class="del-btn btn btn-primary btn-xs" title="Delete this protected content from the selected product." data-id="'+pc_resource_id+'" id="del_'+pc_id+'" onclick="" href="javascript:void(0)"><i aria-hidden="true" class="fa fa-trash"></i></a></div></td></tr>'); 
						 
				 jQuery( ".pro_contentoverlay_outer" ).append('<div id="pro_contentpopup'+pc_id+'" class="pro_contentoverlay"><div class="popup"> <a class="close" href="#">&times;</a><h2 class="head_memb ">DAP Content Protection</h2><div class="pro_content"><div class="protected-product-outer"><div class="protected-product-div"><table width="100%" cellpadding="2" cellspacing="2" class="protected_table"><tr class="protected_table_in"><td valign="middle" width="100%"> <table width="100%" cellpadding="2" cellspacing="2"><tr><td valign="top">Page/Post to be Protected</td><td valign="top" width="50%"><input name="url" type="text" id="url" value="'+pageurl+'" size="60" readonly="" style="background: rgb(204, 204, 204);"></td></tr><tr><td>Select Product(s)</td><td valign="top" width="50%"> <select style="" id="product_all" style=" width: 55% !important;" name="product_all" multiple="multiple" class="productall_ids">'+selectedHtml+'</select> </td></tr><tr> <td valign="top">Link Text</td> <td valign="top" width="50%"><input name="fileName" type="text" id="fileName" value="'+name+'" size="20" maxlength="100"> </td></tr><tr><td valign="top my-content-div">Display on "My Content" Page? <div class="tool-tip my-content-tooltip"><div class="tool-tip-outer"><i class="fa fa-info-circle" aria-hidden="true"></i><div class="toll-tip-desc">'+tooltip_text+'</div></div></div></td><td valign="top" width="50%"><div align="left display_in_list_outer"><label><input class="display_in_list_val" name="display_in_list'+pc_id+'" type="radio" value="Y" '+radioCheckedYes+'/> Yes</label><label><input class="display_in_list_val" name="display_in_list'+pc_id+'" type="radio" value="N" '+radioCheckedNo+'/> No</label> </div></td></tr></table> </td> </tr> <tr class="protected_table_in"> <td valign="middle" width="100%"> <table width="100%" cellpadding="2" cellspacing="2"> <tr class="drip_sett"> <th><span class="tittle">Drip Settings</span></th> </tr> <tr> <td valign="top"> <div id="days_div'+pc_id+'" class="table-outer days_div_cls"> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"> <tbody> <tr> <td valign="top"> <div align="left">Start Day #</div> </td> <td valign="top"> <div align="left"> <input name="start_day" class="days_input start_day_input" type="text" id="start_day'+pc_id+'" value="'+pc_start_day+'" size="4" maxlength="4"> <span class="plainLink">(eg., Day "7")</span> </div> </td> </tr> <tr> <td valign="top"> <div align="left">End Day #</div> </td> <td valign="top"> <div align="left"> <input name="end_day" type="text" class="days_input end_day_input"  id="end_day'+pc_id+'" value="'+pc_end_day+'" size="4" maxlength="4"> <span class="plainLink"> (eg., Day "30")</span> </div> </td> </tr> </tbody> </table> </div> <div align="center" class="scriptheader or-title"><span>OR</span></div><div class="table-outer date_div_cls" id="date_div'+pc_id+'"><table width="100%" border="0" align="center" cellpadding="0" cellspacing="0"><tbody><tr><td><div align="left">Start Date</div></td><td> <div align="left"><input id="start_date'+pc_id+'" name="start_date" type="text" value="'+pc_start_date+'" size="10" maxlength="10"> <span class="plainLink"><a href="javascript:void(0)"><img src="'+img_calc+'" width="16" height="16" border="0" class="get_datepicker" alt="Pick a date"></a> (mm-dd-yyyy)</span> </div></td></tr><tr><td><div align="left">End Date</div></td><td><div align="left"><input id="end_date'+pc_id+'" name="end_date" type="text"  value="'+pc_end_date+'" size="10" maxlength="10"> <span class="plainLink"><a href="javascript:void(0)"><img src="'+img_calc+'" width="16" height="16" class="get_datepicker1" border="0" alt="Pick a date"></a> (mm-dd-yyyy)</span> </div></td></tr></tbody></table></div><div class="protected_content_out"><div class="button-primary next-btn protect_content_cls" id="protected_content'+pc_id+'">Protect Content</div></div> </td> </tr> </table> </td> </tr> </table> </div> </div> </div> </div></div>'); 
										 
			} 
			jQuery("#all_p_id").val(all_products_ids);
			jQuery("#resourceid").val(pc_resource_id);
			jQuery("select.productall_ids").attr('disabled', '');
			jQuery("select.productall_ids").prop('disabled', false);
			document.location.hash = "";
		});
	}
}

function hideProduct(delId){
	jQuery("#row_"+delId[1]).hide();
}
function hideProducts(){
	jQuery(".protected_product_content_table").hide();
	jQuery(".delete_protected_content").hide();
	jQuery( ".protected_product_table_page_select tbody" ).html('');
	jQuery( ".pro_contentoverlay_outer" ).html('');
}  

function deleteProduct(productId, resourceId){
	var post_url = jQuery("#post_url").val();
	jQuery.post(ajaxurl, {
		action: 'delete_live_links_protected_content',
		productId: productId,
		resourceId: resourceId
	}, function(response) {
		console.log(response);
	});
}

function deleteAllProduct(){
	var post_url = jQuery("#post_url").val();
	var productIds = jQuery("#all_p_id").val();
	var resourceId = jQuery("#resourceid").val();
	
	jQuery.post(ajaxurl, {
		action: 'delete_all_protected_content',
		productIds: productIds,
		resourceId: resourceId,
	}, function(response) {
		console.log(response);
	});
}
