initial commit
[namibia] / public / js / app / portal-workspace / valuationview.js
1 ;
2 (function () {
3
4         window._w.valuationview = {
5                 itemId: null,
6                 itemData: null,
7                 formMeta: null,
8                 ti: null,
9                 limited: false,
10                 newItem: false,
11                 validations: 0,
12                 highestOfferId: false,
13                 priceGuideId: false,
14                 firstTimeCheck: true,
15                 firstTimeCheckYear: true,
16                 onValuationViewTemplateReady: function (template, event, eventData)
17                 {
18                         _w.valuationview.itemData = null;
19                         _w.valuationview.ti = _t[template];
20                         _w.valuationview.firstTimeCheck = true;
21                         _w.valuationview.firstTimeCheckYear = true;
22                         _w.valuationview.limited = ('limitedvaluationview' == template)
23                                                         ? true
24                                                         : false;
25                         _w.valuationview.itemId = App.Util.getUrlParam('id');
26                         if (0 == _w.valuationview.itemId || null == _w.valuationview.itemId)
27                         {
28                                 _w.valuationview.newItem = true;
29                                 _w.valuationview.itemData = {stock: {}};
30                                 _w.valuationview.firstTimeCheck = false;
31                                 _w.valuationview.firstTimeCheckYear = false;
32                         }
33
34                         App.DataStore.setData('departments', [{"value": "New", "label": "New"}, {"value": "Used", "label": "Used"}]);
35                         App.DataStore.setData('sparekeys', [{"value": "1", "label": "Yes"}, {"value": "0", "label": "No"}]);
36                         App.DataStore.setData('yesno', [{"value": "1", "label": "Yes"}, {"value": "0", "label": "No"}]);
37
38
39
40                         /*_w.valuationview.setValuationViewFormMeta();
41                          _w.valuationview.ti.hydrate(_w.valuationview.formMeta);*/
42
43                 },
44                 onValuationViewPublished: function (template, event, eventData)
45                 {
46                         _w.valuationview.ti = _t[template];
47                         _w.valuationview.limited = ('limitedvaluationview' == template)
48                                                         ? true
49                                                         : false;
50                         _w.valuationview.setValuationViewFormMeta();
51                         _w.valuationview.ti.hydrate(_w.valuationview.formMeta);
52
53                         if (_w.valuationview.newItem)
54                         {
55                                 _w.valuationview._setupValidation();
56                                 $('#btnSaveAsSales').show();
57                                 $('#btnSaveAsPending').show();
58                                 $('#optSendToSales').show();
59                                 $('#optSendToPg').show();
60                                 $('#btnSendToStock').show();
61                                 $('#btnUpdate').prop('disabled', false);
62                                 $('#printValuationPdf').hide();
63
64
65                                 //HPI Report Hide on New
66                                 $('#requestHPIreport').hide();
67                 $('#requestHPIAccidentReport').hide();
68                                 $('.hpiReport').hide();
69
70                                 /*
71                                  * Permissions
72                                  */
73                                 true == App.permissions.valuationCreateSales ? $('#sectionSelectValuator').show() : $('#sectionSelectValuator').hide();
74                                 true == App.permissions.valuationCreatePriceguide ? $('#optSendToPg').show() : $('#optSendToPg').hide();
75                                 true == App.permissions.valuationCreateComplete ? $('#optSendToSales').show() : $('#optSendToSales').hide();
76                                 true == App.permissions.valuationCreateNew ? $('#btnUpdate').show() : $('#btnUpdate').hide();
77                                 true == App.permissions.valuationCreateStock ? $('#btnSendToStock').show() : $('#btnSendToStock').hide();
78                                 true == App.permissions.valuationCreatePending ? $('#btnSaveAsPending').show() : $('#btnSaveAsPending').hide();
79
80                                 true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_overAllowance').show() : $('#' + _w.valuationview.ti.tid + '_overAllowance').hide();
81                                 true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_standInValue').show() : $('#' + _w.valuationview.ti.tid + '_standInValue').hide();
82                                 true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_projectedRetail').show() : $('#' + _w.valuationview.ti.tid + '_projectedRetail').hide();
83                                 true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_plannedMargin').show() : $('#' + _w.valuationview.ti.tid + '_plannedMargin').hide();
84
85                                 if (!App.permissions.valuationUpdateDamages)
86                                 {
87                                         $('.damages-form').hide();
88                                 }
89                                 else
90                                 {
91                                         $('.damages-form').show();
92                                 }
93                                 if (!App.permissions.valuationUpdateCoverReceived)
94                                 {
95                                         $('.cover-received-form').hide();
96                                 }
97                                 else
98                                 {
99                                         $('.cover-received-form').show();
100                                 }
101                                 
102                                 if (!App.permissions.valuationUploadPhotos)
103                                 {
104                                         $('.photos-form').html(' ');
105                                 }
106                         }
107
108
109
110                         $('#btnRequestHPI').click(function () {
111
112                                 if ('' == $('#HPIusername').val() || '' == $('#HPIpin').val())
113                                 {
114                                         alert('Please enter a valid username and password.');
115                                         return;
116                                 }
117
118                                 $('#HPIdropConfirm').slideToggle();
119                                 $('#HPIresponse').html('');
120                         });
121
122             $('#btnRequestHPIAccident').click(function () {
123
124                 if ('' == $('#HPIAccidentUsername').val() || '' == $('#HPIAccidentPin').val())
125                 {
126                     alert('Please enter a valid username and password.');
127                     return;
128                 }
129
130                 $('#HPIAccidentDropConfirm').slideToggle();
131                 $('#HPIAccidentResponse').html('');
132             });
133
134
135                         App.Util.updateCheckboxStyle($('#acceptHPIdisclaimer'));
136                         $('#HPIbtnConfirm').click(function () {
137                                 if ($('#engineNumber').val() == '') {
138                                         alert('Please update the Vehicle Engine Number and try again');
139                                         return;
140                                 }
141                                 if ($('#vinNumber').val() == '' && $('#registrationNumber').val() == '') {
142                                         alert('Please update the Vin Number or the Registration Number and and try again');
143                                         return;
144                                 }
145                                 if (!$('#acceptHPIdisclaimer').is(':checked'))
146                                 {
147                                         alert('Please accept the conditions before sending.');
148                                         return;
149                                 }
150                                 if (!$('#frmValuationView').valid())
151                                 {
152                                         return;
153                                 }
154                                 $('#HPIbtnConfirm').prop('disabled', true);
155
156                                 var data = _w.valuationview._prepValuationUpdateData();
157                                 App.API.execTask(
158                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
159                                                                 function ()
160                                                                 {
161                                                                         var task = _w.valuationview.limited
162                                                                                                         ? 'Valuation.LimitedUpdate'
163                                                                                                         : 'Valuation.Update';
164                                                                         App.API.getTask(
165                                                                                                         'updateValuation:' + _w.valuationview.itemId, 'Valuation', task, _w.valuationview.itemId,
166                                                                                                         {}, function () {
167                                                                         }, _w.taskContractError
168                                                                                                         );
169                                                                         var user = $('#HPIusername').val();
170                                                                         var pass = $('#HPIpin').val();
171
172                                                                         App.API.getTask(
173                                                                                                         'TransUnionForHPI', 'Stock', 'Utility.TransUnionForHPI', null,
174                                                                                                         {'Filter': {'username': user, 'pass': pass, 'stock': _w.stock.Id}},
175                                                                         function () {
176                                                                                 App.API.execTask(
177                                                                                                                 'TransUnionForHPI', {}, {},
178                                                                                                                 function (data)
179                                                                                                                 {
180                                                                                                                         $('#HPIdropConfirm').hide();
181                                                                                                                         if ('Success' == data.Status)
182                                                                                                                         {
183                                                                                                                                 $('#HPIresponse').html('Success on HPI Report');
184                                                                                                                                 alert('Success on HPI Report');
185                                                                                                                                 App.DataStore.loadSelectListData(
186                                                                                                                                                                 'tuhpi', false, 'Stock', 'Tuhpi.List', null, {
187                                                                                                                                                                         "Filter":
188                                                                                                                                                                                                         {
189                                                                                                                                                                                                                 "stock": _w.valuationview.itemData.stock.id,
190                                                                                                                                                                                                                 "company": App.companyData.id
191                                                                                                                                                                                                         }
192                                                                                                                                                                 }, {}, function ()
193                                                                                                                                 {
194                                                                                                                                         // data is retrieved
195                                                                                                                                         var tuHpiData = App.DataStore.getData('tuhpi');
196
197
198                                                                     _w.valuationview._loadHpiReportData(tuHpiData);
199
200                                                                                                                                         //for (var i = 0; i < tuHpiData.length; i++)
201                                                                                                                                         //{
202                                                                      //   var tuHpiId = tuHpiData[i].id;
203                                                                      //   var tuHpiCreated = tuHpiData[i].created;
204                                                                      //   var tuHpiType = tuHpiData[i].hpi_type;
205                                                                                                                                         //      if (tuHpiId)
206                                                                                                                                         //      {
207                                                                                                                                         //              $('#tuhpiDate').html(tuHpiCreated);
208                                                                      //       $('#tuhpiType').html(tuHpiType);
209                                                                                                                                         //              $('#downloadTuhpi').show();
210                                                                                                                                         //              $('#HPIbtnConfirm').prop('disabled', true);
211                                                                                                                                         //              return;
212                                                                                                                                         //      }
213                                                                                                                                         //      else
214                                                                                                                                         //      {
215                                                                                                                                         //              $('#tuhpiDate').html('Not Requested Yet');
216                                                                      //       $('#tuhpiType').html('Not Requested Yet');
217                                                                                                                                         //              $('#downloadTuhpi').hide();
218                                                                                                                                         //              $('#HPIbtnConfirm').prop('disabled', false);
219                                                                                                                                         //      }
220                                                                                                                                         //}
221                                                                                                                                 });
222                                                                                                                         }
223                                                                                                                         else
224                                                                                                                         {
225                                                                                                                                 $('#HPIresponse').html('API call to remote host failed. No data could be retrieved from remote service.');
226                                                                                                                                 $('#HPIbtnConfirm').prop('disabled', false);
227                                                                                                                         }
228                                                                                                                 }, function (response)
229                                                                                 {
230                                                                                         alert(
231                                                                                                                         undefined != response.StatusReason
232                                                                                                                         ? response.StatusReason
233                                                                                                                         : 'API call to remote host failed. No data could be retrieved from remote service.'
234                                                                                                                         );
235                                                                                         $('#HPIbtnConfirm').prop('disabled', false);
236                                                                                 }
237                                                                                 );
238                                                                         }
239                                                                         , _w.taskContractError
240                                                                                                         );
241                                                                 }, _w.taskExecError
242                                                                 );
243                         });
244
245
246
247
248             App.Util.updateCheckboxStyle($('#acceptHPIAccidentDisclaimer'));
249             $('#HPIAccidentBtnConfirm').click(function () {
250                 if ($('#engineNumber').val() == '') {
251                     alert('Please update the Vehicle Engine Number and try again');
252                     return;
253                 }
254                 if ($('#vinNumber').val() == '' && $('#registrationNumber').val() == '') {
255                     alert('Please update the Vin Number or the Registration Number and and try again');
256                     return;
257                 }
258                 if (!$('#acceptHPIAccidentDisclaimer').is(':checked'))
259                 {
260                     alert('Please accept the conditions before sending.');
261                     return;
262                 }
263                 if (!$('#frmValuationView').valid())
264                 {
265                     return;
266                 }
267                 $('#HPIAccidentBtnConfirm').prop('disabled', true);
268
269                 var data = _w.valuationview._prepValuationUpdateData();
270                 App.API.execTask(
271                     'updateValuation:' + _w.valuationview.itemId, data, {},
272                     function ()
273                     {
274                         var task = _w.valuationview.limited
275                             ? 'Valuation.LimitedUpdate'
276                             : 'Valuation.Update';
277                         App.API.getTask(
278                             'updateValuation:' + _w.valuationview.itemId, 'Valuation', task, _w.valuationview.itemId,
279                             {}, function () {
280                             }, _w.taskContractError
281                         );
282                         var user = $('#HPIAccidentUsername').val();
283                         var pass = $('#HPIAccidentPin').val();
284
285                         App.API.getTask(
286                             'TransUnionForHPIAccident', 'Stock', 'Utility.TransUnionForHPIAccident', null,
287                             {'Filter': {'username': user, 'pass': pass, 'stock': _w.stock.Id}},
288                             function () {
289                                 App.API.execTask(
290                                     'TransUnionForHPIAccident', {}, {},
291                                     function (data)
292                                     {
293                                         $('#HPIAccidentDropConfirm').hide();
294                                         if ('Success' == data.Status)
295                                         {
296                                             $('#HPIresponse').html('Success on HPI Report');
297                                             alert('Success on HPI Report');
298                                             App.DataStore.loadSelectListData(
299                                                 'tuhpi', false, 'Stock', 'Tuhpi.List', null, {
300                                                     "Filter":
301                                                     {
302                                                         "stock": _w.valuationview.itemData.stock.id,
303                                                         "company": App.companyData.id
304                                                     }
305                                                 }, {}, function ()
306                                                 {
307                                                     // data is retrieved
308                                                     var tuHpiData = App.DataStore.getData('tuhpi');
309
310                                                     _w.valuationview._loadHpiReportData(tuHpiData);
311
312                                                     //for (var i = 0; i < tuHpiData.length; i++)
313                                                     //{
314                                                     //    var tuHpiId = tuHpiData[i].id;
315                                                     //    var tuHpiCreated = tuHpiData[i].created;
316                                                     //    var tuHpiType = tuHpiData[i].hpi_type;
317                                                     //    if (tuHpiId)
318                                                     //    {
319                                                     //        $('#tuhpiDate').html(tuHpiCreated);
320                                                     //        $('#tuhpiType').html(tuHpiType);
321                                                     //        $('#downloadTuhpi').show();
322                                                     //        $('#HPIAccidentBtnConfirm').prop('disabled', true);
323                                                     //        return;
324                                                     //    }
325                                                     //    else
326                                                     //    {
327                                                     //        $('#tuhpiDate').html('Not Requested Yet');
328                                                     //        $('#tuhpiType').html('Not Requested Yet');
329                                                     //        $('#downloadTuhpi').hide();
330                                                     //        $('#HPIAccidentBtnConfirm').prop('disabled', false);
331                                                     //    }
332                                                     //}
333                                                 });
334                                         }
335                                         else
336                                         {
337                                             $('#HPIAccidentResponse').html('API call to remote host failed. No data could be retrieved from remote service.');
338                                             $('#HPIAccidentBtnConfirm').prop('disabled', false);
339                                         }
340                                     }, function (response)
341                                     {
342                                         alert(
343                                             undefined != response.StatusReason
344                                                 ? response.StatusReason
345                                                 : 'API call to remote host failed. No data could be retrieved from remote service.'
346                                         );
347                                         $('#HPIAccidentBtnConfirm').prop('disabled', false);
348                                     }
349                                 );
350                             }
351                             , _w.taskContractError
352                         );
353                     }, _w.taskExecError
354                 );
355             });
356
357
358                         if (false != _w.valuationview.newItem)
359                         {
360                                 $('#pricinghistory').hide();
361
362
363
364                         }
365
366                         if (false == _w.valuationview.newItem)
367                         {
368                                 _w.valuationview.ti.hydrate({
369                                         'gridPricingHistoryColumnHeaders': {
370                                                 constructor: 'GridColumnHeader',
371                                                 items: {
372                                                         Date: {
373                                                                 id: 'gridPricingHistoryColumn_Date',
374                                                                 title: 'Date',
375                                                         },
376                                                         Trade: {
377                                                                 id: 'gridPricingHistoryColumn_Trade',
378                                                                 title: 'Trade',
379                                                         },
380                                                         TotalRecon: {
381                                                                 id: 'gridPricingHistoryColumn_totalRecon',
382                                                                 title: 'Total Recon',
383                                                         },
384                                                         km: {
385                                                                 id: 'gridPricingHistoryColumn_km',
386                                                                 title: 'km',
387                                                         },
388                                                         PriceguideOffer: {
389                                                                 id: 'gridPricingHistoryColumn_pricegOffer',
390                                                                 title: 'Priceguide Offer',
391                                                         },
392                                                         AuctionWinningBid: {
393                                                                 id: 'gridPricingHistoryColumn_auctionWinningBid',
394                                                                 title: 'Auction Winning Bid',
395                                                         },
396                                                 }
397                                         },
398                                         'gridPricingHistoryRowRepeater': {}
399                                 });
400                         }
401
402
403                         $('#btnUpdate').prop('disabled', true);
404                         $('#btnFetchTu').click(function () {
405                                 if (!$('#vehicleYear').val()
406                                                                 || !$('#vehicleType').val())
407                                 {
408                                         alert('Vehicle year and type is required to fetch Trade and Retail pricing.');
409                                         return;
410                                 }
411                                 $('#btnFetchTu').prop('disabled', true);
412                                 App.API.getTask(
413                                                                 'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
414                                                                 {}, _w.valuationview._onTuReady, _w.taskContractError
415                                                                 );
416                         });
417                         $('#btnSendToDealDone').click(function () {
418                                 var stockNo = $('#stockNumberDD').val();
419                                 if (null == stockNo || '' == stockNo)
420                                 {
421                                         alert('Please enter a stock number.');
422                                         return;
423                                 }
424                                 if (!$('#frmValuationView').valid())
425                                 {
426                                         return;
427                                 }
428                                 if (!$('#acceptStockDDHPIdisclaimer').is(':checked'))
429                                 {
430                                         alert('Please accept the conditions before sending.');
431                                         return;
432                                 }
433                                 if ('' == $('#mainImage').val())
434                                 {
435                                         alert('The main image is mandatory for moving a vehicle to Deal Done.');
436                                         $('#img_mainImage').addClass('error');
437                                         $('#img_mainImage').removeClass('valid');
438                                         return;
439                                 }
440                                 else
441                                 {
442                                         $('#img_mainImage').removeClass('error');
443                                         $('#img_mainImage').addClass('valid');
444                                 }
445                                 if ('' == $('#vinNumber').val())
446                                 {
447                                         alert('The VIN and Engine number is mandatory for moving a vehicle to Deal Done.');
448                                         $('#vinNumber').addClass('error');
449                                         $('#vinNumber').removeClass('valid');
450                                         return;
451                                 }
452                                 else
453                                 {
454                                         $('#vinNumber').removeClass('error');
455                                         $('#vinNumber').addClass('valid');
456                                 }
457                                 if ('' == $('#engineNumber').val())
458                                 {
459                                         alert('The VIN and Engine number is mandatory for moving a vehicle to Deal Done.');
460                                         $('#engineNumber').addClass('error');
461                                         $('#engineNumber').removeClass('valid');
462                                         return;
463                                 }
464                                 else
465                                 {
466                                         $('#engineNumber').removeClass('error');
467                                         $('#engineNumber').addClass('valid');
468                                 }
469                                 $('#btnUpdate').prop('disabled', true);
470                                 $('#btnSendToDealDone').prop('disabled', true);
471                                 $('#btnSendToDealNotDone').prop('disabled', true);
472                                 var data = _w.valuationview._prepValuationUpdateData();
473
474                 data.Valuation.sendToStockFrom = "1";
475
476                                 App.API.execTask(
477                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
478                                                                 function () {
479                                                                         App.API.directRoute(
480                                                                                                         'dealDoneOnValuation:' + _w.valuationview.itemId,
481                                                                                                         'Valuation', 'Valuation.MoveToDealDone', _w.valuationview.itemId, {},
482                                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
483                                                                                                         );
484                                                                 }, _w.taskExecError
485                                                                 );
486                         });
487                         $('#btnSendToDealNotDone').click(function () {
488                                 if (!$('#frmValuationView').valid())
489                                 {
490                                         return;
491                                 }
492
493                 if(7 == $('#dealNotDoneSelection').val() && '' == $('#dealNotDoneReason').val())
494                 {
495                     alert('Please supply a reason for marking this deal as not done.');
496                     return;
497                 }
498
499                                 $('#btnUpdate').prop('disabled', true);
500                                 $('#btnSendToDealDone').prop('disabled', true);
501                                 $('#doSendToDealDone').prop('disabled', true);
502                                 $('#doSendToDealNotDone').prop('disabled', true);
503                                 var data = _w.valuationview._prepValuationUpdateData();
504                                 App.API.execTask(
505                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
506                                                                 function () {
507                                                                         App.API.directRoute(
508                                                                                                         'dealNotDoneOnValuation:' + _w.valuationview.itemId,
509                                                                                                         'Valuation', 'Valuation.MoveToDealNotDone', _w.valuationview.itemId, {},
510                                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
511                                                                                                         );
512                                                                 }, _w.taskExecError
513                                                                 );
514                         });
515                         $('#doAcceptOffer').click(function () {
516                                 if (!$('#frmValuationView').valid())
517                                 {
518                                         return;
519                                 }
520                                 $('#btnUpdate').prop('disabled', true);
521                                 $('#btnAcceptOffer').prop('disabled', true);
522                                 $('#btnKeepForStock').prop('disabled', true);
523                                 var data = _w.valuationview._prepValuationUpdateData();
524                                 App.API.execTask(
525                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
526                                                                 function () {
527                                                                         App.API.directRoute(
528                                                                                                         'offerAcceptedOnValuation:' + _w.valuationview.itemId,
529                                                                                                         'Valuation', 'Valuation.MoveToOfferAccepted', _w.valuationview.itemId, {},
530                                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
531                                                                                                         );
532                                                                 }, _w.taskExecError
533                                                                 );
534                         });
535                         $('#btnKeepForStock').click(function () {
536                                 if (!$('#frmValuationView').valid())
537                                 {
538                                         return;
539                                 }
540                                 $('#btnUpdate').prop('disabled', true);
541                                 $('#btnAcceptOffer').prop('disabled', true);
542                                 $('#btnKeepForStock').prop('disabled', true);
543                                 var data = _w.valuationview._prepValuationUpdateData();
544                                 App.API.execTask(
545                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
546                                                                 function () {
547                                                                         App.API.directRoute(
548                                                                                                         'keepForStockOnValuation:' + _w.valuationview.itemId,
549                                                                                                         'Valuation', 'Valuation.MoveToKeepForStock', _w.valuationview.itemId, {},
550                                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
551                                                                                                         );
552                                                                 }, _w.taskExecError
553                                                                 );
554                         });
555                         $('#btnArchive').click(function () {
556                                 App.API.directRoute(
557                                                                 'archiveValuation:' + _w.valuationview.itemId,
558                                                                 'Valuation', 'Valuation.MoveToArchive', _w.valuationview.itemId, {},
559                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
560                                                                 );
561                         });
562                         $('#btnUnarchive').click(function () {
563                                 App.API.directRoute(
564                                                                 'unarchiveValuation:' + _w.valuationview.itemId,
565                                                                 'Valuation', 'Valuation.UnArchive', _w.valuationview.itemId, {},
566                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
567                                                                 );
568                         });
569                         $('#btnSaveAsPending').click(function () {
570                                 if (!$('#frmValuationView').valid())
571                                 {
572                                         return;
573                                 }
574                                 $('#btnUpdate').prop('disabled', true);
575                                 $('#btnSendToSales').prop('disabled', true);
576                                 $('#btnSaveAsPending').prop('disabled', true);
577                                 $('#doSendToStock').prop('disabled', true);
578                                 $('#btnSendToPg').prop('disabled', true);
579                                 if (_w.valuationview.newItem)
580                                 {
581                                         _w.valuationview._updatePrice(function () {
582                                                 var data = _w.valuationview._prepValuationUpdateData();
583                                                 App.API.getTask(
584                                                                                 'createValuationPending', 'Valuation', 'Valuation.CreatePending',
585                                                                                 null, {}, $.proxy(function (data) {
586                                                         App.API.execTask(
587                                                                                         'createValuationPending', data, {},
588                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
589                                                                                         );
590                                                 }, this, data), _w.taskContractError
591                                                                                 );
592                                         });
593                                 }
594                                 else
595                                 {
596                                         _w.valuationview._routeToPending();
597                                 }
598                         });
599                         $('#btnSaveAsSales').click(function () {
600                                 var valuators = $('#valuators').val();
601                                 if (null == valuators)
602                                 {
603                                         alert('Please select at least one valuator.');
604                                         return;
605                                 }
606                                 if (!$('#frmValuationView').valid())
607                                 {
608                                         return;
609                                 }
610
611                                 $('#btnSaveAsSales').prop('disabled', true);
612                                 $('#btnUpdate').prop('disabled', true);
613                                 $('#btnSendToSales').prop('disabled', true);
614                                 $('#btnSaveAsPending').prop('disabled', true);
615                                 $('#doSendToStock').prop('disabled', true);
616                                 $('#btnSendToPg').prop('disabled', true);
617                                 if (_w.valuationview.newItem)
618                                 {
619                                         _w.valuationview._updatePrice(function () {
620                                                 var data = _w.valuationview._prepValuationUpdateData();
621                                                 var valuators = $('#valuators').val();
622                                                 data.Valuation.valuators = [];
623                                                 for (var i = 0; i < valuators.length; i++)
624                                                 {
625                                                         data.Valuation.valuators.push({id: valuators[i]});
626                                                 }
627                                                 App.API.getTask(
628                                                                                 'createValuationNew', 'Valuation', 'Valuation.CreateNew',
629                                                                                 null, {}, $.proxy(function (data) {
630                                                         App.API.execTask(
631                                                                                         'createValuationNew', data, {},
632                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
633                                                                                         );
634                                                 }, this, data), _w.taskContractError
635                                                                                 );
636                                         });
637                                 }
638                                 else
639                                 {
640                                         var data = _w.valuationview._prepValuationUpdateData();
641                                         var valuators = $('#valuators').val();
642                                         data.Valuation.valuators = [];
643                                         for (var i = 0; i < valuators.length; i++)
644                                         {
645                                                 data.Valuation.valuators.push({id: valuators[i]});
646                                         }
647                                         App.API.execTask(
648                                                                         'updateValuation:' + _w.valuationview.itemId, data, {},
649                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
650                                                                         );
651                                 }
652                         });
653                         $('#btnSendToSales').click(function () {
654                                 var profile = $('#salesProfile').val();
655                                 var amount = $('#salesAmountOffered').val();
656                                 if (null == profile || '' == amount)
657                                 {
658                                         alert('Please select Sales person and enter an Amount.');
659                                         return;
660                                 }
661                                 if (!$('#frmValuationView').valid())
662                                 {
663                                         return;
664                                 }
665                                 $('#btnUpdate').prop('disabled', true);
666                                 $('#btnSendToSales').prop('disabled', true);
667                                 $('#btnSaveAsPending').prop('disabled', true);
668                                 $('#doSendToStock').prop('disabled', true);
669                                 $('#btnSendToPg').prop('disabled', true);
670                                 if (_w.valuationview.newItem)
671                                 {
672                                         _w.valuationview._updatePrice(function () {
673                                                 var data = _w.valuationview._prepValuationUpdateData();
674                                                 data.Valuation.amountOffered = amount;
675                                                 App.API.getTask(
676                                                                                 'createValuationComplete', 'Valuation', 'Valuation.CreateComplete',
677                                                                                 null, {}, $.proxy(function (data) {
678                                                         App.API.execTask(
679                                                                                         'createValuationComplete', data, {},
680                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
681                                                                                         );
682                                                 }, this, data), _w.taskContractError
683                                                                                 );
684                                         });
685                                 }
686                                 else
687                                 {
688                                         if ('Price Guide' == _w.valuationview.itemData.jobState)
689                                         {
690                                                 App.API.getTask(
691                                                                                 'sendToSalesFull:' + _w.valuationview.itemId, 'Valuation', 'Valuation.SendToSalesFull', _w.valuationview.itemId,
692                                                                                 {}, function () {
693                                                         var data = _w.valuationview._prepValuationUpdateData();
694                                                         data.Valuation.amountOffered = $('#salesAmountOffered').val();
695                                                         App.API.execTask(
696                                                                                         'sendToSalesFull:' + _w.valuationview.itemId, data, {},
697                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
698                                                                                         );
699                                                 }, _w.taskContractError
700                                                                                 );
701                                         }
702                                         else
703                                         {
704                                                 _w.valuationview._routeToComplete();
705                                         }
706                                 }
707                         });
708
709             $('#btnSendToCustomer').click(function () {
710                 var amount = $('#customerAmountOffered').val();
711                 if ('' == amount)
712                 {
713                     alert('Please enter an Amount.');
714                     return;
715                 }
716                 if (!$('#frmValuationView').valid())
717                 {
718                     return;
719                 }
720                 $('#btnUpdate').prop('disabled', true);
721                 $('#btnSendToSales').prop('disabled', true);
722                 $('#btnSaveAsPending').prop('disabled', true);
723                 $('#doSendToStock').prop('disabled', true);
724                 $('#btnSendToPg').prop('disabled', true);
725                 if (_w.valuationview.newItem)
726                 {
727
728                     _w.valuationview._updatePrice(function () {
729                         var data = _w.valuationview._prepValuationUpdateData();
730                         data.Valuation.amountOffered = amount;
731                         App.API.getTask(
732                             'createCustomerValuationComplete', 'Valuation', 'Valuation.CreateCompleteSendToCustomer',
733                             null, {}, $.proxy(function (data) {
734                                 App.API.execTask(
735                                     'createCustomerValuationComplete', data, {},
736                                     _w.valuationview._onValuationUpdated, _w.taskExecError
737                                 );
738                             }, this, data), _w.taskContractError
739                         );
740                     });
741                 }
742                 else
743                 {
744                     if ('Price Guide' == _w.valuationview.itemData.jobState)
745                     {
746                         App.API.getTask(
747                             'sendToCustomerFull:' + _w.valuationview.itemId, 'Valuation', 'Valuation.SendToCustomerFull', _w.valuationview.itemId,
748                             {}, function () {
749                                 var data = _w.valuationview._prepValuationUpdateData();
750                                 data.Valuation.amountOffered = $('#salesAmountOffered').val();
751                                 App.API.execTask(
752                                     'sendToCustomerFull:' + _w.valuationview.itemId, data, {},
753                                     _w.valuationview._onValuationUpdated, _w.taskExecError
754                                 );
755                             }, _w.taskContractError
756                         );
757                     }
758                     else
759                     {
760                         _w.valuationview._routeToCompleteCustomer();
761                     }
762
763                 }
764             });
765
766                         App.Util.updateCheckboxStyle($('#acceptStockHPIdisclaimer'));
767                         App.Util.updateCheckboxStyle($('#acceptStockDDHPIdisclaimer'));
768                         $('#doSendToStock').click(function () {
769                                 var stockNo = $('#stockNumber').val();
770                                 if (null == stockNo || '' == stockNo)
771                                 {
772                                         alert('Please enter a stock number.');
773                                         return;
774                                 }
775                                 if (!$('#frmValuationView').valid())
776                                 {
777                                         return;
778                                 }
779                                 if (!$('#acceptStockHPIdisclaimer').is(':checked'))
780                                 {
781                                         alert('Please accept the conditions before sending.');
782                                         return;
783                                 }
784
785                                 if ('' == $('#mainImage').val())
786                                 {
787                                         alert('The main image is mandatory for moving a vehicle to stock.');
788                                         $('#img_mainImage').addClass('error');
789                                         $('#img_mainImage').removeClass('valid');
790                                         return;
791                                 }
792                                 else
793                                 {
794                                         $('#img_mainImage').removeClass('error');
795                                         $('#img_mainImage').addClass('valid');
796                                 }
797                                 if ('' == $('#registrationNumber').val())
798                                 {
799                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to stock.');
800                                         $('#registrationNumber').addClass('error');
801                                         $('#registrationNumber').removeClass('valid');
802                                         return;
803                                 }
804                                 else
805                                 {
806                                         $('#registrationNumber').removeClass('error');
807                                         $('#registrationNumber').addClass('valid');
808                                 }
809                                 if ('' == $('#vinNumber').val())
810                                 {
811                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to stock.');
812                                         $('#vinNumber').addClass('error');
813                                         $('#vinNumber').removeClass('valid');
814                                         return;
815                                 }
816                                 else
817                                 {
818                                         $('#vinNumber').removeClass('error');
819                                         $('#vinNumber').addClass('valid');
820                                 }
821                                 if ('' == $('#engineNumber').val())
822                                 {
823                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to stock.');
824                                         $('#engineNumber').addClass('error');
825                                         $('#engineNumber').removeClass('valid');
826                                         return;
827                                 }
828                                 else
829                                 {
830                                         $('#engineNumber').removeClass('error');
831                                         $('#engineNumber').addClass('valid');
832                                 }
833                                 $('#btnUpdate').prop('disabled', true);
834                                 $('#btnSendToSales').prop('disabled', true);
835                                 $('#btnSaveAsPending').prop('disabled', true);
836                                 $('#doSendToStock').prop('disabled', true);
837                                 $('#btnSendToPg').prop('disabled', true);
838
839                                 if (_w.valuationview.newItem)
840                                 {
841                                         _w.valuationview._updatePrice(function () {
842                                                 var data = _w.valuationview._prepValuationUpdateData();
843
844                         data.Valuation.sendToStockFrom = "2";
845
846                         App.API.getTask(
847                             'createValuationStock', 'Valuation', 'Valuation.CreateStock',
848                             null, {}, $.proxy(function (data) {
849                                 App.API.execTask(
850                                     'createValuationStock', data, {},
851                                     _w.valuationview._onValuationUpdated, _w.taskExecError
852                                 );
853                             }, this, data), _w.taskContractError
854                         );
855
856                                         });
857
858                                 }
859                                 else
860                                 {
861                     var data = _w.valuationview._prepValuationUpdateData();
862                     data.Valuation.sendToStockFrom = "2";
863
864                     App.API.execTask(
865                         'updateValuation:' + _w.valuationview.itemId, data, {},
866                         function () {
867
868                             _w.valuationview._routeToStock();
869
870                             //App.API.directRoute(
871                             //    'sendToStockValuation:' + _w.valuationview.itemId,
872                             //    'Valuation', 'Valuation.SendToStock', _w.valuationview.itemId, {},
873                             //    _w.valuationview._onValuationUpdated, _w.taskExecError
874                             //);
875                         }, _w.taskExecError
876                     );
877
878                     //App.API.execTask(
879                      //   'updateValuation:' + _w.valuationview.itemId, data, {},
880                      //   _w.valuationview._onValuationUpdated, _w.taskExecError
881                     //);
882                     //
883                                         //_w.valuationview._routeToStock();
884                                 }
885                         });
886                         App.Util.updateCheckboxStyle($('#acceptPgHPIdisclaimer'));
887                         $('#btnSendToPg').click(function () {
888                                 var clubs = $('#clubs').val();
889                                 if (null == clubs)
890                                 {
891                                         alert('Please select at least one club.');
892                                         return;
893                                 }
894                                 if (!$('#acceptPgHPIdisclaimer').is(':checked'))
895                                 {
896                                         alert('Please accept the conditions before sending.');
897                                         return;
898                                 }
899                                 if ('' == $('#registrationNumber').val())
900                                 {
901                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to price guide.');
902                                         $('#registrationNumber').addClass('error');
903                                         $('#registrationNumber').removeClass('valid');
904                                         return;
905                                 }
906                                 else
907                                 {
908                                         $('#registrationNumber').removeClass('error');
909                                         $('#registrationNumber').addClass('valid');
910                                 }
911                                 if ('' == $('#vinNumber').val())
912                                 {
913                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to price guide.');
914                                         $('#vinNumber').addClass('error');
915                                         $('#vinNumber').removeClass('valid');
916                                         return;
917                                 }
918                                 else
919                                 {
920                                         $('#vinNumber').removeClass('error');
921                                         $('#vinNumber').addClass('valid');
922                                 }
923                                 if ('' == $('#engineNumber').val())
924                                 {
925                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to price guide.');
926                                         $('#engineNumber').addClass('error');
927                                         $('#engineNumber').removeClass('valid');
928                                         return;
929                                 }
930                                 else
931                                 {
932                                         $('#engineNumber').removeClass('error');
933                                         $('#engineNumber').addClass('valid');
934                                 }
935                                 if (!$('#frmValuationView').valid())
936                                 {
937                                         return;
938                                 }
939                                 $('#btnUpdate').prop('disabled', true);
940                                 $('#btnSendToSales').prop('disabled', true);
941                                 $('#btnSaveAsPending').prop('disabled', true);
942                                 $('#doSendToStock').prop('disabled', true);
943                                 $('#btnSendToPg').prop('disabled', true);
944                                 if (_w.valuationview.newItem)
945                                 {
946                                         _w.valuationview._updatePrice(function () {
947                                                 var data = _w.valuationview._prepValuationUpdateData();
948                                                 data.Context = {clubs: []};
949                                                 var clubList = $('#clubs').val();
950                                                 for (var i = 0; i < clubList.length; i++)
951                                                 {
952                                                         data.Context.clubs.push({id: clubList[i]});
953                                                 }
954                                                 App.API.getTask(
955                                                                                 'createValuationPriceGuide', 'Valuation', 'Valuation.CreatePriceGuide',
956                                                                                 null, {}, $.proxy(function (data) {
957                                                         App.API.execTask(
958                                                                                         'createValuationPriceGuide', data, {},
959                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
960                                                                                         );
961                                                 }, this, data), _w.taskContractError
962                                                                                 );
963                                         });
964                                 }
965                                 else
966                                 {
967                                         _w.valuationview._routeToPg();
968                                 }
969                         });
970
971                         $('.back-btn').on('click', function () {
972                                 window.history.back();
973                         });
974
975                         _w.valuationview.itemId = App.Util.getUrlParam('id');
976                         if (0 == _w.valuationview.itemId || null == _w.valuationview.itemId)
977                         {
978                                 _w.valuationview.newItem = true;
979                                 _w.valuationview.itemData = {stock: {}};
980
981                 App.DataStore.loadSelectListData(
982                     'years', false, 'Stock', 'Year.SelectList', null,
983                     {}
984                 );
985                 App.DataStore.loadSelectListData(
986                     'categories', false, 'Stock', 'Category.SelectList', null,
987                     {}
988                 );
989
990                 App.DataStore.loadSelectListData(
991                     'fuelTypes', false, 'Stock', 'FuelType.SelectList', null,
992                     {}
993                 );
994                 App.DataStore.loadSelectListData(
995                     'transmissionTypes', false, 'Stock', 'TransmissionType.SelectList', null,
996                     {}
997                 );
998                 App.DataStore.loadSelectListData(
999                     'damages', false, 'Stock', 'Damage.SelectList', null,
1000                     {}
1001                 );
1002                 App.DataStore.loadSelectListData(
1003                     'accessories', false, 'Stock', 'Accessory.SelectList', null,
1004                     {}
1005                 );
1006
1007                                 App.DataStore.loadSelectListGroup([
1008                                         //{dataId: 'years', isStatic: true, workspace: 'Stock', task: 'Year.SelectList'},
1009                                         //{dataId: 'categories', isStatic: true, workspace: 'Stock', task: 'Category.SelectList'},
1010                                         {dataId: 'conditions', isStatic: true, workspace: 'Stock', task: 'Condition.SelectList'},
1011                                         {dataId: 'exteriorColours', isStatic: true, workspace: 'Stock', task: 'ExteriorColour.SelectList'},
1012                                         {dataId: 'interiorColours', isStatic: true, workspace: 'Stock', task: 'InteriorColour.SelectList'},
1013                                         {dataId: 'upholsteries', isStatic: true, workspace: 'Stock', task: 'Upholstery.SelectList'},
1014                                         {dataId: 'papers', isStatic: true, workspace: 'Stock', task: 'Paper.SelectList'},
1015                                         {dataId: 'natis', isStatic: true, workspace: 'Stock', task: 'Natis.SelectList'},
1016                                         {dataId: 'fsh', isStatic: true, workspace: 'Stock', task: 'FullServiceHistory.SelectList'},
1017                                         //{dataId: 'fuelTypes', isStatic: true, workspace: 'Stock', task: 'FuelType.SelectList'},
1018                                         //{dataId: 'transmissionTypes', isStatic: true, workspace: 'Stock', task: 'TransmissionType.SelectList'},
1019                                         //{dataId: 'damages', isStatic: true, workspace: 'Stock', task: 'Damage.SelectList'},
1020                                         //{dataId: 'accessories', isStatic: true, workspace: 'Stock', task: 'Accessory.SelectList'},
1021                                         {dataId: 'clubs', isStatic: true, workspace: 'PriceGuide', task: 'Club.SelectList'},
1022                                         {dataId: 'valuators', isStatic: true, workspace: 'User', task: 'Profile.ValuatorList'},
1023                                         //{dataId: 'sales', isStatic: true, workspace: 'User', task: 'Profile.SalesList'},
1024                                         {dataId: 'regions', isStatic: true, workspace: 'Location', task: 'Region.SelectList'},
1025                                 ]);
1026                                 App.DataStore.loadSelectListData(
1027                                                                 'sales', false, 'User', 'Profile.SalesList', null, {}
1028                                 );
1029                 App.DataStore.loadSelectListData(
1030                     'dealNotDoneSelections', false, 'Valuation', 'Valuation.DealNotDoneSelection', null,
1031                     {}
1032                 );
1033
1034
1035                         }
1036                         else
1037                         {
1038                                 _w.valuationview.newItem = false;
1039                                 var task = _w.valuationview.limited
1040                                                                 ? 'Valuation.LimitedUpdate'
1041                                                                 : 'Valuation.Update';
1042                                 App.API.getTask(
1043                                                                 'updateValuation:' + _w.valuationview.itemId, 'Valuation', task, _w.valuationview.itemId,
1044                                                                 {}, $.proxy(_w.valuationview._onValuationViewDataReceived, _w.valuationview), _w.taskContractError
1045                                                                 );
1046                                 setTimeout(function () {
1047                                         if (null == _w.valuationview.itemData)
1048                                         {
1049                                                 var task = _w.valuationview.limited
1050                                                                                 ? 'Valuation.LimitedUpdate'
1051                                                                                 : 'Valuation.Update';
1052                                                 App.API.getTask(
1053                                                                                 'updateValuation:' + _w.valuationview.itemId, 'Valuation', task, _w.valuationview.itemId,
1054                                                                                 {}, $.proxy(_w.valuationview._onValuationViewDataReceived, _w.valuationview), _w.taskContractError
1055                                                                                 );
1056                                         }
1057                                 }, 3000);
1058                 App.DataStore.loadSelectListData(
1059                     'dealNotDoneSelections', false, 'Valuation', 'Valuation.DealNotDoneSelection', null,
1060                     {}
1061                 );
1062                         }
1063                 },
1064                 loadHistoricalGrid: function (contract, data, options)
1065                 {
1066                         if (_w.valuationview.itemData != null)
1067                         {
1068                                 if (null != App.API.taskContract('gridStockHistory'))
1069                                 {
1070                                         App.API.execTask(
1071                                                                         'gridStockHistory', {Grid: {Filter: {"PricingHistory.stockId": _w.valuationview.itemData.stock.id}}}, options,
1072                                                                         _w.valuationview._onHistoryGridDataReceived, function () {
1073                                                                         }
1074                                         );
1075                                 }
1076                         }
1077                 },
1078                 _onHistoryGridDataReceived: function (response)
1079                 {
1080                         _w.valuationview.gridStatus = 'Active';
1081                         _w.valuationview.ti.hydrateParam('gridPricingHistoryRowRepeater', {});
1082                         var gridData = [];
1083
1084                         if (_w.valuationview.itemData == null || response.Data.DataSet == undefined || response.Data.DataSet.length == 0 )
1085                         {
1086                                 $('#pricing_history_none_found').show();
1087                                 $('#PHColumnHeaders').hide();
1088                         }
1089                         else
1090                         {
1091                                 $('#pricing_history_none_found').hide();
1092                                 $('#PHColumnHeaders').show();
1093                         }
1094
1095                         if(response.Data.DataSet != undefined)
1096                         {
1097                                 for (var i = 0; i < response.Data.DataSet.length; i++)
1098                                         {
1099                                                 var row = response.Data.DataSet[i];
1100
1101                                                 gridData.push({
1102                                                         prepend: {
1103                                                                 Trade: 'R ',
1104                                                                 TotalRecon: 'R ',
1105                                                                 PriceguideOffer: 'R ',
1106                                                                 AuctionWinningBid: 'R '
1107                                                         },
1108                                                         style: {
1109                                                                 Date: '',
1110                                                                 Trade: '',
1111                                                                 TotalRecon: '',
1112                                                                 km: '',
1113                                                                 PriceguideOffer: '',
1114                                                                 AuctionWinningBid: '',
1115                                                         },
1116                                                         items: {
1117                                                                 'Date': row.date,
1118                                                                 'Trade': row.trade,
1119                                                                 'TotalRecon': row.totalRecon,
1120                                                                 'KM': row.km,
1121                                                                 'PriceguideOffer': row.pricegOffer,
1122                                                                 'AuctionWinningBid': row.auctionWinningBid,
1123                                                         }
1124                                                 });
1125                                         }
1126                                 
1127                                 _w.valuationview.ti.hydrateParam('gridPricingHistoryRowRepeater', {
1128                                         constructor: 'GridDataRow',
1129                                         items: gridData
1130                                 });
1131                                 response.Data.Meta.bind = _w.valuationview.pageStockGrid;
1132                                 
1133                         }        
1134                                                 
1135                 },
1136                 _routeToPg: function ()
1137                 {
1138                         App.API.getRoute(
1139                                                         'sendToPg:' + _w.valuationview.itemId, 'Valuation', 'Valuation.SendToPriceGuide', _w.valuationview.itemId,
1140                                                         {}, function () {
1141                                 var data = _w.valuationview._prepValuationUpdateData();
1142                                 data.Context = {clubs: []};
1143                                 var clubList = $('#clubs').val();
1144                                 for (var i = 0; i < clubList.length; i++)
1145                                 {
1146                                         data.Context.clubs.push({id: clubList[i]});
1147                                 }
1148                                 App.API.execRoute(
1149                                                                 'sendToPg:' + _w.valuationview.itemId, data, {},
1150                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
1151                                                                 );
1152                         }, _w.taskContractError
1153                                                         );
1154                 },
1155                 _routeToPending: function ()
1156                 {
1157                         App.API.getRoute(
1158                                                         'sendToPending:' + _w.valuationview.itemId, 'Valuation', 'Valuation.MoveToPending', _w.valuationview.itemId,
1159                                                         {}, function () {
1160                                 var data = _w.valuationview._prepValuationUpdateData();
1161                                 App.API.execRoute(
1162                                                                 'sendToPending:' + _w.valuationview.itemId, data, {},
1163                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
1164                                                                 );
1165                         }, _w.taskContractError
1166                                                         );
1167                 },
1168                 _routeToComplete: function ()
1169                 {
1170                         App.API.getRoute(
1171                                                         'sendToComplete:' + _w.valuationview.itemId, 'Valuation', 'Valuation.MoveToComplete', _w.valuationview.itemId,
1172                                                         {}, function () {
1173                                 var data = _w.valuationview._prepValuationUpdateData();
1174
1175
1176                     //if('' !=  $('#customerAmountOffered').val() && 0 ==  $('#salesAmountOffered').val())
1177                     //{
1178                     //    data.Valuation.amountOffered = $('#customerAmountOffered').val();
1179                     //}
1180                     //if('' !=  $('#salesAmountOffered').val() && 0 ==  $('#customerAmountOffered').val())
1181                     //{
1182                     //    data.Valuation.amountOffered = $('#salesAmountOffered').val();
1183                     //}
1184
1185                     if(0 !=  $('#customerAmountOffered').val() && 0 ==  $('#salesAmountOffered').val())
1186                     {
1187                         data.Valuation.amountOffered = $('#customerAmountOffered').val();
1188                     }
1189                     else
1190                     {
1191                         data.Valuation.amountOffered = $('#salesAmountOffered').val();
1192                     }
1193
1194                                 //data.Valuation.amountOffered = $('#salesAmountOffered').val();
1195                                 App.API.execRoute(
1196                                                                 'sendToComplete:' + _w.valuationview.itemId, data, {},
1197                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
1198                                                                 );
1199                         }, _w.taskContractError
1200                                                         );
1201                 },
1202
1203         _routeToCompleteCustomer: function ()
1204         {
1205             App.API.getRoute(
1206                 'sendToCompleteCustomer:' + _w.valuationview.itemId, 'Valuation', 'Valuation.MoveToCustomerComplete', _w.valuationview.itemId,
1207                 {}, function () {
1208                     var data = _w.valuationview._prepValuationUpdateData();
1209
1210
1211                     //if(0 !=  $('#customerAmountOffered').val() && 0 ==  $('#salesAmountOffered').val())
1212                     //{
1213                     //    data.Valuation.amountOffered = $('#customerAmountOffered').val();
1214                     //}
1215                     //if(0 !=  $('#salesAmountOffered').val() && 0 ==  $('#customerAmountOffered').val())
1216                     //{
1217                     //    data.Valuation.amountOffered = $('#salesAmountOffered').val();
1218                     //}
1219
1220                     if(0 !=  $('#customerAmountOffered').val() && 0 ==  $('#salesAmountOffered').val())
1221                     {
1222                         data.Valuation.amountOffered = $('#customerAmountOffered').val();
1223                     }
1224                     else
1225                     {
1226                         data.Valuation.amountOffered = $('#salesAmountOffered').val();
1227                     }
1228
1229                     //data.Valuation.amountOffered = $('#salesAmountOffered').val();
1230                     App.API.execRoute(
1231                         'sendToCompleteCustomer:' + _w.valuationview.itemId, data, {},
1232                         _w.valuationview._onValuationUpdated, _w.taskExecError
1233                     );
1234                 }, _w.taskContractError
1235             );
1236         },
1237                 _routeToStock: function ()
1238                 {
1239                         App.API.getRoute(
1240                                                         'sendToStock:' + _w.valuationview.itemId, 'Valuation', 'Valuation.SendToStock', _w.valuationview.itemId,
1241                                                         {}, function () {
1242                                 var data = _w.valuationview._prepValuationUpdateData();
1243
1244                                 App.API.execRoute(
1245                                                                 'sendToStock:' + _w.valuationview.itemId, data, {},
1246                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
1247                                                                 );
1248                         }, _w.taskContractError
1249                                                         );
1250                 },
1251                 setValuationViewFormMeta: function (data)
1252                 {
1253
1254                         var damages = {};
1255                         var newtitle = 'Amount offered';
1256
1257
1258                         if ('Dealership Sales' == App.permissions.name)
1259                         {
1260                                 newtitle = "Manager's offer";
1261                         }
1262
1263                         if (undefined != data && undefined != data.stock)
1264                         {
1265
1266                                 //console.log("data.stock.id", data.stock.id);
1267
1268                                 _w.stock.Id = data.stock.id;
1269
1270                                 for (var i = 0; i < data.stock.damages.length; i++)
1271                                 {
1272                                         damages['d' + data.stock.damages[i].damage] = data.stock.damages[i].amount;
1273                                 }
1274                         }
1275                         else
1276                         {
1277                                 data = {"stock": {}};
1278                         }
1279
1280                         _w.valuationview.formMeta = {
1281                 'vehicleYear': {
1282                     type: 'select',
1283                     id: 'vehicleYear',
1284                     title: 'Year',
1285                     dataStoreId: 'years',
1286                     value: data.stock.vehicleYear ? data.stock.vehicleYear : '',
1287                     onChange: function () {
1288                         if (_w.valuationview.firstTimeCheckYear != true) {
1289                             _w.valuationview._listMakesModelsTypes(false, function () {
1290
1291                             });
1292                         }
1293                         _w.valuationview.firstTimeCheckYear = false;
1294                     }
1295                 },
1296                 'category': {
1297                     type: 'select',
1298                     id: 'vehicleCategory',
1299                     title: 'Category',
1300                     dataStoreId: 'categories',
1301                     value: data.stock.type ? data.stock.type.category.id : '',
1302                     onChange: function () {
1303                                             if ($(this).val() == 8) {
1304                             $('#retailPrice').val('');
1305                             $('#tradePrice').val('');
1306                             $('#listPrice').val('');
1307                             _w.valuationview.ti.hydrateParam('infRetailPrice', 'R ' + +'.00');
1308                             _w.valuationview.ti.hydrateParam('infTradePrice', 'R ' + +'.00');
1309                             _w.valuationview.ti.hydrateParam('infListPrice', 'R ' + +'.00');
1310                         }
1311
1312
1313                         if ($(this).val() == 8 && _w.valuationview.itemId == 0) {
1314                             $('#mmCode').html("Other");
1315                         }
1316                         if (!App.DataStore.getItem('BuildSelect:vehicleCategory', false)) {
1317                             if (_w.valuationview.itemData) {
1318
1319
1320                                 //_w.valuationview.itemData.stock.type.category.id = $('#vehicleCategory').val();
1321                                 if (undefined != _w.valuationview.itemData.stock && undefined != _w.valuationview.itemData.stock.type && undefined != _w.valuationview.itemData.stock.type.category) {
1322                                     _w.valuationview.itemData.stock.type.category.id = $('#vehicleCategory').val();
1323                                 }
1324                                 _w.valuationview._listMakesModelsTypes();
1325                             }
1326                         }
1327                         $('#' + _w.valuationview.ti.tid + '_makeManual').hide();
1328                         $('#' + _w.valuationview.ti.tid + '_modelManual').hide();
1329                         $('#' + _w.valuationview.ti.tid + '_typeManual').hide();
1330                         $('#makeManual').val('');
1331                         $('#modelManual').val('');
1332                         $('#typeManual').val('');
1333                         $('#' + _w.valuationview.ti.tid + '_make').show();
1334                         $('#' + _w.valuationview.ti.tid + '_model').show();
1335                         $('#' + _w.valuationview.ti.tid + '_type').show();
1336                     }
1337                 },
1338                 'make': {
1339                     type: 'select',
1340                     id: 'vehicleMake',
1341                     title: 'Vehicle Make',
1342                     dataStoreId: 'makes',
1343                     value: data.stock.type ? data.stock.type.model.make.id : '',
1344                     onChange: function () {
1345                         if (!App.DataStore.getItem('BuildSelect:vehicleMake', false)) {
1346
1347                             $('#vehicleMakeManual').val('');
1348                             $('#vehicleModelManual').val('');
1349                             $('#vehicleTypeManual').val('');
1350                             if (-1 == $('#vehicleMake').val()) {
1351                                 $('#' + _w.valuationview.ti.tid + '_make').hide();
1352                                 $('#' + _w.valuationview.ti.tid + '_model').hide();
1353                                 $('#' + _w.valuationview.ti.tid + '_type').hide();
1354                                 $('#' + _w.valuationview.ti.tid + '_makeManual').show();
1355                                 $('#' + _w.valuationview.ti.tid + '_modelManual').show();
1356                                 $('#' + _w.valuationview.ti.tid + '_typeManual').show();
1357                                 //$('#makeManual').val(''); vehicleMakeManual
1358                                 //$('#modelManual').val('');
1359                                 //$('#typeManual').val('');
1360                             }
1361                             else {
1362                                 $('#' + _w.valuationview.ti.tid + '_makeManual').hide();
1363                                 $('#' + _w.valuationview.ti.tid + '_modelManual').hide();
1364                                 $('#' + _w.valuationview.ti.tid + '_typeManual').hide();
1365                                 $('#' + _w.valuationview.ti.tid + '_make').show();
1366                                 $('#' + _w.valuationview.ti.tid + '_model').show();
1367                                 $('#' + _w.valuationview.ti.tid + '_type').show();
1368                                 if (_w.valuationview.itemData) {
1369
1370
1371                                     if (undefined != _w.valuationview.itemData.stock && undefined != _w.valuationview.itemData.stock.type && undefined != _w.valuationview.itemData.stock.type.model) {
1372                                         //console.log("_w.valuationview.itemData", _w.valuationview.itemData);
1373                                         _w.valuationview.itemData.stock.type.model.make.id = $('#vehicleMake').val();
1374                                     }
1375
1376                                     _w.valuationview._listMakesModelsTypes();
1377                                 }
1378                             }
1379
1380                         }
1381                     }
1382                 },
1383                 'model': {
1384                     type: 'select',
1385                     id: 'vehicleModel',
1386                     title: 'Vehicle Model',
1387                     dataStoreId: 'models',
1388                     value: data.stock.type ? data.stock.type.model.id : '',
1389                     onChange: function () {
1390                         if (!App.DataStore.getItem('BuildSelect:vehicleModel', false)) {
1391
1392                             $('#vehicleModelManual').val('');
1393                             $('#vehicleTypeManual').val('');
1394                             if (-1 == $('#vehicleModel').val()) {
1395                                 $('#' + _w.valuationview.ti.tid + '_model').hide();
1396                                 $('#' + _w.valuationview.ti.tid + '_type').hide();
1397                                 $('#' + _w.valuationview.ti.tid + '_modelManual').show();
1398                                 $('#' + _w.valuationview.ti.tid + '_typeManual').show();
1399                             }
1400                             else {
1401                                 $('#' + _w.valuationview.ti.tid + '_modelManual').hide();
1402                                 $('#' + _w.valuationview.ti.tid + '_typeManual').hide();
1403                                 $('#' + _w.valuationview.ti.tid + '_model').show();
1404                                 $('#' + _w.valuationview.ti.tid + '_type').show();
1405
1406                                 if (_w.valuationview.itemData) {
1407                                     if (undefined != _w.valuationview.itemData.stock && undefined != _w.valuationview.itemData.stock.type && undefined != _w.valuationview.itemData.stock.type.model) {
1408                                         _w.valuationview.itemData.stock.type.model.id = $('#vehicleModel').val();
1409                                     }
1410                                     _w.valuationview._listMakesModelsTypes();
1411                                 }
1412                             }
1413                         }
1414                     }
1415                 },
1416                 'type': {
1417                     type: 'select',
1418                     id: 'vehicleType',
1419                     title: 'Vehicle Type',
1420                     dataStoreId: 'types',
1421                     value: data.stock.type ? data.stock.type.id : '',
1422                     onChange: function (data) {
1423
1424                         $('#vehicleTypeManual').val('');
1425                         if (-1 == $('#vehicleType').val()) {
1426                             $('#' + _w.valuationview.ti.tid + '_type').hide();
1427                             $('#' + _w.valuationview.ti.tid + '_typeManual').show();
1428                         }
1429                         else {
1430                             $('#' + _w.valuationview.ti.tid + '_typeManual').hide();
1431                             $('#' + _w.valuationview.ti.tid + '_type').show();
1432
1433
1434                             if (_w.valuationview.firstTimeCheck != true) {
1435                                 if (_w.valuationview.newItem) {
1436                                     _w.valuationview._updatePrice(null, false);
1437                                 }
1438                                 else {
1439                                     _w.valuationview._updatePrice();
1440                                 }
1441                             }
1442                             else {
1443                                 _w.valuationview.firstTimeCheck = false;
1444                             }
1445
1446                         }
1447
1448
1449                     }
1450                 },
1451                 'makeManual': {
1452                     type: 'input',
1453                     id: 'vehicleMakeManual',
1454                     title: 'Vehicle Make',
1455                     //dataStoreId : 'makes',
1456                     value: data.stock.type ? data.stock.type.model.make.id : '',
1457                 },
1458                 'modelManual': {
1459                     type: 'input',
1460                     id: 'vehicleModelManual',
1461                     title: 'Vehicle Model',
1462                     //dataStoreId : 'models',
1463                     value: data.stock.type ? data.stock.type.model.id : '',
1464                 },
1465                 'typeManual': {
1466                     type: 'input',
1467                     id: 'vehicleTypeManual',
1468                     title: 'Vehicle Type',
1469                     //dataStoreId : 'types',
1470                     value: data.stock.type ? data.stock.type.id : '',
1471                 },
1472                 'mmCode': {
1473                     type: 'input',
1474                     id: 'mmCode',
1475                     title: 'MM Code',
1476                     style: 'disable',
1477                     setAttrib: 'readonly',
1478                     value: data.stock.type ? data.stock.type.mmCode : ''
1479                 },
1480                 'fuelType': {
1481                     type: 'select',
1482                     id: 'vehicleFuelType',
1483                     title: 'Fuel Type',
1484                     dataStoreId: 'fuelTypes',
1485                     value: data.stock.fuelType ? data.stock.fuelType : ''
1486                 },
1487                 'transmissionType': {
1488                     type: 'select',
1489                     id: 'vehicleTransmissionType',
1490                     title: 'Transmission Type',
1491                     dataStoreId: 'transmissionTypes',
1492                     value: data.stock.transmissionType ? data.stock.transmissionType : ''
1493                 },
1494                 'registrationNumber': {
1495                     type: 'input',
1496                     id: 'registrationNumber',
1497                     title: 'Registration no',
1498                     value: data.stock.registrationNumber ? data.stock.registrationNumber : '',
1499                     style: 'capitalise'
1500                 },
1501                 'vinNumber': {
1502                     type: 'input',
1503                     id: 'vinNumber',
1504                     title: 'Vin no',
1505                     value: data.stock.vinNumber ? data.stock.vinNumber : '',
1506                     style: 'capitalise'
1507                 },
1508                 'engineNumber': {
1509                     type: 'input',
1510                     id: 'engineNumber',
1511                     title: 'Eng. no',
1512                     value: data.stock.engineNumber ? data.stock.engineNumber : '',
1513                     style: 'capitalise'
1514                 },
1515                 'sighted': {
1516                     type: 'select',
1517                     id: 'sighted',
1518                     title: 'Sighted',
1519                     dataStoreId: 'yesno',
1520                     value: undefined != data.sighted && null != data.sighted
1521                         ? (data.sighted == true ? "1" : "0")
1522                         : "0"
1523                 },
1524                 'licenseDiscExpired': {
1525                     type: 'select',
1526                     id: 'licenseDiscExpired',
1527                     title: 'License Disc Expired',
1528                     dataStoreId: 'yesno',
1529                     value: undefined != data.licenseDiscExpired && null != data.licenseDiscExpired
1530                         ? (data.licenseDiscExpired == true ? "1" : "0")
1531                         : "0"
1532                 },
1533                 'km': {
1534                     type: 'input',
1535                     id: 'km',
1536                     title: 'Kms',
1537                     value: data.stock.km ? data.stock.km : ''
1538                 },
1539                 'condition': {
1540                     type: 'select',
1541                     id: 'vehicleCondition',
1542                     title: 'Condition',
1543                     dataStoreId: 'conditions',
1544                     value: data.stock.condition ? data.stock.condition : ''
1545                 },
1546                 'exteriorColour': {
1547                     type: 'select',
1548                     id: 'exteriorColour',
1549                     title: 'Main ext. colour',
1550                     dataStoreId: 'exteriorColours',
1551                     value: data.stock.exteriorColour ? data.stock.exteriorColour : ''
1552                 },
1553                 'interiorColour': {
1554                     type: 'select',
1555                     id: 'interiorColour',
1556                     title: 'Main int. colour',
1557                     dataStoreId: 'interiorColours',
1558                     value: data.stock.interiorColour ? data.stock.interiorColour : ''
1559                 },
1560                 'upholstery': {
1561                     type: 'select',
1562                     id: 'vehicleUpholstery',
1563                     title: 'Upholstery',
1564                     dataStoreId: 'upholsteries',
1565                     value: data.stock.upholstery ? data.stock.upholstery : ''
1566                 },
1567                 'papers': {
1568                     type: 'select',
1569                     id: 'vehiclePapers',
1570                     title: 'Papers',
1571                     dataStoreId: 'papers',
1572                     value: data.stock.papers ? data.stock.papers : ''
1573                 },
1574                 'natis': {
1575                     type: 'select',
1576                     id: 'vehicleNatis',
1577                     title: 'Natis',
1578                     dataStoreId: 'natis',
1579                     value: data.stock.natis ? data.stock.natis : ''
1580                 },
1581                 'spareKeys': {
1582                     type: 'select',
1583                     id: 'spareKeys',
1584                     title: 'Spare keys',
1585                     dataStoreId: 'sparekeys',
1586                     value: undefined != data.stock.spareKeys && null != data.stock.spareKeys
1587                         ? (data.stock.spareKeys == true ? "1" : "0")
1588                         : null
1589                 },
1590                 'fullServiceHistory': {
1591                     type: 'select',
1592                     id: 'fullServiceHistory',
1593                     title: 'Full service history',
1594                     dataStoreId: 'fsh',
1595                     value: data.stock.fullServiceHistory ? data.stock.fullServiceHistory : ''
1596                 },
1597                 'fshNotes': {
1598                     type: 'textarea-small',
1599                     id: 'fshNotes',
1600                     title: 'FSH notes',
1601                     value: data.stock.fshNotes ? data.stock.fshNotes : ''
1602                 },
1603                 'damages': {
1604                     type: 'damageDetails',
1605                     disabled: !App.permissions.valuationUpdateDamages,
1606                     id: 'damages',
1607                     dataStoreId: 'damages',
1608                     data: data.stock.damages ? data.stock.damages : {}
1609                 },
1610                 'damageTotal': 'R 0.00',
1611                 'damageNotes': {
1612                     type: 'textarea-styled',
1613                     disabled: !App.permissions.valuationUpdateDamages,
1614                     id: 'damageNotes',
1615                     title: 'Damages comments',
1616                     style: 'damages-comments',
1617                     value: data.stock.damageNotes ? data.stock.damageNotes : ''
1618                 },
1619                 'previousRepairsNoted': {
1620                     type: 'checkbox',
1621                     id: 'previousRepairsNoted',
1622                     title: 'Previous repairs',
1623                     style: 'damages-comments',
1624                     value: data.stock.previousRepairsNoted ? data.stock.previousRepairsNoted : false
1625                 },
1626                 'previousRepairsNotes': {
1627                     type: 'textarea-styled',
1628                     disabled: !App.permissions.valuationUpdateDamages,
1629                     id: 'previousRepairsNotes',
1630                     title: 'Previous repairs notes',
1631                     style: 'damages-comments',
1632                     value: data.stock.previousRepairsNotes ? data.stock.previousRepairsNotes : '',
1633                     onChange: function () {
1634                         var haveData = ('' != $(this).val() ? true : false);
1635                         $('#previousRepairsNoted').prop('checked', haveData);
1636                     }
1637                 },
1638                 'coverReceived': {
1639                     type: 'textarea-styled',
1640                     disabled: !App.permissions.valuationUpdateCoverReceived,
1641                     id: 'coverReceived',
1642                     title: 'Cover Received',
1643                     style: 'cover-received',
1644                     value: data.stock.coverReceived ? data.stock.coverReceived : ''
1645                 },
1646                 'accessories': {
1647                     type: 'checkGroup',
1648                     id: 'accessories',
1649                     dataStoreId: 'accessories',
1650                     itemName: 'accessory',
1651                     data: data.stock.accessories ? data.stock.accessories : {}
1652                 },
1653                 'accessoryNotes': {
1654                     type: 'textarea-styled',
1655                     id: 'accessoryNotes',
1656                     title: 'Comments',
1657                     style: 'comment mobile-comment',
1658                     areaStyle: 'comment-text-box',
1659                     value: data.stock.accessoryNotes ? data.stock.accessoryNotes : ''
1660                 },
1661                 'mainImage': {
1662                     type: 'image',
1663                     id: 'mainImage',
1664                     baseImage: 'main_img_car.jpg',
1665                     view: !App.permissions.valuationUploadPhotos,
1666                     value: data.stock.mainImage ? data.stock.mainImage : ''
1667                 },
1668                 'frontImage': {
1669                     type: 'image',
1670                     id: 'frontImage',
1671                     baseImage: 'front_car.jpg',
1672                     view: !App.permissions.valuationUploadPhotos,
1673                     value: data.stock.frontImage ? data.stock.frontImage : ''
1674                 },
1675                 'leftImage': {
1676                     type: 'image',
1677                     id: 'leftImage',
1678                     baseImage: 'left_car.jpg',
1679                     view: !App.permissions.valuationUploadPhotos,
1680                     value: data.stock.leftImage ? data.stock.leftImage : ''
1681                 },
1682                 'rightImage': {
1683                     type: 'image',
1684                     id: 'rightImage',
1685                     baseImage: 'right_car.jpg',
1686                     view: !App.permissions.valuationUploadPhotos,
1687                     value: data.stock.rightImage ? data.stock.rightImage : ''
1688                 },
1689                 'backImage': {
1690                     type: 'image',
1691                     id: 'backImage',
1692                     baseImage: 'back_car.jpg',
1693                     view: !App.permissions.valuationUploadPhotos,
1694                     value: data.stock.backImage ? data.stock.backImage : ''
1695                 },
1696                 'interiorImage': {
1697                     type: 'image',
1698                     id: 'interiorImage',
1699                     baseImage: 'interior_car.jpg',
1700                     view: !App.permissions.valuationUploadPhotos,
1701                     value: data.stock.interiorImage ? data.stock.interiorImage : ''
1702                 },
1703                 'engineImage': {
1704                     type: 'image',
1705                     id: 'engineImage',
1706                     baseImage: 'engine_car.jpg',
1707                     view: !App.permissions.valuationUploadPhotos,
1708                     value: data.stock.engineImage ? data.stock.engineImage : ''
1709                 },
1710                 'natisImage': {
1711                     type: 'image',
1712                     id: 'natisImage',
1713                     baseImage: 'copy_of_natis_car.jpg',
1714                     view: !App.permissions.valuationUploadPhotos,
1715                     value: data.stock.natisImage ? data.stock.natisImage : ''
1716                 },
1717                 'clubs': {
1718                     type: 'select',
1719                     id: 'clubs',
1720                     title: 'Select clubs',
1721                     dataStoreId: 'clubs',
1722                     multiple: true,
1723                     value: ''
1724                 },
1725                 'print': {
1726                     constructor: 'Button',
1727                     items: ('New Valuation' == data.jobState
1728                     && 'Dealership Valuator' != App.permissions.name
1729                     && 'Dealership Sales' != App.permissions.name)
1730                         ? {
1731                         Export: {
1732                             preset: 'Print',
1733                             id: 'printValuationPdf',
1734                             handler: _w.valuationview.printValuationPdf
1735                         },
1736                         ExportTC: {
1737                             preset: 'PrintTC',
1738                             id: 'printValuationPdfTC',
1739                             handler: _w.valuationview.printValuationPdfTC
1740                         }
1741                     }
1742                         : {
1743                         Export: {
1744                             preset: 'Print',
1745                             id: 'printValuationPdf',
1746                             handler: _w.valuationview.printValuationPdf
1747                         }
1748                     }
1749                 },
1750                 'infCreated': data.created ? ((data.created).split(' '))[0] : '',
1751                 'infValuationNumber': data.valuationNumber ? data.valuationNumber : '',
1752                 'infReferenceNumber': data.stock.referenceNumber ? data.stock.referenceNumber : '',
1753                 'infStatus': data.jobState ? data.jobState : '',
1754                 'infCreatedBy': data.createdBy && data.createdBy.firstName
1755                     ? data.createdBy.firstName + ' ' + data.createdBy.familyName
1756                     : '',
1757                 'infValuator': data.valuatedBy && data.valuatedBy.firstName
1758                     ? data.valuatedBy.firstName + ' ' + data.valuatedBy.familyName
1759                     : '',
1760                 'infSalesUser': data.salesProfile && data.salesProfile.firstName
1761                     ? data.salesProfile.firstName + ' ' + data.salesProfile.familyName
1762                     : '',
1763                 'infLoadedOnPriceGuide': data.stock.loadedOnPriceGuide
1764                     ? ((data.stock.loadedOnPriceGuide).split(' '))[0] : '',
1765                 'infTradePrice': data.stock.tradePrice ? 'R ' + data.stock.tradePrice : '0.00',
1766                 'infRetailPrice': data.stock.retailPrice ? 'R ' + data.stock.retailPrice : '0.00',
1767                 'infListPrice': data.stock.listPrice ? 'R ' + data.stock.listPrice : '0.00',
1768                 'firstName': {
1769                     type: 'input',
1770                     id: 'firstName',
1771                     title: 'Customer name',
1772                     value: data.firstName ? data.firstName : ''
1773                 },
1774                 'familyName': {
1775                     type: 'input',
1776                     id: 'familyName',
1777                     title: 'Customer surname',
1778                     value: data.familyName ? data.familyName : ''
1779                 },
1780                 'idNumber': {
1781                     type: 'input',
1782                     id: 'idNumber',
1783                     title: 'ID',
1784                     value: data.idNumber ? data.idNumber : ''
1785                 },
1786                 'mobile': {
1787                     type: 'mobile',
1788                     id: 'mobile',
1789                     title: 'Mobile',
1790                     value: data.mobile ? data.mobile : ''
1791                 },
1792                 'email': {
1793                     type: 'input',
1794                     id: 'email',
1795                     title: 'Email',
1796                     value: data.email ? data.email : ''
1797                 },
1798                 'department': {
1799                     type: 'select',
1800                     id: 'department',
1801                     title: 'Department',
1802                     dataStoreId: 'departments',
1803                     value: data.department ? data.department : ''
1804                 },
1805                 'region': {
1806                     type: 'select',
1807                     id: 'region',
1808                     title: 'Region',
1809                     dataStoreId: 'regions',
1810                     value: data.region && data.region.id ? data.region.id : '',
1811                     onChange: function () {
1812                         if (!App.DataStore.getItem('BuildSelect:region', false)) {
1813                             App.DataStore.loadSelectListData(
1814                                 'cities', false, 'Location', 'Town.SelectList', null,
1815                                 {
1816                                     "Filter": {
1817                                         "region": $(this).val()
1818                                     }
1819                                 }
1820                             );
1821                         }
1822                     }
1823                 },
1824                 /*'city' : {
1825                  type        : 'select',
1826                  id          : 'city',
1827                  title       : 'Town',
1828                  dataStoreId : 'cities',
1829                  value       : data.city && data.city.id ? data.city.id : '',
1830                  options        : {
1831                  minimumInputLength: 3
1832                  }
1833                  },*/
1834                 /*'street' : {
1835                  type  : 'input',
1836                  id    : 'street',
1837                  title : 'Street',
1838                  value : data.street ? data.street : '',
1839                  maxlength : 75
1840                  },*/
1841                 'requiredPrice': {
1842                     type: 'input',
1843                     style: 'rand-input',
1844                     id: 'requiredPrice',
1845                     title: 'Required price',
1846                     value: data.requiredPrice ? data.requiredPrice : ''
1847                 },
1848                 'amountOffered': {
1849                     type: 'input',
1850                     disabled: true,
1851                     style: 'rand-input',
1852                     id: 'amountOffered',
1853                     title: newtitle,
1854                     value: data.amountOffered ? data.amountOffered : ''
1855                 },
1856                 'bankSettlement': {
1857                     type: 'input',
1858                     disabled: false,
1859                     style: 'rand-input',
1860                     id: 'bankSettlement',
1861                     title: 'Bank Settlement',
1862                     value: data.bankSettlement ? data.bankSettlement : ''
1863                 },
1864                 'overAllowance': {
1865                     type: 'input',
1866                     style: 'rand-input',
1867                     id: 'overAllowance',
1868                     title: 'O.A',
1869                     value: data.overAllowance ? data.overAllowance : '',
1870                     onChange: function () {
1871
1872                         //var totalOfferVal = (parseInt(document.getElementById('amountOffered').value)).toFixed(2) + (parseInt(document.getElementById('overAllowance').value)).toFixed(2);
1873
1874                         if (isNaN(parseInt(document.getElementById('overAllowance').value))) {
1875
1876                             //var totalOfferVal = (parseInt(document.getElementById('amountOffered').value)).toFixed(2) + val((0.00).toFixed(2));
1877                             $('#standInValue').val((parseInt(document.getElementById('amountOffered').value)).toFixed(2));
1878                         }
1879                         else {
1880                             $('#standInValue').val((Number((parseInt(document.getElementById('amountOffered').value))) + Number((parseInt(document.getElementById('overAllowance').value)))).toFixed(2)); //andreb // need to change the value on change -> do sum -> populate previousRepairsNoted
1881                         }
1882                     }
1883
1884                 },
1885                 'standInValue': {
1886                     type: 'input',
1887                     disabled: true,
1888                     style: 'rand-input',
1889                     id: 'standInValue',
1890                     title: 'Total offer',
1891                     value: (parseInt(data.overAllowance) + parseInt(data.amountOffered)).toFixed(2)
1892                         ? (parseInt(data.overAllowance) + parseInt(data.amountOffered)).toFixed(2) : ''
1893
1894                 },
1895                 'projectedRetail': {
1896                     type: 'input',
1897                     style: 'rand-input',
1898                     id: 'projectedRetail',
1899                     title: 'Projected retail',
1900                     value: data.projectedRetail ? data.projectedRetail : ''
1901                 },
1902                 'plannedMargin': {
1903                     type: 'input',
1904                     style: 'rand-input',
1905                     id: 'plannedMargin',
1906                     title: 'Planned margin',
1907                     value: data.plannedMargin ? data.plannedMargin : ''
1908                 },
1909                 'valuators': {
1910                     type: 'select',
1911                     id: 'valuators',
1912                     title: 'Select valuator',
1913                     dataStoreId: 'valuators',
1914                     multiple: true,
1915                     value: data.valuators ? data.valuators : []
1916                 },
1917                 'salesProfile': {
1918                     type: 'select',
1919                     id: 'salesProfile',
1920                     title: 'Sales person',
1921                     dataStoreId: 'sales',
1922                     value: ''
1923                 },
1924                 'salesAmountOffered': {
1925                     type: 'input',
1926                     style: 'rand-inputs',
1927                     id: 'salesAmountOffered',
1928                     title: 'Amount',
1929                     value: data.amountOffered ? data.amountOffered : '0.00',
1930                     onFocus: function () {
1931                         var $_this = $(this),
1932                             value = $_this.val();
1933
1934                         if (value == '0.00') {
1935                             $_this.val('');
1936                         }
1937                     },
1938                     onBlur: function () {
1939                         var $_this = $(this),
1940                             value = $_this.val();
1941
1942                         if (value === '') {
1943                             $_this.val('0.00');
1944                         }
1945                     }
1946                 },
1947                 'salesComments': {
1948                     type: 'textarea-styled',
1949                     id: 'salesComments',
1950                     title: 'Comments',
1951                     style: 'comment',
1952                     areaStyle: 'comment-text-box',
1953                     value: data.salesComments ? data.salesComments : ''
1954                 },
1955
1956                 'customerAmountOffered': {
1957                     type: 'input',
1958                     style: 'rand-inputs',
1959                     id: 'customerAmountOffered',
1960                     title: 'Amount',
1961                     value: data.amountOffered ? data.amountOffered : '0.00',
1962                     onFocus: function () {
1963                         var $_this = $(this),
1964                             value = $_this.val();
1965
1966                         if (value == '0.00') {
1967                             $_this.val('');
1968                         }
1969                     },
1970                     onBlur: function () {
1971                         var $_this = $(this),
1972                             value = $_this.val();
1973
1974                         if (value === '') {
1975                             $_this.val('0.00');
1976                         }
1977                     }
1978                 },
1979                 'customerComments': {
1980                     type: 'textarea-styled',
1981                     id: 'customerComments',
1982                     title: 'Comments',
1983                     style: 'comment',
1984                     areaStyle: 'comment-text-box',
1985                     value: data.salesComments ? data.salesComments : ''
1986                 },
1987
1988                 'stockNumber': {
1989                     type: 'input',
1990                     id: 'stockNumber',
1991                     title: 'Stock number',
1992                     value: data.stock.stockNumber ? data.stock.stockNumber : ''
1993                 },
1994                 'stockNumberDD': {
1995                     type: 'input',
1996                     id: 'stockNumberDD',
1997                     title: 'Stock number',
1998                     value: data.stock.stockNumber ? data.stock.stockNumber : ''
1999                 },
2000                 'dealNotDoneSelection': {
2001                     type: 'select',
2002                     id: 'dealNotDoneSelection',
2003                     title: 'Reason',
2004                     dataStoreId: 'dealNotDoneSelections',
2005                     value: data.dealNotDoneSelection ? data.dealNotDoneSelection : ''
2006                 },
2007
2008                 'dealNotDoneReason': {
2009                     type: 'textarea-styled',
2010                     id: 'dealNotDoneReason',
2011                     title: 'Description',
2012                     style: 'comment',
2013                     areaStyle: 'comment-text-box',
2014                     value: data.dealNotDoneReason ? data.dealNotDoneReason : ''
2015                 }
2016             };
2017                 },
2018                 printValuationPdf: function ()
2019                 {
2020                         var task = 'Pdf.Print003';
2021                         if ('New Valuation' == _w.valuationview.itemData.jobState
2022                                                         && ('Dealership Valuator' == App.permissions.name
2023                                                                                         || 'Dealership Sales' == App.permissions.name))
2024                         {
2025                                 // T&C version
2026                                 task = 'Pdf.Print001';
2027                         }
2028                         else if ('Dealership Valuator' == App.permissions.name
2029                                                         || 'Dealership Sales' == App.permissions.name)
2030                         {
2031                                 task = 'Pdf.Print002';
2032                         }
2033                         App.API.getTask(
2034                                                         'printValuation:' + _w.valuationview.itemData.stock.id,
2035                                                         'Valuation', task, _w.valuationview.itemId,
2036                                                         {}, function () {
2037                                 App.API.execTask(
2038                                                                 'printValuation:' + _w.valuationview.itemData.stock.id, {}, {},
2039                                                                 _w.valuationview._onExportReceived, _w.taskExecError,
2040                                                                 'EXPORT', true
2041                                                                 );
2042                         }, _w.taskContractError
2043                                                         );
2044                 },
2045                 printValuationPdfTC: function ()
2046                 {
2047                         // Consider the T&C requirement.
2048                         var task = 'Pdf.Print001';
2049                         App.API.getTask(
2050                                                         'printValuation:' + _w.valuationview.itemData.stock.id,
2051                                                         'Valuation', task, _w.valuationview.itemId,
2052                                                         {}, function () {
2053                                 App.API.execTask(
2054                                                                 'printValuation:' + _w.valuationview.itemData.stock.id, {}, {},
2055                                                                 _w.valuationview._onExportReceived, _w.taskExecError,
2056                                                                 'EXPORT', true
2057                                                                 );
2058                         }, _w.taskContractError
2059                                                         );
2060                 },
2061                 _listMakesModelsTypes: function (fromItemData, callback)
2062                 {
2063                         if (fromItemData)
2064                         {
2065                                 var year = _w.valuationview.itemData.stock.vehicleYear;
2066                                 var category = _w.valuationview.itemData.stock.type.category.id;
2067                                 var make = _w.valuationview.itemData.stock.type.model.make.id;
2068                                 var model = _w.valuationview.itemData.stock.type.model.id;
2069                                 var type = _w.valuationview.itemData.stock.type.id;
2070                                 var mmcode = _w.valuationview.itemData.stock.type.mmcode;
2071                         }
2072                         else
2073                         {
2074                                 var year = $('#vehicleYear').val();
2075                                 var category = $('#vehicleCategory').val();
2076                                 var make = $('#vehicleMake').val();
2077                                 var model = $('#vehicleModel').val();
2078                                 var type = $('#vehicleType').val();
2079                                 var mmcode = $('#mmCode').val();
2080                         }
2081                         if (year && category)
2082                         {
2083                                 App.DataStore.loadSelectListData(
2084                                                                 'makes', false, 'Stock', 'Utility.ListMakes', null,
2085                                                                 {"Filter": {
2086                                                                                 "category": category,
2087                                                                                 "year": year
2088                                                                         }}, {}, $.proxy(function (categoryId)
2089                                 {
2090                                         if (8 == categoryId)
2091                                         {
2092                                                 var data = App.DataStore.getData('makes');
2093                                                 data.unshift({
2094                                                         value: -1,
2095                                                         label: 'Custom'
2096                                                 });
2097                                                 App.DataStore.setData('makes', data);
2098                                         }
2099                                 }, this, category)
2100                                                                 );
2101                         }
2102                         if (make && year && category)
2103                         {
2104                                 App.DataStore.loadSelectListData(
2105                                                                 'models', false, 'Stock', 'Utility.ListModels', null,
2106                                                                 {"Filter": {
2107                                                                                 "make": make,
2108                                                                                 "category": category,
2109                                                                                 "year": year
2110                                                                         }}, {}, $.proxy(function (categoryId)
2111                                 {
2112                                         if (8 == categoryId)
2113                                         {
2114                                                 var data = App.DataStore.getData('models');
2115                                                 data.unshift({
2116                                                         value: -1,
2117                                                         label: 'Custom'
2118                                                 });
2119                                                 App.DataStore.setData('models', data);
2120                                         }
2121                                 }, this, category)
2122                                                                 );
2123                         }
2124                         if (model && year && category)
2125                         {
2126                                 App.DataStore.loadSelectListData(
2127                                                                 'types', false, 'Stock', 'Utility.ListTypes', null,
2128                                                                 {"Filter": {
2129                                                                                 "model": model,
2130                                                                                 "category": category,
2131                                                                                 "year": year
2132                                                                         }}, {}, $.proxy(function (categoryId, callback)
2133                                 {
2134                                         if (8 == categoryId)
2135                                         {
2136                                                 var data = App.DataStore.getData('types');
2137                                                 data.unshift({
2138                                                         value: -1,
2139                                                         label: 'Custom'
2140                                                 });
2141                                                 App.DataStore.setData('types', data);
2142                                         }
2143                                         if (callback)
2144                                         {
2145                                                 callback();
2146                                         }
2147                                 }, this, category, callback)
2148                                                                 );
2149                         }
2150                 },
2151                 _onDataAndTemplate: function ()
2152                 {
2153                         App.DataStore.loadSelectListData(
2154                                                         'tuhpi', false, 'Stock', 'Tuhpi.List', null, {
2155                                                                 "Filter":
2156                                                                                                 {
2157                                                                                                         "stock": _w.valuationview.itemData.stock.id,
2158                                                                                                         "company": App.companyData.id
2159
2160                                                                                                 }
2161                                                         }, {}, function ()
2162                         {
2163                                 // data is retrieved
2164                                 var tuHpiData = App.DataStore.getData('tuhpi');
2165
2166                 _w.valuationview._loadHpiReportData(tuHpiData);
2167
2168
2169                         });
2170
2171                         var total = 0.00;
2172
2173
2174
2175                         if (null == App.API.taskContract('gridStockHistory'))
2176                         {
2177                                 App.API.getTask(
2178                                                                 'gridStockHistory', 'Stock', 'PricingHistory.Grid', null,
2179                                                                 {}, _w.valuationview.loadHistoricalGrid, _w.taskContractError
2180                                                                 );
2181                         }
2182                         else
2183                         {
2184                                 _w.valuationview.loadHistoricalGrid(null, {}, {});
2185                         }
2186
2187                         $.each($.find('.damage-input'), function (i, input) {
2188                                 total += parseFloat($(input).val());
2189                         });
2190                         $('#' + _w.valuationview.ti.tid + '_damageTotal').html('R ' + total);
2191                         $('#doAcceptOffer').prop('disabled', true);
2192                         $('#doRemoveAccept').prop('disabled', true);
2193
2194                         
2195                         $('#doRemoveAcceptSlider').click(function () {
2196                                         $('#dropStock').insertAfter( '#btnKeepForStock'); //moved the div to reuse the code
2197                                         $('#dropStock').slideDown();
2198                                         $('#doSendToStock').hide();
2199                                         $('#stockNumber').prop('disabled', false);
2200                                         $('#stockNumberDD').prop('disabled', false);
2201                                         $('#doRemoveAcceptSlider').prop('disabled', true);
2202                                         $('#doRemoveAccept').prop('disabled', false);
2203                                         $('#doRemoveAccept').show();
2204                                         $('#btnFetchTu').prop('disabled', true);
2205                                 });
2206
2207                         $('#doRemoveAccept').click(function () {
2208                                 
2209                                 var stockNo = $('#stockNumber').val();
2210                                 if (null == stockNo || '' == stockNo)
2211                                 {
2212                                         //show the stock number field
2213                                         
2214                                         alert('Please enter a stock number.');
2215                                         return;
2216                                 }
2217                                 if (!$('#frmValuationView').valid())
2218                                 {
2219                                         return;
2220                                 }
2221                                 if (!$('#acceptStockHPIdisclaimer').is(':checked'))
2222                                 {
2223                                         alert('Please accept the conditions before sending.');
2224                                         return;
2225                                 }
2226                                 $('#btnUpdate').prop('disabled', true);
2227                                 $('#btnRemoveAccept').prop('disabled', true);
2228                                 $('#btnRemove').prop('disabled', true);
2229                                 $('#btnAcceptOffer').prop('disabled', true);
2230                                 $('#btnKeepForStock').prop('disabled', true);
2231                         
2232                                 var data = _w.valuationview._prepValuationUpdateData();
2233                                 
2234                                 /*var data = _w.valuationview._prepValuationUpdateData();
2235                                         App.API.getTask(
2236                                                                                 'createValuationStock', 'Valuation', 'Valuation.UpdateStock',
2237                                                                                 null, {}, $.proxy(function (data) {
2238                                                         App.API.execTask(
2239                                                                                         'createValuationStock', data, {},
2240                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
2241                                                                                         );
2242                                                 }, this, data), _w.taskContractError
2243                                                                                 );*/
2244                                         //Move valuation to stock, to try out the 2nd function in order to not Repeat Oneself
2245 //                                      var data = _w.valuationview._prepValuationUpdateData();
2246                                                                                 /*      App.API.execTask(
2247                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
2248                                                                 function () {
2249                                                                         App.API.directRoute(
2250                                                                                                         'keepForStockOnValuation:' + _w.valuationview.itemId,
2251                                                                                                         'Valuation', 'Valuation.MoveToKeepForStock', _w.valuationview.itemId, {},
2252                                                                                                         _w.valuationview._onValuationUpdated, _w.taskExecError
2253                                                                                                         );
2254                                                                 }, _w.taskExecError
2255                                                                 );*/
2256
2257                                 App.API.getTask(
2258                                                                 'PriceGuideRemove' + _w.valuationview.itemData.stock.priceGuide, 'PriceGuide', 'PriceGuide.Remove',
2259                                                                 _w.valuationview.itemData.stock.priceGuide,
2260                                                                 {}, function () {
2261                                         App.API.execTask(
2262                                                                         'PriceGuideRemove' + _w.valuationview.itemData.stock.priceGuide, data, {},
2263                                                                         function () {
2264                                                                                 App.API.directRoute(
2265                                                                                                                 'offerAcceptedOnValuation:' + _w.valuationview.itemId,
2266                                                                                                                 'Valuation', 'Valuation.MoveToOfferAccepted', _w.valuationview.itemId, {},
2267                                                                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
2268                                                                                                                 );
2269                                                                         }, _w.taskExecError
2270                                                                         );
2271                                 }, _w.taskContractError
2272                                                                 );
2273                                 
2274                                 
2275                                 //send to stock
2276                                 App.API.getRoute(
2277                                                 'sendToStock:' + _w.valuationview.itemId, 'Valuation', 'Valuation.SendToStock', _w.valuationview.itemId,
2278                                                 {}, function () {
2279                                                 var data = _w.valuationview._prepValuationUpdateData();
2280                                                 App.API.execRoute(
2281                                                                                 'sendToStock:' + _w.valuationview.itemId, data, {},
2282                                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
2283                                                                                 );
2284                                         }, _w.taskContractError
2285                                 );
2286                                 
2287                                 
2288                                 
2289                         });
2290
2291
2292
2293                         $('#btnRemove').click(function () {
2294                                 if (!$('#frmValuationView').valid())
2295                                 {
2296                                         return;
2297                                 }
2298                                 $('#btnUpdate').prop('disabled', true);
2299                                 $('#btnRemoveAccept').prop('disabled', true);
2300                                 $('#btnRemove').prop('disabled', true);
2301                                 $('#btnAcceptOffer').prop('disabled', true);
2302                                 $('#btnKeepForStock').prop('disabled', true);
2303                                 var data = _w.valuationview._prepValuationUpdateData();
2304                                 App.API.getTask(
2305                                                                 'PriceGuideRemove' + _w.valuationview.itemData.stock.priceGuide, 'PriceGuide', 'PriceGuide.Remove',
2306                                                                 _w.valuationview.itemData.stock.priceGuide,
2307                                                                 {}, function () {
2308                                         App.API.execTask(
2309                                                                         'PriceGuideRemove' + _w.valuationview.itemData.stock.priceGuide, data, {},
2310                                                                         function () {
2311                                                                                 App.API.directRoute(
2312                                                                                                                 'keepForStockOnValuation:' + _w.valuationview.itemId,
2313                                                                                                                 'Valuation', 'Valuation.MoveToKeepForStock', _w.valuationview.itemId, {},
2314                                                                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
2315                                                                                                                 );
2316                                                                         }, _w.taskExecError
2317                                                                         );
2318                                 }, _w.taskContractError
2319                                                                 );
2320                         });
2321
2322                         if (_w.valuationview.itemData
2323                                                         && _w.valuationview.itemData.region
2324                                                         && _w.valuationview.itemData.region.id)
2325                         {
2326                                 App.DataStore.loadSelectListData(
2327                                                                 'cities', false, 'Location', 'Town.SelectList', null,
2328                                                                 {"Filter": {
2329                                                                                 "region": _w.valuationview.itemData.region.id
2330                                                                         }}
2331                                 );
2332                         }
2333                         if (null != _w.valuationview.itemData.stock.priceGuide
2334                                                         && 0 < _w.valuationview.itemData.stock.highestOffer)
2335                         {
2336                                 _w.valuationview.priceGuideId = _w.valuationview.itemData.stock.priceGuide;
2337                                 App.API.getTask(
2338                                                                 'offerList', 'PriceGuide', 'Offer.List',
2339                                                                 _w.valuationview.itemData.stock.priceGuide, {}, function () {
2340                                         App.API.execTask(
2341                                                                         'offerList', {}, {},
2342                                                                         function (response)
2343                                                                         {
2344                                                                                 var offers = response.Data;
2345                                                                                 if (offers.length)
2346                                                                                 {
2347                                                                                         var highest = 0;
2348                                                                                         var lowestDate = 0;
2349                                                                                         var highestId = 0;
2350                                                                                         var valid = 0;
2351                                                                                         for (var x in offers)
2352                                                                                         {
2353                                                                                                 if ('Valid Offer' != offers[x].status
2354                                                                                                                                 && 'Updateable Offer' != offers[x].status)
2355                                                                                                 {
2356                                                                                                         continue;
2357                                                                                                 }
2358                                                                                                 valid++;
2359                                                                                                 var dateInt = parseInt(
2360                                                                                                                                 offers[x].created.split(' ')[0].split('-').join('')
2361                                                                                                                                 + offers[x].created.split(' ')[1].split(':').join('')
2362                                                                                                                                 );
2363                                                                                                 if ((parseInt(offers[x].amount) == highest && dateInt < lowestDate)
2364                                                                                                                                 || parseInt(offers[x].amount) > highest)
2365                                                                                                 {
2366                                                                                                         highest = parseInt(offers[x].amount);
2367                                                                                                         highestId = x;
2368                                                                                                         lowestDate = dateInt;
2369                                                                                                 }
2370                                                                                         }
2371                                                                                         if (0 == valid)
2372                                                                                         {
2373                                                                                                 var modalbody = '<div style="font-weight:bold;color:#9B2022;">There are no valid offers!</div>';
2374                                                                                                 $('#dealDoneOfferList').html(modalbody);
2375                                                                                                 $('#doAcceptOffer').prop('disabled', true);
2376                                                                                                 $('#doRemoveAccept').prop('disabled', true);
2377                                                                                                 return;
2378                                                                                         }
2379                                                                                         _w.valuationview.highestOfferId = highestId;
2380                                                                                         var modalbody = '<table class="table table-bordered table-condensed table-striped">';
2381                                                                                         modalbody += '<tr class="table-header-red"><td>Company</td><td>Date Offered</td><td>Amount</td></tr>';
2382                                                                                         for (var x in offers)
2383                                                                                         {
2384                                                                                                 if ('Valid Offer' != offers[x].status
2385                                                                                                                                 && 'Updateable Offer' != offers[x].status)
2386                                                                                                 {
2387                                                                                                         continue;
2388                                                                                                 }
2389                                                                                                 var isOwn = highestId == x
2390                                                                                                                                 ? true
2391                                                                                                                                 : false;
2392                                                                                                 modalbody +=
2393                                                                                                                                 '<tr class="modalrow ' + (isOwn ? 'red' : 'black') + '">'
2394                                                                                                                                 + '<td class="date">' + offers[x].company.name + '</td>'
2395                                                                                                                                 + '<td class="date">' + offers[x].created.split(' ')[0] + '</td>'
2396                                                                                                                                 + '<td class="wide">R' + offers[x].amount.split('.')[0] + '</td>'
2397                                                                                                                                 + '</tr>';
2398                                                                                         }
2399                                                                                         modalbody += '</table>';
2400                                                                                         $('#doAcceptOffer').prop('disabled', false);
2401                                                                                         $('#doRemoveAccept').prop('disabled', false);
2402                                                                                 }
2403                                                                                 else
2404                                                                                 {
2405                                                                                         var modalbody = '<div style="font-weight:bold;color:#9B2022;">There are no valid offers!</div>';
2406                                                                                 }
2407                                                                                 $('#dealDoneOfferList').html(modalbody);
2408                                                                         }, _w.taskExecError
2409                                                                         );
2410                                 }, _w.taskContractError
2411                                                                 );
2412                         }
2413
2414                         $('#HPIhide').show();
2415                         if (_w.valuationview.limited)
2416                         {
2417                                 $('input').prop('disabled', true);
2418                                 $('button').prop('disabled', true);
2419                                 $('checkbox').prop('disabled', true);
2420                                 $('textarea').prop('disabled', true);
2421
2422                                 $('#downloadTuhpi').prop('disabled', false);
2423                                 $('#overAllowance').prop('disabled', false);
2424                                 $('#standInValue').prop('disabled', true);
2425                                 $('#btnUnarchive').prop('disabled', false);
2426                                 $('#printValuationPdf').prop('disabled', false);
2427                                 $('#optSendToSales').prop('disabled', false);
2428                                 $('#salesProfile').prop('disabled', false);
2429                                 $('button[data-id="salesProfile"]').prop('disabled', false);
2430                                 $('#salesAmountOffered').prop('disabled', false);
2431                                 $('#salesComments').prop('disabled', false);
2432                                 $('#btnSendToSales').prop('disabled', false);
2433                                 $('#printValuationPdf').prop('disabled', false);
2434                                 $('#btnSendToPg').prop('disabled', false);
2435                                 $('#acceptStockHPIdisclaimer').prop('disabled', false);
2436                                 $('#acceptStockDDHPIdisclaimer').prop('disabled', false);
2437                                 $('button[data-id="clubs"]').prop('disabled', false);
2438
2439                 $('#optSendToCustomer').prop('disabled', false);
2440                 $('#customerAmountOffered').prop('disabled', false);
2441                 $('#customerComments').prop('disabled', false);
2442
2443                                 // Mobi buttons
2444                                 $('#mobiAuctionBtn').prop('disabled', false);
2445                                 $('#mobiPriceGuideBtn').prop('disabled', false);
2446                                 $('#mobiValuationsBtn').prop('disabled', false);
2447                         }
2448                         if (App.permissions.settingsHpiReport == false)
2449                         {
2450                                 $('#requestHPIreport').hide();
2451                 $('#requestHPIAccidentReport').hide();
2452                         }
2453
2454                         $('#sectionSelectValuator').hide();
2455                         if (!_w.valuationview.newItem)
2456                         {
2457                                 if (App.permissions.settingsHpiReport
2458                                                                 && 'New Valuation' != _w.valuationview.itemData.jobState)
2459                                 {
2460                                         $('#requestHPIreport').show();
2461                     $('#requestHPIAccidentReport').show();
2462                                 }
2463                                 $('#retailPrice').val(_w.valuationview.itemData.stock.retailPrice);
2464                                 $('#tradePrice').val(_w.valuationview.itemData.stock.tradePrice);
2465                 $('#listPrice').val(_w.valuationview.itemData.stock.listPrice);
2466
2467                 //console.log('_w.valuationview.itemData',_w.valuationview.itemData);
2468
2469                                 switch (_w.valuationview.itemData.jobState)
2470                                 {
2471                                         case 'New Valuation':
2472
2473                         //console.log('_w.valuationview.itemData.isPublicCustomer',_w.valuationview.itemData.isPublicCustomer);
2474
2475                         if(_w.valuationview.itemData.isPublicCustomer)
2476                         {
2477                             $('#optSendToCustomer').show();
2478                         }
2479                                                 $('#btnSaveAsSales').show();
2480                                                 $('#btnSaveAsPending').show();
2481                                                 $('#optSendToPg').show();
2482                                                 $('#btnSendToStock').show();
2483                                                 $('#btnArchive').show();
2484                                                 true == App.permissions.valuationCreateSales
2485                                                                                 ? $('#sectionSelectValuator').show()
2486                                                                                 : $('#sectionSelectValuator').hide();
2487                                                 if (!App.permissions.valuationUpdateDamages)
2488                                                 {
2489                                                         $('.damages-form').hide();
2490                                                 }
2491                                                 else
2492                                                 {
2493                                                         $('.damages-form').show();
2494                                                 }
2495                                                 if (!App.permissions.valuationUploadPhotos)
2496                                                 {
2497                                                         $('.photos-form').html('&nbsp;');
2498                                                 }
2499                                                 break;
2500                                         case 'Pending Valuation':
2501                         if(_w.valuationview.itemData.isPublicCustomer)
2502                         {
2503                             $('#optSendToCustomer').show();
2504                         }
2505                                                 $('#optSendToSales').show();
2506                                                 $('#optSendToPg').show();
2507                                                 $('#btnSendToStock').show();
2508                                                 $('#btnArchive').show();
2509
2510                                                 if (null != _w.valuationview.itemData.stock.priceGuide
2511                                                                                 && 0 < _w.valuationview.itemData.stock.highestOffer)
2512                                                 {
2513                                                         $('#btnAcceptOffer').show();
2514                                                         $('#doAcceptOffer').show();
2515                                                         $('#btnKeepForStock').show();
2516                                                         $('#btnSendToDealNotDone').show();
2517                                                         $('#doSendToDealNotDone').show();
2518                                                 }
2519                                                 else
2520                                                 {
2521                                                         $('#btnSendToDealDone').show();
2522                                                         $('#doSendToDealDone').show();
2523                                                         $('#doSendToDealNotDone').show();
2524                                                 }
2525                                                 if (!App.permissions.valuationUpdateDamages)
2526                                                 {
2527                                                         $('.damages-form').hide();
2528                                                 }
2529                                                 else
2530                                                 {
2531                                                         $('.damages-form').show();
2532                                                 }
2533                                                 if (!App.permissions.valuationUploadPhotos)
2534                                                 {
2535                                                         $('.photos-form').html('&nbsp;');
2536                                                 }
2537                                                 break;
2538                                         case 'Complete Valuation':
2539
2540                                                 $('#optSendToSales').show();
2541                                                 $('#optSendToPg').show();
2542                                                 $('#btnSendToStock').show();
2543                                                 $('#btnArchive').show();
2544                                                 if (null != _w.valuationview.itemData.stock.priceGuide
2545                                                                                 && 0 < _w.valuationview.itemData.stock.highestOffer)
2546                                                 {
2547
2548
2549
2550                                                         if (_w.valuationview.itemData.previousState == 'Offer Accepted')
2551                                                         {
2552                                                                 //console.log("previousState", _w.valuationview.itemData);
2553                                                                 $('#btnAcceptOffer').hide;
2554                                                         }
2555                                                         else {
2556                                                                 $('#btnAcceptOffer').show();
2557                                                         }
2558
2559
2560                                                         $('#doAcceptOffer').show();
2561                                                         $('#btnKeepForStock').show();
2562                                                         $('#btnSendToDealNotDone').show();
2563                                                 }
2564                                                 else
2565                                                 {
2566                                                         $('#btnSendToDealDone').show();
2567                                                         $('#doSendToDealDone').show();
2568                                                         $('#doSendToDealNotDone').show();
2569                                                 }
2570                                                 break;
2571                                         case 'Offer Accepted':
2572                                                 $('#optSendToPg').show();
2573                                                 $('#optSendToSales').show();
2574                                                 $('#btnSendToStock').show();
2575                                                 $('#btnSendToStock').prop('disabled', false);
2576                                                 $('#btnKeepForStock').hide();
2577                                                 $('#stockNumber').prop('disabled', false);
2578                                                 $('#doSendToStock').prop('disabled', false);
2579                                                 $('#btnArchive').show();
2580                                                 $('#btnArchive').prop('disabled', false);
2581                                                 break;
2582                                         case 'Deal Done':
2583
2584                                                 $('#btnSendToStock').show();
2585                                                 $('#btnSendToStock').prop('disabled', false);
2586                                                 $('#stockNumber').prop('disabled', false);
2587                                                 $('#doSendToStock').prop('disabled', false);
2588                                                 $('#doRemoveAcceptSlider').prop('disabled', false);
2589                                                 $('#btnArchive').show();
2590                                                 $('#btnArchive').prop('disabled', false);
2591                                                 break;
2592                                         case 'Deal Not Done':
2593                                                 $('#btnArchive').show();
2594                                                 break;
2595                                         case 'Archived':
2596                                                 $('#btnUnarchive').show();
2597                                                 break;
2598                                         case 'Price Guide':
2599                                         $('#doRemoveAcceptSlider').prop('disabled', false);
2600                                                 $('#optSendToSales').show();
2601                                                 $('#btnSendToDealNotDone').show();
2602                                                 if (null != _w.valuationview.itemData.stock.priceGuide
2603                                                                                 && 0 < _w.valuationview.itemData.stock.highestOffer)
2604                                                 {
2605                                                         $('#btnRemoveAccept').show();
2606                                                         $('#doRemoveAccept').show();
2607                                                         $('#btnRemove').show();
2608                                                 }
2609                                                 break;
2610                                 }
2611                         }
2612                         else
2613                         {
2614                                 $('#requestHPIreport').hide();
2615                 $('#requestHPIAccidentReport').hide();
2616                         }
2617
2618                         /*
2619                          * Permissions
2620                          */
2621                         $('#optSendToPg').prop('disabled', true == App.permissions.valuationRoutePriceguide ? false : true);
2622                         $('#optSendToSales').prop('disabled', true == App.permissions.valuationRouteComplete ? false : true);
2623                         $('#btnUpdate').prop('disabled', true == App.permissions.valuationUpdate ? false : true);
2624                         $('#btnSendToStock').prop('disabled', true == App.permissions.valuationRouteStock ? false : true);
2625                         $('#btnSaveAsPending').prop('disabled', true == App.permissions.valuationRoutePending ? false : true);
2626                         $('#btnAcceptOffer').prop('disabled', true == App.permissions.valuationRouteDealDone ? false : true);
2627                         $('#doSendToDealNotDone').prop('disabled', true == App.permissions.valuationRouteDealDone ? false : true);
2628                         $('#doSendToDealDone').prop('disabled', true == App.permissions.valuationRouteDealDone ? false : true);
2629                         $('#btnRemoveAccept').prop('disabled', true == App.permissions.valuationRouteDealDone ? false : true);
2630                         $('#btnKeepForStock').prop('disabled', true == App.permissions.valuationRouteDealNotDone ? false : true);
2631                         $('#btnSendToDealNotDone').prop('disabled', true == App.permissions.valuationRouteDealNotDone ? false : true);
2632                         $('#btnRemove').prop('disabled', true == App.permissions.valuationRouteDealNotDone ? false : true);
2633                         $('#btnExpire').prop('disabled', true == App.permissions.valuationRouteDealNotDone ? false : true);
2634                         if ('Dealership Sales' == App.permissions.name && !_w.valuationview.newItem)
2635                         {
2636                                 $('#btnSaveAsPending').hide();
2637                         }
2638
2639                         $('#btnArchive').prop('disabled', true == App.permissions.valuationArchive ? false : true);
2640                         $('#printValuationPdf').prop('disabled', true == App.permissions.valuationPrint ? false : true);
2641                         $('#btnB4cAccidentReport').prop('disabled', true == App.permissions.valuationB4cReport ? false : true);
2642                         $('#btnBwmAccidentReport').prop('disabled', true == App.permissions.valuationBmw ? false : true);
2643
2644
2645
2646                         true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_overAllowance').show() : $('#' + _w.valuationview.ti.tid + '_overAllowance').hide();
2647                         true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_standInValue').show() : $('#' + _w.valuationview.ti.tid + '_standInValue').hide();
2648                         true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_projectedRetail').show() : $('#' + _w.valuationview.ti.tid + '_projectedRetail').hide();
2649                         true == App.permissions.valuationPricingDetails ? $('#' + _w.valuationview.ti.tid + '_plannedMargin').show() : $('#' + _w.valuationview.ti.tid + '_plannedMargin').hide();
2650
2651
2652                         _w.valuationview._setupValidation();
2653                 },
2654                 _onValuationViewDataReceived: function (response)
2655                 {
2656                         _w.valuationview.itemId = response.Data.id;
2657                         _w.valuationview.itemData = response.Data;
2658                         _w.valuationview._listMakesModelsTypes(true);
2659                         _w.valuationview.setValuationViewFormMeta(response.Data);
2660                         _w.valuationview.ti.hydrate(_w.valuationview.formMeta);
2661                         _w.valuationview.ti.onPublish(_w.valuationview._onDataAndTemplate);
2662
2663
2664             App.DataStore.loadSelectListData(
2665                 'years', false, 'Stock', 'Year.SelectList', null,
2666                 {}
2667             );
2668             App.DataStore.loadSelectListData(
2669                 'categories', false, 'Stock', 'Category.SelectList', null,
2670                 {}
2671             );
2672
2673             App.DataStore.loadSelectListData(
2674                 'fuelTypes', false, 'Stock', 'FuelType.SelectList', null,
2675                 {}
2676             );
2677             App.DataStore.loadSelectListData(
2678                 'transmissionTypes', false, 'Stock', 'TransmissionType.SelectList', null,
2679                 {}
2680             );
2681             App.DataStore.loadSelectListData(
2682                 'damages', false, 'Stock', 'Damage.SelectList', null,
2683                 {}
2684             );
2685             App.DataStore.loadSelectListData(
2686                 'accessories', false, 'Stock', 'Accessory.SelectList', null,
2687                 {}
2688             );
2689
2690                         App.DataStore.loadSelectListGroup([
2691                                 {dataId: 'conditions', isStatic: true, workspace: 'Stock', task: 'Condition.SelectList'},
2692                                 {dataId: 'exteriorColours', isStatic: true, workspace: 'Stock', task: 'ExteriorColour.SelectList'},
2693                                 {dataId: 'interiorColours', isStatic: true, workspace: 'Stock', task: 'InteriorColour.SelectList'},
2694                                 {dataId: 'upholsteries', isStatic: true, workspace: 'Stock', task: 'Upholstery.SelectList'},
2695                                 {dataId: 'papers', isStatic: true, workspace: 'Stock', task: 'Paper.SelectList'},
2696                                 {dataId: 'natis', isStatic: true, workspace: 'Stock', task: 'Natis.SelectList'},
2697                                 {dataId: 'fsh', isStatic: true, workspace: 'Stock', task: 'FullServiceHistory.SelectList'},
2698                                 //{dataId: 'fuelTypes', isStatic: true, workspace: 'Stock', task: 'FuelType.SelectList'},
2699                                 //{dataId: 'transmissionTypes', isStatic: true, workspace: 'Stock', task: 'TransmissionType.SelectList'},
2700                                 //{dataId: 'damages', isStatic: true, workspace: 'Stock', task: 'Damage.SelectList'},
2701                                 //{dataId: 'accessories', isStatic: true, workspace: 'Stock', task: 'Accessory.SelectList'},
2702                                 {dataId: 'clubs', isStatic: true, workspace: 'PriceGuide', task: 'Club.SelectList'},
2703                                 {dataId: 'valuators', isStatic: true, workspace: 'User', task: 'Profile.ValuatorList'},
2704                                 {dataId: 'sales', isStatic: true, workspace: 'User', task: 'Profile.SalesList'},
2705                                 {dataId: 'regions', isStatic: true, workspace: 'Location', task: 'Region.SelectList'},
2706                 {dataId: 'dealNotDoneSelections', isStatic: true, workspace: 'Valuation', task: 'Valuation.DealNotDoneSelection'},
2707                         ]);
2708                 },
2709                 _setupValidation: function ()
2710                 {
2711                         App.DataStore.listen('regValidation', 'damages', function (id, damages) {
2712                                 var rules = {
2713                                         firstName: {required: true, minlength: 3},
2714                                         familyName: {required: true, minlength: 3},
2715                                         idNumber: {required: false, minlength: 13, maxlength: 13, digits: true},
2716                                         mobile: {required: true, mobile: true},
2717                                         salesAmountOffered: {number: true},
2718                     customerAmountOffered: {number: true},
2719                     bankSettlement: {number: true},
2720                                         overAllowance: {number: true},
2721                                         standInValue: {number: true},
2722                                         projectedRetail: {number: true},
2723                                         plannedMargin: {number: true},
2724                                         vehicleYear: "required",
2725                                         vehicleCategory: "required",
2726                                         vehicleMake: {required: function () {
2727                                                         return $('#vehicleMake').parent().css('display') != 'none';
2728                                                 }},
2729                                         vehicleModel: {required: function () {
2730                                                         return $('#vehicleModel').parent().css('display') != 'none';
2731                                                 }},
2732                                         vehicleType: {required: function () {
2733                                                         return $('#vehicleType').parent().css('display') != 'none';
2734                                                 }},
2735                                         vehicleMakeManual: {required: function () {
2736                                                         return $('#vehicleMakeManual').parent().parent().css('display') != 'none';
2737                                                 }},
2738                                         vehicleModelManual: {required: function () {
2739                                                         return $('#vehicleModelManual').parent().parent().css('display') != 'none';
2740                                                 }},
2741                                         vehicleTypeManual: {required: function () {
2742                                                         return $('#vehicleTypeManual').parent().parent().css('display') != 'none';
2743                                                 }},
2744                                         vehicleFuelType: "required",
2745                                         vehicleTransmissionType: "required",
2746                                         registrationNumber: "required",
2747                                         km: {required: true, digits: true}
2748                                 };
2749                                 for (var i = 0; i < damages.length; i++)
2750                                 {
2751                                         rules['damage' + damages[i].value + 'Amount'] = {number: true};
2752                                 }
2753                                 $('#frmValuationView').validate({
2754                                         "rules": rules,
2755                                         messages: {
2756                                                 firstName: {
2757                                                         minlength: "This field is required."
2758                                                 },
2759                                                 familyName: {
2760                                                         minlength: "This field is required."
2761                                                 },
2762                                                 idNumber: {
2763                                                         minlength: "Must be 13 digits.",
2764                                                         maxlength: "Must be 13 digits."
2765                                                 },
2766                                                 vehicleYear: "This field is required.",
2767                                                 vehicleCategory: "This field is required.",
2768                                                 vehicleMake: "This field is required.",
2769                                                 vehicleModel: "This field is required.",
2770                                                 vehicleType: "This field is required.",
2771                                                 vehicleMakeManual: "This field is required.",
2772                                                 vehicleModelManual: "This field is required.",
2773                                                 vehicleTypeManual: "This field is required.",
2774                                                 vehicleFuelType: "This field is required.",
2775                                                 vehicleTransmissionType: "This field is required.",
2776                                                 registrationNumber: "This field is required.",
2777                                                 km: {required: "This field is required."}
2778                                         },
2779                                         invalidHandler: function (event, validator) {
2780                                                 var errors = validator.numberOfInvalids();
2781                                                 if (0 < _w.valuationview.validations && errors) {
2782                                                         var message = errors == 1
2783                                                                                         ? 'You missed 1 field. It has been highlighted'
2784                                                                                         : 'You missed ' + errors + ' fields. They have been highlighted';
2785                                                         alert(message);
2786                                                 }
2787                                                 _w.valuationview.validations++;
2788                                         },
2789                                         submitHandler: function (form) {
2790                                                 $('#btnUpdate').prop('disabled', true);
2791                                                 var data = _w.valuationview._prepValuationUpdateData();
2792
2793                                                 App.API.execTask(
2794                                                                                 'updateValuation:' + _w.valuationview.itemId, data, {},
2795                                                                                 _w.valuationview._onValuationUpdated, _w.taskExecError
2796                                                                                 );
2797                                         }
2798                                 });
2799                                 try {
2800                                         _w.valuationview.validations = 0;
2801                                         $('#frmValuationView').valid();
2802                                 } catch (err) {
2803                                 }
2804                                 $('label.error').remove();
2805                                 $('.valid').removeClass('valid');
2806                         });
2807                 },
2808                 _onTuReady: function (response, callback)
2809                 {
2810                         // Do a check here to see if we have cat other if so return else do
2811                         if (_w.valuationview.itemData.stock.category != 8)
2812                         {
2813                                 //
2814                                 App.API.execTask(
2815                                                                 'TransUnionFromMmCode', {
2816                                                                         Filter: {
2817                                                                                 vehicleYear: parseInt($('#vehicleYear').val()),
2818                                                                                 type: parseInt($('#vehicleType').val())
2819                                                                         }
2820                                                                 }, {}, function (data) {
2821                                         _w.valuationview._onTuReceived(data);
2822                                         if (callback)
2823                                         {
2824                                                 callback();
2825                                         }
2826                                 }
2827                                 , function () {
2828                                         alert('There were no trade and retail from TransUnion');
2829                                         if (callback)
2830                                         {
2831                                                 callback();
2832                                         }
2833                                 }
2834                                 );
2835
2836                         }
2837                         else {
2838                                 if (callback)
2839                                 {
2840                                         callback();
2841                                 }
2842                                 return;
2843                         }
2844
2845                 },
2846                 _onTuReceived: function (response)
2847                 {
2848                         $('#btnFetchTu').prop('disabled', false);
2849                         if ('Success' != response.Data.Status)
2850                         {
2851                                 alert(response.Data.Status);
2852
2853                                 if ('No Results From TransUnion' == response.Data.Status || 'No Values From TransUnion' == response.Data.Status) {
2854                                         //write zero values for transunion failed
2855                                         var vals = 0.00;
2856                                         $('#retailPrice').val(vals);
2857                                         $('#tradePrice').val(vals);
2858                                         $('#listPrice').val(vals);
2859                                         _w.valuationview.ti.hydrateParam('infRetailPrice', 'R ' + vals);
2860                                         _w.valuationview.ti.hydrateParam('infTradePrice', 'R ' + vals);
2861                                         _w.valuationview.ti.hydrateParam('infListPrice', 'R ' + vals);
2862                                 }
2863                                 return;
2864                         }
2865                         var vals = response.Data.VehicleDetails[0].Value;
2866                         $('#retailPrice').val(vals.RetailPrice);
2867                         $('#tradePrice').val(vals.TradePrice);
2868             $('#listPrice').val(vals.NewPrice);
2869                         $('#MmCode').val(vals.MmCode);
2870                         _w.valuationview.ti.hydrateParam('infRetailPrice', 'R ' + vals.RetailPrice);
2871                         _w.valuationview.ti.hydrateParam('infTradePrice', 'R ' + vals.TradePrice);
2872             _w.valuationview.ti.hydrateParam('infListPrice', 'R ' + vals.NewPrice);
2873                         _w.valuationview.ti.hydrateParam('infMmCode', ' ' + vals.MmCode);
2874
2875
2876                 },
2877                 _updatePrice: function (callback, apicall)
2878                 {
2879
2880                         if ('' != $('#vehicleType').val() && null != $('#vehicleType').val())
2881                         {
2882                                 App.API.getTask(
2883                                                                 'GetMmCode' + $('#vehicleType').val(), 'Stock', 'Type.GetMmCode', null,
2884                                                                 {id: $('#vehicleType').val()},
2885                                 function (response) {
2886
2887                                         $('#mmCode').html(response.Data.mmCode);
2888                                         if (apicall !== false)
2889                                         {
2890                                                 if ($('#vehicleYear').val()
2891                                                                                 && $('#vehicleType').val())
2892                                                 {
2893                                                         App.API.getTask(
2894                                                                                         'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
2895                                                                                         {}, function (response) {
2896                                                                 _w.valuationview._onTuReady(response, callback);
2897                                                         }, _w.taskContractError);
2898
2899                                                 }
2900                                         }
2901                                         else
2902                                         {
2903                                                 if (callback)
2904                                                 {
2905                                                         callback();
2906                                                 }
2907                                         }
2908                                 }, _w.taskContractError);
2909                         }
2910                         else
2911                         {
2912                                 $('#mmCode').html('');
2913                                 if (callback)
2914                                 {
2915                                         callback();
2916                                 }
2917                         }
2918                 },
2919                 _prepValuationUpdateData: function ()
2920                 {
2921                         function isValidEmailAddress(emailAddress) {
2922                                 var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
2923                                 return pattern.test(emailAddress);
2924                         }
2925                         ;
2926
2927                         var data = _w.valuationview.ti.harvest();
2928                         data.km = '' == data.km
2929                                                         ? 0
2930                                                         : parseInt(data.km);
2931                         var retailPrice = $('#retailPrice').val();
2932                         var tradePrice = $('#tradePrice').val();
2933             var listPrice = $('#listPrice').val();
2934                         var mmCode = $('#MmCode').val();
2935
2936                         data.retailPrice = ('' == retailPrice)
2937                                                         ? 0.00
2938                                                         : parseFloat(retailPrice);
2939                         data.tradePrice = ('' == tradePrice)
2940                                                         ? 0.00
2941                                                         : parseFloat(tradePrice);
2942             data.listPrice = ('' == listPrice)
2943                 ? 0.00
2944                 : parseFloat(listPrice);
2945                         delete data.damageTotal;
2946
2947                         if (-1 == data.make)
2948                         {
2949                                 delete data.make;
2950                                 delete data.model;
2951                                 delete data.type;
2952                         }
2953                         if (-1 == data.model)
2954                         {
2955                                 delete data.model;
2956                                 delete data.type;
2957                         }
2958                         if (-1 == data.type)
2959                         {
2960                                 delete data.type;
2961                         }
2962
2963                         delete data.amountOffered;
2964 //                      if ('' == data.overAllowance)
2965 //                      {
2966 //                              delete data.overAllowance;
2967 //                      }
2968
2969                         if ('' == data.overAllowance)
2970                         {
2971                                 delete data.overAllowance;
2972                         }
2973                         else
2974                         {
2975                                 data.overAllowance = parseFloat(data.overAllowance);
2976                         }
2977
2978                         if ('' == data.standInValue)
2979                         {
2980                                 delete data.standInValue;
2981                         }
2982                         else
2983                         {
2984                                 data.standInValue = parseFloat(data.standInValue);
2985                         }
2986
2987                         if ('' == data.projectedRetail)
2988                         {
2989                                 delete data.projectedRetail;
2990                         }
2991                         else
2992                         {
2993                                 data.projectedRetail = parseFloat(data.projectedRetail);
2994                         }
2995
2996                         if ('' == data.plannedMargin)
2997                         {
2998                                 delete data.plannedMargin;
2999                         }
3000                         else
3001                         {
3002                                 data.plannedMargin = parseFloat(data.plannedMargin);
3003                         }
3004
3005             if ('' == data.bankSettlement)
3006             {
3007                 data.bankSettlement = 0.0;
3008             }
3009             else
3010             {
3011                 data.bankSettlement = parseFloat(data.bankSettlement);
3012             }
3013
3014                         if ('' == data.requiredPrice)
3015                         {
3016                                 data.requiredPrice = 0.0;
3017                         }
3018                         else
3019                         {
3020                                 data.requiredPrice = parseFloat(data.requiredPrice);
3021                         }
3022
3023                         if ('' == data.mainImage)
3024                         {
3025                                 delete data.mainImage;
3026                         }
3027                         if ('' == data.leftImage)
3028                         {
3029                                 delete data.leftImage;
3030                         }
3031                         if ('' == data.backImage)
3032                         {
3033                                 delete data.backImage;
3034                         }
3035                         if ('' == data.engineImage)
3036                         {
3037                                 delete data.engineImage;
3038                         }
3039                         if ('' == data.frontImage)
3040                         {
3041                                 delete data.frontImage;
3042                         }
3043                         if ('' == data.rightImage)
3044                         {
3045                                 delete data.rightImage;
3046                         }
3047                         if ('' == data.interiorImage)
3048                         {
3049                                 delete data.interiorImage;
3050                         }
3051                         if ('' == data.natisImage)
3052                         {
3053                                 delete data.natisImage;
3054                         }
3055                         delete data.clubs;
3056
3057
3058                         var postData = {Stock: {}, Valuation: {}};
3059                         var valuationFields = [
3060                                 "firstName", "familyName", "idNumber", "mobile",
3061                                 "email", "department", "amountOffered", "bankSettlement", "overAllowance",
3062                                 "standInValue", "projectedRetail", "plannedMargin",
3063                                 "salesProfile", "amountOffered", "salesComments", "customerComments",
3064                                 "region", "city", "street", "requiredPrice", "sighted", "licenseDiscExpired",
3065                 "dealNotDoneSelection", "dealNotDoneReason"
3066                         ];
3067                         for (var field in data)
3068                         {
3069                                 if (-1 == valuationFields.indexOf(field))
3070                                 {
3071                                         postData.Stock[field] = data[field];
3072                                 }
3073                                 else
3074                                 {
3075                                         postData.Valuation[field] = data[field];
3076                                 }
3077                         }
3078                         if ('' == postData.Valuation.idNumber)
3079                         {
3080                                 delete postData.Valuation.idNumber;
3081                         }
3082
3083
3084                         if (!isValidEmailAddress(postData.Valuation.email))
3085                         {
3086                                 testEmail = postData.Valuation.email;
3087                                 postData.Valuation.email = null;
3088                         }
3089
3090
3091                         if ('' == postData.Valuation.email)
3092                         {
3093                                 postData.Valuation.email = null; //postData.Valuation.email;
3094                         }
3095
3096                         var stockNum = $('#stockNumberDD').val();
3097                         if ('' == postData.Stock.stockNumber
3098                                 && '' != postData.Stock.stockNumberDD)
3099                         {
3100                                 postData.Stock.stockNumber = postData.Stock.stockNumberDD;
3101                         }
3102                         if (undefined != postData.Stock.stockNumberDD)
3103                         {
3104                                 delete postData.Stock.stockNumberDD;
3105                         }
3106
3107                         return postData;
3108
3109
3110                 },
3111                 _onHpiDownloadButtonClick: function (event)
3112                 {
3113             var hpiType = event.currentTarget.dataset.value;
3114             var hpiId = event.currentTarget.dataset.id;
3115
3116             if('ACC' == hpiType)
3117             {
3118                 App.API.getTask(
3119                     'printTuhpi:' + _w.stock.Id, 'Stock', 'Tuhpi.PrintAccident', _w.stock.Id,
3120                     {'PdfTemplate':{'recordId':hpiId}}, function () {
3121                         App.API.execTask(
3122                             'printTuhpi:' + _w.stock.Id, {}, {},
3123                             function () {
3124                             }, _w.taskExecError,
3125                             'EXPORT', true
3126                         );
3127                     }, _w.taskContractError
3128                 );
3129             }
3130             else
3131             {
3132                 App.API.getTask(
3133                     'printTuhpi:' + _w.stock.Id, 'Stock', 'Tuhpi.Print', _w.stock.Id,
3134                     {'PdfTemplate':{'recordId':hpiId}}, function () {
3135                         App.API.execTask(
3136                             'printTuhpi:' + _w.stock.Id, {}, {},
3137                             function () {
3138                             }, _w.taskExecError,
3139                             'EXPORT', true
3140                         );
3141                     }, _w.taskContractError
3142                 );
3143             }
3144
3145                 },
3146         _loadHpiReportData: function (hpiData)
3147         {
3148             var tuHpiData = hpiData;
3149
3150             if(0 < tuHpiData.length)
3151             {
3152                 $('#HPIreportData').html('');
3153                 var tuHpiId = '';
3154                 var tuHpiCreated = '';
3155                 var tuHpiType = '';
3156                 var tuHpiButtonType = '';
3157             }
3158
3159             for (var i = 0; i < tuHpiData.length; i++)
3160             {
3161                 if(3 > i)
3162                 {
3163
3164                     tuHpiId = tuHpiData[i].id;
3165                     tuHpiCreated = tuHpiData[i].created;
3166                     tuHpiType = tuHpiData[i].hpi_type;
3167                     tuHpiButtonType = tuHpiData[i].hpi_type;
3168
3169                     var hpiDataHtml = '<div class="control-group mobile-control-group row-fluid" style="display: block;border:1px solid #d3d3d3;" id="' + i + '">'
3170                         +'<div class="control-group mobile-control-group span4" style="padding-left:10px; padding-top:13px;">Last date requested:</div>'
3171                         +'<div class="control-group mobile-control-group span4" style="padding-left:10px;border-left:1px solid #d3d3d3; padding-top:13px;">'
3172                         +'<div id="tuhpiDate_' + i + '" class="span9">Not requested yet.</div>'
3173                         +'</div>'
3174                         +'<div class="control-group mobile-control-group span4" style="padding-left:10px;border-left:1px solid #d3d3d3; padding-top:13px;">'
3175                         +'<div id="tuhpiType_' + i + '" class="span8">Not requested yet.</div>'
3176                         +'<div class="span4">'
3177                         +'<button id="downloadTuhpi_' + tuHpiId + '" class="btn pull-right span12" data-id="' + tuHpiId + '" data-value="' + tuHpiButtonType + '" type="button" style="margin:-5px 0 0 0;" >view</button>'
3178                         +'</div>'
3179                         +'</div>'
3180                         +'</div>';
3181
3182                     $('#HPIreportData').append(hpiDataHtml);
3183
3184                     if (tuHpiId)
3185                     {
3186                         $('#tuhpiDate_' + i).html(tuHpiCreated);
3187                         $('#tuhpiType_' + i).html(tuHpiType);
3188                         $('#downloadTuhpi').show();
3189                         $('#HPIbtnConfirm').prop('disabled', false);
3190                     }
3191                     else
3192                     {
3193                         $('#tuhpiDate_' + i).html('Not Requested Yet');
3194                         $('#tuhpiType_' + i).html('Not Requested Yet');
3195                         $('#downloadTuhpi').hide();
3196                     }
3197
3198
3199                     $('#downloadTuhpi_' + tuHpiId).click(function(event)
3200                     {
3201                         _w.valuationview._onHpiDownloadButtonClick(event);
3202                     });
3203
3204                 }
3205
3206             }
3207
3208         },
3209         _onValuationUpdated : function( response )
3210         {
3211             window.location.hash = '/valuations';
3212         }
3213         };
3214
3215 })();