Advertisement
Fabbrogas

Untitled

May 24th, 2016
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var app = {
  2.     // Application Constructor
  3.     initialize: function() {
  4.         this.bindEvents();
  5.     persistenceTest();
  6.     databaseCreateSchema(true, false, false);
  7.     setupHomePageProjects();
  8.     createEventHandlers();
  9.     },
  10.     // Bind Event Listeners
  11.     //
  12.     // Bind any events that are required on startup. Common events are:
  13.     // 'load', 'deviceready', 'offline', and 'online'.
  14.     bindEvents: function() {
  15.         document.addEventListener('deviceready', this.onDeviceReady, false);
  16.     },
  17.     // deviceready Event Handler
  18.     //
  19.     // The scope of 'this' is the event. In order to call the 'receivedEvent'
  20.     // function, we must explicitly call 'app.receivedEvent(...);'
  21.     onDeviceReady: function() {
  22.         app.receivedEvent('deviceready');
  23.     },
  24.     // Update DOM on a Received Event
  25.     receivedEvent: function(id) {
  26.         var parentElement = document.getElementById(id);
  27.         var listeningElement = parentElement.querySelector('.listening');
  28.         var receivedElement = parentElement.querySelector('.received');
  29.  
  30.         listeningElement.setAttribute('style', 'display:none;');
  31.         receivedElement.setAttribute('style', 'display:block;');
  32.  
  33.         console.log('Received Event: ' + id);
  34.     }
  35.  
  36.  
  37. };
  38.  
  39. app.initialize();
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55. var Task = persistence.define('Task', {
  56.   name: "TEXT",
  57.   done: "BOOL"
  58. });
  59.  
  60.  
  61.  
  62. function persistenceTest() {
  63.  
  64.     console.log("persistenceTest1");
  65.     persistence.store.websql.config(persistence, 'ptest', 'A database description', 5 * 1024 * 1024);
  66.  
  67.     console.log("persistenceTest2");
  68.  
  69.     //persistenceSchemaSync();
  70.     console.log("persistenceTest3");
  71.  
  72.     //persistenceReset();
  73.     console.log("persistenceTest4");
  74. }
  75.  
  76.  
  77.  
  78. function persistenceSchemaSync() {
  79. }
  80.  
  81. function persistenceReset() {
  82.     persistenceFlush();
  83. };
  84.  
  85. function persistenceFlush() {
  86. }
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94. function testJSONLoad() {
  95.     console.log("testJSONLoad1");
  96.     //  $.getJSON("http://localhost:8080/cc/tablet/UserTestPassword.jsp", {UserName: "ky1a21w2a1wv1lemore", Password: "b2t$g6y*"}, function(data) {
  97.     //  $.getJSON("/cc/tablet/UserTestPassword.jsp", {UserName: "ky1a21w2a1wv1lemore", Password: "b2t$g6y*"}, function(data) {
  98.     $.getJSON("http://10.60.74.102:8080/cc/tablet/UserTestPassword.jsp", {UserName: "ky1a21w2a1wv1lemore", Password: "b2t$g6y*"}, function(data) {
  99.         //  $.getJSON("alex.builderlynx.com:8080/cc/tablet/UserTestPassword.jsp", {UserName: "ky1a21w2a1wv1lemore", Password: "b2t$g6y*"}, function(data) {
  100.         console.log(data);
  101.         console.log(data.AuthenticationPassword);
  102.         console.log(data.AuthenticationUsername);
  103.         console.log(data.AuthenticationRequestResult);
  104.         alert(data.AuthenticationRequestResult);
  105.     });
  106. console.log("testJSONLoad2");
  107. }
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114.  
  115. // Wait for Cordova to load
  116. //
  117. document.addEventListener("deviceready", onDeviceReady, false);
  118.  
  119. // Cordova is ready
  120. //
  121. function onDeviceReady() {
  122.     console.log("onDeviceReady***1");
  123.  
  124.  
  125. }
  126.  
  127. function cleanString(str) {
  128.     str = str.replace(/[^a-zA-Z 0-9]+/g,'');
  129.     str = str.replace(/[ ]+/g, '');
  130.     return str;
  131. }
  132.  
  133. function processUnitDirectory(blUnit, actionOnDirectory) {
  134.     blProject = blUnit.blProject;
  135.     blUnit.fetch("BLProject", function (blProject) {
  136.         blDirectory = "BuilderLynx";
  137.         console.log("here1:" + blUnit.Name);
  138.         console.log("here1:" + blProject);
  139.         window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
  140.             function(fileSystem) {
  141.                 console.log("here2");
  142.                 fileSystem.root.getDirectory(blDirectory, {create: true}, function (dirBuilderLynx) {
  143.                     console.log("here3");
  144.                     dirBuilderLynx.getDirectory(cleanString(blProject.Name), {create: true}, function (dirProject) {
  145.                         console.log("here4");
  146.                         dirProject.getDirectory(cleanString(blUnit.Name), {create: true}, function (dirUnit) {
  147.                             console.log("here5");
  148.                             actionOnDirectory(dirUnit);
  149.                         }, fileOperationFail);
  150.                     }, fileOperationFail);
  151.                 }, fileOperationFail);
  152.             }, fileOperationFail);
  153.     });
  154. }
  155.  
  156.  
  157.  
  158. function fileOperationFail(error) {
  159.     console.log("fileOperationFail***2");
  160.     errorDesc = "";
  161.     if (error.code == FileError.NOT_FOUND_ERR) {
  162.         errorDesc = error.code + "NOT_FOUND_ERR";
  163.     } else if (error.code == FileError.SECURITY_ERR) {
  164.         errorDesc = error.code + "SECURITY_ERR";
  165.     } else if (error.code == FileError.ABORT_ERR) {
  166.         errorDesc = error.code + "ABORT_ERR";
  167.     } else if (error.code == FileError.NOT_READABLE_ERR) {
  168.         errorDesc = error.code + "NOT_READABLE_ERR";
  169.     } else if (error.code == FileError.ENCODING_ERR) {
  170.         errorDesc = error.code + "ENCODING_ERR";
  171.     } else if (error.code == FileError.NO_MODIFICATION_ALLOWED_ERR) {
  172.         errorDesc = error.code + "NO_MODIFICATION_ALLOWED_ERR";
  173.     } else if (error.code == FileError.INVALID_STATE_ERR) {
  174.         errorDesc = error.code + "INVALID_STATE_ERR";
  175.     } else if (error.code == FileError.SYNTAX_ERR) {
  176.         errorDesc = error.code + "SYNTAX_ERR";
  177.     } else if (error.code == FileError.INVALID_MODIFICATION_ERR) {
  178.         errorDesc = error.code + "INVALID_MODIFICATION_ERR";
  179.     } else if (error.code == FileError.QUOTA_EXCEEDED_ERR) {
  180.         errorDesc = error.code + "QUOTA_EXCEEDED_ERR";
  181.     } else if (error.code == FileError.TYPE_MISMATCH_ERR) {
  182.         errorDesc = error.code + "TYPE_MISMATCH_ERR";
  183.     } else if (error.code == FileError.PATH_EXISTS_ERR) {
  184.         errorDesc = error.code + "PATH_EXISTS_ERR";
  185.     }
  186.     console.log(errorDesc);
  187.     displayErrorMessage(errorDesc);
  188. }
  189.  
  190.  
  191. function displayErrorMessage() {
  192.     $('#PageReportError').html(message);
  193.     $('#PageReportError').popup();
  194. }
  195.  
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.  
  203.  
  204.  
  205.  
  206.  
  207.  
  208.  
  209.  
  210.  
  211.  
  212.  
  213.  
  214.  
  215. SQLDatabaseName = "BuilderLynxPDI";
  216. SQLDatabaseVersion = "1.0";
  217. SQLDatabaseSize = 5 * 1024 * 1024;
  218. SQLDatabase = null;
  219. SQLQueries = 0;
  220. SQLErrors = 0;
  221.  
  222. var BLProject = BLProject != null ? BLProject : null;
  223. var BLUnit = BLUnit != null ? BLUnit : null;
  224. var BLUser = BLUser != null ? BLUser : null;
  225. var BLRoom = BLRoom != null ? BLRoom : null;
  226. var BLDeficiencyType = BLDeficiencyType != null ? BLDeficiencyType : null;
  227. var BLDeficiency = BLDeficiency != null ? BLDeficiency : null;
  228. var BLSupplierDepartment = BLSupplierDepartment != null ? BLSupplierDepartment : null;
  229.  
  230. //DECLARATION VAR
  231. //var BLPic = BLPic != null ? BLPic : null;
  232.  
  233.  
  234.  
  235.  
  236. // Populate the database
  237.  
  238. function databaseCreateSchema(resetSchema, populateDatabase, dropAllData) {
  239.  
  240.     console.log("Create BLProject");
  241.     BLProject = persistence.define('BLProject', {
  242.         RemoteID: "INT",
  243.         Name: "TEXT",
  244.         CompanyName: "TEXT",
  245.         TarionRegistrationNumber: "TEXT",
  246.         Municipality: "TEXT",
  247.         Domain: "TEXT",
  248.     });
  249.  
  250.  
  251.     console.log("Create BLUnit");
  252.     BLUnit = persistence.define('BLUnit', {
  253.         RemoteID: "INT",
  254.         Name: "TEXT",
  255.         BuyerClosingDate: "TEXT",
  256.         MunicipalAddress: "TEXT",
  257.         City: "TEXT",
  258.         TarionEnrollmentNumber: "TEXT",
  259.     });
  260.     BLProject.hasMany("BLUnits", BLUnit, "BLProject");
  261.  
  262.     console.log("Create BLUser");
  263.     BLUser = persistence.define('BLUser', {
  264.         RemoteID: "INT",
  265.         Username: "TEXT",
  266.         Password: "TEXT",
  267.         Name1: "TEXT",
  268.         Name2: "TEXT",
  269.         Name3: "TEXT",
  270.         Name4: "TEXT",
  271.         Phone1: "TEXT",
  272.         Phone2: "TEXT",
  273.         Email: "TEXT",
  274.         Street: "TEXT",
  275.         City: "TEXT",
  276.         Province: "TEXT",
  277.         PostalCode: "TEXT",
  278.     });
  279.     BLUser.hasOne("BLProject", BLProject);
  280.     BLUser.hasOne("BLUnit", BLUnit);
  281.     BLUnit.hasOne("BLUser", BLUser);
  282.     BLProject.hasOne("BLUser", BLUser);
  283.  
  284.  
  285.     console.log("Create BLRoom");
  286.     BLRoom = persistence.define('BLRoom', {
  287.         RemoteID: "INT",
  288.         Name: "TEXT",
  289.     });
  290.     BLProject.hasMany("BLRooms", BLRoom, "BLProject");
  291.  
  292.  
  293.     console.log("Create BLSupplierDepartment");
  294.     BLSupplierDepartment = persistence.define('BLSupplierDepartment', {
  295.         RemoteID: "INT",
  296.         CompanyName: "TEXT",
  297.         ContactName: "TEXT",
  298.         Phone1: "TEXT",
  299.         Phone2: "TEXT",
  300.         Email: "TEXT",
  301.     });
  302.     BLProject.hasMany("BLSupplierDepartments", BLSupplierDepartment, "BLProject");
  303.  
  304.  
  305.     console.log("Create BLDeficiencyType");
  306.     BLDeficiencyType = persistence.define('BLDeficiencyType', {
  307.         RemoteID: "INT",
  308.         Name: "TEXT",
  309.     });
  310.     BLProject.hasMany("BLDeficiencyTypes", BLDeficiencyType, "BLProject");
  311.     BLDeficiencyType.hasOne("BLSupplierDepartment", BLSupplierDepartment);
  312.  
  313.     console.log("Create BLDeficiencyTypeDescription");
  314.     BLDeficiencyTypeDescription = persistence.define('BLDeficiencyTypeDescription', {
  315.         RemoteID: "INT",
  316.         Description: "TEXT",
  317.     });
  318.     BLDeficiencyTypeDescription.hasOne("BLDeficiencyType", BLDeficiencyType);
  319.     BLDeficiencyType.hasMany("BLDeficiencyTypeDescriptions", BLDeficiencyTypeDescription, "BLDeficiencyType");
  320.  
  321.     console.log("Create BLFormTemplate");
  322.     BLFormTemplate = persistence.define('BLFormTemplate', {
  323.         RemoteID: "INT",
  324.         Title: "TEXT",
  325.         Description: "TEXT",
  326.         Text: "TEXT",
  327.     });
  328.     BLProject.hasMany("BLFormTemplates", BLFormTemplate, "BLProject");
  329.  
  330.     //CAMERA ***************************************************************************************
  331.     /*console.log("Create BLPic");
  332.     BLPic = persistence.define('BLPic', {
  333.         RemoteID: "INT",
  334.         imageUrl: "TEXT",
  335.     });
  336.     BLProject.hasMany("BLPic", BLPic, "BLProject");*/
  337.     //FINE CAMERA **********************************************************************************
  338.  
  339.     console.log("Create BLDeficiency");
  340.     BLDeficiency = persistence.define('BLDeficiency', {
  341.         RemoteID: "INT",
  342.         Description: "TEXT",
  343.         Source: "TEXT",
  344.         Status: "TEXT",
  345.         ChargeBack: "TEXT",
  346.         Saved: "BOOL",
  347.     });
  348.     BLDeficiency.hasOne("BLRoom", BLRoom);
  349.     BLDeficiency.hasOne("BLDeficiencyType", BLDeficiencyType);
  350.     BLDeficiency.hasOne("BLUnit", BLUnit);
  351.     BLDeficiency.hasOne("BLProject", BLProject);
  352.     BLDeficiency.hasOne("BLSupplierDepartment", BLSupplierDepartment);
  353.     BLDeficiency.hasOne("BLSupplierDepartmentChargeBack", BLSupplierDepartment);
  354.     //CAMERA ***************************************************************************************
  355.     //BLDeficiency.hasOne("BLPic",BLPic);
  356.     //FINE CAMERA **********************************************************************************
  357.     BLUnit.hasMany("BLDeficiencies", BLDeficiency, "BLUnit");
  358.  
  359.  
  360.  
  361.     console.log("populateDB start");
  362.     if (resetSchema) {
  363.         persistenceReset();
  364.     }
  365.  
  366.     if (dropAllData) {
  367.         BLDeficiency.all().list(function (objects) {
  368.             objects.forEach(function (object) {
  369.                 persistence.remove(object);
  370.             });
  371.             console.log("Deleted all BLDeficiency");
  372.         });
  373.  
  374.         BLDeficiencyType.all().list(function (objects) {
  375.             objects.forEach(function (object) {
  376.                 persistence.remove(object);
  377.             });
  378.             console.log("Deleted all BLDeficiencyType");
  379.         });
  380.  
  381.         BLDeficiencyTypeDescription.all().list(function (objects) {
  382.             objects.forEach(function (object) {
  383.                 persistence.remove(object);
  384.             });
  385.             console.log("Deleted all BLDeficiencyTypeDescription");
  386.         });
  387.  
  388.         BLFormTemplate.all().list(function (objects) {
  389.             objects.forEach(function (object) {
  390.                 persistence.remove(object);
  391.             });
  392.             console.log("Deleted all BLFormTemplate");
  393.         });
  394.  
  395.         BLRoom.all().list(function (objects) {
  396.             objects.forEach(function (object) {
  397.                 persistence.remove(object);
  398.             });
  399.             console.log("Deleted all BLRoom");
  400.         });
  401.  
  402.         BLSupplierDepartment.all().list(function (objects) {
  403.             objects.forEach(function (object) {
  404.                 persistence.remove(object);
  405.             });
  406.             console.log("Deleted all BLSupplierDepartment");
  407.         });
  408.  
  409.         BLUnit.all().list(function (objects) {
  410.             objects.forEach(function (object) {
  411.                 persistence.remove(object);
  412.             });
  413.             console.log("Deleted all BLUnit");
  414.         });
  415.  
  416.         BLUser.all().list(function (objects) {
  417.             objects.forEach(function (object) {
  418.                 persistence.remove(object);
  419.             });
  420.             console.log("Deleted all BLUser");
  421.         });
  422.  
  423.         BLProject.all().list(function (objects) {
  424.             objects.forEach(function (object) {
  425.                 persistence.remove(object);
  426.             });
  427.             console.log("Deleted all BLProject");
  428.         });
  429.  
  430.         //PROVA CAMERA *****************************************************************************
  431.         /*BLPic.all().list(function (objects) {
  432.             objects.forEach(function (object) {
  433.                 persistence.remove(object);
  434.             });
  435.             console.log("Deleted all BLPic");
  436.         });*/
  437.         //FINE PROVA CAMERA ***********************************************************************
  438.     }
  439.  
  440.     persistence.schemaSync(function() {
  441.         console.log("Schema sync done");
  442.  
  443.         if (populateDatabase) {
  444.             databasePopulateDB();
  445.         }
  446.  
  447.     });
  448. }
  449.  
  450.  
  451. //DEMO DATABASE ************************************************************************************
  452. function databasePopulateDB() {
  453.  
  454.         var BLProject1 = new BLProject({RemoteID: 703273, Name: "Northshore1", CompanyName: "Fram Building Group", Plan: "2030-33"});
  455.         var BLProject2 = new BLProject({RemoteID: 123456, Name: "West Village 2B", CompanyName: "Kylemore Communities", Plan: "2030-33"});
  456.  
  457.         var BLUnit201 = createBLUnit(BLProject1, 1, "Suite 201", "2012/03/05");
  458.         var BLUnit202 = createBLUnit(BLProject1, 2, "Suite 202", "2012/03/07");
  459.         var BLUnit203 = createBLUnit(BLProject1, 3, "Suite 203", "2012/03/08");
  460.         var BLUnit302 = createBLUnit(BLProject1, 4, "Suite 301", "2012/03/09");
  461.         var BLUnit303 = createBLUnit(BLProject1, 5, "Suite 302", "2012/03/02");
  462.  
  463.         var BLLot1 = createBLUnit(BLProject2, 5, "Lot 1", "2012/03/05");
  464.         var BLLot2 = createBLUnit(BLProject2, 6, "Lot 2", "2012/03/04");
  465.         var BLLot3 = createBLUnit(BLProject2, 7, "Lot 3", "2012/03/03");
  466.         var BLLot4 = createBLUnit(BLProject2, 8, "Lot 4", "2012/03/02");
  467.         var BLLot5 = createBLUnit(BLProject2, 9, "Lot 5", "2012/03/01");
  468.  
  469.         createBLUser(BLProject1, BLUnit201, 1, "John1", "Smith1", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "201 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  470.         createBLUser(BLProject1, BLUnit202, 2, "John2", "Smith2", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "202 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  471.         createBLUser(BLProject1, BLUnit203, 3, "John3", "Smith3", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "203 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  472.         createBLUser(BLProject1, BLUnit302, 4, "John4", "Smith4", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "302 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  473.         createBLUser(BLProject1, BLUnit303, 5, "John5", "Smith5", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "303 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  474.  
  475.         createBLUser(BLProject2, BLLot1, 6, "Dave1", "Smith1", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "1 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  476.         createBLUser(BLProject2, BLLot2, 7, "Dave2", "Smith2", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "2 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  477.         createBLUser(BLProject2, BLLot3, 8, "Dave3", "Smith3", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "3 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  478.         createBLUser(BLProject2, BLLot4, 9, "Dave4", "Smith4", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "4 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  479.         createBLUser(BLProject2, BLLot5, 10, "Dave5", "Smith5", "416-425-2925", "416-425-4233", "alex@builderlynx.com", "5 Donlea Drive", "Toronto", "ON", "M4G 2M4");
  480.  
  481.         var p1S1 = createBLSupplierDepartment(BLProject1, 1, "Elec Contractors1", "Jeff Martino");
  482.         var p1S2 = createBLSupplierDepartment(BLProject1, 2, "Flooring Contractors2", "Jeff Martino");
  483.         var p1S3 = createBLSupplierDepartment(BLProject1, 3, "Plumbing Contractors3", "Jeff Martino");
  484.         var p1S4 = createBLSupplierDepartment(BLProject1, 4, "Paint Contractors4", "Jeff Martino");
  485.         var p1S5 = createBLSupplierDepartment(BLProject1, 5, "HVAC Contractors5", "Jeff Martino");
  486.         var p1S6 = createBLSupplierDepartment(BLProject1, 6, "Drywall Contractors6", "Jeff Martino");
  487.  
  488.         createBLSupplierDepartment(BLProject2, 7, "Elec Contractors1", "Jeff Martino");
  489.         createBLSupplierDepartment(BLProject2, 8, "Tile and Hardwood Contractors2", "Jeff Martino");
  490.         createBLSupplierDepartment(BLProject2, 9, "Plumbing Contractors3", "Jeff Martino");
  491.         createBLSupplierDepartment(BLProject2, 10, "Paint Contractors4", "Jeff Martino");
  492.         createBLSupplierDepartment(BLProject2, 11, "HVAC Contractors5", "Jeff Martino");
  493.         createBLSupplierDepartment(BLProject2, 12, "Drywall Contractors6", "Jeff Martino");
  494.  
  495.         var p1Foyer = createBLRoom(BLProject1, 1, "Foyer");
  496.         var p1Dinig = createBLRoom(BLProject1, 2, "Dining");
  497.         var p1Living = createBLRoom(BLProject1, 3, "Living");
  498.         var p1Stairs = createBLRoom(BLProject1, 4, "Stairs");
  499.         var p1MasterBedroom = createBLRoom(BLProject1, 5, "Master Bedroom");
  500.         var p1Bedroom2 = createBLRoom(BLProject1, 6, "Bedroom 2");
  501.         var p1Bedroom3 = createBLRoom(BLProject1, 7, "Bedroom 3");
  502.         var p1MainBathroom = createBLRoom(BLProject1, 8, "Main Bathroom");
  503.         var p1EnsuiteBathroom = createBLRoom(BLProject1, 9, "Ensuite Bathroom");
  504.  
  505.         var p1Other = createBLDeficiencyType(BLProject1, 1, "Other", null);
  506.         var p1Electrical = createBLDeficiencyType(BLProject1, 2, "Electrical", p1S1);
  507.         var p1Flooring = createBLDeficiencyType(BLProject1, 3, "Flooring", p1S2);
  508.         var p1Tile = createBLDeficiencyType(BLProject1, 4, "Tile", p1S2);
  509.         var p1Hardwood = createBLDeficiencyType(BLProject1, 5, "Hardwood", p1S2);
  510.         var p1Carpet = createBLDeficiencyType(BLProject1, 6, "Carpet", p1S2);
  511.         var p1Plumbing = createBLDeficiencyType(BLProject1, 7, "Plumbing", p1S3);
  512.         var p1Paint = createBLDeficiencyType(BLProject1, 8, "Paint", p1S4);
  513.         var p1HVAC = createBLDeficiencyType(BLProject1, 9, "HVAC", p1S5);
  514.         var p1Drywall = createBLDeficiencyType(BLProject1, 10, "Drywall", p1S6);
  515.  
  516.         createBLDeficiencyType(BLProject2, 11, "Other", -1);
  517.         createBLDeficiencyType(BLProject2, 12, "Electrical", -1);
  518.         createBLDeficiencyType(BLProject2, 13, "Flooring", -1);
  519.         createBLDeficiencyType(BLProject2, 14, "Tile", -1);
  520.         createBLDeficiencyType(BLProject2, 15, "Hardwood", -1);
  521.         createBLDeficiencyType(BLProject2, 16, "Carpet", -1);
  522.         createBLDeficiencyType(BLProject2, 17, "Plumbing", -1);
  523.         createBLDeficiencyType(BLProject2, 18, "Paint", -1);
  524.         createBLDeficiencyType(BLProject2, 19, "HVAC", -1);
  525.         createBLDeficiencyType(BLProject2, 20, "Drywall", -1);
  526.  
  527.         createBLDeficiency(BLUnit201, p1Foyer, p1HVAC, "Fix something1", "PDI", "New", p1S1);
  528.         createBLDeficiency(BLUnit202, p1Bedroom2, p1Electrical, "Broken Outlet", "Purchaser", "New", p1S2);
  529.         createBLDeficiency(BLUnit201, p1Bedroom2, p1Tile, "Fix somethingafdfad", "Conciliation", "Finished", p1S2);
  530.         createBLDeficiency(BLUnit201, p1Living, p1Hardwood, "Fix somethingbxvbxvbx", "Seasonal", "Deferred", p1S2);
  531.         createBLDeficiency(BLUnit201, p1Living, p1HVAC, "Fix somethingyutuytutyu", "Construction", "New", p1S3);
  532.         createBLDeficiency(BLUnit201, p1Stairs, p1Electrical, "Fix somethingklhklhjkl", "Inspection", "Sending", p1S1);
  533.         createBLDeficiency(BLUnit201, p1MainBathroom, p1Plumbing, "Fix somethingmbnvmnmv", "PDI", "New", p1S5);
  534.  
  535.         createBLFormTemplate(BLProject1, "1", "PDI Report", "Description of some kind", "PDI REPORT\n\nProject: #Project.Name.99#\nUser: #User.Name1.99# #User.Name2.99# #User.Name3.99# #User.Name4.99#\nUnit: #Unit.Name.99##Unit.Name.99##Unit.Name.99##System.Date# Some more text\nClosingDate: #Unit.Buyer Closing Date.99#\nEnd \nUnit: #Unit.Name.99# of PDI Report\nUnit: #Unit.Name.99#\nProject: #User.Name1.99# #User.Name2.99# #User.Name3.99# #User.Name4.99#\n\n");
  536.  
  537.         persistence.flush(function(err) {
  538.             console.log("Done Flushing!");
  539.             persistence.dump(null, [BLProject], function(dump) {
  540.                 console.log("DUMP START1");
  541.                 console.log(dump);
  542.                 console.log("DUMP DONE1");
  543.             });
  544.  
  545.  
  546. //              createEventHandlers();
  547.  
  548.             //setupHomePageProjects();
  549.  
  550. //              testFillReport();
  551.  
  552.         });
  553.  
  554.  
  555. }
  556.  
  557. function createBLUnit(blProject, remoteID, name, buyerClosingDate, municipalAddress, city, tarionEnrollmentNumber) {
  558.     var newUnit = new BLUnit({RemoteID: remoteID, Name: name, BuyerClosingDate: buyerClosingDate, MunicipalAddress: municipalAddress, City: city, TarionEnrollmentNumber: tarionEnrollmentNumber});
  559.     blProject.BLUnits.add(newUnit);
  560.     persistence.add(newUnit);
  561.     return newUnit;
  562. }
  563.  
  564. function createBLUser(blProject, blUnit, remoteID, name1, name2, phone1, phone2, email, street, city, province, postalCode) {
  565.     if (remoteID == 685438) {
  566.         console.log(remoteID);
  567.     }
  568.     var newUser = new BLUser({RemoteID: remoteID, Name1: name1, Name2: name2, Phone1: phone1, Phone2: phone2, Email: email, Street: street, City: city, Province: province, PostalCode: postalCode});
  569.     if (blUnit != null) {
  570.         blUnit.BLUser = newUser;
  571.         newUser.BLUnit = blUnit;
  572.     }
  573.     newUser.BLProject = blProject;
  574.     persistence.add(newUser);
  575.     return newUser;
  576. }
  577.  
  578. function createBLRoom(blProject, remoteID, name) {
  579.     var newRoom = new BLRoom({RemoteID: remoteID, Name: name});
  580.     blProject.BLRooms.add(newRoom);
  581.     persistence.add(newRoom);
  582.     return newRoom;
  583. }
  584.  
  585. function createBLDeficiencyType(blProject, remoteID, name, supplierDepartment) {
  586.     var newDefType = new BLDeficiencyType({RemoteID: remoteID, Name: name, BLDefaultSupplierDepartment: supplierDepartment});
  587.     blProject.BLDeficiencyTypes.add(newDefType);
  588.     newDefType.BLSupplierDepartment = supplierDepartment;
  589.     persistence.add(newDefType);
  590.  
  591.     /*for (i = 1; i < 10; i ++) {
  592. //          createBLDeficiencyTypeDescription(blProject, newDefType, remoteID * 10, "Description " + i + name);
  593.     }*/
  594.  
  595.     return newDefType;
  596. }
  597.  
  598. /*function createBLDeficiencyTypeDescription(blProject, blDeficiencyType, remoteID, description) {
  599.     var newDefTypeDesc = new BLDeficiencyTypeDescription({RemoteID: remoteID, Description: description});
  600.     blDeficiencyType.BLDeficiencyTypeDescriptions.add(newDefTypeDesc);
  601.     persistence.add(newDefTypeDesc);
  602.     return newDefTypeDesc;
  603. }*/
  604.  
  605. //CAMERA *******************************************************************************************
  606. /*function createBLPic(blProject, remoteID, imageUrl) {
  607.     var newPic = new BLPic({RemoteID: remoteID, ImageUrl: imageUrl });
  608.     blProject.BLPic.add(newPic);
  609.     persistence.add(newPic);
  610.     return newPic;
  611. }*/
  612. //END CAMERA ***************************************************************************************
  613.  
  614. function createBLSupplierDepartment(blProject, remoteID, companyName, contactName) {
  615.     var newSD = new BLSupplierDepartment({RemoteID: remoteID, CompanyName: companyName, ContactName: contactName});
  616.     blProject.BLSupplierDepartments.add(newSD);
  617.     persistence.add(newSD);
  618.     return newSD;
  619. }
  620.  
  621. function createBLFormTemplate(blProject, remoteID, title, description, text) {
  622.     var newFT = new BLFormTemplate({RemoteID: remoteID, Title: title, Description: description, Text: text});
  623.     blProject.BLFormTemplates.add(newFT);
  624.     persistence.add(newFT);
  625.     return newFT;
  626. }
  627.  
  628. //PROVA CAMERA
  629. //blPic ALLA FINE DA CANCELLARE SE NON FUNZIONA, AGGIUNGERE blPic ALLA FINE DELLA PRIMA RIGA QUANDO SI PROVA
  630. function createBLDeficiency(blUnit, blRoom, blDeficiencyType, description, source, status, blSupplierDepartment) {
  631.     var newDeficiency = new BLDeficiency({Description: description, Source: source, Status: status, Saved: true});
  632.     newDeficiency.BLUnit = blUnit;
  633.     newDeficiency.BLProject = blUnit.BLProject;
  634.     newDeficiency.BLRoom = blRoom;
  635.     newDeficiency.BLDeficiencyType = blDeficiencyType;
  636.     newDeficiency.BLSupplierDepartment = blSupplierDepartment;
  637.     //NEXT LINE DA ELIMINARE SE NON VA
  638.     //newDeficiency.BLPic = blPic;
  639.  
  640.     persistence.add(newDeficiency);
  641.     return newDeficiency;
  642. }
  643.  
  644.  
  645. function logDatabaseStatus() {
  646.     console.log("***DATABASE STATUS***");
  647.     console.log("DatabaseName: " + SQLDatabaseName);
  648.     console.log("SQLErrors   : " + SQLErrors);
  649.     console.log("***DATABASE STATUS***");
  650. }
  651.  
  652.  
  653. function setupHomePageProjects() {
  654.     $('#PageHomeListProject').empty();
  655.     BLProject.all().list(function (projects) {
  656.         projects.forEach(function (project) {
  657.             $('#PageHomeListProject').append($('<li/>', {
  658.                 'data-theme': "a"}).append($('<a/>', {
  659.                     'href': 'index.html#PageProject',
  660.                     'data-transition': 'slide',
  661.                     'class': 'projectButton',
  662.                     'projectID': project.id,
  663.                     'text': project.Name
  664.             })));
  665.         });
  666.         $("#PageHomeListProject").listview('refresh');
  667.         console.log(BLProject);
  668.     });
  669. }
  670.  
  671.  
  672.  
  673. function setupProjectPage(projectID) {
  674.     BLProject.load(projectID, function(project) {
  675.  
  676.         // If different project, then blank out list first
  677.         if ($("#PageProjectProjectName").text() != project.Name) {
  678.             $("#PageProjectProjectName").html(project.Name);
  679.  
  680.             document.BLProject = project;
  681.  
  682.             console.log("BLProject.BLUser: " + BLProject.BLUser);
  683.  
  684.             var projects = BLProject.all().filter("id", '=', project.id).prefetch("BLUser");
  685.             projects.list(null, function(results, err) {
  686.                 if (results) {
  687.                     var blp = results[0];
  688.                     var blu = blp.BLUser;
  689.                     if (blu != null) {
  690.                         $("#PageProjectUserInfo").html(blu.Name1 + " " + blu.Name2);
  691.                     }
  692.                 }
  693.             });
  694.  
  695. //                      BLUser.load(BLProject.BLUser, function(blUser) {
  696. //                          if (blUser != null) {
  697. //                              $("#PageProjectUserInfo").html(blUser.Name1 + " " + blUser.Name2);
  698. //                          }
  699. //                      });
  700.             $('#PageProjectListUnit').empty();
  701.             var units = BLUnit.all().filter("BLProject", '=', projectID);
  702.             units.list(null, function(results, err) {
  703.                 if (results) {
  704.                     for (i = 0; i < results.length; i ++) {
  705.                         unit = results[i];
  706.                         $('#PageProjectListUnit').append($('<li/>', {
  707.                             'data-theme': "a"}).append($('<a/>', {
  708.                                 'href': 'index.html#PageUnit',
  709.                                 'class': 'unitButton',
  710.                                 'data-transition': 'slide',
  711.                                 'unitID' : unit.id,
  712.                                 'text': unit.Name
  713.                         })));
  714.                         console.log(unit.Name);
  715.                     }
  716.                     $("#PageProjectListUnit").listview('refresh');
  717.                 } else {
  718.                     console.log("no units");
  719.                 }
  720.             });
  721.         }
  722.     });
  723. }
  724.  
  725.  
  726.  
  727.  
  728. function setupUnitPage(unitID) {
  729.     console.log("Parameter unitID=" + unitID);
  730.  
  731.     BLUnit.load(unitID, function(unit) {
  732.  
  733.         document.BLUnit = unit;
  734.  
  735.         if ($("#PageUnitUnitName").text() != unit.Name) {
  736.  
  737.             $("#PageUnitUnitName").html(unit.Name);
  738. //                      $("#PageUnitUnitName2").html(unit.Name);
  739.             $("#PageUnitUnitBuyerClosingDate").html(unit.BuyerClosingDate != null ? unit.BuyerClosingDate : "N/A");
  740.             $("#PageUnitUnitPurchaseDate").html(unit.PurchaseDate != null ? unit.PurchaseDate : "N/A");
  741.             $("#PageUnitUnitOccupancyDate").html(unit.OccupancyDate != null ? unit.OccupancyDate : "N/A");
  742.             $("#PageUnitUnitMunicipalAddress").html(unit.MunicipalAddress != null ? unit.MunicipalAddress : "N/A");
  743.             $("#PageUnitUnitCity").html(unit.City != null ? unit.City : "N/A");
  744.             $("#PageUnitUnitModel").html(unit.Model != null ? unit.Model : "N/A");
  745.             $("#PageUnitUnitCode").html(unit.Code != null ? unit.Code : "N/A");
  746.             $("#PageUnitUnitTarion").html(unit.Tarion != null ? unit.Tarion : "N/A");
  747.  
  748.             BLUser.findBy("BLUnit", unit.id, function(purchaser) {
  749.                 if (purchaser) {
  750.                     $("#PageUnitPurchaserName").text(purchaser.Name1 + " " + purchaser.Name2 + ", " + purchaser.Name3 + " " + purchaser.Name4);
  751.                     $("#PageUnitPurchaserPhone1").html(purchaser.Phone1 != null ? purchaser.Phone1 : "N/A");
  752.                     $("#PageUnitPurchaserPhone2").html(purchaser.Phone2 != null ? purchaser.Phone2 : "N/A");
  753.                     $("#PageUnitPurchaserEmail").html(purchaser.Email != null ? purchaser.Email : "N/A");
  754.                     $("#PageUnitPurchaserStreet").html(purchaser.Street != null ? purchaser.Street : "N/A");
  755.                     $("#PageUnitPurchaserCity").html(purchaser.City != null ? purchaser.City : "N/A");
  756.                     $("#PageUnitPurchaserProvince").html(purchaser.Province != null ? purchaser.Province : "N/A");
  757.                     $("#PageUnitPurchaserPostalCode").html(purchaser.PostalCode != null ? purchaser.PostalCode : "N/A");
  758.                 }
  759.             });
  760.  
  761.             $('#PageUnitGridDeficiencies').empty();
  762.             var defs = BLDeficiency.all().filter("BLUnit", '=', unit.id).prefetch("BLRoom").prefetch("BLDeficiencyType");
  763.             defs.list(null, function(results, err) {
  764.                 if (results) {
  765.                     defsTable = $('#PageUnitGridDeficiencies');
  766.                     defsTable.append($('<thead/>')).append(
  767.                                              $('<tr/>', {'class': 'blBold'}).append(
  768.                                              $('<td/>', {'class': 'blBold'}).text('View')
  769.                                            , $('<td/>', {'class': 'blBold'}).text('Room')
  770.                                            , $('<td/>', {'class': 'blBold'}).text('Type')
  771.                                            , $('<td/>', {'class': 'blBold'}).text('Description')
  772.                                            , $('<td/>', {'class': 'blBold'}).text('Source')
  773.                                            , $('<td/>', {'class': 'blBold'}).text('Status')
  774.                                            , $('<td/>', {'class': 'blBold'}).text('Supplier')
  775.                                            //ELIMINARE PROSSIMA RIGA SE NON FUNZIONA
  776.                                            //, $('<td/>', {'class': 'blBold'}).text('Pic')
  777.                                            ));
  778.                     for (i = 0; i < results.length; i ++) {
  779.                         def = results[i];
  780.                         pageUnitGridDeficienciesDeficiencyAppend(def, i);
  781.                     }
  782.                 } else {
  783.                     console.log("no defs");
  784.                 }
  785.                 $('#PageUnitButtonAddDeficiency').attr('href', "index.html#PageModifyDeficiency").attr('class', 'addDeficiencyButton').attr('unitID', unit.id);
  786. //                          $('#PageUnitGridDeficiencies').append($('<div/>', {'class': "grid_12"}).append($('<a/>', {
  787. //                              'href': 'index.html#PageModifyDeficiency?unitID=' + unit.id,
  788. //                              'id': 'PageUnitButtonAddDeficiency',
  789. //                              'data-transition': 'slide',
  790. //                              'text': 'Add Deficiency'
  791. //                          })));
  792.                 $("#PageUnitButtonAddDeficiency").trigger("create");
  793.             });
  794.  
  795.         }
  796.     });
  797.  
  798. }
  799.  
  800.  
  801. function createEventHandlers() {
  802.     console.log("createEventHandlers");
  803.  
  804.     // Setup for jqm.page.params.js plugin
  805.     $(document).bind("pagebeforechange", function( event, data ) {
  806.         $.mobile.pageData = (data && data.options && data.options.pageData) ? data.options.pageData : null;
  807.     });
  808.  
  809.     $( document ).bind("mobileinit", function() {
  810.         // Make your jQuery Mobile framework configuration changes here!
  811.         $.support.cors = true;
  812.         $.mobile.allowCrossDomainPages = true;
  813.     });
  814.  
  815.     $(document).on("vclick", ".projectButton", function() {
  816.         setupProjectPage($(this).attr("projectID"));
  817.     });
  818.  
  819.  
  820.     $(document).on("vclick", ".unitButton", function() {
  821.         setupUnitPage($(this).attr("unitID"));
  822.     });
  823.  
  824.  
  825.     $(document).on("vclick", ".addDeficiencyButton", function() {
  826.     //          setupDeficiencyPage($(this).attr("unitID"));
  827.         pageModifyDeficiencyActivate($(this).attr("unitID"), null);
  828.     });
  829.  
  830.  
  831.  
  832.  
  833.     $("#PageProjectSync").on("pageshow", function(e, data){
  834.         console.log("1111PageSync.Project=" + document.BLProject);
  835.         if (document.BLProject != null) {
  836.             console.log("PageSync.Project=" + document.BLProject);
  837.             console.log("PageSync.ProjectName=" + document.BLProject.Name);
  838.  
  839.             $("#PageProjectSyncProjectName").html(document.BLProject.Name);
  840.             $("#PageProjectSyncDomain").val(document.BLProject.Domain);
  841.  
  842.             var defsToSync = BLDeficiency.all().filter("RemoteID", '=', "0").filter("BLProject", '=', document.BLProject.id).prefetch("BLRoom").prefetch("BLDeficiencyType");
  843.             defsToSync.list(null, function(results, err) {
  844.                 if (results) {
  845.                     var objects = "Deficiencies: " + results.length;
  846.                     $("#PageProjectSyncObjectCountText").val(objects);
  847.                 }
  848.             });
  849.  
  850.             var projects = BLProject.all().filter("id", '=', document.BLProject.id).prefetch("BLUser");
  851.             projects.list(null, function(results, err) {
  852.                 if (results) {
  853.                     var blp = results[0];
  854.                     var blu = blp.BLUser;
  855.                     if (blu != null) {
  856.                         $("#PageProjectSyncUsername").val(blu.Username);
  857.                         $("#PageProjectSyncPassword").val(blu.Password);
  858.                     }
  859.                 }
  860.             });
  861.  
  862.         }
  863.     });
  864.  
  865.     $("#PageUnit").on("pageshow", function(e, data){
  866.  
  867.  
  868.     });
  869.  
  870.  
  871.     $("#PageModifyDeficiency").on("pageshow", function(e, data){
  872.         if ($.mobile.pageData && $.mobile.pageData.unitID){
  873.             console.log("Parameter unitID=" + $.mobile.pageData.unitID);
  874.             console.log("Parameter unitID=" + $.mobile.pageData.deficiencyID);
  875.  
  876.             pageModifyDeficiencyActivate($.mobile.pageData.unitID, $.mobile.pageData.deficiencyID);
  877.         }
  878.     });
  879.  
  880.     $(document).delegate(".ui-page","pagebeforehide", function(evt, ui){
  881.     //      alert('pagebeforehide fired');
  882.     });
  883.  
  884.  
  885.     $("index.html#PageModifyDeficiency").on("pagecontainerbeforechange", function(e, data){
  886.         var deficiency = document.BLDeficiency;
  887.         if (deficiency != null) {
  888.             if ( ! deficiency.Saved) {
  889.                 persistence.remove(deficiency);
  890.                 persistence.flush();
  891.             }
  892.         }
  893.     });
  894.  
  895. }
  896.  
  897. var blankCellValue = "<div>&nbsp;</div>";
  898.  
  899. function pageUnitGridDeficienciesDeficiencyAppend (deficiency, row) {
  900.     defsTable = $('#PageUnitGridDeficiencies tbody');
  901.  
  902.     defsTable.append($('<tr>', {'class': 'blTR'}).append(
  903.                       $('<td/>', {'class': 'blTD'}).append($('<a/>', {'class': 'button',
  904.                                                                 'href': 'index.html#PageModifyDeficiency?deficiencyID=' + deficiency.id + '&unitID=' + deficiency.BLUnit.id,
  905.                                                                 'data-transition': 'slide', 'data-role': 'link', 'name': 'PageModifyDeficiencyLink',
  906.                                                                 'text': 'View'
  907.                                                                 }))
  908.                     , $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_Room"}).html(deficiency.BLRoom != null ? deficiency.BLRoom.Name : blankCellValue)
  909.                     , $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_DeficiencyType"}).html(deficiency.BLDeficiencyType != null ? deficiency.BLDeficiencyType.Name : blankCellValue)
  910.                     , $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_Description"}).html(deficiency.Description)
  911.                     , $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_Source"}).html(deficiency.Source)
  912.                     , $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_Status"}).html(deficiency.Status)
  913.                     , $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_SupplierDepartment"}).html(deficiency.BLSupplierDepartment != null ? deficiency.BLSupplierDepartment.CompanyName : blankCellValue)
  914.                     //DA ELIMINARE SE NON VANNO LE IMMAGINI ************************************************************************************************************************************************************************
  915.                     //, $('<td/>', {'class': 'blTD', 'id': "Deficiency_" + deficiency.id + "_Pic"}).html(deficiency.Pic)
  916.                     )).trigger('create');
  917. }
  918.  
  919. function pageUnitGridDeficienciesDeficiencyUpdate (deficiency) {
  920.     $('#Deficiency_' + deficiency.id + "_Room").html(deficiency.BLRoom != null ? deficiency.BLRoom.Name : blankCellValue);
  921.     $('#Deficiency_' + deficiency.id + "_DeficiencyType").html(deficiency.BLDeficiencyType != null ? deficiency.BLDeficiencyType.Name : blankCellValue);
  922.     $('#Deficiency_' + deficiency.id + "_Description").html(deficiency.Description);
  923.     $('#Deficiency_' + deficiency.id + "_Source").html(deficiency.Source);
  924.     $('#Deficiency_' + deficiency.id + "_Status").html(deficiency.Status);
  925.     $('#Deficiency_' + deficiency.id + "_SupplierDepartment").html(deficiency.BLSupplierDepartment != null ? deficiency.BLSupplierDepartment.CompanyName : blankCellValue);
  926.     //DA ELIMINARE SE NON VANNO LE IMMAGINI ************************************************************************************************************************************************************************
  927.     //$('#Deficiency_' + deficiency.id + "_Pic").html(deficiency.Pic);
  928. }
  929.  
  930.  
  931.  
  932. var DeficiencySource = null;
  933. var DeficiencyStatus = null;
  934.  
  935. function pageModifyDeficiencyActivate(unitID, deficiencyID) {
  936.     BLUnit.load(unitID, function(unit) {
  937.         var deficiency = null;
  938.         if (deficiencyID == null) {
  939.             deficiency = new BLDeficiency({BLUnit: unitID, BLProject: unit.BLProject, Saved: false});
  940.             if (document.DeficiencySource != null) {
  941.                 deficiency.Source = document.DeficiencySource;
  942.             }
  943.             if (document.DeficiencyStatus != null) {
  944.                 deficiency.Status = document.DeficiencyStatus;
  945.             }
  946.             pageModifyDeficiencySetup(unit, deficiency);
  947.         } else {
  948.             BLDeficiency.load(deficiencyID, function(deficiency) {
  949.                 pageModifyDeficiencySetup(unit, deficiency);
  950.             });
  951.         }
  952.     });
  953. }
  954.  
  955. function pageModifyDeficiencySetup(unit, deficiency) {
  956.     // If different unit, then blank out list first
  957.     if (deficiency._new) {
  958.         $("#PageModifyDeficiencyUnitName").html(unit.Name + " Add Deficiency");
  959.     } else {
  960.         $("#PageModifyDeficiencyUnitName").html(unit.Name + " Modify Deficiency");
  961.     }
  962.     $("#PageModifyDeficiencyUnitName").attr('persistenceID', unit.id);
  963.  
  964.     document.BLDeficiency = deficiency;
  965.  
  966.     $('#DeficiencyRoom').empty();
  967.     addSelectOption("#DeficiencyRoom", "", "", deficiency.BLRoom == null ? "" : deficiency.BLRoom.id);
  968.     var rooms = BLRoom.all().filter("BLProject", '=', unit.BLProject).order("Name", true);
  969.     rooms.list(null, function(results, err) {
  970.         if (results) {
  971.             for (var i = 0; i < results.length; i ++) {
  972.                 room = results[i];
  973.                 addSelectOption("#DeficiencyRoom", room.id, room.Name, deficiency.BLRoom == null ? "" : deficiency.BLRoom.id);
  974.             }
  975.             $("#DeficiencyRoom").selectmenu("refresh", true);
  976.         } else {
  977.             console.log("no rooms");
  978.         }
  979.     });
  980.  
  981.  
  982.     //PROVA ALERT
  983.     //alert("RESETTING TYPE");
  984.     $('#DeficiencyType').empty();
  985.     addSelectOption("#DeficiencyType", "", "", deficiency.BLDeficiencyType == null ? "" : deficiency.BLDeficiencyType.id);
  986.     var defTypes = BLDeficiencyType.all().filter("BLProject", '=', unit.BLProject).order("Name", true);
  987.     defTypes.list(null, function(results, err) {
  988.         if (results) {
  989.             for (var i = 0; i < results.length; i ++) {
  990.                 defType = results[i];
  991.                 addSelectOption("#DeficiencyType", defType.id, defType.Name, deficiency.BLDeficiencyType == null ? "" : deficiency.BLDeficiencyType.id);
  992.             }
  993.             $("#DeficiencyType").selectmenu("refresh", true);
  994.         } else {
  995.             console.log("no def types");
  996.         }
  997.     });
  998.     //alert("TYPE RESET");
  999.  
  1000.     $('#DeficiencyDescription').val(deficiency.Description);
  1001.     //$('#DeficiencyDescription').trigger("create");
  1002.     $('#DeficiencySource').val(deficiency.Source).attr('selected', true).siblings('option').removeAttr('selected');
  1003.     $('#DeficiencySource').selectmenu("refresh", true);
  1004.     $('#DeficiencyStatus').val(deficiency.Status).attr('selected', true).siblings('option').removeAttr('selected');
  1005.     $('#DeficiencyStatus').selectmenu("refresh", true);
  1006.  
  1007.  
  1008.     if ("True" == deficiency.ChargeBack) {
  1009.         $('#DeficiencyChargeBackYes').attr('checked', true).checkboxradio("refresh");
  1010.         $('#DeficiencyChargeBackNo').removeAttr('checked').checkboxradio("refresh"); ;
  1011.     } else {
  1012.         $('#DeficiencyChargeBackYes').removeAttr('checked').checkboxradio("refresh"); ;
  1013.         $('#DeficiencyChargeBackNo').attr('checked', true).checkboxradio("refresh"); ;
  1014.     }
  1015.  
  1016.  
  1017.     $('#DeficiencySupplier').empty();
  1018.     addSelectOption("#DeficiencySupplier", "", "", deficiency.BLSupplierDepartment == null ? "" : deficiency.BLSupplierDepartment.id);
  1019.     var supplierDepartments = BLSupplierDepartment.all().filter("BLProject", '=', unit.BLProject).order("CompanyName", true);
  1020.     supplierDepartments.list(null, function(results, err) {
  1021.         if (results) {
  1022.             for (i = 0; i < results.length; i ++) {
  1023.                 supplierDepartment = results[i];
  1024.                 addSelectOption("#DeficiencySupplier", supplierDepartment.id, supplierDepartment.CompanyName + " " + supplierDepartment.ContactName, deficiency.BLSupplierDepartment == null ? "" : deficiency.BLSupplierDepartment.id);
  1025.             }
  1026.             $("#DeficiencySupplier").selectmenu("refresh", true);
  1027.             } else {
  1028.             console.log("no def types");
  1029.         }
  1030.     });
  1031.  
  1032.     $('#DeficiencySupplierChargeBack').empty();
  1033.     addSelectOption("#DeficiencySupplierChargeBack", "", "", deficiency.BLSupplierDepartmentChargeBack == null ? "" : deficiency.BLSupplierDepartmentChargeBack.id);
  1034.     var supplierDepartmentsChargeBack = BLSupplierDepartment.all().filter("BLProject", '=', unit.BLProject).order("CompanyName", true);
  1035.     supplierDepartments.list(null, function(results, err) {
  1036.         if (results) {
  1037.             for (i = 0; i < results.length; i ++) {
  1038.                 supplierDepartment = results[i];
  1039.                 addSelectOption("#DeficiencySupplierChargeBack", supplierDepartment.id, supplierDepartment.CompanyName + " " + supplierDepartment.ContactName, deficiency.BLSupplierDepartmentChargeBack == null ? "" : deficiency.BLSupplierDepartmentChargeBack.id);
  1040.             }
  1041.             $("#DeficiencySupplierChargeBack").selectmenu("refresh", true);
  1042.             } else {
  1043.             console.log("no def types");
  1044.         }
  1045.     });
  1046.  
  1047.  
  1048.  
  1049.     //CAMERA O UNO O L'ALTRO, DA PROVARE ENTRAMBI*******************************************
  1050.     /*alert("RESETTING PIC");
  1051.     $('#ShowImageTaken').removeAttr('imageUrl');
  1052.  
  1053.     alert("PIC RESET");*/
  1054.     //END CAMERA ***************************************************************************
  1055.  
  1056.     pageDeficiencyBlankForm();
  1057. }
  1058.  
  1059. function pageDeficiencyBlankForm() {
  1060.   //$('#DeficiencyRoom').empty();
  1061.   //$('#DeficiencyType').empty();
  1062.   //$('#DeficiencyDescription').empty();
  1063.   //$('#DeficiencyTypeDescription').empty();
  1064.   //$('#DeficiencySupplier').empty();
  1065.   //$('#DeficiencySupplierChargeBack').empty();
  1066.   //$('#DeficiencySupplier').empty();
  1067.   //$('#DeficiencySupplierChargeBack').empty();
  1068.   //$('#DeficiencyPic').empty();
  1069.  
  1070. }
  1071.  
  1072. function addSelectOption(elementID, value, text, valueToSelect) {
  1073.     $(elementID).append($('<option/>', {
  1074.     'value': value,
  1075.     'text': text}));
  1076.  
  1077.     if (valueToSelect == null) {
  1078.         valueToSelect = "";
  1079.     }
  1080.  
  1081. //      if (elementID == "#DeficiencyType") {
  1082. //          console.log(elementID + " '" + value + "' '" + text + "' =test: '" + valueToSelect + "' comp: " + (value == valueToSelect) );
  1083. //      }
  1084.  
  1085. //      if (value == valueToSelect) {
  1086. //          console.log("matched: " + elementID);
  1087. //      }
  1088.  
  1089.     if (value == "") {
  1090.         $(elementID).val(value).attr('data-placeholder', "true");
  1091.     }
  1092.     if (value == valueToSelect) {
  1093. //          console.log("*****" + elementID + ": " + value + " = " + valueToSelect);
  1094.         $(elementID).val(value).attr('selected', true).siblings('option').removeAttr('selected');
  1095.     }
  1096. }
  1097.  
  1098.  
  1099. $('#DeficiencyType').click(function(e) {
  1100.     //$('#DeficiencyTypeDescription').empty();
  1101.     BLDeficiencyType.load($('#DeficiencyType').val(), function(deficiencyType) {
  1102.  
  1103.         if (deficiencyType.BLSupplierDepartment != null) {
  1104.             $('#DeficiencySupplier').val(deficiencyType.BLSupplierDepartment.id).attr('selected', true).siblings('option').removeAttr('selected');
  1105.         } else {
  1106.             $('#DeficiencySupplier').val("").attr('selected', true).siblings('option').removeAttr('selected');
  1107.         }
  1108.         $("#DeficiencySupplier").selectmenu("refresh", true);
  1109.  
  1110.         //var defTypeDescs = BLDeficiencyTypeDescription.all().filter("BLDeficiencyType", '=', deficiencyType.id);
  1111.         defTypeDescs.list(null, function(results, err) {
  1112.             if (results) {
  1113.                 for (i = 0; i < results.length; i ++) {
  1114.                     defTypeDesc = results[i];
  1115.                     console.log(defTypeDesc.id);
  1116.                     console.log(defTypeDesc.Description);
  1117.                     /*$('#DeficiencyTypeDescription').append($('<option/>', {
  1118.                         'value': defTypeDesc.id,
  1119.                         'text': defTypeDesc.Description
  1120.                     }));*/
  1121.                 }
  1122.                 //$("#DeficiencyTypeDescription").selectmenu("refresh", true);
  1123.             } else {
  1124.                 console.log("no def type descs");
  1125.             }
  1126.         });
  1127.     });
  1128. });
  1129.  
  1130.     /*$('#DeficiencyTypeDescription').click(function(e) {
  1131.         BLDeficiencyTypeDescription.load($('#DeficiencyTypeDescription').val(), function(deficiencyTypeDescription) {
  1132.             $('#DeficiencyDescription').append(" " + deficiencyTypeDescription.Description);
  1133.         });
  1134.     });*/
  1135.  
  1136. $('#DeficiencyChargeBackYes').click(function(e) {
  1137.     $('#DeficiencySupplierChargeBack').val("");
  1138.     $('#DeficiencySupplierChargeBack').removeAttr("disabled");
  1139. });
  1140.  
  1141. $('#DeficiencyChargeBackNo').click(function(e) {
  1142.     $('#DeficiencySupplierChargeBack').val("");
  1143.     $('#DeficiencySupplierChargeBack').attr("disabled");
  1144. });
  1145.  
  1146. //CAMERA *******************************************************************************************
  1147. /*$('#DeficiencyPic').click(function(e) {
  1148.     $('#ShowImageTaken').val("");
  1149.     $('#DeficiencyPic').append($('<option/>', {
  1150.         'value': defPic.id,
  1151.         'text': defPic.imageUrl
  1152.     }));
  1153. });*/
  1154. //FINE CAMERA **************************************************************************************
  1155.  
  1156. $('#PageModifyDeficiencyButtonSave').click(function(e) {
  1157.     var defUnit = $("#PageModifyDeficiencyUnitName").attr('persistenceID');
  1158.     BLUnit.load(defUnit, function(unit) {
  1159.  
  1160.         var defProject = unit.BLProject;
  1161.         var defRoom = $('#DeficiencyRoom').val();
  1162.         var defType = $('#DeficiencyType').val();
  1163.         var defDesc = $('#DeficiencyDescription').val();
  1164.         var defSource = $('#DeficiencySource').val();
  1165.         var defStatus = $('#DeficiencyStatus').val();
  1166.         var defSupplier = $('#DeficiencySupplier').val();
  1167.         var defChargeBack = $('input[name*=DeficiencyChargeBack]:checked').val();
  1168.         var defSupplierChargeBack = $('#DeficiencySupplierChargeBack').val();
  1169.         //DA ELIMINARE SE CAMERA E' DA TOGLIERE ****************************************************
  1170.         //var defPic = $('#ShowImageTaken').val();
  1171.  
  1172.  
  1173.  
  1174.         console.log("defProject: " + defProject);
  1175.         console.log("defUnit: " + defUnit);
  1176.         console.log("defRoom: " + defRoom);
  1177.         console.log("defType: " + defType);
  1178.         console.log("defDesc: " + defDesc);
  1179.         console.log("defSource: " + defSource);
  1180.         console.log("defStatus: " + defStatus);
  1181.         console.log("defSupplier: " + defSupplier);
  1182.         console.log("defChargeBack: " + defChargeBack);
  1183.         console.log("defSupplierChargeBack: " + defSupplierChargeBack);
  1184.         //DA ELIMINARE SE CAMERA E' DA TOGLIERE ****************************************************
  1185.         //console.log("defPic: " + defPic);
  1186.  
  1187.         document.DeficiencySource = defSource;
  1188.         document.DeficiencyStatus = defStatus;
  1189.  
  1190.         var deficiency = document.BLDeficiency;
  1191.         if (deficiency != null) {
  1192.             deficiency.BLProject = defProject;
  1193.             deficiency.BLUnit = defUnit;
  1194.             deficiency.BLRoom = defRoom;
  1195.             deficiency.BLDeficiencyType = defType;
  1196.             deficiency.Description = defDesc;
  1197.             deficiency.Source = defSource;
  1198.             deficiency.Status = defStatus;
  1199.             deficiency.BLSupplierDepartment = defSupplier;
  1200.             deficiency.BLSupplierDepartmentChargeBack = defSupplierChargeBack;
  1201.             //DA ELIMINARE SE CAMERA E' DA TOGLIERE ************************************************
  1202.             //deficiency.BLPic = defPic;
  1203.  
  1204.             if (defChargeBack != null) {
  1205.                 deficiency.ChargeBack = defChargeBack;
  1206.             }
  1207.  
  1208.             var saved = deficiency.Saved;
  1209.             deficiency.Saved = true;
  1210.             persistence.add(deficiency);
  1211.             persistence.flush();
  1212.  
  1213.             if ( ! saved) {
  1214.                 pageUnitGridDeficienciesDeficiencyAppend(deficiency);
  1215.             } else {
  1216.                 pageUnitGridDeficienciesDeficiencyUpdate(deficiency);
  1217.             }
  1218.         }
  1219.     });
  1220.  
  1221. });
  1222.  
  1223. $('#PageModifyDeficiencyButtonCancel').click(function(e) {
  1224.     var deficiency = document.BLDeficiency;
  1225.     if (deficiency != null) {
  1226.         if ( ! deficiency.Saved) {
  1227.             persistence.remove(deficiency);
  1228.             persistence.flush();
  1229.         }
  1230.     }
  1231. //          $.mobile.changePage("index.html#PageUnit", { transition: "slideup"} );
  1232. });
  1233.  
  1234.  
  1235.  
  1236. $("#SetupButton").click(function(e) {
  1237.     e.preventDefault();
  1238.     //alert("SetupButton is clicked");
  1239.     $.mobile.changePage("index.html#PageSetup", { transition: "slideup"} );
  1240.     return false;
  1241. });
  1242.  
  1243.  
  1244. $("#PageSetupDownloadProject").click(function (e) {
  1245.     e.preventDefault();
  1246.     domain = $("#PageSetupDomain").val();
  1247.     username = $("#PageSetupUsername").val();
  1248.     password = $("#PageSetupPassword").val();
  1249.     details = $("#PageSetupDetails");
  1250.     details.append("Starting Download\n");
  1251.     details.append("Domain: " + domain + "\n");
  1252.     details.append("Username: " + username + "\n");
  1253.     details.append("Password: " + password + "\n");
  1254.     details.append("Calling Authentication\n");
  1255.  
  1256.     console.log(domain + ", " + username + ", " + password);
  1257.  
  1258.     $.getJSON("http://" + domain + "/cc/tablet/UserTestPassword.jsp", {UserName: username, Password: password}, function(data) {
  1259. //          alert(data.AuthenticationRequestResult);
  1260.         console.log(data);
  1261.         console.log(data.AuthenticationPassword);
  1262.         console.log(data.AuthenticationUsername);
  1263.         console.log(data.AuthenticationRequestResult);
  1264.         details.append("AuthenticationRequestResult: '" + data.AuthenticationRequestResult + "'\n");
  1265.         if ("Successful Login" == data.AuthenticationRequestResult) {
  1266.             details.append("Get Project Info\n");
  1267.             $.getJSON("http://" + domain + "/cc/tablet/GetProject.jsp", {UserName: username, Password: password}, function(data) {
  1268.                 try {
  1269.                     details.append("Got Project Info\n");
  1270.  
  1271. //                      alert("Name: " + data.Properties[3].Value);
  1272.                     var projectP = propertiesToObject(data.Properties);
  1273.                     details.append("ProjectName: " + projectP.Name + "'\n");
  1274.                     details.append("ProjectID: " + projectP.ID + "'\n");
  1275.  
  1276.                     var blProject = new BLProject({RemoteID: projectP.ID, Name: projectP.Name, Plan: projectP.Plan, CompanyName: projectP.CompanyName, TarionRegistrationNumber: projectP.TarionRegistrationNumber, Municipality: projectP.Municipality});
  1277.                     blProject.Domain = domain;
  1278.                     persistence.add(blProject);
  1279.  
  1280.                     persistence.flush(null, function(err) {
  1281.                         details.append("Storing Project\n");
  1282.  
  1283.                         console.log("Done Flushing!");
  1284.  
  1285.                         details.append("Updating Project List\n");
  1286.  
  1287.                         setupHomePageProjects();
  1288.  
  1289.                         details.append("Downloading Supplier Departments\n");
  1290.  
  1291.                         downloadProjectSupplierDepartments(blProject);
  1292.                     });
  1293.                 } catch (ex) {
  1294.                     alert(ex);
  1295.                 }
  1296.             });
  1297.         }
  1298.     });
  1299.  
  1300. });
  1301.  
  1302.  
  1303. function propertiesToObject(properties) {
  1304.     var obj = new Object();
  1305.     for (i = 0; i < properties.length; i ++) {
  1306.         obj[properties[i].Name] = properties[i].Value;
  1307.     }
  1308. //      console.log(obj);
  1309.     return obj;
  1310. }
  1311.  
  1312. var BatchSize = 3;
  1313.  
  1314.  
  1315. function downloadProjectSupplierDepartments(blProject) {
  1316.     alert("Downloading Supplier Departments (1/7)");
  1317.     details = $("#PageSetupDetails");
  1318.     details.append("SupplierDepartment Sending JSON Request\n");
  1319.     $.getJSON("http://" + domain + "/cc/tablet/GetSupplierDepartments.jsp", {}, function(data) {
  1320.         try {
  1321.             details.append("SupplierDepartment Processing Response\n");
  1322.             var supplierDepartments = data.SupplierDepartments;
  1323.             details.append("Records: " + supplierDepartments.length + "\n");
  1324.  
  1325.             processSupplierDepartments(blProject, supplierDepartments, 0);
  1326.  
  1327.         } catch (ex) {
  1328.             alert(ex);
  1329.         }
  1330.     });
  1331. }
  1332.  
  1333. function processSupplierDepartments(blProject, supplierDepartments, startFrom) {
  1334.     var addedObjects = false;
  1335.     for (var i = startFrom; i < supplierDepartments.length && i < startFrom + BatchSize; i ++) {
  1336.  
  1337.         po = supplierDepartments[i];
  1338.         sdp = propertiesToObject(po.Properties);
  1339.         //console.log(sdp);
  1340.  
  1341.         blSupplierDepartment = createBLSupplierDepartment(blProject, sdp.ID, sdp.CompanyName, sdp.ContactName);
  1342.         blSupplierDepartment.Phone1 = sdp.OfficePhone;
  1343.         blSupplierDepartment.Phone1 = sdp.MobilePhone;
  1344.         blSupplierDepartment.Email = sdp.Email;
  1345.         if (i % 10 == 0) {
  1346.             details.append("SupplierDepartment Record " + i + " of " + supplierDepartments.length + "\n");
  1347.         }
  1348.         addedObjects = true;
  1349.     }
  1350.     details.append("SupplierDepartment Done Creating Objects\n");
  1351.  
  1352.     if (addedObjects) {
  1353.         persistence.flush(null, function(err) {
  1354.             if (err != null) {
  1355. //                  alert(err);
  1356.             }
  1357.             details.append("SupplierDepartment Done Flush\n");
  1358.             console.log("Done SupplierDepartments Flushing!");
  1359.             processSupplierDepartments(blProject, supplierDepartments, startFrom + BatchSize);
  1360.         });
  1361.     } else {
  1362.         //downloadProjectDeficiencyTypes(blProject);
  1363.         downloadProjectUnits(blProject);
  1364.     }
  1365. }
  1366.  
  1367. function downloadProjectDeficiencyTypes(blProject) {
  1368.     alert("Downloading Deficiency Types (3/7)");
  1369.     details = $("#PageSetupDetails");
  1370.     details.append("DeficiencyTypes Sending JSON Request\n");
  1371.     $.getJSON("http://" + domain + "/cc/tablet/GetDeficiencyTypes.jsp", {}, function(data) {
  1372.         try {
  1373.             details.append("DeficiencyTypes Processing Response\n");
  1374.             var defTypes = data.DeficiencyTypes;
  1375.             details.append("Records: " + defTypes.length + "\n");
  1376.  
  1377.             $("#PageSetupSliderRecords").attr("value", 0);
  1378.             $("#PageSetupSliderRecords").attr("max", defTypes.length);
  1379.  
  1380.             for (var i = 0; i < defTypes.length; i ++) {
  1381.                 po = defTypes[i];
  1382.                 dtp = propertiesToObject(po.Properties);
  1383.  
  1384.                 sdid = dtp.SupplierDepartment;
  1385.                 if (sdid != "-1") {
  1386.                     ( function (dtp) {
  1387.                         var sds = BLSupplierDepartment.all().filter("RemoteID", '=', dtp.SupplierDepartment);
  1388.                         sds.list(null, function(results, err) {
  1389.                             console.log("results: " + results.length);
  1390.                             if (results && results.length > 0) {
  1391. //                                  alert("found Supplier Department");
  1392.                                 sd = results[0];
  1393.                                 var blDefType = createBLDeficiencyType(blProject, dtp.ID, dtp.Name, sd);
  1394.                             }
  1395.                         });
  1396.                     })(dtp);
  1397.  
  1398.                 } else {
  1399.                     var blDefType = createBLDeficiencyType(blProject, dtp.ID, dtp.Name, null);
  1400.                 }
  1401.  
  1402.                 if (i % 10 == 0) {
  1403.                     details.append("DeficiencyType Record " + i + " of " + defTypes.length + "\n");
  1404.                 }
  1405.             }
  1406.  
  1407. /*
  1408.             var names = new Array();
  1409.             var dtids = new Array();
  1410.             for (var i = 0; i < defTypes.length; i ++) {
  1411.                 $("#PageSetupSliderRecords").attr("value", i);
  1412.                 $("#PageSetupSliderRecords").attr("val", i);
  1413.                 $("#PageSetupSliderRecords").slider("refresh", true);
  1414.                 $("#PageSetupSliderRecords").slider();
  1415.  
  1416.                 po = defTypes[i];
  1417.                 dtp = propertiesToObject(po.Properties);
  1418.  
  1419.                 sdid = dtp.SupplierDepartment;
  1420.                 if (sdid != "-1") {
  1421.                     var sds = BLSupplierDepartment.all().filter("RemoteID", '=', sdid);
  1422.                     names[i] = dtp.Name;
  1423.                     dtids[i] = dtp.ID;
  1424.                     // Not sure why this query always returns nothing
  1425.                     sds.list(null, function(results, err) {
  1426.                         console.log("results: " + results.length);
  1427.                         if (results && results.length > 0) {
  1428. //                              alert("found Supplier Department");
  1429.                             sd = results[0];
  1430.                             var blDefType = createBLDeficiencyType(blProject, dtids[i], names[i], sd);
  1431.                         }
  1432.                     });
  1433.                 } else {
  1434.                     var blDefType = createBLDeficiencyType(blProject, dtp.ID, dtp.Name, null);
  1435.                 }
  1436.  
  1437.                 if (i % 10 == 0) {
  1438.                     details.append("DeficiencyType Record " + i + " of " + defTypes.length + "\n");
  1439.                 }
  1440.             }
  1441. */
  1442.             details.append("Deficiency Types Done Creating Objects\n");
  1443.  
  1444.             persistence.flush(null, function(err) {
  1445.                 details.append("DeficiencyTypes Done Flush\n");
  1446.                 console.log("Done DeficiencyTypes Flushing!");
  1447.                 downloadProjectRooms(blProject);
  1448.             });
  1449.  
  1450.         } catch (ex) {
  1451.             alert(ex);
  1452.         }
  1453.     });
  1454. }
  1455.  
  1456. function downloadProjectUnits(blProject) {
  1457.     alert("Downloading Units (2/7)");
  1458.     details = $("#PageSetupDetails");
  1459.     details.append("Units Sending JSON Request\n");
  1460.     $.getJSON("http://" + domain + "/cc/tablet/GetUnits.jsp", {}, function(data) {
  1461.         try {
  1462.             details.append("Units Processing Response\n");
  1463.             var units = data.Units;
  1464.             details.append("Records: " + units.length + "\n");
  1465.  
  1466.             $("#PageSetupSliderRecords").attr("value", 0);
  1467.             $("#PageSetupSliderRecords").attr("max", units.length);
  1468.             for (var i = 0; i < units.length; i ++) {
  1469.                 $("#PageSetupSliderRecords").attr("value", i);
  1470.                 $("#PageSetupSliderRecords").attr("val", i);
  1471.                 $("#PageSetupSliderRecords").slider("refresh", true);
  1472.                 $("#PageSetupSliderRecords").slider();
  1473.  
  1474.                 po = units[i];
  1475.                 up = propertiesToObject(po.Properties);
  1476.                 //console.log(sdp);
  1477.  
  1478.                 var blUnit = createBLUnit(blProject, up.ID, up.Name, up.BuyerClosingDate, up.MunicipalAddress, up.City, up.TarionEnrollmentNumber);
  1479.  
  1480.                 if (i % 10 == 0) {
  1481.                     details.append("Unit Record " + i + " of " + units.length + "\n");
  1482.                 }
  1483.             }
  1484.             details.append("Units Done Creating Objects\n");
  1485.  
  1486.             persistence.flush(null, function(err) {
  1487.                 details.append("Units Done Flush\n");
  1488.                 console.log("Done Units Flushing!");
  1489.                 downloadProjectDeficiencyTypes(blProject);
  1490.             });
  1491.  
  1492.         } catch (ex) {
  1493.             alert(ex);
  1494.         }
  1495.     });
  1496. }
  1497.  
  1498.  
  1499. function downloadProjectRooms(blProject) {
  1500.     alert("Downloading Rooms (4/7)");
  1501.     details = $("#PageSetupDetails");
  1502.     details.append("Room Sending JSON Request\n");
  1503.     $.getJSON("http://" + domain + "/cc/tablet/GetRooms.jsp", {}, function(data) {
  1504.         try {
  1505.             details.append("Room Processing Response\n");
  1506.             var rooms = data.Rooms;
  1507.             details.append("Records: " + rooms.length + "\n");
  1508.  
  1509.             processRooms(blProject, rooms, 0);
  1510.  
  1511.         } catch (ex) {
  1512.             alert(ex);
  1513.         }
  1514.     });
  1515. }
  1516.  
  1517. function processRooms(blProject, rooms, startFrom) {
  1518.     var addedObjects = false;
  1519.     for (var i = startFrom; i < rooms.length && i < startFrom + BatchSize; i ++) {
  1520.  
  1521.         po = rooms[i];
  1522.         sdp = propertiesToObject(po.Properties);
  1523.         //console.log(sdp);
  1524.  
  1525.         blRoom = createBLRoom(blProject, sdp.ID, sdp.Name);
  1526.         if (i % 10 == 0) {
  1527.             details.append("Rooms Record " + i + " of " + rooms.length + "\n");
  1528.         }
  1529.         addedObjects = true;
  1530.     }
  1531.     details.append("Rooms Done Creating Objects\n");
  1532.  
  1533.     if (addedObjects) {
  1534.         persistence.flush(null, function(err) {
  1535.             if (err != null) {
  1536. //                  alert(err);
  1537.             }
  1538.             details.append("Rooms Done Flush\n");
  1539.             console.log("Done Rooms Flushing!");
  1540.             processRooms(blProject, rooms, startFrom + BatchSize);
  1541.         });
  1542.     } else {
  1543.         downloadProjectUsers(blProject);
  1544.     }
  1545. }
  1546.  
  1547.  
  1548.  
  1549. function downloadProjectUsers(blProject) {
  1550.     alert("Downloading Users (5/7)");
  1551.     details = $("#PageSetupDetails");
  1552.     details.append("Users Sending JSON Request\n");
  1553.     $.getJSON("http://" + domain + "/cc/tablet/GetUsers.jsp", {}, function(data) {
  1554.         try {
  1555.             details.append("Users Processing Response\n");
  1556.             var users = data.Users;
  1557.             details.append("Records: " + users.length + "\n");
  1558.  
  1559.             processUsers(blProject, users, 0, 1);
  1560.  
  1561.         } catch (ex) {
  1562.             alert(ex);
  1563.         }
  1564.     });
  1565. }
  1566.  
  1567. function processUsers(blProject, users, startFrom, batchSize) {
  1568.     var addedObjects = false;
  1569.  
  1570.     var username = $("#PageSetupUsername").val();
  1571.     var password = $("#PageSetupPassword").val();
  1572.  
  1573.     for (var i = startFrom; i < users.length && i < startFrom + batchSize; i ++) {
  1574.  
  1575.         po = users[i];
  1576.         sdp = propertiesToObject(po.Properties);
  1577.  
  1578.         var trid = sdp.TreeRootID;
  1579.         if (sdp.ID == 685438) {
  1580.             console.log(trid);
  1581.         }
  1582.         var st = sdp.ID + " " + sdp.UserName;
  1583.         console.log(st);
  1584.         var sds = BLUnit.all().filter("RemoteID", '=', trid);
  1585.         // Not sure why this query always returns nothing
  1586.         sds.list(null, function(results, err) {
  1587.             if (sdp.ID == 685438) {
  1588.                 console.log(trid);
  1589.             }
  1590. //              console.log("results: " + results.length);
  1591.             var unit = null;
  1592.             if (results && results.length > 0) {
  1593. //                              alert("found Supplier Department");
  1594.                 unit = results[0];
  1595.             }
  1596.             var blUser = createBLUser(blProject, unit, sdp.ID, sdp.Name1, sdp.Name2, sdp.HomePhone, sdp.CellPhone, sdp.Email, sdp.StreetAddress, sdp.City, sdp.Province, sdp.PostalCode);
  1597.             blUser.Name3 = sdp.Name3;
  1598.             blUser.Name4 = sdp.Name4;
  1599.             blUser.Username = sdp.UserName;
  1600.             blUser.Password = sdp.Password;
  1601.  
  1602.             if (username == blUser.Username) {
  1603.                 blProject.BLUser = blUser;
  1604.             }
  1605.             var st2 = blUser.RemoteID + " " + blUser.Username;
  1606.             console.log(st2);
  1607.         });
  1608.  
  1609.  
  1610.         if (i % 10 == 0) {
  1611.             details.append("Users Record " + i + " of " + users.length + "\n");
  1612.         }
  1613.         addedObjects = true;
  1614.     }
  1615.     details.append("Users Done Creating Objects\n");
  1616.  
  1617.     if (addedObjects) {
  1618.         persistence.flush(null, function(err) {
  1619.             if (err != null) {
  1620. //                  alert(err);
  1621.             }
  1622.             details.append("Users Done Flush\n");
  1623.             console.log("Done Users Flushing!");
  1624.             processUsers(blProject, users, startFrom + batchSize, batchSize);
  1625.         });
  1626.     } else {
  1627.         //alert("All Done Downloading");
  1628.         downloadProjectFormTemplates(blProject);
  1629.     }
  1630. }
  1631.  
  1632.  
  1633. function downloadProjectFormTemplates(blProject) {
  1634.     alert("Downloading FormTemplates (6/7)");
  1635.     details = $("#PageSetupDetails");
  1636.     details.append("FormTemplates Sending JSON Request\n");
  1637.     $.getJSON("http://" + domain + "/cc/tablet/GetFormTemplates.jsp", {}, function(data) {
  1638.         try {
  1639.             details.append("FormTemplates Processing Response\n");
  1640.             var records = data.FormTemplates;
  1641.             details.append("Records: " + records.length + "\n");
  1642.  
  1643.             processFormTemplates(blProject, records, 0, 1);
  1644.  
  1645.         } catch (ex) {
  1646.             alert(ex);
  1647.         }
  1648.     });
  1649. }
  1650.  
  1651. function processFormTemplates(blProject, records, startFrom, batchSize) {
  1652.     var addedObjects = false;
  1653.     for (var i = startFrom; i < records.length && i < startFrom + batchSize; i ++) {
  1654.  
  1655.         po = records[i];
  1656.         sdp = propertiesToObject(po.Properties);
  1657.  
  1658.         var blFormTemplate = createBLFormTemplate(blProject, sdp.ID, sdp.Title, sdp.Description, sdp.Text);
  1659.  
  1660.         if (i % 10 == 0) {
  1661.             details.append("FormTemplates Record " + i + " of " + records.length + "\n");
  1662.         }
  1663.         addedObjects = true;
  1664.     }
  1665.     details.append("FormTemplates Done Creating Objects\n");
  1666.  
  1667.     if (addedObjects) {
  1668.         persistence.flush(null, function(err) {
  1669.             if (err != null) {
  1670. //                  alert(err);
  1671.             }
  1672.             details.append("FormTemplates Done Flush\n");
  1673.             console.log("Done FormTemplates Flushing!");
  1674.             processFormTemplates(blProject, records, startFrom + batchSize, batchSize);
  1675.         });
  1676.     } else {
  1677.         alert("All Done Downloading (7/7)");
  1678.         //downloadProjectUnits(blProject);
  1679.     }
  1680. }
  1681.  
  1682.  
  1683.  
  1684.  
  1685.  
  1686. $("#PageProjectSyncProject").click(function (e) {
  1687.     e.preventDefault();
  1688.     domain = $("#PageProjectSyncDomain").val();
  1689.     username = $("#PageProjectSyncUsername").val();
  1690.     password = $("#PageProjectSyncPassword").val();
  1691.     details = $("#PageProjectSyncDetails");
  1692.  
  1693.     if ("" == domain) {
  1694.         alert("Domain can not be blank");
  1695.         return;
  1696.     }
  1697.     if ("" == username) {
  1698.         alert("Username can not be blank");
  1699.         return;
  1700.     }
  1701.     if ("" == password) {
  1702.         alert("Password can not be blank");
  1703.         return;
  1704.     }
  1705.  
  1706.     details.append("Starting Sync\n");
  1707.     details.append("Domain: " + domain + "\n");
  1708.     details.append("Username: " + username + "\n");
  1709.     details.append("Password: " + password + "\n");
  1710.     details.append("Calling Authentication\n");
  1711.  
  1712.     var hash = true;
  1713.     if (password.length != 32) {
  1714.         hash = false;
  1715.     }
  1716.  
  1717.     console.log(domain + ", " + username + ", " + password);
  1718.  
  1719.     $.post("http://" + domain + "/cc/tablet/UserTestPassword.jsp", {UserName: username, Password: password, Hash: hash}, function(data) {
  1720. //          alert(data.AuthenticationRequestResult);
  1721.         console.log(data);
  1722.         console.log(data.AuthenticationPassword);
  1723.         console.log(data.AuthenticationUsername);
  1724.         console.log(data.AuthenticationRequestResult);
  1725.         details.append("AuthenticationRequestResult: '" + data.AuthenticationRequestResult + "'\n");
  1726.         if ("Successful Login" == data.AuthenticationRequestResult) {
  1727.             details.append("Sending Deficiencies\n");
  1728.  
  1729.             var defsToSync = BLDeficiency.all().filter("RemoteID", '=', "0").filter("BLProject", '=', document.BLProject.id).prefetch("BLRoom").prefetch("BLDeficiencyType").prefetch("BLUnit").prefetch("BLSupplierDepartment");
  1730.             defsToSync.list(null, function(results, err) {
  1731.                 if (results) {
  1732.                     $("#PageProjectSyncSliderRecords").attr("value", 0);
  1733.                     $("#PageProjectSyncSliderRecords").attr("max", results.length);
  1734.                     console.log("Def Count: " + results.length);
  1735.  
  1736.                     details.append("Deficiency Count: " + results.length + "\n");
  1737.  
  1738.                     var countDefs = results.length;
  1739.                     var countSent = 0;
  1740.                     var countResult = 0;
  1741.                     var countSuccess = 0;
  1742.                     var countError = 0;
  1743.  
  1744.                     for (var i = 0; i < results.length; i ++) {
  1745.                         var def = results[i];
  1746.                         details.append("Deficiency: " + i + " Sending\n");
  1747.  
  1748.                         if (def.BLDeficiencyType == null) {
  1749.                             persistence.remove(def);
  1750.                         } else {
  1751.  
  1752.                             $("#PageProjectSyncSliderRecords").attr("value", i);
  1753.                             $("#PageProjectSyncSliderRecords").attr("val", i);
  1754.                             $("#PageProjectSyncSliderRecords").slider("refresh", true);
  1755.                             $("#PageProjectSyncSliderRecords").slider();
  1756.  
  1757.                             var sdid = -1;
  1758.                             if (def.BLSupplierDepartment != null) {
  1759.                                 sdid = def.BLSupplierDepartment.RemoteID;
  1760.                             }
  1761.                             countSent ++;
  1762.                             $.getJSON("http://" + domain + "/cc/tablet/UploadDeficiency.jsp",
  1763.                                 {Description: def.Description,
  1764.                                  Source: def.Source,
  1765.                                  Status: def.Status,
  1766.                                  DeficiencyType: def.BLDeficiencyType.RemoteID,
  1767.                                  Room: def.BLRoom.RemoteID,
  1768.                                  Unit: def.BLUnit.RemoteID,
  1769.                                  SupplierDepartment: sdid},
  1770.                             function(data) {
  1771.                                 try {
  1772.                                     countResult ++;
  1773.                                     console.log("Deficiency: " + i + " Result\n");
  1774.                                     details.append("Deficiency: " + i + " Result\n");
  1775.                                     var defRemoteID = data.Deficiency[0].ID;
  1776.                                     details.append("Deficiency: " + i + " defRemoteID:" + defRemoteID + "\n");
  1777.                                     console.log("Deficiency: " + i + " defRemoteID:" + defRemoteID + "\n");
  1778.                                     def.RemoteID = defRemoteID;
  1779.                                     persistence.add(def);
  1780.                                     persistence.flush();
  1781.                                     countSuccess ++;
  1782.                                     console.log("After Flush: Success:" + countSuccess);
  1783.  
  1784.                                     if (i = results.length) {
  1785.                                         alert("Sync Finished.  \n" +
  1786.                                               "Count Objects: " + countDefs + "\n" +
  1787.                                               "Count Sent   : " + countSent + "\n" +
  1788.                                               "Count Result : " + countResult + "\n" +
  1789.                                               "Count Success: " + countSuccess + "\n" +
  1790.                                               "Count Error  : " + countError + "\n");
  1791.                                     }
  1792.                                 } catch (ex) {
  1793.                                     countError ++;
  1794.                                     console.log(ex.toString());
  1795.                                 }
  1796.                             });
  1797.                         }
  1798.                     }
  1799.                 }
  1800.             });
  1801.  
  1802.  
  1803.         }
  1804.     }, "json");
  1805.  
  1806. });
  1807.  
  1808.  
  1809.  
  1810.  
  1811.  
  1812.  
  1813.  
  1814. $("#PageSetupCreateSchema").click(function (e) {
  1815.     databaseCreateSchema(true, false, true);
  1816. });
  1817.  
  1818.  
  1819. $("#PageSetupSetupDemoProjects").click(function (e) {
  1820.     databaseCreateSchema(false, true, true);
  1821. });
  1822.  
  1823.  
  1824.  
  1825.  
  1826.  
  1827.  
  1828.  
  1829.  
  1830.  
  1831.  
  1832.  
  1833.  
  1834. //********************************************
  1835. //Utils and testing functions
  1836. //********************************************
  1837.  
  1838.  
  1839. function syncTest() {
  1840.     console.log("Starting Sync Test");
  1841.     var sync = callWhenDone(function() { console.log("all jobs are done!"); });
  1842.     var endJob = function(){ console.log("one job ended"); sync(-1); };
  1843.     for (var i=0; i<10; ++i) {
  1844.         sync(+1);
  1845.         console.log("starting job: " + i);
  1846.         setTimeout(endJob, Math.random()*10000); // to replace with your async function
  1847.     }
  1848. }
  1849.  
  1850. /**
  1851.  * callWhenDone: a simple synchronized callback closure
  1852.  * @author adrienjoly
  1853.  */
  1854. var callWhenDone = function(callback) {
  1855.         var counter = 0;
  1856.         return function (incr) {
  1857.                 if (0 == (counter += incr))
  1858.                         callback();
  1859.         };
  1860. };
  1861.  
  1862. // example use:
  1863. //var sync = callWhenDone(function() { console.log("all jobs are done!"); });
  1864. //var endJob = function(){ console.log("one job ended"); sync(-1); };
  1865. //for (var i=0; i<10; ++i) {
  1866. //       sync(+1);
  1867. //        setTimeout(endJob, Math.random()*10000); // to replace with your async function
  1868. //}
  1869.  
  1870. function pSchemaSync() {
  1871.     var sync = callWhenDone(function() {
  1872.         console.log("done sync");
  1873.     });
  1874.     sync(+1);
  1875.     persistence.schemaSync(function(tx) {
  1876.         console.log("schema sync done");
  1877.         sync(-1);
  1878.     });
  1879.  
  1880. }
  1881.  
  1882. // Query the database
  1883. //
  1884. function queryDB(tx) {
  1885.     tx.executeSql('SELECT * FROM BLUnit', [], querySuccess, errorCB);
  1886. }
  1887.  
  1888. // Query the success callback
  1889. //
  1890. function querySuccess(tx, results) {
  1891.     var len = results.rows.length;
  1892.     console.log("DEMO table: " + len + " rows found.");
  1893.     for (var i=0; i<len; i++){
  1894.         console.log("Row = " + i + " BLID = " + results.rows.item(i).BLID + " Data =  " + results.rows.item(i).Name);
  1895.     }
  1896. }
  1897.  
  1898. // Transaction error callback
  1899. //
  1900. function errorCB(err) {
  1901.     SQLErrors ++;
  1902.     console.log("Error processing SQL: "+err.code + ": Message: " + err.message);
  1903. }
  1904.  
  1905. function nullCB() {
  1906.     SQLErrors ++;
  1907.     console.log("NullCallBack");
  1908. }
  1909.  
  1910. // Transaction success callback
  1911. //
  1912. function successCB() {
  1913.     if (SQLDatabase != null) {
  1914.         SQLDatabase.transaction(queryDB, errorCB);
  1915.     }
  1916.  
  1917.     logDatabaseStatus();
  1918. }
  1919.  
  1920.  
  1921.  
  1922.  
  1923.  
  1924. function getDatabaseObject(table, ID, jquerySelectorText) {
  1925.  
  1926.     SQLDatabase.transaction(
  1927.         function(transaction) {
  1928.             console.log("mess1: " + ID);
  1929.             transaction.executeSql(
  1930.                 'SELECT * FROM BLProject WHERE BLID = ?',
  1931.                 [parseInt(ID)],
  1932.                 function(transaction, result) {
  1933.                     console.log("inner result: " + result.rows.length);
  1934.                     if (result != null && result.rows != null) {
  1935.                         for (var i = 0; i < result.rows.length; i++) {
  1936.                             var row = result.rows.item(i);
  1937.                             $(jquerySelectorText).html(row.Name);
  1938.                         }
  1939.                     }
  1940.                 },
  1941.                 errorCB
  1942.             );
  1943.         },
  1944.         errorCB,
  1945.         nullCB
  1946.     );
  1947. }
  1948.  
  1949. function applyFunctionToDatabaseObject(table, ID, functionToApply) {
  1950.  
  1951.     SQLDatabase.transaction(
  1952.         function(transaction) {
  1953.             console.log("mess1: " + ID);
  1954.             transaction.executeSql(
  1955.                 'SELECT * FROM ' + table + ' WHERE BLID = ?',
  1956.                 [parseInt(ID)],
  1957.                 functionToApply,
  1958.                 errorCB
  1959.             );
  1960.         },
  1961.         errorCB,
  1962.         nullCB
  1963.     );
  1964. }
  1965.  
  1966.  
  1967. function applyFunctionToDatabaseResult(query, functionToApply) {
  1968.  
  1969.     SQLDatabase.transaction(
  1970.         function(transaction) {
  1971.             console.log("applyFunctionToDatabaseResult.query: " + query);
  1972.             transaction.executeSql(
  1973.                 query,
  1974.                 [],
  1975.                 functionToApply,
  1976.                 errorCB
  1977.             );
  1978.         },
  1979.         errorCB,
  1980.         nullCB
  1981.     );
  1982. }
  1983.  
  1984. function getDatabaseObjectSuccess(tx, results) {
  1985.     var len = results.rows.length;
  1986.     console.log("DEMO table: " + len + " rows found.");
  1987.     for (var i=0; i<len; i++){
  1988.         console.log("getDatabaseObject.Row = " + i + " ID = " + results.rows.item(i).ID + " Data =  " + results.rows.item(i).Name);
  1989.     }
  1990. }
  1991.  
  1992.  
  1993. function generatePDIReport(someText) {
  1994.     console.log("onDeviceReady***1");
  1995.  
  1996.     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
  1997.         function(fileSystem) {
  1998.             console.log("gotFTinternalanon***2 someText: '" + someText + "'");
  1999.             fileSystem.root.getFile("readme.html", {create: true},
  2000.                 function (fileEntry) {
  2001.                     fileEntry.createWriter(
  2002.                         function (writer) {
  2003.                             gotFileWriter(writer, someText);
  2004.                         }, fail);
  2005.                 }, fail);
  2006.         }
  2007.         ,
  2008.         function (error) {
  2009.         });
  2010. }
  2011.  
  2012. function gotFS(fileSystem) {
  2013.     console.log("gotFT***2");
  2014.     fileSystem.root.getFile("readme.txt", {create: true}, gotFileEntry, fail);
  2015. }
  2016.  
  2017. function gotFileEntry(fileEntry) {
  2018.     console.log("gotFileEntry***2: " + fileEntry.fullURL());
  2019.     fileEntry.createWriter(gotFileWriter, fail);
  2020. }
  2021.  
  2022. function gotFileWriter(writer, someText) {
  2023.     console.log("gotFileWriter***3");
  2024.     writer.onwrite = function(evt) {
  2025.         console.log("write success***4");
  2026.     };
  2027.     writer.onwritestart = function(evt) {
  2028.         console.log("writestart***6");
  2029.     };
  2030.     writer.onabort = function(evt) {
  2031.         console.log("abort***7");
  2032.     };
  2033.     writer.onerror = function(evt) {
  2034.         console.log("error***8");
  2035.     };
  2036.     writer.onwriteend = function(evt) {
  2037.         console.log("writeend***9");
  2038.       //  navigator.app.loadUrl('file:///mnt/sdcard/readme.txt');
  2039.         window.plugins.childBrowser.showWebPage("file:///mnt/sdcard/readme.html", { showLocationBar: true });
  2040.         console.log("writeend***10");
  2041.     };
  2042.  
  2043.     writer.write("some sample text1234'" + someText + "'");
  2044.     // contents of file now 'some sample text'
  2045. //        writer.truncate(11);
  2046.     // contents of file now 'some sample'
  2047. //        writer.seek(4);
  2048.     // contents of file still 'some sample' but file pointer is after the 'e' in 'some'
  2049.     writer.write(" different text123");
  2050.     writer.write(someText);
  2051.     // contents of file now 'some different text'
  2052. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement