Advertisement
Fabbrogas

Untitled

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