click to refresh issue
[namibia] / public / js / app / util.js
1 ;
2 (function () {
3
4         _App.Util = function ()
5         {
6                 this.initialize();
7         };
8
9         _App.Util.prototype =
10         {
11
12                 startupTime: 0,
13                 theSecond: -1,
14
15                 initialize: function ()
16                 {
17                         this.startupTime = this.unixTimestamp();
18                 },
19
20                 unixTimestamp: function ()
21                 {
22                         return Math.round((new Date().getTime() / 1000));
23                 },
24
25                 getUrlParam: function (name)
26                 {
27                         hashLoc = window.location.hash.split("?");
28                         return decodeURI(
29                                 (RegExp(name + '=' + '(.+?)(&|$)').exec(hashLoc[1]) || [, null])[1]
30                         );
31                 },
32
33                 ie: (function ()
34                 {
35                         var undef,
36                             v   = 3,
37                             div = document.createElement('div'),
38                             all = div.getElementsByTagName('i');
39                         while (
40                                 div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
41                                         all[0]
42                                 )
43                         {
44                                 ;
45                         }
46                         return v > 4
47                                 ? v
48                                 : undef;
49                 }()),
50
51                 updateCheckboxStyle: function ($_checkbox)
52                 {
53                         if ($_checkbox.hasClass('no-mod'))
54                         {
55                                 return;
56                         }
57                         var label = $_checkbox.parent('label');
58                         if (label.length)
59                         {
60                                 $(label).addClass('checkbox');
61                         }
62                         else
63                         {
64                                 $_checkbox.wrap('<label class="checkbox"/>');
65                         }
66                         $('<span class="styled-checkbox" />').insertAfter($_checkbox);
67                         if (!!this.ie && this.ie < 9)
68                         {
69                                 $_checkbox.set_checked = function () {
70                                         if (this.checked)
71                                         {
72                                                 form.find('input[name="' + this.name + '"] + span').removeClass('checked');
73                                                 $(this).next('span').addClass('checked').blur();
74                                         }
75                                 };
76                                 $_checkbox.set_checked();
77                                 $_checkbox.bind('change', function () {
78                                         this.set_checked();
79                                 });
80                         }
81                         if ($_checkbox.value == 'on')
82                         {
83                                 $_checkbox.value = true;
84                         }
85                 },
86
87                 updateCheckboxStyles: function (form)
88                 {
89                         var $$_checkboxes = form.find('input[type=checkbox]');
90                         $.each($$_checkboxes, function (i, checkbox) {
91                                 var $_checkbox = $(checkbox);
92                                 if ($_checkbox.hasClass('no-mod'))
93                                 {
94                                         return;
95                                 }
96                                 var label = $_checkbox.parent('label');
97                                 if (label.length)
98                                 {
99                                         $(label).addClass('checkbox');
100                                 }
101                                 else
102                                 {
103                                         $_checkbox.wrap('<label class="checkbox"/>');
104                                 }
105                                 $('<span class="styled-checkbox" />').insertAfter($_checkbox);
106                                 if (!!this.ie && this.ie < 9)
107                                 {
108                                         checkbox.set_checked = function () {
109                                                 if (this.checked)
110                                                 {
111                                                         form.find('input[name="' + this.name + '"] + span').removeClass('checked');
112                                                         $(this).next('span').addClass('checked').blur();
113                                                 }
114                                         };
115                                         checkbox.set_checked();
116                                         $_checkbox.bind('change', function () {
117                                                 this.set_checked();
118                                         });
119                                 }
120                                 if (checkbox.value == 'on')
121                                 {
122                                         checkbox.value = true;
123                                 }
124                         });
125                 },
126
127                 updateTimeLeft: function ()
128                 {
129                         $('.time-left-dynamic').each(function()
130                         {
131                                 var value = $(this).attr('data-value');
132                                 var numDays = $(this).attr('data-days');
133                                 var endDate = $(this).attr('data-date');
134                                 $(this).html(
135                                         App.Util.calculateTimeLeft(
136                                                 value,
137                                                 numDays,
138                                                 endDate,
139                                                 true
140                                         )
141                                 );
142                         });
143                 },
144
145                 calculateTimeLeft: function (value, numDays, endDate, isUpdate)
146                 {
147                         var dateTime  = value.split(' '),
148                             date      = dateTime[0],
149                             time      = dateTime[1],
150                             dateParts = date.split('-').map(function (part) {
151                                     return parseInt(part, 10);
152                             }),
153                             timeParts = time.split(':').map(function (part) {
154                                     return parseInt(part, 10);
155                             });
156                         var timeObject = new Date();
157                         var currentDateTime = new Date(timeObject.getTime() - (1000 * App.timeDiff));
158                         if (endDate)
159                         {
160                                 var dateTime  = endDate.split(' '),
161                                     date      = dateTime[0],
162                                     time      = dateTime[1],
163                                     dateParts = date.split('-').map(function (part) {
164                                             return parseInt(part, 10);
165                                     }),
166                                     timeParts = time.split(':').map(function (part) {
167                                             return parseInt(part, 10);
168                                     });
169                                 var expireDateTime = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
170                         }
171                         else
172                         {
173                                 var dateTime  = value.split(' '),
174                                     date      = dateTime[0],
175                                     time      = dateTime[1],
176                                     dateParts = date.split('-').map(function (part) {
177                                             return parseInt(part, 10);
178                                     }),
179                                     timeParts = time.split(':').map(function (part) {
180                                             return parseInt(part, 10);
181                                     });
182                                 var expireDateTime = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
183                                 expireDateTime.setDate(expireDateTime.getDate() + parseInt(numDays));
184                         }
185                         var difference = expireDateTime.getTime() - currentDateTime.getTime();
186                         var daysDifference, hoursDifference, minutesDifference;
187
188                         daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
189                         difference -= daysDifference * 1000 * 60 * 60 * 24;
190                         hoursDifference = Math.floor(difference / 1000 / 60 / 60);
191                         difference -= hoursDifference * 1000 * 60 * 60;
192                         minutesDifference = Math.floor(difference / 1000 / 60);
193
194                         if (expireDateTime.getTime() < currentDateTime.getTime())
195                         {
196                                 return '0m';
197                         }
198
199                         var result = daysDifference > 0
200                                 ? daysDifference + 'd, ' + hoursDifference + 'h, ' + minutesDifference + 'm'
201                                 : hoursDifference + 'h, ' + minutesDifference + 'm';
202                         if (isUpdate)
203                         {
204                                 return result;
205                         }
206                         return '<span class="time-left-dynamic" '
207                                + 'data-value="' + value + '" '
208                                + 'data-days="' + numDays + '" '
209                                + 'data-date="' + endDate + '">'
210                                + result + '</span>';
211                 },
212
213                 calculateTimeLeftHours: function (value, numHours)
214                 {
215                         var dateTime  = value.split(' '),
216                             date      = dateTime[0],
217                             time      = dateTime[1],
218                             dateParts = date.split('-').map(function (part) {
219                                     return parseInt(part, 10);
220                             }),
221                             timeParts = time.split(':').map(function (part) {
222                                     return parseInt(part, 10);
223                             });
224                         var timeObject = new Date();
225                         var currentDateTime = new Date(timeObject.getTime() - (1000 * App.timeDiff));
226                         var expireDateTime = new Date(dateParts[0], dateParts[1] - 1, dateParts[2], timeParts[0], timeParts[1], timeParts[2]);
227                         var addSeconds = expireDateTime.setSeconds(expireDateTime.getSeconds() + numHours * 3600);
228                         expireDateTime = new Date(expireDateTime.getSeconds() + addSeconds);
229                         //console.log('expireDateTime2',expireDateTime2 ) ;
230                         var difference = expireDateTime.getTime() - currentDateTime.getTime();
231                         var daysDifference, hoursDifference, minutesDifference;
232
233                         daysDifference = Math.floor(difference / 1000 / 60 / 60 / 24);
234                         difference -= daysDifference * 1000 * 60 * 60 * 24;
235                         hoursDifference = Math.floor(difference / 1000 / 60 / 60);
236                         difference -= hoursDifference * 1000 * 60 * 60;
237                         minutesDifference = Math.floor(difference / 1000 / 60);
238                         difference -= minutesDifference * 1000 * 60;
239
240                         if (expireDateTime.getTime() < currentDateTime.getTime())
241                         {
242                                 return '0m';
243                         }
244
245                         return daysDifference > 0
246                                 ? ((daysDifference * 2) + hoursDifference) + 'h, ' + minutesDifference + 'm'
247                                 : hoursDifference + 'h, ' + minutesDifference + 'm';
248
249                         /*? daysDifference + 'd, ' + hoursDifference + 'h, ' + minutesDifference + 'm'
250                          : hoursDifference + 'h, ' + minutesDifference + 'm';*/
251                 },
252
253                 updateClock: function ()
254                 {
255                         var timeObject = new Date();
256                         var currentTime = new Date(timeObject.getTime() - (1000 * App.timeDiff));
257                         var currentHours = currentTime.getHours();
258                         var currentMinutes = currentTime.getMinutes();
259                         var currentSeconds = currentTime.getSeconds();
260                         currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
261                         currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
262                         currentHours = ( currentHours == 0 ) ? 12 : currentHours;
263                         var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds;
264                         $("#clock").html(currentTimeString);
265                         $("#clockmobi").html(currentTimeString);
266                         if (parseInt(currentSeconds) < App.Util.theSecond)
267                         {
268                                 App.Util.updateTimeLeft();
269                         }
270                         App.Util.theSecond = parseInt(currentSeconds);
271                 },
272
273                 setCookie: function (name, value, days)
274                 {
275                         if (days)
276                         {
277                                 var date = new Date();
278                                 date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
279                                 var expires = "; expires=" + date.toGMTString();
280                         }
281                         else
282                         {
283                                 var expires = "";
284                         }
285                         document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
286                 },
287
288                 getCookie: function (name, defaultValue)
289                 {
290                         var nameEQ = escape(name) + "=";
291                         var ca = document.cookie.split(';');
292                         for (var i = 0; i < ca.length; i++)
293                         {
294                                 var c = ca[i];
295                                 while (c.charAt(0) == ' ')
296                                 {
297                                         c = c.substring(1, c.length);
298                                 }
299                                 if (c.indexOf(nameEQ) == 0)
300                                 {
301                                         return unescape(c.substring(nameEQ.length, c.length));
302                                 }
303                         }
304                         return undefined == defaultValue
305                                 ? null
306                                 : defaultValue;
307                 },
308
309                 formatDate: function (formatDate, formatString)
310                 {
311                         if (formatDate instanceof Date)
312                         {
313                                 var months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
314                                 var yyyy = formatDate.getFullYear();
315                                 var yy = yyyy.toString().substring(2);
316                                 var m = formatDate.getMonth() + 1;
317                                 var mm = m < 10 ? "0" + m : m;
318                                 var mmm = months[m];
319                                 var d = formatDate.getDate();
320                                 var dd = d < 10 ? "0" + d : d;
321
322                                 var h = formatDate.getHours();
323                                 var hh = h < 10 ? "0" + h : h;
324                                 var n = formatDate.getMinutes();
325                                 var nn = n < 10 ? "0" + n : n;
326                                 var s = formatDate.getSeconds();
327                                 var ss = s < 10 ? "0" + s : s;
328
329                                 formatString = formatString.replace(/yyyy/i, yyyy);
330                                 formatString = formatString.replace(/yy/i, yy);
331                                 formatString = formatString.replace(/mmm/i, mmm);
332                                 formatString = formatString.replace(/mm/i, mm);
333                                 formatString = formatString.replace(/m/i, m);
334                                 formatString = formatString.replace(/dd/i, dd);
335                                 formatString = formatString.replace(/d/i, d);
336                                 formatString = formatString.replace(/hh/i, hh);
337                                 formatString = formatString.replace(/h/i, h);
338                                 formatString = formatString.replace(/nn/i, nn);
339                                 formatString = formatString.replace(/n/i, n);
340                                 formatString = formatString.replace(/ss/i, ss);
341                                 formatString = formatString.replace(/s/i, s);
342
343                                 return formatString;
344                         }
345                         else
346                         {
347                                 return "";
348                         }
349                 }
350
351         };
352
353         String.prototype.replaceAll = function (str1, str2, ignore)
354         {
355                 return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof(str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);
356         };
357
358         jQuery.validator.addMethod("notNull", function (value, element, params) {
359                         return this.optional(element) || value != null;
360                 }, "Please select a value."
361         );
362
363         jQuery.validator.addMethod("mobile", function (value, element, params) {
364                         return this.optional(element) || value.match(/^[0-9]\d{8}$/) != null;
365                 }, "Must be a valid mobile number."
366         );
367
368         jQuery.validator.addMethod("companyReg", function (value, element, params) {
369                         return this.optional(element) || value.match(/^\d{4}\/\d{6}\/\d{2}$/) != null;
370                 }, "Incorrect format."
371         );
372
373         $.validator.setDefaults({
374                 ignore: [],
375                 errorPlacement: function (error, element) {
376                         //error.prepend('<br/>');
377                         if (element.hasClass('selectpicker'))
378                         {
379                                 var elem = $('button[data-id=' + element.attr("name") + ']');
380                                 elem.addClass('error');
381                                 error.insertAfter(elem);
382                         }
383                         else
384                         {
385                                 error.insertAfter(element);
386                         }
387                 },
388                 unhighlight: function (element, errorClass, validClass) {
389                         if ($(element).hasClass('selectpicker'))
390                         {
391                                 $('button[data-id=' + $(element).attr("name") + ']').removeClass(errorClass).addClass(validClass);
392                         }
393                         else
394                         {
395                                 $(element).removeClass(errorClass).addClass(validClass);
396                         }
397                         $(element.form).find("label[for=" + element.id + "]." + errorClass)
398                                 .remove();//.removeClass(errorClass);
399                 }
400         });
401
402
403 })();
404
405 $.fn.setCursorPosition = function (pos) {
406         if ($(this).get(0).setSelectionRange)
407         {
408                 $(this).get(0).setSelectionRange(pos, pos);
409         }
410         else if ($(this).get(0).createTextRange)
411         {
412                 var range = $(this).get(0).createTextRange();
413                 range.collapse(true);
414                 range.moveEnd('character', pos);
415                 range.moveStart('character', pos);
416                 range.select();
417         }
418 };