function format ( d ) {
    // `d` is the original data object for the row
    return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
        '<tr>'+
            '<td>Full name:</td>'+
            '<td>'+d.name+'</td>'+
        '</tr>'+
        '<tr>'+
            '<td>Extension number:</td>'+
            '<td>'+d.extn+'</td>'+
        '</tr>'+
        '<tr>'+
            '<td>Extra info:</td>'+
            '<td>And any further details here (images etc)...</td>'+
        '</tr>'+
    '</table>';
}
var product_id	= 0;
$(document).ready(function() {
	
	function getUrlParameter(name) {
		name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
		var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
		var results = regex.exec(location.search);
		return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
	};
	
	var table	= $('#show_record').DataTable({
  		"columnDefs": [
		    { "orderable": false, "targets": -1, "data": null, "defaultContent": "<button>Click here</button>" }
		  ],
		"order": [[ 2, "desc" ]],
		 "oLanguage": {
            "sLengthMenu": "Show _MENU_ Entries",
            // "sSearch": "Search in page"
        },
    	"lengthMenu": [[10,30,60,100], [10,30,60,100]],
    	"paging": false
	});
	
	var table1	= $('#show_record1').DataTable({
//		"scrollX": true,
		  "responsive": true,
            
  		"columnDefs": [
		    {"orderable": false, "targets": -1 }
		  ],		 
		 "oLanguage": {
            "sLengthMenu": "Show _MENU_ Entries"
        },
    	"lengthMenu": [[10,30,60,100], [10,30,60,100]]	
	});
//	table1.buttons().container()
//    .appendTo( $('ul.pagination', table1.table().container() ) );
	
	//Add event listener for opening and closing details
    $('#show_record tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row( tr );
 
        if ( row.child.isShown() ) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child( format(row.data()) ).show();
            tr.addClass('shown');
        }
    } );
	
	$('#show_record tbody').on( 'click', 'button', function () {
	    var store_hash	= getUrlParameter('store_hash');
	    var payload		= getUrlParameter('signed_payload');
		var data		= table.row( $(this).parents('tr') ).data();
		product_id		= data[0];
		var product_name= data[1];	
		var url      	= window.location.href;
		var queryParam 	= url ? url.split('?')[1] : window.location.search.slice(1); 
		
		if(product_name.length>30){
			product_name 	= product_name.substring(0, 30);
			product_name	= product_name+"..";
		}
		window.location = "//wishlist.appsserver.net/bigcommerce_apps/wishlist/load_customer.php?signed_payload="+payload+"&product_id="+product_id+"&pro_name="+encodeURIComponent(product_name)+"&"+queryParam;
    });
	
	$(document).on( 'click', '#down_btn', function () {
		product_id	= getUrlParameter('product_id');
		var payload		= getUrlParameter('signed_payload');
		console.log("product_id "+product_id);
		
		$.ajax({type: "POST",
			dataType: 'json',
			crossDomain:true,
			url: "//wishlist.appsserver.net/bigcommerce_apps/wishlist/customers.php?payload="+payload,
			data: {id:product_id},
			success:function(result) {
				var rows=result;
				console.log(rows);
				var file_name	= "product_id_"+product_id+".csv";
				
				function exportToCsv(filename, rows) {
					var processRow = function (row) {
						var finalVal = '';
						for (var j = 0; j < row.length; j++) {
							var innerValue = row[j] === null ? '' : row[j].toString();
							if (row[j] instanceof Date) {
								innerValue = row[j].toLocaleString();
							};
							var result = innerValue.replace(/"/g, '""');
							if (result.search(/("|,|\n)/g) >= 0)
								result = '"' + result + '"';
							if (j > 0)
								finalVal += ',';
							finalVal += result;
						}
						return finalVal + '\n';
					};

					var csvFile = '';
					for (var i = 0; i < rows.length; i++) {
						csvFile += processRow(rows[i]);
					}

					var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
					if (navigator.msSaveBlob) { // IE 10+
						navigator.msSaveBlob(blob, filename);
					} else {
						var link = document.createElement("a");
						if (link.download !== undefined) { // feature detection
							// Browsers that support HTML5 download attribute
							var url = URL.createObjectURL(blob);
							link.setAttribute("href", url);
							link.setAttribute("download", filename);
							link.style.visibility = 'hidden';
							document.body.appendChild(link);
							link.click();
							document.body.removeChild(link);
						}
					}
				}
				exportToCsv(file_name,rows);			
			}
		});	
	});
	
	$(document).on( 'click', '#request_btn', function () {
		console.log("Request a feature ");
		
		var url      	= window.location.href;
		var queryParam 	= url ? url.split('?')[1] : window.location.search.slice(1);
		
		window.location = "//wishlist.appsserver.net/bigcommerce_apps/wishlist/load_form.php?"+queryParam;
	});
		
	$(document).on( 'click', '#back_btn', function () {
		
//		var url      	= window.location.href;
//		var queryParam 	= url ? url.split('?')[1] : window.location.search.slice(1);
		// var payload		= getUrlParameter('store_hash');
		var payload		= getUrlParameter('signed_payload');
		window.location = "//wishlist.appsserver.net/bigcommerce_apps/wishlist/load.php?signed_payload="+payload;
    });
	
	$(".phone").on("keypress keyup blur",function (event) {    
	   $(this).val($(this).val().replace(/[^\d].+/, ""));
		if ((event.which < 48 || event.which > 57)) {
			event.preventDefault();
		}
    });
	//setTimeout( function(){
		
		$('input.name').blur(function(){
			if($(this).val() == ''){
				$('.name').css('border-color', 'red');   
			}
		});
		$('input.email').blur(function(){
			if($(this).val() == ''){
				$('.email').css('border-color', 'red');   
			}
		});
		$('textarea.comments').blur(function(){
			if($(this).val() == ''){
				$('#comments').css('border-color', 'red');    
			}
		});
		
	//}, 2500);
	
});