function pdfHTMLdownload() {


    try {
        console.log("generating pdf...");
        var doc = new jsPDF();
        var specialElementHandlers = {
            '#content': function (element, renderer) {
                return true;
            }
        };


        doc.fromHTML($('#content').html(), 20, 5, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });
        var pdfOutput = doc.output();
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {

            console.log(fileSystem.name);
            console.log(fileSystem.root.name);
            console.log(fileSystem.root.fullPath);

            fileSystem.root.getFile("smat_invoice.pdf", { create: true }, function (entry) {
                var fileEntry = entry;
                console.log(entry);

                entry.createWriter(function (writer) {
                    writer.onwrite = function (evt) {
                        alert("Download Complete2!\n Location:Internal Storage/smat_invoice.pdf");
                    };

                    console.log("writing to file");
                    writer.write(pdfOutput);
                }, function (error) {
                    console.log(error);
                });

            }, function (error) {
                console.log(error);
            });
        },
function (event) {
    console.log(evt.target.error.code);
});
       // var pdfOutput = doc.output();
        //doc.save('sample.pdf');
        // console.log(pdfOutput)

        //NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
      

    }
    catch (e) {
        alert(e.msg);
    }
}

function getQuotationDetails(){
	var quid=getParameterByName('invid', window.location.href);
	var qtres;
	$.ajax({
			type:"POST",
			data: { req: "INVPRV", quid: quid },
			url:url+"invoiceServices.php",
			dataType:"JSON",
			success:function(result){
				//console.log(JSON.stringify(result));
				//alert(result.op.status);
				if(result.op.status==true){
					//console.log(result.op.fdata.bname);
					qtres=result;
				}
				else{
					
				}
			},error:function(xhr,status,error){
				//alert(xhr.responseText);
				 alert(xhr.responseText);
				//$("#formmsg").css("color","red").html(xhr.responseText);
				
			},async:false,
		});
		return qtres;
}

//alert(sessionStorage.getItem('qdata'));
function pdfdownload() {

    
    try {
        var products = getQuotationDetails();
        //alert(JSON.parse(products['bname']));
        //alert("generating pdf...");
	
        var doc = new jsPDF();
        doc.setFont("times");
        doc.setFontType("bold");
        doc.setFontSize(20);
		var bname=(products.op.fdata.bname).replace(/\^/g,"'");
		var baddrr=(products.op.fdata.address).replace(/\^/g,"'");
		$("#bfd").html('<div class="bns_name"><span id="bname">'+bname+'</span></div><div class="bns_number"><span >'+baddrr+'</span></div><div class="bns_number"><span >'+products.op.fdata.cityname+' - '+products.op.fdata.postal_code+'</span></div><div class="bns_mail"><span >'+products.op.fdata.mailid+'</span></div>'+'<div class="bns_number"><span >'+products.op.fdata.mbl_no+'</span></div></div>');
					
          doc.text(10, 20, bname);
        doc.setFontSize(18);
        //doc.setFont("courier");
        doc.setFontType("normal");
        doc.text(10, 28, baddrr);
        doc.text(10, 36, products.op.fdata.cityname+'-'+products.op.fdata.postal_code);
        doc.text(10, 44, products.op.fdata.mailid);
        doc.text(10, 52, products.op.fdata.mbl_no);
        doc.text(10, 60, 'Date:'+ products.op.fdata.qdate);
        doc.setLineWidth(0.5);
        doc.line(10, 65, 200, 65);
        doc.rect(10, 70, 190, 12, 'FD');
        doc.setFontType("bold");
        doc.setFontSize(22);
        doc.setTextColor(255, 255, 255);

		$("#qtno").html('Invoice #'+products.op.fdata.qtno);
        doc.text(75, 78, qtype+products.op.fdata.qtno);
        doc.setFontSize(20);
        doc.setTextColor(0, 0, 0);
		var cname=(products.op.fdata.fname).replace(/\^/g,"'");
         doc.text(15, 90, 'To ' + cname);
        $("#cname").html('To ' + cname);
		
        doc.setFontSize(18);
        doc.text(20, 100, '#');
        doc.text(30, 100, 'Description');
        doc.text(100, 100, 'Qty');
        doc.text(120, 100, 'Unit Price');
        doc.text(170, 100, 'Amount');
        doc.setLineWidth(0.5);
        doc.line(10, 105, 200, 105);
        doc.setFontSize(16);
        doc.setFontType("normal");
        var textpos = 105;
        var lpos = 105;
        var sttl = 0;
        var tbody = "";
     for (var i = 0; i < products.op.sdata.length; i++) {
          var sno=i+1;
		 // alert(sno);
          textpos =lpos+8;
           lpos = textpos + 3;
            sttl += parseFloat(products.op.sdata[i]["ttlamt"]);
            doc.text(20, textpos,sno.toString());
            doc.text(30, textpos, products.op.sdata[i]['prd_name']);
            doc.text(105, textpos, products.op.sdata[i]["ttlqty"]);
            doc.text(125, textpos, products.op.sdata[i]["unitprice"]);
            doc.text(198, textpos, products.op.sdata[i]["ttlamt"],'right');
            doc.setLineWidth(0.5);
            doc.line(10, lpos, 200, lpos);
            tbody += ' <tr><td>' + sno + '</td><td class="text-left">' +products.op.sdata[i]['prd_name'] + '</td><td>' + products.op.sdata[i]["ttlqty"] + '</td><td>' +products.op.sdata[i]["unitprice"] + '</td><td class="text-right">' +products.op.sdata[i]["ttlamt"] + '</td></tr>';
			
        }
		var taxper=0;
      
        var tax = (sttl * taxper) / 100;
        textpos = lpos + 8;
        lpos = textpos + 3;
        doc.line(10, lpos, 200, lpos);
        textpos = lpos + 8;
        lpos = textpos + 3;
        doc.text(130, textpos, 'Sub Total');
        doc.text(198, textpos, (sttl.toFixed(2)).toString(),'right');
        doc.line(10, lpos, 200, lpos);
        textpos = lpos + 8;
        lpos = textpos + 3;
        doc.text(130, textpos, 'Tax');
        doc.text(198, textpos, (tax.toFixed(2)).toString(), 'right');
        doc.line(10, lpos, 200, lpos);
        textpos = lpos + 8;
        //lpos = textpos + 3;
        doc.text(130, textpos, 'Total');
        doc.rect(160, lpos, 40, 12, 'FD');
        doc.setFontSize(18);
        doc.setFontType("bold");
        doc.setTextColor(255, 255, 255);
        doc.text(198, textpos, (((tax + sttl)).toFixed(2)).toString(), 'right');
        tbody += ' <tr><td colspan = "5"><span style="visibility:hidden;">1<span></td></tr><tr><td colspan="4" class="text-right">Subtotal</td><td class="text-right font_bold" >' + (sttl.toFixed(2)).toString() + '</td></tr><tr><td colspan="4" class="text-right">Tax</td><td class="text-right font_bold" >' + (tax.toFixed(2)).toString() + '</td></tr><tr><td colspan="4" class="text-right font_bold" id="gtotal">Total ('+sessionStorage.getItem("munit")+')</td><td class="text-right font_bold background" >' + (((tax + sttl)).toFixed(2)).toString() + '</td></tr>';
        $("#qpreview").html(tbody);
        doc.setTextColor(0, 0, 0);
        doc.setFontType("normal");
        textpos = lpos + 25;
        doc.text(10, textpos, 'Date:');
        var today = new Date();
       // alert((today.getDay()).toString() + '-' + (today.getMonth()).toString() + '-' + (today.getFullYear()).toString());
        doc.setFontType("bold");
        doc.text(25, textpos, products.op.fdata.qdate);
        $("#cdate").html(products.op.fdata.qdate);
        textpos = lpos + 33;
        doc.setFontType("normal");
        doc.text(10, textpos, 'Valid Until:');
        doc.setFontType("bold");
        //today = today.setDate(today.getDate() + 7);
       // alert(today.getDate());
        doc.text(42, textpos, products.op.fdata.tdate);
        $("#vdate").html(products.op.fdata.tdate);
		
        doc.setFontType("normal");
        textpos = lpos + 55;
        doc.text(10, textpos, 'To Contact Us, if You Have any qustions.');
        textpos = lpos + 63;
        doc.text(10, textpos, 'We are always in Your Service,');
        textpos = lpos + 71;
        doc.text(10, textpos, bname);
		$("#fbname").html(bname);
      //  doc.line(10, lpos + 44, 200, lpos + 44);
        var pdfOutput = doc.output();
        //doc.save('sample.pdf');
       // alert(pdfOutput)

    //NEXT SAVE IT TO THE DEVICE'S LOCAL FILE SYSTEM
	
    window.requestFileSystem (LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
     
        var direntry = fileSystem.root;
        direntry.getDirectory('CrmLeader', { create: true }, function (dirEntry) {
           
            dirEntry.getDirectory('Documents', { create: true }, function (subDirEntry) {
                
                var filename = 'CrmLeader/Documents/invoice_crm_' + today.getDate() + '_' + today.getMonth() + '_' + today.getFullYear() + '_' + today.getHours() + '_' + today.getMinutes() + '_' + today.getSeconds() + '.pdf';
                //alert(filename);
                fileSystem.root.getFile (filename, { create: true }, function (entry) {
                    var fileEntry = entry;
                    
                    entry.createWriter(function (writer) {
                        writer.onwrite = function (evt) {
                            sessionStorage.setItem('filename', filename);
                            
                            //alert(sessionStorage.getItem('filename'));
                          // window.plugins.socialsharing.share('Hi! Sir/madam, I have attached the quatation above. Kindly check the quotation', 'Quotation', 'file:///storage/emulated/0/' + filename);
                            //alert("Download Complete1!\n Location:Internal Storage/CrmLeader/Documents/" + filename);
                        };

                        //  alert("writing to file");
                        writer.write(pdfOutput);
                    }, function (error) {
                        alert(error);
                    });

                }, function (error) {
                    alert(error);
                });
            },
    function (event) {
        alert(evt.target.error.code);
                alert(JSON.stringify(subDirEntry));

            }, onErrorDircreate);
        }, onErrorDircreate);

   
    });
   
    }
    catch (e) {
        alert(e.message);
    }
}

function jsonDownload(jdata) {
    try{
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
           
            // alert(fileSystem.name);
            // alert(fileSystem.root.name);
            // alert(fileSystem.root.fullPath);
            var direntry = fileSystem.root;
            direntry.getDirectory('My Accounts', { create: true }, function (dirEntry) {

                dirEntry.getDirectory('Json', { create: true }, function (subDirEntry) {

                    var filename = 'My Accounts/Json/payee' + '.json';
                    //alert(filename);
                 // var jdata = [{ name: 'vasinathan v', mblo: "9543344694" }];
                  //  alert(jdata);
                     fileSystem.root.getFile (filename, { create: true }, function (entry) {
                        var fileEntry = entry;

                       entry.createWriter(function (writer) {
                            writer.onwrite = function (evt) {
                                readjsonfile();
                                $("#pcode,#pname").val("");
                                alert("Added Sucessfully");
                            };

                            //  alert("writing to file");
                            writer.write(jdata);
                        }, function (error) {
                            alert(error);
                        });

                    }, function (error) {
                        alert(error);
                    });
                },
        function (event) {
            alert(evt.target.error.code);
            alert(JSON.stringify(subDirEntry));

        }, onErrorDircreate);
            }, onErrorDircreate);

            /*    */
        });
    }
    catch (e) {
        alert(e.message);
    }
}

function readjsonfile() {
    try {
       // var adres = addDirectories();
       // alert(adres);
        sessionStorage.setItem('pedata', "");
        $("#pid").val(1);
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
            var filename = 'My Accounts/Json/payee' + '.json';
          //  alert(filename);
            fileSystem.root.getFile(filename, { create: true }, function (fileEntry) {
                 fileEntry.file(function (file) {
                     var reader = new FileReader();
                     reader.onloadend = function () {
                         sessionStorage.setItem('pedata', this.result);
                         var odata = JSON.parse(this.result);
                         if (this.result=="") {
                             $("#pid").val(1);
                         }
                         else {
                             $("#pid").val(odata.length + 1);
                             pdata = '';
                             $("#add_details tbody").empty();
                             $.each(odata, function (index, value) {
                                 pdata = ' <tr><th scope="row">' + value['pid'] + '</th><td>' + value['pcode'] + ' ' + value['pname'] + '</td></tr>';
                                 $("#add_details tbody").append(pdata);
                             });
                         }

                        // alert(this.result);
                         //displayFileData(fileEntry.fullPath + ": " + this.result);
                     };
     
                     reader.readAsText(file);
                 },readFileerror);
             });
        });
    }
    catch (e) {
        alert(e.message);
    }
}
function addDirectories() {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) {
        var direntry = fileSystem.root;
        direntry.getDirectory('My Accounts', { create: true }, function (dirEntry) {
            dirEntry.getDirectory('Json', { create: true }, function (subDirEntry) {
                
            }, onErrorDircreate);
        }, onErrorDircreate);
    });
    return true;
}

function onErrorLoadFs(error) {
    alert("onErrorLoadFs error has occurred: Code = " + error.code + "source:" + error.source + "target:" + error.target);
}

function onErrorCreateFile(error) {
    alert("onErrorLoadFs error has occurred: Code = " + error.code + "source:" + error.source + "target:" + error.target);
}
function onErrorDownloadFS(error) {
    alert("onErrorDownloadFS error has occurred: Code = " + error.code + "source:" + error.source + "target:" + error.target);
}
function onErrorReadFile(error) {
    alert("onErrorReadFile error has occurred: Code = " + error.code + "source:" + error.source + "target:" + error.target);
}
function onErrorDircreate(error) {
    alert("onDirectorycreate error has occurred: Code = " + error.code + "source:" + error.source + "target:" + error.target);
}
function readFileerror(error) {
    alert(JSON.stringify(error));
}

try{
    //document.addEventListener("deviceready", readjsonfile, false);
}
catch (e) {
    alert(e.message);
}