480729073b9848cb26a74a4faae9ed2f83c51c88
[namibia] / public / js / app / portal-workspace / stockview.js
1 ;(function(){
2
3         window._w.stockview = {
4
5                 itemId      : null,
6                 itemData    : null,
7                 formMeta    : null,
8                 ti          : null,
9                 limited     : false,
10                 newItem     : false,
11                 validations : 0,
12                 dates       : [],
13
14                 onStockViewTemplateReady : function( template, event, eventData )
15                 {
16                         _w.stockview.itemData = null;
17                         _w.stockview.ti = _t[template];
18                         _w.stockview.limited = ('limitedstockview' == template)
19                                 ? true
20                                 : false;
21                         _w.stockview.itemId = App.Util.getUrlParam('id');
22                         if (0 == _w.stockview.itemId || null == _w.stockview.itemId)
23                         {
24                                 _w.stockview.newItem = true;
25                                 _w.stockview.itemData = {
26                                                 stock       : {},
27                                                 vehicleYear : null,
28                                                 type        : {
29                                                         category    : {
30                                                                 id : null
31                                                         },
32                                                         model       : {
33                                                                 id   : null,
34                                                                 make : {
35                                                                         id : null
36                                                                 }
37                                                         }
38                                                 }
39                                 };
40                         }
41                         _w.stockview.dates = [];
42                         var phData = App.DataStore.getData('publicHolidays');
43                         for (var i = 0; i < phData.length; i++)
44                         {
45                                 var dateParts = phData[i].holiday.split('-').map(function(part){
46                                                 return parseInt(part, 10);
47                                         });
48                                 var holiday = new Date(dateParts[0], dateParts[1]-1, dateParts[2]);
49                                 _w.stockview.dates.push(holiday.toDateString());
50                         }
51
52                         App.DataStore.setData('sparekeys', [{"value":"1", "label":"Yes"}, {"value":"0", "label":"No"}]);
53                 },
54
55                 onStockViewPublished : function( template, event, eventData )
56                 {
57
58                         _w.stockview.ti = _t[template];
59                         _w.stockview.limited = ('limitedstockview' == template)
60                                 ? true
61                                 : false;
62                         _w.stockview.setStockViewFormMeta();
63                         _w.stockview.ti.hydrate(_w.stockview.formMeta);
64                         if (_w.stockview.newItem)
65                         {
66                                 _w.stockview._setupValidation();
67                                 $('#btnSendToAuction').show();
68                                 $('#btnUpdate').prop('disabled', false);
69                                 $('#printStockPdf').hide();
70
71                                 /*
72                                  * Permissions
73                                  */
74                                 true == App.permissions.stockCreate ? $('#btnUpdate').show() : $('#btnUpdate').hide();
75                                 true == App.permissions.stockRouteAuction && !App.companyData.tC ? $('#optSendToAuction').show() : $('#optSendToAuction').hide();
76                                 if (!App.permissions.stockUpdateDamages)
77                                 {
78                                         $('.damages-form').hide();
79                                 }
80                                 
81                                 if (!App.permissions.stockUploadPhotos)
82                                 {
83                                         $('.photos-form').hide();
84                                 }
85                         }
86
87                         if ( $('#tuhpiDate').val= '' )
88                         {
89                                 $('#downloadTuhpi').hide();
90                         }
91
92                         $('#btnRequestHPI').click(function () {
93
94                                 if ('' == $('#HPIusername').val() || '' ==  $('#HPIpin').val())
95                                 {
96                                         alert('Please enter a valid username and password.');
97                                         return;
98                                 }
99
100                                 $('#HPIdropConfirm').slideToggle();
101                                 $('#HPIresponse').html('');
102                         });
103
104             $('#btnRequestHPIAccident').click(function () {
105
106                 if ('' == $('#HPIAccidentUsername').val() || '' == $('#HPIAccidentPin').val())
107                 {
108                     alert('Please enter a valid username and password.');
109                     return;
110                 }
111
112                 $('#HPIAccidentDropConfirm').slideToggle();
113                 $('#HPIAccidentResponse').html('');
114             });
115
116
117                         App.Util.updateCheckboxStyle($('#acceptHPIdisclaimer'));
118                         $('#HPIbtnConfirm').click(function () {
119
120                                 if ( $('#engineNumber').val() == '' )
121                                 {
122                                         alert('Please update the Vehicle Engine Number and try again');
123                                         return;
124                                 }
125                                 if ( $('#vinNumber').val() == '' &&  $('#registrationNumber').val() == '')
126                                 {
127                                         alert('Please update the Vin Number or the Registration Number and and try again');
128                                         return;
129                                 }
130                                 if (!$('#acceptHPIdisclaimer').is(':checked'))
131                                 {
132                                         alert('Please accept the conditions before sending.');
133                                         return;
134                                 }
135                                 if (!$('#frmStockView').valid())
136                                 {
137                                         return;
138                                 }
139                                 $('#HPIbtnConfirm').prop('disabled', true);
140                                 var data = _w.stockview._prepStockUpdateData();
141                                 App.API.execTask(
142                                                 'updateStock:' + _w.stockview.itemId, {"Stock":data}, {},
143                                                 function()
144                                                 {
145                                                         var task = _w.stockview.limited
146                                                                 ? 'Stock.LimitedUpdate'
147                                                                 : 'Stock.Update';
148                                                         App.API.getTask(
149                                                                         'updateStock:' + _w.stockview.itemId, 'Stock', task, _w.stockview.itemId,
150                                                                         {}, function(){}, _w.taskContractError
151                                                                 );
152                                                         var user = $('#HPIusername').val();
153                                                         var pass = $('#HPIpin').val();
154
155                                                         App.API.getTask(
156                                                                         'TransUnionForHPI', 'Stock', 'Utility.TransUnionForHPI', null,
157                                                                         {'Filter' : {'username' : user ,'pass' : pass , 'stock' : _w.stockview.itemId}},
158                                                                         function() {
159                                                                                 App.API.execTask(
160                                                                                                 'TransUnionForHPI',{}, {},
161                                                                                                 function(data)
162                                                                                                 {
163                                                                                                         $('#HPIdropConfirm').hide();
164                                                                                                         if ('Success' == data.Status)
165                                                                                                         {
166                                                                                                                 $('#HPIresponse').html('Success on HPI Report');
167                                                                                                                 alert('Success on HPI Report');
168                                                                                                                 App.DataStore.loadSelectListData(
169                                                                                                                                 'tuhpi', false, 'Stock', 'Tuhpi.List', null,
170                                                                                                                                 {"Filter":
171                                                                                                                                         {
172                                                                                                                                                 "stock"                 : _w.stockview.itemId,
173                                                                                                                                                 "company"               : App.companyData.id
174                                                                                                                                         }
175                                                                                                                                 }, {},function()
176                                                                                                                                 {
177                                                                                                                                         // data is retrieved
178                                                                                                                                         var tuHpiData = App.DataStore.getData('tuhpi');
179
180                                                                     _w.stockview._loadHpiReportData(tuHpiData);
181
182                                                                                                                                         //for (var i = 0; i < tuHpiData.length; i++)
183                                                                                                                                         //{
184                                                                                                                                         //      var tuHpiId = tuHpiData[i].id
185                                                                                                                                         //      var tuHpiCreated = tuHpiData[i].created
186                                                                                                                                         //      if (tuHpiId)
187                                                                                                                                         //      {
188                                                                                                                                         //              $('#tuhpiDate').html(tuHpiCreated);
189                                                                                                                                         //              $('#downloadTuhpi').show();
190                                                                                                                                         //              $('#HPIbtnConfirm').prop('disabled', true);
191                                                                                                                                         //              return;
192                                                                                                                                         //      }
193                                                                                                                                         //      else
194                                                                                                                                         //      {
195                                                                                                                                         //              $('#tuhpiDate').html('Not Requested Yet');
196                                                                                                                                         //              $('#downloadTuhpi').hide();
197                                                                                                                                         //              $('#HPIbtnConfirm').prop('disabled', false);
198                                                                                                                                         //      }
199                                                                                                                                         //}
200                                                                                                                                 }
201                                                                                                                         );
202                                                                                                         }
203                                                                                                         else
204                                                                                                         {
205                                                                                                                 $('#HPIresponse').html('API call to remote host failed. No data could be retrieved from remote service.');
206                                                                                                                 $('#HPIbtnConfirm').prop('disabled', false);
207                                                                                                         }
208                                                                                                 }, function(response)
209                                                                                                 {
210                                                                                                         alert(
211                                                                                                                 undefined != response.StatusReason
212                                                                                                                         ? response.StatusReason
213                                                                                                                         : 'API call to remote host failed. No data could be retrieved from remote service.'
214                                                                                                         );
215                                                                                                         $('#HPIbtnConfirm').prop('disabled', false);
216                                                                                                 }
217                                                                                 );
218                                                                         }
219                                                                         , _w.taskContractError
220                                                         );
221                                                 }, _w.taskExecError
222                                                 );
223                         });
224
225             App.Util.updateCheckboxStyle($('#acceptHPIAccidentDisclaimer'));
226             $('#HPIAccidentBtnConfirm').click(function () {
227
228                 if ( $('#engineNumber').val() == '' )
229                 {
230                     alert('Please update the Vehicle Engine Number and try again');
231                     return;
232                 }
233                 if ( $('#vinNumber').val() == '' &&  $('#registrationNumber').val() == '')
234                 {
235                     alert('Please update the Vin Number or the Registration Number and and try again');
236                     return;
237                 }
238                 if (!$('#acceptHPIAccidentDisclaimer').is(':checked'))
239                 {
240                     alert('Please accept the conditions before sending.');
241                     return;
242                 }
243                 if (!$('#frmStockView').valid())
244                 {
245                     return;
246                 }
247                 $('#HPIAccidentBtnConfirm').prop('disabled', true);
248                 var data = _w.stockview._prepStockUpdateData();
249
250                 App.API.execTask(
251                     'updateStock:' + _w.stockview.itemId, {"Stock":data}, {},
252                     function()
253                     {
254                         var task = _w.stockview.limited
255                             ? 'Stock.LimitedUpdate'
256                             : 'Stock.Update';
257                         App.API.getTask(
258                             'updateStock:' + _w.stockview.itemId, 'Stock', task, _w.stockview.itemId,
259                             {}, function(){}, _w.taskContractError
260                         );
261                         var user = $('#HPIAccidentUsername').val();
262                         var pass = $('#HPIAccidentPin').val();
263
264                         App.API.getTask(
265                             'TransUnionForHPIAccident', 'Stock', 'Utility.TransUnionForHPIAccident', null,
266                             {'Filter' : {'username' : user ,'pass' : pass , 'stock' : _w.stockview.itemId}},
267                             function() {
268                                 App.API.execTask(
269                                     'TransUnionForHPIAccident',{}, {},
270                                     function(data)
271                                     {
272                                         $('#HPIdropConfirm').hide();
273                                         if ('Success' == data.Status)
274                                         {
275                                             $('#HPIresponse').html('Success on HPI Report');
276                                             alert('Success on HPI Report');
277                                             App.DataStore.loadSelectListData(
278                                                 'tuhpi', false, 'Stock', 'Tuhpi.List', null,
279                                                 {"Filter":
280                                                 {
281                                                     "stock"             : _w.stockview.itemId,
282                                                     "company"           : App.companyData.id
283                                                 }
284                                                 }, {},function()
285                                                 {
286                                                     // data is retrieved
287                                                     var tuHpiData = App.DataStore.getData('tuhpi');
288
289                                                     _w.stockview._loadHpiReportData(tuHpiData);
290
291                                                 }
292                                             );
293                                         }
294                                         else
295                                         {
296                                             $('#HPIresponse').html('API call to remote host failed. No data could be retrieved from remote service.');
297                                             $('#HPIbtnConfirm').prop('disabled', false);
298                                         }
299                                     }, function(response)
300                                     {
301                                         alert(
302                                             undefined != response.StatusReason
303                                                 ? response.StatusReason
304                                                 : 'API call to remote host failed. No data could be retrieved from remote service.'
305                                         );
306                                         $('#HPIbtnConfirm').prop('disabled', false);
307                                     }
308                                 );
309                             }
310                             , _w.taskContractError
311                         );
312                     }, _w.taskExecError
313                 );
314             });
315
316                         //$('#downloadTuhpi').click(function () {
317                         //      App.API.getTask(
318                         //                      'printTuhpi:' + _w.stockview.itemId, 'Stock', 'Tuhpi.Print', _w.stockview.itemId,
319                         //                      {}, function() {
320                         //                              App.API.execTask(
321                         //                                              'printTuhpi:' + _w.stockview.itemId, {}, {},
322                         //                                              function () {}, _w.taskExecError,
323                         //                                              'EXPORT', true
324                         //                              );
325                         //                      }, _w.taskContractError
326                         //      );
327                         //});
328
329             $('#btn_mainImage').change(function () {
330                                 if ('' == $('#mainImage').val())
331                                 {
332                                         $('#img_mainImage').addClass('error');
333                                         $('#img_mainImage').removeClass('valid');
334                                 }
335                                 else
336                                 {
337                                         $('#img_mainImage').removeClass('error');
338                                         $('#img_mainImage').addClass('valid');
339                                 }
340                         });
341
342                         $('#btnFetchTu').click(function () {
343                                 if (!$('#vehicleYear').val()
344                                         || !$('#vehicleType').val())
345                                 {
346                                         alert('Vehicle year and type is required to fetch Trade and Retail pricing.');
347                                         return;
348                                 }
349                                 App.API.getTask(
350                                                 'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
351                                                 {}, _w.stockview._onTuReady, _w.taskContractError
352                                 );
353                         });
354                         $('#btnUpdate').prop('disabled', true);
355                         $('#btnArchive').click(function () {
356                                 App.API.directRoute(
357                                                 'archiveStock:' + _w.stockview.itemId,
358                                                 'Stock', 'Stock.MoveToArchive', _w.stockview.itemId, {},
359                                                 _w.stockview._onStockUpdated, _w.taskExecError
360                                                 );
361                         });
362                         $('#btnUnarchive').click(function () {
363                                 App.API.directRoute(
364                                                 'unarchiveStock:' + _w.stockview.itemId,
365                                                 'Stock', 'Stock.MoveToStock', _w.stockview.itemId, {},
366                                                 _w.stockview._onStockUpdated, _w.taskExecError
367                                                 );
368                         });
369                         App.Util.updateCheckboxStyle($('#acceptPgHPIdisclaimer'));
370                         $('#btnSendToPg').click(function () {
371                                 var clubs = $('#clubs').val();
372                                 if (null == clubs)
373                                 {
374                                         alert('Please select at least one club.');
375                                         return;
376                                 }
377                                 if (!$('#acceptPgHPIdisclaimer').is(':checked'))
378                                 {
379                                         alert('Please accept the conditions before sending.');
380                                         return;
381                                 }
382                                 if ('' == $('#registrationNumber').val())
383                                 {
384                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to price guide.');
385                                         $('#registrationNumber').addClass('error');
386                                         $('#registrationNumber').removeClass('valid');
387                                         return;
388                                 }
389                                 else
390                                 {
391                                         $('#registrationNumber').removeClass('error');
392                                         $('#registrationNumber').addClass('valid');
393                                 }
394                                 if ('' == $('#vinNumber').val())
395                                 {
396                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to price guide.');
397                                         $('#vinNumber').addClass('error');
398                                         $('#vinNumber').removeClass('valid');
399                                         return;
400                                 }
401                                 else
402                                 {
403                                         $('#vinNumber').removeClass('error');
404                                         $('#vinNumber').addClass('valid');
405                                 }
406                                 if ('' == $('#engineNumber').val())
407                                 {
408                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to price guide.');
409                                         $('#engineNumber').addClass('error');
410                                         $('#engineNumber').removeClass('valid');
411                                         return;
412                                 }
413                                 else
414                                 {
415                                         $('#engineNumber').removeClass('error');
416                                         $('#engineNumber').addClass('valid');
417                                 }
418                                 if (!$('#frmStockView').valid())
419                                 {
420                                         return;
421                                 }
422                                 $('#btnSendToPg').prop('disabled', true);
423                                 App.API.execTask(
424                                         'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
425                                         function () {
426                                                 App.API.getRoute(
427                                                                 'sendToPg:' + _w.stockview.itemId, 'Stock', 'Stock.SendToPriceGuide', _w.stockview.itemId,
428                                                                 {}, function() {
429                                                                         var clubList = $('#clubs').val();
430                                                                         var clubs = [];
431                                                                         for (var i = 0; i < clubList.length; i++)
432                                                                         {
433                                                                                 clubs.push({id: clubList[i]});
434                                                                         }
435                                                                         App.API.execRoute(
436                                                                                         'sendToPg:' + _w.stockview.itemId, {Context: {clubs: clubs}}, {},
437                                                                                         _w.stockview._onStockUpdated, _w.taskExecError
438                                                                         );
439                                                                 }, _w.taskContractError
440                                                 );
441                                         }, _w.taskExecError
442                                 );
443                         });
444
445                         $('.back-btn').on('click', function(){
446                                 window.history.back();
447                         });
448
449                         $('#btnSendToRetail').click(function () {
450                                 var reservePrice = $('#retailAmountRequired').val();
451                                 if ('' == reservePrice || isNaN(reservePrice))
452                                 {
453                                         alert('Please provide minimum retail price.');
454                                         return;
455                                 }
456                                 if (!$('#frmStockView').valid())
457                                 {
458                                         return;
459                                 }
460                                 $('#btnSendToRetail').prop('disabled', true);
461                                 App.API.execTask(
462                                                 'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
463                                                 function () {
464                                                         App.API.directRoute(
465                                                                         'retailStock:' + _w.stockview.itemId,
466                                                                         'Stock', 'Stock.SendToRetail', _w.stockview.itemId, {},
467                                                                         _w.stockview._onStockUpdated, _w.taskExecError
468                                                                         );
469                                                 }, _w.taskExecError
470                                 );
471                         });
472                         $('#btnReclaimFromRetail').click(function () {
473                                 if (!$('#frmStockView').valid())
474                                 {
475                                         return;
476                                 }
477                                 $('#btnReclaimFromRetail').prop('disabled', true);
478                                 App.API.execTask(
479                                                 'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
480                                                 function () {
481                                                         App.API.directRoute(
482                                                                         'retailReclaimStock:' + _w.stockview.itemId,
483                                                                         'Stock', 'Stock.ReclaimFromRetail', _w.stockview.itemId, {},
484                                                                         _w.stockview._onStockUpdated, _w.taskExecError
485                                                         );
486                                                 }, _w.taskExecError
487                                 );
488                         });
489                         $('#btnSendToTc').click(function () {
490                                 if (!$('#frmStockView').valid())
491                                 {
492                                         return;
493                                 }
494                                 $('#btnSendToTc').prop('disabled', true);
495                                 if (8 != $('#vehicleCategory').val())
496                                 {
497                                         App.API.getTask(
498                                                 'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
499                                                 {}, _w.stockview._onTuTcUpdateReady, _w.taskContractError
500                                         );
501                                 }
502                                 else
503                                 {
504                                         App.API.execTask(
505                                                 'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
506                                                 function () {
507                                                         App.API.directRoute(
508                                                                 'tcStock:' + _w.stockview.itemId,
509                                                                 'Stock', 'Stock.SendToTradeCenter', _w.stockview.itemId, {},
510                                                                 _w.stockview._onStockUpdated, _w.taskExecError
511                                                         );
512                                                 }, _w.taskExecError
513                                         );
514                                 }
515                         });
516                         App.Util.updateCheckboxStyle($('#acceptAuctionHPIdisclaimer'));
517                         $('#btnSendToAuction').click(function () {
518                                 var endDate = $('#endDate').val();
519                                 var reservePrice = $('#reservePrice').val();
520                                 if ('' == endDate || '' == reservePrice || isNaN(reservePrice))
521                                 {
522                                         alert('Please provide end date and reserve price.');
523                                         return;
524                                 }
525
526                                 if (!$('#frmStockView').valid())
527                                 {
528                                         return;
529                                 }
530                                 if (!$('#acceptAuctionHPIdisclaimer').is(':checked'))
531                                 {
532                                         alert('Please accept the conditions before sending.');
533                                         return;
534                                 }
535
536                                 if ('' == $('#mainImage').val())
537                                 {
538                                         alert('The main image is mandatory for moving a vehicle to auction.');
539                                         $('#img_mainImage').addClass('error');
540                                         $('#img_mainImage').removeClass('valid');
541                                         return;
542                                 }
543                                 else
544                                 {
545                                         $('#img_mainImage').removeClass('error');
546                                         $('#img_mainImage').addClass('valid');
547                                 }
548                                 if ('' == $('#registrationNumber').val())
549                                 {
550                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to auction.');
551                                         $('#registrationNumber').addClass('error');
552                                         $('#registrationNumber').removeClass('valid');
553                                         return;
554                                 }
555                                 else
556                                 {
557                                         $('#registrationNumber').removeClass('error');
558                                         $('#registrationNumber').addClass('valid');
559                                 }
560                                 if ('' == $('#vinNumber').val())
561                                 {
562                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to auction.');
563                                         $('#vinNumber').addClass('error');
564                                         $('#vinNumber').removeClass('valid');
565                                         return;
566                                 }
567                                 else
568                                 {
569                                         $('#vinNumber').removeClass('error');
570                                         $('#vinNumber').addClass('valid');
571                                 }
572                                 if ('' == $('#engineNumber').val())
573                                 {
574                                         alert('The Registration, VIN and Engine number is mandatory for moving a vehicle to auction.');
575                                         $('#engineNumber').addClass('error');
576                                         $('#engineNumber').removeClass('valid');
577                                         return;
578                                 }
579                                 else
580                                 {
581                                         $('#engineNumber').removeClass('error');
582                                         $('#engineNumber').addClass('valid');
583                                 }
584
585
586                                 $('#btnSendToAuction').prop('disabled', true);
587                                 if (_w.stockview.newItem)
588                                 {
589                                         var data = {};
590                                         data.Stock = _w.stockview._prepStockUpdateData();
591                                         data.Context = {endDate: endDate, reservePrice: reservePrice};
592                                         App.API.execTask(
593                                                 'createStockAuction', data, {},
594                                                 _w.stockview._onStockUpdated, _w.taskExecError
595                                         );
596                                 }
597                                 else
598                                 {
599                                         if (8 != $('#vehicleCategory').val())
600                                         {
601                                                 App.API.getTask(
602                                                         'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
603                                                         {}, _w.stockview._onTuUpdateReady, _w.taskContractError
604                                                 );
605                                         }
606                                         else
607                                         {
608                                                 App.API.execTask(
609                                                         'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
610                                                         function () {
611                                                                 App.API.getRoute(
612                                                                         'sendToAuction:' + _w.stockview.itemId, 'Stock', 'Stock.SendToAuction', _w.stockview.itemId,
613                                                                         {}, function() {
614                                                                                 var endDate = $('#endDate').val();
615                                                                                 var reservePrice = $('#reservePrice').val();
616                                                                                 App.API.execRoute(
617                                                                                         'sendToAuction:' + _w.stockview.itemId, {Context: {endDate: endDate, reservePrice: reservePrice}}, {},
618                                                                                         _w.stockview._onStockUpdated, _w.taskExecError
619                                                                                 );
620                                                                         }, _w.taskContractError
621                                                                 );
622                                                         }, _w.taskExecError
623                                                 );
624                                         }
625                                 }
626                         });
627                         if (null != _w.stockview.itemData)
628                         {
629                                 _w.stockview._onDataAndTemplate();
630                         }
631                         if (false == _w.stockview.newItem)
632                         {
633                                 _w.stockview.ti.hydrate({
634                                         'gridPricingHistoryColumnHeaders': {
635                                                 constructor: 'GridColumnHeader',
636                                                 items: {
637                                                         Date: {
638                                                                 id: 'gridPricingHistoryColumn_Date',
639                                                                 title: 'Date',
640                                                         },
641                                                         Trade: {
642                                                                 id: 'gridPricingHistoryColumn_Trade',
643                                                                 title: 'Trade',
644                                                         },
645                                                         TotalRecon: {
646                                                                 id: 'gridPricingHistoryColumn_totalRecon',
647                                                                 title: 'Total Recon',
648                                                         },
649                                                         km: {
650                                                                 id: 'gridPricingHistoryColumn_km',
651                                                                 title: 'km',
652                                                         },
653                                                         PriceguideOffer: {
654                                                                 id: 'gridPricingHistoryColumn_pricegOffer',
655                                                                 title: 'Priceguide Offer',
656                                                         },
657                                                         AuctionWinningBid: {
658                                                                 id: 'gridPricingHistoryColumn_auctionWinningBid',
659                                                                 title: 'Auction Winning Bid',
660                                                         }
661                                                 }
662                                         },
663                                         'gridPricingHistoryRowRepeater': {}
664                                 });
665                         }
666                         else
667                         {
668                                 $('#pricinghistory').hide();
669                         }
670
671                         _w.stockview.itemId = App.Util.getUrlParam('id');
672                         if (0 == _w.stockview.itemId || null == _w.stockview.itemId)
673                         {
674                                 App.API.getTask(
675                                         'createStock', 'Stock', 'Stock.Create',
676                                         null, {}, function(){}, _w.taskContractError
677                                 );
678                                 App.API.getTask(
679                                         'createStockAuction', 'Stock', 'Stock.CreateAuction',
680                                         null, {}, function(){}, _w.taskContractError
681                                 );
682                                 App.DataStore.loadSelectListGroup([
683                    {dataId: 'years', isStatic: true, workspace: 'Stock', task: 'Year.SelectList'},
684                    {dataId: 'categories', isStatic: true, workspace: 'Stock', task: 'Category.SelectList'},
685                    {dataId: 'conditions', isStatic: true, workspace: 'Stock', task: 'Condition.SelectList'},
686                    {dataId: 'exteriorColours', isStatic: true, workspace: 'Stock', task: 'ExteriorColour.SelectList'},
687                    {dataId: 'interiorColours', isStatic: true, workspace: 'Stock', task: 'InteriorColour.SelectList'},
688                    {dataId: 'upholsteries', isStatic: true, workspace: 'Stock', task: 'Upholstery.SelectList'},
689                    {dataId: 'papers', isStatic: true, workspace: 'Stock', task: 'Paper.SelectList'},
690                    {dataId: 'natis', isStatic: true, workspace: 'Stock', task: 'Natis.SelectList'},
691                    {dataId: 'fsh', isStatic: true, workspace: 'Stock', task: 'FullServiceHistory.SelectList'},
692                    {dataId: 'fuelTypes', isStatic: true, workspace: 'Stock', task: 'FuelType.SelectList'},
693                    {dataId: 'transmissionTypes', isStatic: true, workspace: 'Stock', task: 'TransmissionType.SelectList'},
694                    {dataId: 'damages', isStatic: true, workspace: 'Stock', task: 'Damage.SelectList'},
695                    {dataId: 'accessories', isStatic: true, workspace: 'Stock', task: 'Accessory.SelectList'},
696                    {dataId: 'clubs', isStatic: true, workspace: 'PriceGuide', task: 'Club.SelectList'}
697                 ]);
698
699                         }
700                         else
701                         {
702                                 _w.stockview.newItem = false;
703                                 var task = _w.stockview.limited
704                                         ? 'Stock.LimitedUpdate'
705                                         : 'Stock.Update';
706                                 App.API.getTask(
707                                                 'updateStock:' + _w.stockview.itemId, 'Stock', task, _w.stockview.itemId,
708                                                 {}, $.proxy( _w.stockview._onStockViewDataReceived, this ), _w.taskContractError
709                                         );
710                         }
711                 },
712
713                 setStockViewFormMeta : function( data )
714                 {
715                         var damages = {};
716                         if (undefined != data)
717                         {
718                                 for (var i = 0; i < data.damages.length; i++)
719                                 {
720                                         damages['d' + data.damages[i].damage] = data.damages[i].amount;
721                                 }
722                         }
723                         else
724                         {
725                                 data = {};
726                         }
727
728                         _w.stockview.formMeta = {
729                                 'vehicleYear' : {
730                                         type        : 'select',
731                                         id          : 'vehicleYear',
732                                         title       : 'Year',
733                                         dataStoreId : 'years',
734                                         value       : data.vehicleYear ? data.vehicleYear : '',
735                                         onChange    : function () {
736                                                 if (!App.DataStore.getItem('BuildSelect:vehicleYear', false))
737                                                 {
738                                                         if (_w.stockview.itemData)
739                                                         {
740                                                                 _w.stockview.itemData.vehicleYear = $('#vehicleYear').val();
741                                                                 _w.stockview._listMakesModelsTypes(function () {
742                                                                         if ($('#vehicleYear').val() && $('#vehicleType').val())
743                                                                         {
744                                                                                 App.API.getTask(
745                                                                                                 'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
746                                                                                                 {}, _w.stockview._onTuReady, _w.taskContractError
747                                                                                 );
748                                                                         }
749                                                                 });
750                                                         }
751                                                 }
752                                         }
753                                 },
754                                 'category' : {
755                                         type        : 'select',
756                                         id          : 'vehicleCategory',
757                                         title       : 'Category',
758                                         dataStoreId : 'categories',
759                                         value       : data.type ? data.type.category.id : '',
760                                         onChange    : function () {
761
762                                                 if ($(this).val() == 8)
763                                                 {
764                                                         $('#retailPrice').val('');
765                                                         $('#tradePrice').val('');
766                             $('#listPrice').val('');
767                                                         $('#' + _w.stockview.ti.tid + '_initialTradePrice').val($('#' + _w.stockview.ti.tid + '_tradePrice').html());
768                                                         $('#' + _w.stockview.ti.tid + '_updatedTradePrice').val('');
769                                                         $('#' + _w.stockview.ti.tid + '_retailPrice').html('R ' + '.00');
770                                                         $('#' + _w.stockview.ti.tid + '_tradePrice').html('R ' + '.00');
771                             $('#' + _w.stockview.ti.tid + '_listPrice').html('R ' + '.00');
772                                                 }
773
774
775
776                                                 if ($(this).val() == 8 && _w.stockview.itemId == 0)
777                                                 {
778                                                         $('#mmCode').html("Other");
779
780                                                 }
781                                                 if (!App.DataStore.getItem('BuildSelect:vehicleCategory', false))
782                                                 {
783                                                         if (_w.stockview.itemData)
784                                                         {
785                                                                 _w.stockview.itemData.type.category.id = $('#vehicleCategory').val();
786                                                                 _w.stockview._listMakesModelsTypes();
787                                                         }
788                                                 }
789                                                 $('#' + _w.stockview.ti.tid + '_makeManual').hide();
790                                                 $('#' + _w.stockview.ti.tid + '_modelManual').hide();
791                                                 $('#' + _w.stockview.ti.tid + '_typeManual').hide();
792                                                 $('#makeManual').val('');
793                                                 $('#modelManual').val('');
794                                                 $('#typeManual').val('');
795                                                 $('#' + _w.stockview.ti.tid + '_make').show();
796                                                 $('#' + _w.stockview.ti.tid + '_model').show();
797                                                 $('#' + _w.stockview.ti.tid + '_type').show();
798                                         }
799                                 },
800                                 'make' : {
801                                         type        : 'select',
802                                         id          : 'vehicleMake',
803                                         title       : 'Vehicle Make',
804                                         dataStoreId : 'makes',
805                                         value       : data.type ? data.type.model.make.id : '',
806                                         onChange    : function () {
807                                                 if (!App.DataStore.getItem('BuildSelect:vehicleMake', false))
808                                                 {
809                                                         $('#vehicleMakeManual').val('');
810                                                         $('#vehicleModelManual').val('');
811                                                         $('#vehicleTypeManual').val('');
812                                                         if (-1 == $('#vehicleMake').val())
813                                                         {
814                                                                 $('#' + _w.stockview.ti.tid + '_make').hide();
815                                                                 $('#' + _w.stockview.ti.tid + '_model').hide();
816                                                                 $('#' + _w.stockview.ti.tid + '_type').hide();
817                                                                 $('#' + _w.stockview.ti.tid + '_makeManual').show();
818                                                                 $('#' + _w.stockview.ti.tid + '_modelManual').show();
819                                                                 $('#' + _w.stockview.ti.tid + '_typeManual').show();
820                                                         }
821                                                         else
822                                                         {
823                                                                 $('#' + _w.stockview.ti.tid + '_makeManual').hide();
824                                                                 $('#' + _w.stockview.ti.tid + '_modelManual').hide();
825                                                                 $('#' + _w.stockview.ti.tid + '_typeManual').hide();
826                                                                 $('#' + _w.stockview.ti.tid + '_make').show();
827                                                                 $('#' + _w.stockview.ti.tid + '_model').show();
828                                                                 $('#' + _w.stockview.ti.tid + '_type').show();
829                                                                 if (_w.stockview.itemData)
830                                                                 {
831                                                                         _w.stockview.itemData.type.model.make.id = $('#vehicleMake').val();
832                                                                         _w.stockview._listMakesModelsTypes();
833                                                                 }
834                                                         }
835                                                 }
836                                         }
837                                 },
838                                 'model' : {
839                                         type        : 'select',
840                                         id          : 'vehicleModel',
841                                         title       : 'Vehicle Model',
842                                         dataStoreId : 'models',
843                                         value       : data.type ? data.type.model.id : '',
844                                         onChange    : function () {
845                                                 if (!App.DataStore.getItem('BuildSelect:vehicleModel', false))
846                                                 {
847                                                         $('#vehicleModelManual').val('');
848                                                         $('#vehicleTypeManual').val('');
849
850                                                         if (-1 == $('#vehicleModel').val())
851                                                         {
852                                                                 $('#' + _w.stockview.ti.tid + '_model').hide();
853                                                                 $('#' + _w.stockview.ti.tid + '_type').hide();
854                                                                 $('#' + _w.stockview.ti.tid + '_modelManual').show();
855                                                                 $('#' + _w.stockview.ti.tid + '_typeManual').show();
856                                                         }
857                                                         else
858                                                         {
859                                                                 $('#' + _w.stockview.ti.tid + '_modelManual').hide();
860                                                                 $('#' + _w.stockview.ti.tid + '_typeManual').hide();
861                                                                 $('#' + _w.stockview.ti.tid + '_model').show();
862                                                                 $('#' + _w.stockview.ti.tid + '_type').show();
863                                                                 if (_w.stockview.itemData)
864                                                                 {
865                                                                         _w.stockview.itemData.type.model.id = $('#vehicleModel').val();
866                                                                         _w.stockview._listMakesModelsTypes();
867                                                                 }
868                                                         }
869                                                 }
870                                         }
871                                 },
872                                 'type' : {
873                                         type        : 'select',
874                                         id          : 'vehicleType',
875                                         title       : 'Vehicle Type',
876                                         dataStoreId : 'types',
877                                         value       : data.type ? data.type.id : '',
878                                         onChange    : function () {
879                                                 if (!App.DataStore.getItem('BuildSelect:vehicleType', false))
880                                                 {
881                                                         $('#vehicleTypeManual').val('');
882                                                         if (-1 == $('#vehicleType').val())
883                                                         {
884                                                                 $('#' + _w.stockview.ti.tid + '_type').hide();
885                                                                 $('#' + _w.stockview.ti.tid + '_typeManual').show();
886                                                         }
887                                                         else
888                                                         {
889                                                                 $('#' + _w.stockview.ti.tid + '_typeManual').hide();
890                                                                 $('#' + _w.stockview.ti.tid + '_type').show();
891                                                                 if ($('#vehicleYear').val()
892                                                                         && $('#vehicleType').val())
893                                                                 {
894                                                                         App.API.getTask(
895                                                                                         'TransUnionFromMmCode', 'Stock', 'Utility.TransUnionFromMmCode', null,
896                                                                                         {}, _w.stockview._onTuReady, _w.taskContractError
897                                                                         );
898                                                                 }
899                                                                 if ('' != $(this).val() && null != $(this).val())
900                                                                 {
901
902                                                                         App.API.getTask(
903                                                                                         'GetMmCode' + $(this).val(), 'Stock', 'Type.GetMmCode', null,
904                                                                                         {id:$(this).val()}, function(response){
905                                                                                                 $('#mmCode').html(response.Data.mmCode);
906                                                                                         }, _w.taskContractError
907                                                                         );
908                                                                 }
909                                                                 else
910                                                                 {
911                                                                         $('#mmCode').html('');
912                                                                 }
913                                                         }
914                                                 }
915                                         }
916                                 },
917
918                                 'makeManual' : {
919                                         type        : 'input',
920                                         id          : 'vehicleMakeManual',
921                                         title       : 'Vehicle Make',
922                                         //dataStoreId : 'makesManual',
923                                         value       : data.type ? data.type.model.make.id : '',
924                                 },
925                                 'modelManual' : {
926                                         type        : 'input',
927                                         id          : 'vehicleModelManual',
928                                         title       : 'Vehicle Model',
929                                         //dataStoreId : 'modelsManual',
930                                         value       : data.type ? data.type.model.id : '',
931                                 },
932                                 'typeManual' : {
933                                         type        : 'input',
934                                         id          : 'vehicleTypeManual',
935                                         title       : 'Vehicle Type',
936                                         //dataStoreId : 'typesManual',
937                                         value       : data.type ? data.type.id : '',
938                                 },
939
940                                 'mmCode' : {
941                                         type        : 'input',
942                                         id          : 'mmCode',
943                                         title       : 'MM Code',
944                                         style           : 'disable',
945                                         setAttrib       : 'readonly',
946                                         value       : data.type ? data.type.mmCode : ''
947                                 },
948
949                                 'stockNumber' : {
950                                         type            : 'input',
951                                         id              : 'stockNumber',
952                                         title           : 'Stock number',
953                                         value           : data.stockNumber ? data.stockNumber : ''
954                                 },
955
956                                 'fuelType' : {
957                                         type        : 'select',
958                                         id          : 'vehicleFuelType',
959                                         title       : 'Fuel Type',
960                                         dataStoreId : 'fuelTypes',
961                                         value       : data.fuelType ? data.fuelType : ''
962                                 },
963                                 'transmissionType' : {
964                                         type        : 'select',
965                                         id          : 'vehicleTransmissionType',
966                                         title       : 'Transmission Type',
967                                         dataStoreId : 'transmissionTypes',
968                                         value       : data.transmissionType ? data.transmissionType : ''
969                                 },
970                                 'condition' : {
971                                         type        : 'select',
972                                         id          : 'vehicleCondition',
973                                         title       : 'Condition',
974                                         dataStoreId : 'conditions',
975                                         value       : data.condition ? data.condition : ''
976                                 },
977                                 'exteriorColour' : {
978                                         type        : 'select',
979                                         id          : 'exteriorColour',
980                                         title       : 'Main ext. colour',
981                                         dataStoreId : 'exteriorColours',
982                                         value       : data.exteriorColour ? data.exteriorColour : ''
983                                 },
984                                 'interiorColour' : {
985                                         type  : 'select',
986                                         id    : 'interiorColour',
987                                         title : 'Main int. colour',
988                                         dataStoreId : 'interiorColours',
989                                         value : data.interiorColour ? data.interiorColour : ''
990                                 },
991                                 'upholstery' : {
992                                         type        : 'select',
993                                         id          : 'vehicleUpholstery',
994                                         title       : 'Upholstery',
995                                         dataStoreId : 'upholsteries',
996                                         value       : data.upholstery ? data.upholstery : ''
997                                 },
998                                 'papers' : {
999                                         type        : 'select',
1000                                         id          : 'vehiclePapers',
1001                                         title       : 'Papers',
1002                                         dataStoreId : 'papers',
1003                                         value       : data.papers ? data.papers : ''
1004                                 },
1005                                 'natis' : {
1006                                         type        : 'select',
1007                                         id          : 'vehicleNatis',
1008                                         title       : 'Natis',
1009                                         dataStoreId : 'natis',
1010                                         value       : data.natis ? data.natis : ''
1011                                 },
1012                                 'spareKeys' : {
1013                                         type        : 'select',
1014                                         id          : 'spareKeys',
1015                                         title       : 'Spare keys',
1016                                         dataStoreId : 'sparekeys',
1017                                         value       : undefined != data.spareKeys && null != data.spareKeys
1018                                                                         ? (data.spareKeys == true ? "1" : "0")
1019                                                                         : null
1020                                 },
1021                                 'fullServiceHistory' : {
1022                                         type        : 'select',
1023                                         id          : 'fullServiceHistory',
1024                                         title       : 'Full service history',
1025                                         dataStoreId : 'fsh',
1026                                         value       : data.fullServiceHistory ? data.fullServiceHistory : ''
1027                                 },
1028                                 'registrationNumber' : {
1029                                         type  : 'input',
1030                                         id    : 'registrationNumber',
1031                                         title : 'Registration no',
1032                                         value : data.registrationNumber ? data.registrationNumber : '',
1033                     style       : 'capitalise'
1034                                 },
1035                                 'vinNumber' : {
1036                                         type  : 'input',
1037                                         id    : 'vinNumber',
1038                                         title : 'Vin no',
1039                                         value : data.vinNumber ? data.vinNumber : '',
1040                     style       : 'capitalise'
1041                                 },
1042                                 'engineNumber' : {
1043                                         type  : 'input',
1044                                         id    : 'engineNumber',
1045                                         title : 'Eng. no',
1046                                         value : data.engineNumber ? data.engineNumber : '',
1047                     style       : 'capitalise'
1048                                 },
1049                                 'km' : {
1050                                         type  : 'input',
1051                                         id    : 'km',
1052                                         title : 'Kms',
1053                                         value : data.km ? data.km : ''
1054                                 },
1055                                 'fshNotes' : {
1056                                         type  : 'textarea-small',
1057                                         id    : 'fshNotes',
1058                                         title : 'FSH notes',
1059                                         value : data.fshNotes ? data.fshNotes : ''
1060                                 },
1061                                 'damages' : {
1062                                         type        : 'damageDetails',
1063                                         disabled        : !App.permissions.stockUpdateDamages,
1064                                         id          : 'damages',
1065                                         dataStoreId : 'damages',
1066                                         data        : data.damages ? data.damages : {}
1067                                 },
1068                                 'previousRepairsNoted' : {
1069                                         type  : 'checkbox',
1070                                         id    : 'previousRepairsNoted',
1071                                         title : 'Previous repairs',
1072                                         style : 'damages-comments',
1073                                         value : data.previousRepairsNoted ? data.previousRepairsNoted : false
1074                                 },
1075                                 'previousRepairsNotes' : {
1076                                         type  : 'textarea-styled',
1077                                         disabled        : !App.permissions.stockUpdateDamages,
1078                                         id    : 'previousRepairsNotes',
1079                                         title : 'Previous repairs notes',
1080                                         style : 'damages-comments',
1081                                         value : data.previousRepairsNotes ? data.previousRepairsNotes : '',
1082                                         onChange: function(){
1083                                                 var haveData = ('' != $(this).val() ? true : false);
1084                                                 $('#previousRepairsNoted').prop('checked', haveData);
1085                                         }
1086                                 },
1087                                 'damageTotal' : 'R 0.00',
1088                                 'damageNotes' : {
1089                                         type  : 'textarea-styled',
1090                                         disabled        : !App.permissions.stockUpdateDamages,
1091                                         id    : 'damageNotes',
1092                                         title : 'Damages comments',
1093                                         style : 'damages-comments',
1094                                         value : data.damageNotes ? data.damageNotes : ''
1095                                 },
1096                                 'coverReceived' : {
1097                                         type  : 'textarea-styled',
1098                                         disabled        : !App.permissions.stockUpdateCoverReceived,
1099                                         id    : 'coverReceived',
1100                                         title : 'Cover Received',
1101                                         style : 'cover-received',
1102                                         value : data.coverReceived ? data.coverReceived : ''
1103                                 },
1104                                 'accessories' : {
1105                                         type        : 'checkGroup',
1106                                         id          : 'accessories',
1107                                         dataStoreId : 'accessories',
1108                                         itemName    : 'accessory',
1109                                         data        : data.accessories ? data.accessories : {}
1110                                 },
1111                                 'accessoryNotes' : {
1112                                         type      : 'textarea-styled',
1113                                         id        : 'accessoryNotes',
1114                                         title     : 'Comments',
1115                                         style     : 'comment',
1116                                         areaStyle : 'comment-text-box',
1117                                         value     : data.accessoryNotes ? data.accessoryNotes : ''
1118                                 },
1119                                 'mainImage' : {
1120                                         type  : 'image',
1121                                         id    : 'mainImage',
1122                                         baseImage : 'main_img_car.jpg',
1123                                         view  : !App.permissions.stockUploadPhotos,
1124                                         value : data.mainImage ? data.mainImage : ''
1125                                 },
1126                                 'frontImage' : {
1127                                         type  : 'image',
1128                                         id    : 'frontImage',
1129                                         baseImage : 'front_car.jpg',
1130                                         view  : !App.permissions.stockUploadPhotos,
1131                                         value : data.frontImage ? data.frontImage : ''
1132                                 },
1133                                 'leftImage' : {
1134                                         type  : 'image',
1135                                         id    : 'leftImage',
1136                                         baseImage : 'left_car.jpg',
1137                                         view  : !App.permissions.stockUploadPhotos,
1138                                         value : data.leftImage ? data.leftImage : ''
1139                                 },
1140                                 'rightImage' : {
1141                                         type  : 'image',
1142                                         id    : 'rightImage',
1143                                         baseImage : 'right_car.jpg',
1144                                         view  : !App.permissions.stockUploadPhotos,
1145                                         value : data.rightImage ? data.rightImage : ''
1146                                 },
1147                                 'backImage' : {
1148                                         type  : 'image',
1149                                         id    : 'backImage',
1150                                         baseImage : 'back_car.jpg',
1151                                         view  : !App.permissions.stockUploadPhotos,
1152                                         value : data.backImage ? data.backImage : ''
1153                                 },
1154                                 'interiorImage' : {
1155                                         type  : 'image',
1156                                         id    : 'interiorImage',
1157                                         baseImage : 'interior_car.jpg',
1158                                         view  : !App.permissions.stockUploadPhotos,
1159                                         value : data.interiorImage ? data.interiorImage : ''
1160                                 },
1161                                 'engineImage' : {
1162                                         type  : 'image',
1163                                         id    : 'engineImage',
1164                                         baseImage : 'engine_car.jpg',
1165                                         view  : !App.permissions.stockUploadPhotos,
1166                                         value : data.engineImage ? data.engineImage : ''
1167                                 },
1168                                 'natisImage' : {
1169                                         type  : 'image',
1170                                         id    : 'natisImage',
1171                                         baseImage : 'copy_of_natis_car.jpg',
1172                                         view  : !App.permissions.stockUploadPhotos,
1173                                         value : data.natisImage ? data.natisImage : ''
1174                                 },
1175                                 'clubs' : {
1176                                         type        : 'select',
1177                                         id          : 'clubs',
1178                                         title       : 'Select clubs',
1179                                         dataStoreId : 'clubs',
1180                                         multiple    : true,
1181                                         value       : ''
1182                                 },
1183                                 'endDate' : {
1184                                         type  : 'date',
1185                                         id    : 'endDate',
1186                                         title : 'Auction end date',
1187                                         dtopt : {startDate: "+1d", endDate:"+" + App.serverConfig.auctionMaxDays + "d", daysOfWeekDisabled: [0], beforeShowDay: function(date) {
1188                                                 if (date.getDay() == 6 && !App.openDays[App.Util.formatDate(date, 'yyyy-mm-dd')])
1189                                                 {
1190                                                         return false;
1191                                                 }
1192                                                 for (var i = 0; i < _w.stockview.dates.length; i++)
1193                                                 {
1194                                                         if (_w.stockview.dates[i] == date.toDateString())
1195                                                         {
1196                                                                 return false;
1197                                                         }
1198                                                 }
1199                                                 return true;
1200                                         }},
1201                                         value : ''
1202                                 },
1203                                 'reservePrice' : {
1204                                         type  : 'input',
1205                                         id    : 'reservePrice',
1206                                         title : 'Reserve price',
1207                                         value : ''
1208                                 },
1209                                 'retailAmountRequired' : {
1210                                         type  : 'input',
1211                                         id    : 'retailAmountRequired',
1212                                         title : 'Minimum retail price',
1213                                         value : data.retailAmountRequired ? data.retailAmountRequired : ''
1214                                 },
1215                                 'print': {
1216                                         constructor: 'Button',
1217                                         items: {
1218                                                 Export: {
1219                                                         preset: 'Print',
1220                                                         id: 'printStockPdf',
1221                                                         handler: _w.stockview.printStockPdf
1222                                                 }
1223                                         }
1224                                 },
1225                 'printAuction': {
1226                     constructor: 'Button',
1227                     items: {
1228                         Export: {
1229                             preset: 'Print',
1230                             id: 'printStockAuctionPdf',
1231                             handler: _w.stockview.printStockAuctionPdf
1232                         }
1233                     }
1234                 },
1235                                 'complaint' : {
1236                                         type  : 'textarea-styled',
1237                                         id    : 'complaint',
1238                                         title : 'Complaint',
1239                                         value : '',
1240                                         areaStyle : 'span12',
1241                                         style : 'span10'
1242                                 },
1243
1244
1245                                 'dateCreatedPriceGuide': data.created,
1246                                 'loadedOnPriceGuide': data.loadedOnPriceGuide,
1247                                 'numberOfOffers': data.numberOfOffers,
1248                                 'highestOffer': 'R ' + data.highestOffer,
1249                                 'timesListed': data.timesListed,
1250                                 'highestBid': 'R ' + data.highestBid,
1251                                 'referenceNumber': data.referenceNumber,
1252                                 'jobState': ('Stock' == data.jobState || 'Trade Center' == data.jobState)
1253                         && data.auction
1254                         && (
1255                         data.auction.jobState == 'Undone'
1256                         || data.auction.jobState == 'Relist'
1257                         )
1258                                         ? 'Relist'
1259                                         : data.jobState,
1260
1261
1262
1263
1264                                 'tradePrice' : data.tradePrice ? 'R ' + data.tradePrice : 'R 0.00',
1265                                 'initialTradePrice' : 0.00 != data.oldTradePrice
1266                                         ? 'R ' + data.oldTradePrice + (data.oldTradePriceDate ? '<br/>' + data.oldTradePriceDate : '')
1267                                         : (data.tradePrice
1268                                                 ? 'R ' + data.tradePrice + (data.tradePriceDate ? '<br/>' + data.tradePriceDate : '')
1269                                                 : 'R 0.00'
1270                                         ),
1271                                 'updatedTradePrice' : 0.00 != data.oldTradePrice
1272                                         ? 'R ' + data.tradePrice + (data.tradePriceDate ? '<br/>' + data.tradePriceDate : '')
1273                                         : 'R 0.00',
1274                                 'retailPrice': data.retailPrice ? 'R ' + data.retailPrice : 'R 0.00',
1275
1276                 'listPrice' : data.listPrice ? 'R ' + data.listPrice : 'R 0.00',
1277
1278                         };
1279                 },
1280
1281                 printStockPdf : function()
1282                 {
1283                         App.API.getTask(
1284                                         'printStock:' + _w.stockview.itemId, 'Stock', 'Pdf.Print', _w.stockview.itemId,
1285                                         {}, function() {
1286                                                 App.API.execTask(
1287                                                                 'printStock:' + _w.stockview.itemId, {}, {},
1288                                                                 function () {}, _w.taskExecError,
1289                                                                 'EXPORT', true
1290                                                 );
1291                                         }, _w.taskContractError
1292                         );
1293                 },
1294         printStockAuctionPdf : function()
1295         {
1296             App.API.getTask(
1297                 'printStock:' + _w.stockview.itemId, 'Auction', 'Pdf.PrintPortal', _w.stockview.itemData.auction.id,
1298                 {}, function() {
1299                     App.API.execTask(
1300                         'printStock:' + _w.stockview.itemId, {}, {},
1301                         function () {}, _w.taskExecError,
1302                         'EXPORT', true
1303                     );
1304                 }, _w.taskContractError
1305             );
1306         },
1307                 loadHistoricalGrid : function( contract, data, options )
1308                 {
1309                         App.API.execTask(
1310                                         'gridStockHistory', {Grid:{Filter:{"PricingHistory.stockId":_w.stockview.itemId}}}, options,
1311                                         _w.stockview._onHistoryGridDataReceived, _w.taskExecError
1312                                         );
1313                 },
1314
1315                 _onHistoryGridDataReceived : function( response )
1316                 {
1317                         _w.stockview.gridStatus = 'Active';
1318                         _w.stockview.ti.hydrateParam('gridPricingHistoryRowRepeater', {});
1319                         var gridData = [];
1320
1321                         if (response.Data.DataSet.length == 0)
1322                         {
1323                                 $('#pricing_history_none_found').show();
1324                                 $('#PHColumnHeaders').hide();
1325                         }
1326                         else
1327                         {
1328                                 $('#pricing_history_none_found').hide();
1329                                 $('#PHColumnHeaders').show();
1330                         }
1331
1332                         for (var i = 0; i < response.Data.DataSet.length; i++)
1333                         {
1334                                 var row = response.Data.DataSet[i];
1335
1336                                 gridData.push({
1337                                         prepend: {
1338                                                 Trade                                   : 'R ',
1339                                                 TotalRecon                              : 'R ',
1340                                                 PriceguideOffer                 : 'R ',
1341                                                 AuctionWinningBid               : 'R '
1342                                         },
1343
1344                                         style: {
1345                                                 Date                                    : '',
1346                                                 Trade                                   : '',
1347                                                 TotalRecon                              : '',
1348                                                 km                                              : '',
1349                                                 PriceguideOffer                 : '',
1350                                                 AuctionWinningBid               : '',
1351
1352
1353                                         },
1354                                         items: {
1355
1356
1357                                                 'Date'                          : row.date,
1358                                                 'Trade'                         : row.trade,
1359                                                 'TotalRecon'            : row.totalRecon,
1360                                                 'KM'                            : row.km,
1361                                                 'PriceguideOffer'       : row.pricegOffer,
1362                                                 'AuctionWinningBid' : row.auctionWinningBid,
1363
1364                                 }
1365                                 });
1366                         }
1367                         _w.stockview.ti.hydrateParam('gridPricingHistoryRowRepeater', {
1368                                 constructor : 'GridDataRow',
1369                                 items       : gridData
1370                         });
1371                         //response.Data.Meta.bind = _w.stockview.pageStockGrid;
1372                 },
1373
1374                 _listMakesModelsTypes : function( callback )
1375                 {
1376
1377
1378                         if (!_w.stockview.itemData.vehicleYear)
1379                         {
1380                                 return;
1381                         }
1382                         if (_w.stockview.itemData.type
1383                                         && _w.stockview.itemData.type.category
1384                                         && _w.stockview.itemData.type.category.id)
1385                         {
1386                                 App.DataStore.loadSelectListData(
1387                                                 'makes', false, 'Stock', 'Utility.ListMakes', null,
1388                                                 {"Filter": {
1389                                                         "category" : _w.stockview.itemData.type.category.id,
1390                                                         "year" : _w.stockview.itemData.vehicleYear
1391                                                         }}, {}, $.proxy(function(categoryId)
1392                                                         {
1393                                                                 if (8 == categoryId)
1394                                                                 {
1395                                                                         var data = App.DataStore.getData('makes');
1396                                                                         data.unshift({
1397                                                                                 value: -1,
1398                                                                                 label: 'Custom'
1399                                                                         });
1400                                                                         App.DataStore.setData('makes', data);
1401                                                                 }
1402                                                         }, this, _w.stockview.itemData.type.category.id)
1403                                                 );
1404                                 if (_w.stockview.itemData.type
1405                                                 && _w.stockview.itemData.type.model
1406                                                 && _w.stockview.itemData.type.model.make
1407                                                 && _w.stockview.itemData.type.model.make.id)
1408                                 {
1409                                         App.DataStore.loadSelectListData(
1410                                                         'models', false, 'Stock', 'Utility.ListModels', null,
1411                                                         {"Filter": {
1412                                                                 "make" : _w.stockview.itemData.type.model.make.id,
1413                                                                 "category" : _w.stockview.itemData.type.category.id,
1414                                                                 "year" : _w.stockview.itemData.vehicleYear
1415                                                                 }}, {}, $.proxy(function(categoryId)
1416                                                                 {
1417                                                                         if (8 == categoryId)
1418                                                                         {
1419                                                                                 var data = App.DataStore.getData('models');
1420                                                                                 data.unshift({
1421                                                                                         value: -1,
1422                                                                                         label: 'Custom'
1423                                                                                 });
1424                                                                                 App.DataStore.setData('models', data);
1425                                                                         }
1426                                                                 }, this, _w.stockview.itemData.type.category.id)
1427                                                         );
1428                                         if (_w.stockview.itemData.type.model.id)
1429                                         {
1430                                                 App.DataStore.loadSelectListData(
1431                                                                 'types', false, 'Stock', 'Utility.ListTypes', null,
1432                                                                 {"Filter": {
1433                                                                         "model" : _w.stockview.itemData.type.model.id,
1434                                                                         "category" : _w.stockview.itemData.type.category.id,
1435                                                                         "year" : _w.stockview.itemData.vehicleYear
1436                                                                         }}, {}, $.proxy(function(categoryId, callback)
1437                                                                         {
1438                                                                                 if (8 == categoryId)
1439                                                                                 {
1440                                                                                         var data = App.DataStore.getData('types');
1441                                                                                         data.unshift({
1442                                                                                                 value: -1,
1443                                                                                                 label: 'Custom'
1444                                                                                         });
1445                                                                                         App.DataStore.setData('types', data);
1446                                                                                 }
1447                                                                                 if (callback)
1448                                                                                 {
1449                                                                                         callback();
1450                                                                                 }
1451                                                                         }, this, _w.stockview.itemData.type.category.id, callback)
1452                                                                 );
1453                                         }
1454                                 }
1455                         }
1456                 },
1457
1458                 _onDataAndTemplate : function ()
1459                 {
1460                         _w.stockview.relistReservePrice = _w.stockview.itemData.auction
1461                                                                                                 && _w.stockview.itemData.auction.reservePrice
1462                                 ? _w.stockview.itemData.auction.reservePrice
1463                                 : '';
1464                         $('#reservePrice').val(_w.stockview.relistReservePrice);
1465                         if (!_w.stockview.newItem)
1466                         {
1467                                 App.DataStore.loadSelectListData(
1468                                                         'tuhpi', false, 'Stock', 'Tuhpi.List', null,{"Filter":
1469                                                                 {
1470                                                                         "stock"                 : _w.stockview.itemId,
1471                                                                         "company"               : App.companyData.id
1472
1473                                                                 }}, {},function() {
1474                                                                  // data is retrieved
1475                                                                  var tuHpiData = App.DataStore.getData('tuhpi');
1476
1477                                 _w.stockview._loadHpiReportData(tuHpiData);
1478
1479                                                                  //for (var i = 0; i < tuHpiData.length; i++)
1480                                                                         //{
1481                                                                         //      var tuHpiId = tuHpiData[i].id
1482                                                                         //      var tuHpiCreated = tuHpiData[i].created
1483                                                                         //      //created
1484                                  //
1485                                                                         //      if (tuHpiId)
1486                                                                         //      {
1487                                                                         //              $('#tuhpiDate').html(tuHpiCreated);
1488                                                                         //              $('#downloadTuhpi').show();
1489                                                                         //              $('#HPIbtnConfirm').prop('disabled', false);
1490                                                                         //              return;
1491                                                                         //      }
1492                                                                         //      else
1493                                                                         //      {
1494                                                                         //              $('#tuhpiDate').html('Not Requested Yet');
1495                                                                         //              $('#downloadTuhpi').hide();
1496                                                                         //              $('#HPIbtnConfirm').prop('disabled', false);
1497                                                                         //      }
1498                                                                         //}
1499                                 });
1500                                 if ('Sold' == _w.stockview.itemData.jobState
1501                                         && true == _w.stockview.itemData.auction.Within30DaysOfEnd
1502                                         && App.companyData.id == _w.stockview.itemData.auction.company)
1503                                 {
1504                                         $('#btnDispute').show();
1505                                         $('#btnLogDispute').click(function() {
1506                                                 var comp = $('#complaint').val();
1507                                                 if ('' == comp)
1508                                                 {
1509                                                         alert('Please specify the complaint.');
1510                                                         return;
1511                                                 }
1512                                                 var data = {
1513                                                                 Dispute : {
1514                                                                         againstCompany : _w.stockview.itemData.auction.soldToCompany,
1515                                                                         auction        : _w.stockview.itemData.auction.id,
1516                                                                         complaint      : comp
1517                                                                 }
1518                                                 };
1519                                                 App.API.getTask(
1520                                                                 'createDispute', 'Dispute', 'Dispute.Create',
1521                                                                 null, {}, function(){
1522                                                                         App.API.execTask(
1523                                                                                         'createDispute', data, {},
1524                                                                                         function() {
1525                                                                                                 alert('Dispute logged.');
1526                                                                                                 $('#dropDsp').slideToggle();
1527                                                                                         }, function() {}
1528                                                                         );
1529                                                                 }, _w.taskContractError
1530                                                         );
1531                                         });
1532                                 }
1533                         }
1534
1535                         $('#endDate').prop('readonly', true);
1536
1537                         var total = 0.00;
1538                         $.each($.find('.rand-input'), function(i, input) {
1539                                 total += parseFloat($(input).val());
1540                         });
1541                         $('#' + _w.stockview.ti.tid + '_damageTotal').html('R ' + total);
1542                         $('#' + _w.stockview.ti.tid + '_initialTradePrice').val($('#' + _w.stockview.ti.tid + '_tradePrice').html());
1543                         $('#' + _w.stockview.ti.tid + '_updatedTradePrice').val(_w.stockview.itemData.tradePrice);
1544                         $('#retailPrice').val(_w.stockview.itemData.retailPrice);
1545                         $('#tradePrice').val(_w.stockview.itemData.tradePrice);
1546             $('#listPrice').val(_w.stockview.itemData.listPrice);
1547                         if ('Archived' == _w.stockview.itemData.jobState)
1548                         {
1549                                 true == App.permissions.stockUnarchive ? $('#btnUnarchive').show() : $('#btnUnarchive').hide();
1550                         }
1551                         if ('Retail' == _w.stockview.itemData.jobState)
1552                         {
1553                                 true == App.permissions.stockReclaimRetail ? $('#btnReclaimFromRetail').show() : $('#btnReclaimFromRetail').hide();
1554                         }
1555
1556                         /*
1557                          * Permissions
1558                          */
1559                         if ('Stock' == _w.stockview.itemData.jobState || _w.stockview.newItem)
1560                         {
1561                                 true == App.permissions.stockUpdate ? $('#btnUpdate').show() : $('#btnUpdate').hide();
1562                                 true == App.permissions.stockRouteRetail && !_w.stockview.newItem ? $('#optSendToRetail').show() : $('#optSendToRetail').hide();
1563                                 true == App.permissions.stockRoutePriceguide ? $('#optSendToPg').show() : $('#optSendToPg').hide();
1564                                 if (true == App.permissions.stockRouteAuction)
1565                                 {
1566                                         App.companyData.tC
1567                                                 ? $('#btnSendToTc').show()
1568                                                 : $('#optSendToAction').show();
1569                                         if (_w.stockview.newItem)
1570                                         {
1571                                                 $('#btnSendToTc').hide();
1572                                         }
1573                                 }
1574                                 else
1575                                 {
1576                                         $('#optSendToAction').hide();
1577                                 }
1578                                 true == App.permissions.stockArchive ? $('#btnArchive').show() : $('#btnArchive').hide();
1579                         }
1580                         if ('Auction' == _w.stockview.itemData.jobState)
1581                         {
1582                                 (true == App.permissions.stockUpdate && "0.00" == _w.stockview.itemData.highestBid) ? $('#btnUpdate').show() : $('#btnUpdate').hide();
1583                                 $('#btnSendToTc').hide();
1584                                 $('#optSendToAction').hide();
1585                                 $('#optSendToRetail').hide();
1586                                 $('#optSendToPg').hide();
1587                                 $('#btnArchive').hide();
1588                         }
1589             if ('Relist' == _w.stockview.itemData.jobState)
1590             {
1591                 (true == App.permissions.stockUpdate && "0.00" == _w.stockview.itemData.highestBid) ? $('#btnUpdate').show() : $('#btnUpdate').hide();
1592                 $('#btnSendToTc').hide();
1593                 $('#optSendToAction').hide();
1594                 $('#optSendToRetail').hide();
1595                 $('#optSendToPg').hide();
1596                 $('#btnArchive').show();
1597             }
1598
1599                         true == App.permissions.stockPrint ? $('#printStockPdf').show() : $('#printStockPdf').hide();
1600                         true == App.permissions.stockB4cReport ? $('#btnB4cAccidentReport').show() : $('#btnB4cAccidentReport').hide();
1601                         true == App.permissions.stockBmw ? $('#btnBwmAccidentReport').show() : $('#btnBwmAccidentReport').hide();
1602
1603                         if (!App.permissions.pgPage && !App.permissions.auctionPag)
1604                         {
1605                                 $('.pg-a-data-wrapper').hide();
1606                         }
1607                         if (true == App.permissions.pgPage) { $('.price-guide-info').show(); };
1608                         if (true == App.permissions.auctionPage) { $('.auction-info').show(); };
1609
1610                         if (App.permissions.settingsHpiReport == false)
1611                         {
1612                                 $('#requestHPIreport').hide();
1613                 $('#requestHPIAccidentReport').hide();
1614                         }
1615
1616                         if (_w.stockview.newItem)
1617                         {
1618                                 $('.info-block').hide();
1619                                 $('#optSendToPg').hide();
1620                                 $('#printStockPdf').hide();
1621                                 $('#btnArchive').hide();
1622
1623                                 //HPI Report Hide on New
1624                                 $('#requestHPIreport').hide();
1625                 $('#requestHPIAccidentReport').hide();
1626                                 $('.hpiReport').hide();
1627                         }
1628                         else
1629                         {
1630                                 if (App.permissions.settingsHpiReport)
1631                                 {
1632                                         $('#requestHPIreport').show();
1633                     $('#requestHPIAccidentReport').show();
1634                                 }
1635                                 if (null == App.API.taskContract('gridStockHistory'))
1636                                 {
1637                                         App.API.getTask(
1638                                                         'gridStockHistory', 'Stock', 'PricingHistory.Grid', null,
1639                                                         {}, _w.stockview.loadHistoricalGrid, _w.taskContractError
1640                                                         );
1641                                         $('#pricing_history_none_found').hide();
1642                                         $('#PHColumnHeaders').hide();
1643                                 }
1644                                 else
1645                                 {
1646                                         _w.stockview.loadHistoricalGrid( null, {}, {} );
1647                                 }
1648                         }
1649
1650             if ('Sold' == _w.stockview.itemData.jobState)
1651             {
1652                 $('.printStockPdf').addClass('hide');
1653                 $('.printStockAuctionPdf').removeClass('hide');
1654             }
1655
1656                         _w.stockview._setupValidation();
1657                 },
1658
1659                 _onStockViewDataReceived : function( response )
1660                 {
1661                         _w.stockview.itemId = response.Data.id;
1662                         _w.stockview.itemData = response.Data;
1663                         _w.stockview._listMakesModelsTypes();
1664                         _w.stockview.setStockViewFormMeta(response.Data);
1665                         _w.stockview.ti.hydrate(_w.stockview.formMeta);
1666                         if (_w.stockview.ti.published)
1667                         {
1668                                 _w.stockview._onDataAndTemplate();
1669                         }
1670                         App.DataStore.loadSelectListGroup([
1671                {dataId: 'years', isStatic: true, workspace: 'Stock', task: 'Year.SelectList'},
1672                {dataId: 'categories', isStatic: true, workspace: 'Stock', task: 'Category.SelectList'},
1673                {dataId: 'conditions', isStatic: true, workspace: 'Stock', task: 'Condition.SelectList'},
1674                {dataId: 'exteriorColours', isStatic: true, workspace: 'Stock', task: 'ExteriorColour.SelectList'},
1675                {dataId: 'interiorColours', isStatic: true, workspace: 'Stock', task: 'InteriorColour.SelectList'},
1676                {dataId: 'upholsteries', isStatic: true, workspace: 'Stock', task: 'Upholstery.SelectList'},
1677                {dataId: 'papers', isStatic: true, workspace: 'Stock', task: 'Paper.SelectList'},
1678                {dataId: 'natis', isStatic: true, workspace: 'Stock', task: 'Natis.SelectList'},
1679                {dataId: 'fsh', isStatic: true, workspace: 'Stock', task: 'FullServiceHistory.SelectList'},
1680                {dataId: 'fuelTypes', isStatic: true, workspace: 'Stock', task: 'FuelType.SelectList'},
1681                {dataId: 'transmissionTypes', isStatic: true, workspace: 'Stock', task: 'TransmissionType.SelectList'},
1682                {dataId: 'damages', isStatic: true, workspace: 'Stock', task: 'Damage.SelectList'},
1683                {dataId: 'accessories', isStatic: true, workspace: 'Stock', task: 'Accessory.SelectList'},
1684                {dataId: 'clubs', isStatic: true, workspace: 'PriceGuide', task: 'Club.SelectList'}
1685             ]);
1686                 },
1687
1688                 _setupValidation : function ()
1689                 {
1690                         App.DataStore.listen('regValidation', 'damages', function(id, damages) {
1691                                 var rules = {
1692                                         mainImage: "required",
1693                                         vehicleYear: "required",
1694                                         vehicleCategory: "required",
1695
1696                                         //category
1697
1698                                         vehicleMake: { required: function(){
1699                                                 return $('#vehicleMake').parent().css('display') != 'none';
1700                                         } },
1701                                         vehicleModel: { required: function(){
1702                                                 return $('#vehicleModel').parent().css('display') != 'none';
1703                                         } },
1704                                         vehicleType: { required: function(){
1705                                                 return $('#vehicleType').parent().css('display') != 'none';
1706                                         } },
1707
1708                                         stockNumber: "required",
1709
1710                                         vehicleMakeManual: { required: function(){
1711                                                 return $('#vehicleMakeManual').parent().parent().css('display') != 'none';
1712                                         } },
1713                                         vehicleModelManual: { required: function(){
1714                                                 return $('#vehicleModelManual').parent().parent().css('display') != 'none';
1715                                         } },
1716                                         vehicleTypeManual: { required: function(){
1717                                                 return $('#vehicleTypeManual').parent().parent().css('display') != 'none';
1718                                         } },
1719
1720                                         vehicleFuelType: "required",
1721                                         vehicleTransmissionType: "required",
1722                                         registrationNumber: "required",
1723                                         km: { required: true, digits: true }
1724                                 };
1725                                 for (var i = 0; i < damages.length; i++)
1726                                 {
1727                                         rules['damage' + damages[i].value + 'Amount'] = {number: true};
1728                                 }
1729
1730                                 $('#frmStockView').validate({
1731                                         "rules": rules,
1732                                         messages: {
1733                                                 mainImage : "This field is required.",
1734                                                 vehicleYear : "This field is required.",
1735                                                 vehicleCategory : "This field is required.",
1736                                                 vehicleMake : "This field is required.",
1737                                                 vehicleModel : "This field is required.",
1738                                                 stockNumber : "This field is required.",
1739                                                 vehicleType : "This field is required.",
1740
1741                                                 vehicleMakeManual : "This field is required.",
1742                                                 vehicleModelManual : "This field is required.",
1743                                                 vehicleTypeManual : "This field is required.",
1744
1745                                                 vehicleFuelType : "This field is required.",
1746                                                 vehicleTransmissionType : "This field is required.",
1747                                                 registrationNumber : "This field is required.",
1748                                                 km : {required: "This field is required."}
1749                                         },
1750                                         invalidHandler: function(event, validator) {
1751                                             var errors = validator.numberOfInvalids();
1752                                             if (0 < _w.stockview.validations && errors)
1753                                             {
1754                                                       var message = errors == 1
1755                                                         ? 'You missed 1 field. It has been highlighted'
1756                                                         : 'You missed ' + errors + ' fields. They have been highlighted';
1757                                                       alert(message);
1758                                                 }
1759                                             _w.stockview.validations++;
1760                                         },
1761                                         submitHandler: function( form ) {
1762                                                 $('#btnUpdate').prop('disabled', true);
1763                                                 var data = _w.stockview._prepStockUpdateData();
1764                                                 if (_w.stockview.newItem)
1765                                                 {
1766                                                         App.API.execTask(
1767                                                                         'createStock', {"Stock":data}, {},
1768                                                                         _w.stockview._onStockUpdated, _w.taskExecError
1769                                                                         );
1770                                                 }
1771                                                 else
1772                                                 {
1773                                                         App.API.execTask(
1774                                                                         'updateStock:' + _w.stockview.itemId, {"Stock":data}, {},
1775                                                                         _w.stockview._onStockUpdated, _w.taskExecError
1776                                                                         );
1777                                                 }
1778                                         }
1779                                 });
1780                                 $('#btnUpdate').prop('disabled', false);
1781
1782                                 try {
1783                                         _w.stockview.validations = 0;
1784                                         $('#frmStockView').valid();
1785                                 } catch(err) {}
1786                                 $('label.error').remove();
1787                                 $('.valid').removeClass('valid');
1788                         });
1789                 },
1790
1791                 _onTuTcUpdateReady : function ()
1792                 {
1793                         App.API.execTask(
1794                                         'TransUnionFromMmCode', {
1795                                                 Filter : {
1796                                                         vehicleYear : parseInt($('#vehicleYear').val()),
1797                                                         type : parseInt($('#vehicleType').val()),
1798                                                         stockId : _w.stockview.itemId
1799                                                 }
1800                                 }, {},
1801                                 _w.stockview._onTuTcUpdateReceived, function(){}
1802                         );
1803                 },
1804
1805                 _onTuTcUpdateReceived : function ( response )
1806                 {
1807                         if ('Success' != response.Data.Status)
1808                         {
1809                                 App.API.execTask(
1810                                                 'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
1811                                                 function () {
1812                                                         App.API.directRoute(
1813                                                                         'tcStock:' + _w.stockview.itemId,
1814                                                                         'Stock', 'Stock.SendToTradeCenter', _w.stockview.itemId, {},
1815                                                                         _w.stockview._onStockUpdated, _w.taskExecError
1816                                                                         );
1817                                                 }, _w.taskExecError
1818                                 );
1819                                 return;
1820                         }
1821                         var vals = response.Data.VehicleDetails[0].Value;
1822                         $('#retailPrice').val(vals.RetailPrice);
1823                         $('#tradePrice').val(vals.TradePrice);
1824             $('#listPrice').val(vals.NewPrice);
1825                         $('#' + _w.stockview.ti.tid + '_retailPrice').html('R ' + vals.RetailPrice + '.00');
1826                         $('#' + _w.stockview.ti.tid + '_tradePrice').html('R ' + vals.TradePrice + '.00');
1827             $('#' + _w.stockview.ti.tid + '_listPrice').html('R ' + vals.NewPrice + '.00');
1828                         App.API.execTask(
1829                                         'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
1830                                         function () {
1831                                                 App.API.directRoute(
1832                                                                 'tcStock:' + _w.stockview.itemId,
1833                                                                 'Stock', 'Stock.SendToTradeCenter', _w.stockview.itemId, {},
1834                                                                 _w.stockview._onStockUpdated, _w.taskExecError
1835                                                                 );
1836                                         }, _w.taskExecError
1837                         );
1838                 },
1839
1840                 _onTuUpdateReady : function ()
1841                 {
1842                         App.API.execTask(
1843                                         'TransUnionFromMmCode', {
1844                                                 Filter : {
1845                                                         vehicleYear : parseInt($('#vehicleYear').val()),
1846                                                         type : parseInt($('#vehicleType').val()),
1847                                                         stockId : _w.stockview.itemId
1848                                                 }
1849                                 }, {},
1850                                 _w.stockview._onTuUpdateReceived, function(){}
1851                         );
1852                 },
1853
1854                 _onTuUpdateReceived : function ( response )
1855                 {
1856                         if ('Success' != response.Data.Status)
1857                         {
1858                                 App.API.execTask(
1859                                                 'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
1860                                                 function () {
1861                                                         App.API.getRoute(
1862                                                                         'sendToAuction:' + _w.stockview.itemId, 'Stock', 'Stock.SendToAuction', _w.stockview.itemId,
1863                                                                         {}, function() {
1864                                                                                 var endDate = $('#endDate').val();
1865                                                                                 var reservePrice = $('#reservePrice').val();
1866                                                                                 App.API.execRoute(
1867                                                                                                 'sendToAuction:' + _w.stockview.itemId, {Context: {endDate: endDate, reservePrice: reservePrice}}, {},
1868                                                                                                 _w.stockview._onStockUpdated, _w.taskExecError
1869                                                                                 );
1870                                                                         }, _w.taskContractError
1871                                                         );
1872                                                 }, _w.taskExecError
1873                                 );
1874                                 return;
1875                         }
1876                         var vals = response.Data.VehicleDetails[0].Value;
1877                         $('#retailPrice').val(vals.RetailPrice);
1878                         $('#tradePrice').val(vals.TradePrice);
1879             $('#listPrice').val(vals.NewPrice);
1880                         $('#' + _w.stockview.ti.tid + '_retailPrice').html('R ' + vals.RetailPrice + '.00');
1881                         $('#' + _w.stockview.ti.tid + '_tradePrice').html('R ' + vals.TradePrice + '.00');
1882             $('#' + _w.stockview.ti.tid + '_listPrice').html('R ' + vals.NewPrice + '.00');
1883                         App.API.execTask(
1884                                         'updateStock:' + _w.stockview.itemId, {"Stock":_w.stockview._prepStockUpdateData()}, {},
1885                                         function () {
1886                                                 App.API.getRoute(
1887                                                                 'sendToAuction:' + _w.stockview.itemId, 'Stock', 'Stock.SendToAuction', _w.stockview.itemId,
1888                                                                 {}, function() {
1889                                                                         var endDate = $('#endDate').val();
1890                                                                         var reservePrice = $('#reservePrice').val();
1891                                                                         App.API.execRoute(
1892                                                                                         'sendToAuction:' + _w.stockview.itemId, {Context: {endDate: endDate, reservePrice: reservePrice}}, {},
1893                                                                                         _w.stockview._onStockUpdated, _w.taskExecError
1894                                                                         );
1895                                                                 }, _w.taskContractError
1896                                                 );
1897                                         }, _w.taskExecError
1898                         );
1899                 },
1900
1901                 _onTuReady : function ()
1902                 {
1903                         App.API.execTask(
1904                                         'TransUnionFromMmCode', {
1905                                                 Filter : {
1906                                                         vehicleYear : parseInt($('#vehicleYear').val()),
1907                                                         type : parseInt($('#vehicleType').val())
1908                                                 }
1909                                 }, {},
1910                                 _w.stockview._onTuReceived, function(){alert('There were no trade and retail from TransUnion');}
1911                         );
1912                 },
1913
1914                 _onTuReceived : function ( response )
1915                 {
1916                         if ('Success' != response.Data.Status)
1917                         {
1918                                 if ('No Results From TransUnion' == response.Data.Status || 'No Values From TransUnion' == response.Data.Status) {
1919                                         //write zero values for transunion failed
1920                                         var vals = 0.00;
1921                                         $('#retailPrice').val(vals);
1922                                         $('#tradePrice').val(vals);
1923                                         $('#listPrice').val(vals);
1924                                         $('#' + _w.stockview.ti.tid + '_retailPrice').html(vals);
1925                                         $('#' + _w.stockview.ti.tid + '_tradePrice').html(vals);
1926                                         $('#' + _w.stockview.ti.tid + '_listPrice').html(vals);
1927                                 }
1928                                 alert(response.Data.Status);
1929                                 return;
1930                         }
1931                         var vals = response.Data.VehicleDetails[0].Value;
1932                         $('#retailPrice').val(vals.RetailPrice);
1933                         $('#tradePrice').val(vals.TradePrice);
1934             $('#listPrice').val(vals.NewPrice);
1935                         $('#' + _w.stockview.ti.tid + '_retailPrice').html('R ' + vals.RetailPrice + '.00');
1936                         $('#' + _w.stockview.ti.tid + '_tradePrice').html('R ' + vals.TradePrice + '.00');
1937             $('#' + _w.stockview.ti.tid + '_listPrice').html('R ' + vals.NewPrice + '.00');
1938                 },
1939
1940                 _prepStockUpdateData : function()
1941                 {
1942                         var data = _w.stockview.ti.harvest();
1943                         data.km = '' == data.km
1944                                 ? 0
1945                                 : parseInt(data.km);
1946                         var retailPrice = $('#retailPrice').val();
1947                         var tradePrice  = $('#tradePrice').val();
1948             var listPrice  = $('#listPrice').val();
1949                         var retailAmountRequired  = $('#retailAmountRequired').val();
1950                         data.retailPrice = ('' == retailPrice)
1951                                 ? 0.00
1952                                 : parseFloat(retailPrice);
1953                         data.tradePrice = ('' == tradePrice)
1954                                 ? 0.00
1955                                 : parseFloat(tradePrice);
1956             data.listPrice = ('' == listPrice)
1957                 ? 0.00
1958                 : parseFloat(listPrice);
1959                         data.retailAmountRequired = ('' == retailAmountRequired)
1960                                 ? 0.00
1961                                 : parseFloat(retailAmountRequired);
1962                         delete data.damageTotal;
1963                         if (-1 == data.make)
1964                         {
1965                                 delete data.make;
1966                                 delete data.model;
1967                                 delete data.type;
1968                         }
1969                         if (-1 == data.model)
1970                         {
1971                                 delete data.model;
1972                                 delete data.type;
1973                         }
1974                         if (-1 == data.type)
1975                         {
1976                                 delete data.type;
1977                         }
1978                         if ('' == data.mainImage)
1979                         {
1980                                 delete data.mainImage;
1981                         }
1982                         if ('' == data.leftImage)
1983                         {
1984                                 delete data.leftImage;
1985                         }
1986                         if ('' == data.backImage)
1987                         {
1988                                 delete data.backImage;
1989                         }
1990                         if ('' == data.engineImage)
1991                         {
1992                                 delete data.engineImage;
1993                         }
1994                         if ('' == data.frontImage)
1995                         {
1996                                 delete data.frontImage;
1997                         }
1998                         if ('' == data.rightImage)
1999                         {
2000                                 delete data.rightImage;
2001                         }
2002                         if ('' == data.interiorImage)
2003                         {
2004                                 delete data.interiorImage;
2005                         }
2006                         if ('' == data.natisImage)
2007                         {
2008                                 delete data.natisImage;
2009                         }
2010                         delete data.clubs;
2011                         return data;
2012                 },
2013
2014                 _onStockUpdated : function( response )
2015                 {
2016                         window.location.hash = '/stock';
2017                 },
2018         _onHpiDownloadButtonClick: function (event)
2019         {
2020             //console.log('event.currentTarget.dataset',event.currentTarget.dataset);
2021
2022             var hpiType = event.currentTarget.dataset.value;
2023             var hpiId = event.currentTarget.dataset.id;
2024
2025             //console.log('hpiId',hpiId);
2026             //console.log('hpiType',hpiType);
2027
2028             if('ACC' == hpiType)
2029             {
2030                 App.API.getTask(
2031                     'printTuhpiAccident:' + _w.stockview.itemId, 'Stock', 'Tuhpi.PrintAccident', _w.stockview.itemId,
2032                     {'PdfTemplate':{'recordId':hpiId}}, function () {
2033                         App.API.execTask(
2034                             'printTuhpiAccident:' + _w.stockview.itemId, {}, {},
2035                             function () {
2036                             }, _w.taskExecError,
2037                             'EXPORT', true
2038                         );
2039                     }, _w.taskContractError
2040                 );
2041             }
2042             else
2043             {
2044                 App.API.getTask(
2045                     'printTuhpi:' + _w.stockview.itemId, 'Stock', 'Tuhpi.Print', _w.stockview.itemId,
2046                     {'PdfTemplate':{'recordId':hpiId}}, function () {
2047                         App.API.execTask(
2048                             'printTuhpi:' + _w.stockview.itemId, {}, {},
2049                             function () {
2050                             }, _w.taskExecError,
2051                             'EXPORT', true
2052                         );
2053                     }, _w.taskContractError
2054                 );
2055
2056             }
2057
2058         },
2059         _loadHpiReportData: function (hpiData) {
2060             var tuHpiData = hpiData;
2061
2062             if (0 < tuHpiData.length) {
2063                 $('#HPIreportData').html('');
2064                 var tuHpiId = '';
2065                 var tuHpiCreated = '';
2066                 var tuHpiType = '';
2067                 var tuHpiButtonType = '';
2068             }
2069
2070             for (var i = 0; i < tuHpiData.length; i++) {
2071                 if (3 > i) {
2072
2073                     tuHpiId = tuHpiData[i].id;
2074                     tuHpiCreated = tuHpiData[i].created;
2075                     tuHpiType = tuHpiData[i].hpi_type;
2076                     tuHpiButtonType = tuHpiData[i].hpi_type;
2077
2078                     var hpiDataHtml = '<div class="control-group mobile-control-group row-fluid" style="display: block;border:1px solid #d3d3d3;" id="' + i + '">'
2079                         + '<div class="control-group mobile-control-group span4" style="padding-left:10px; padding-top:13px;">Last date requested:</div>'
2080                         + '<div class="control-group mobile-control-group span4" style="padding-left:10px;border-left:1px solid #d3d3d3; padding-top:13px;">'
2081                         + '<div id="tuhpiDate_' + i + '" class="span9">Not requested yet.</div>'
2082                         + '</div>'
2083                         + '<div class="control-group mobile-control-group span4" style="padding-left:10px;border-left:1px solid #d3d3d3; padding-top:13px;">'
2084                         + '<div id="tuhpiType_' + i + '" class="span8">Not requested yet.</div>'
2085                         + '<div class="span4">'
2086                         + '<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>'
2087                         + '</div>'
2088                         + '</div>'
2089                         + '</div>';
2090
2091                     $('#HPIreportData').append(hpiDataHtml);
2092
2093                     if (tuHpiId) {
2094                         $('#tuhpiDate_' + i).html(tuHpiCreated);
2095                         $('#tuhpiType_' + i).html(tuHpiType);
2096                         $('#downloadTuhpi').show();
2097                         $('#HPIbtnConfirm').prop('disabled', false);
2098                     }
2099                     else {
2100                         $('#tuhpiDate_' + i).html('Not Requested Yet');
2101                         $('#tuhpiType_' + i).html('Not Requested Yet');
2102                         $('#downloadTuhpi').hide();
2103                     }
2104
2105
2106                     $('#downloadTuhpi_' + tuHpiId).click(function (event) {
2107                         _w.stockview._onHpiDownloadButtonClick(event);
2108                     });
2109
2110                 }
2111             }
2112         }
2113     };
2114
2115
2116 })();