// Generated by CoffeeScript 1.6.2
/* ma_utility.coffee
*/


(function() {
  'use strict';  maApp.service('ma', function(lang) {
    this.ArrApJsonToObjectJson = function(arrApJson, arrFldToShow, showAllFields) {
      /*
      convert:
      maAppData = {
        "rl_kTbl": {
          "headers":["Linkki id:70","Resurssi id:90",
          "names": ["rl_asResource_Link_ID", "rl_asResource_id",
          "types": ["at", "at",
          "arrays": [["100026", "100025", "100024"], ["HIT"
        },
        "wcr_kTbl": {}
      }
      
      to:
      ret.columns = [
        {
        id: "title",
        name: "Title",
        field: "title"
        }, {...
      ]
      ret.data = [ ]
      */

      var arrFldToShowIsArray, arrFldToShowPos, arrFldToShowTbl, arrIdx, colIdx, colPos, column, constantToName, fldName, fldNameLower, fldNum, found, i, len, nameArr, pos, rec, ret, retTbl, table, tbl, tblNamePos, tblPos;

      ret = {};
      constantToName = function(constantName) {
        var fldName, start;

        start = constantName.match(/[A-Z]/);
        if (start) {
          fldName = constantName.substring(start.index);
          fldName = fldName.replace(/_/g, " ");
          fldName = lang.Current(fldName);
          return fldName;
        } else {
          return constantName;
        }
      };
      for (table in arrApJson) {
        arrFldToShowTbl = arrFldToShow[table];
        if (arrFldToShowTbl) {
          tbl = arrApJson[table];
          tblNamePos = [];
          i = 0;
          while (i < tbl.names.length) {
            fldNameLower = tbl.names[i].toLowerCase();
            tblNamePos[fldNameLower] = i;
            i = i + 1;
          }
          arrFldToShowIsArray = jQuery.isArray(arrFldToShowTbl);
          arrFldToShowPos = {};
          if (arrFldToShowIsArray) {
            i = 0;
            pos = 0;
            while (i < arrFldToShowTbl.length) {
              rec = arrFldToShowTbl[i];
              fldNameLower = rec.name.toLowerCase();
              if (showAllFields || (!rec.hidden && !arrFldToShowPos[fldNameLower])) {
                arrFldToShowPos[fldNameLower] = {
                  pos: pos,
                  rec: rec
                };
                pos = pos + 1;
              }
              tblPos = tblNamePos[fldNameLower];
              if (tblPos >= 0) {
                tbl.names[tblPos] = rec.name;
              }
              i = i + 1;
            }
          }
          retTbl = {
            columns: [],
            data: []
          };
          nameArr = [];
          len = tbl.names.length;
          i = 0;
          arrIdx = 0;
          while (i < len) {
            fldName = tbl.names[i];
            fldNameLower = fldName.toLowerCase();
            found = false;
            if (arrFldToShowTbl === 1) {
              found = 1;
            } else if (arrFldToShowTbl === 0) {
              found = false;
            } else if (arrFldToShowIsArray) {
              found = arrFldToShowPos[fldNameLower];
              if (found) {
                found = found.rec;
                fldName = found.name;
              }
            }
            if (found) {
              column = {};
              column.id = arrIdx;
              column.field = fldName;
              if (found !== 1) {
                column.name = found.header;
                if (found.width > 0) {
                  column.width = found.width;
                }
                if (found.format && found.format !== "") {
                  column.format = found.format;
                }
              } else if (tbl.headers) {
                column.name = tbl.headers[i];
                colPos = column.name.lastIndexOf(":");
                if (colPos > 0) {
                  column.width = parseFloat(column.name.substring(colPos + 1));
                  column.name = column.name.substring(0, colPos);
                }
              } else {
                column.name = constantToName(fldName);
              }
              column.type = tbl.types[i];
              if (column.type === "al" && fldName.match(/_ah/)) {
                column.type = "ah";
              }
              colIdx = arrIdx;
              if (!showAllFields && arrFldToShowPos[fldNameLower]) {
                colIdx = arrFldToShowPos[fldNameLower].pos;
              }
              retTbl.columns[colIdx] = column;
              nameArr[colIdx] = column.field;
              arrIdx = arrIdx + 1;
            }
            i++;
          }
          i = 0;
          while (i < tbl.arrays[0].length) {
            fldNum = 0;
            rec = {};
            rec.id = i + 1;
            while (fldNum < retTbl.columns.length) {
              found = false;
              fldName = "";
              if (!retTbl.columns[fldNum]) {
                found = false;
              } else {
                fldName = retTbl.columns[fldNum].field;
                fldNameLower = fldName.toLowerCase();
                if (arrFldToShowTbl === 1) {
                  found = true;
                } else if (arrFldToShowTbl === 0) {
                  found = false;
                } else if (arrFldToShowIsArray) {
                  found = arrFldToShowPos[fldNameLower];
                }
              }
              if (found) {
                pos = tblNamePos[fldNameLower];
                rec[fldName] = tbl.arrays[pos][i];
              }
              fldNum++;
            }
            retTbl.data[i] = rec;
            i++;
          }
          ret[table] = retTbl;
        }
      }
      return ret;
    };
    this.TextToDateParse = function(data) {
      var fld, fldName, rec, _i, _len, _ref, _results;

      if (data !== void 0) {
        _ref = data.columns;
        _results = [];
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          fld = _ref[_i];
          if (fld.type === "ad") {
            fldName = fld.field;
            _results.push((function() {
              var _j, _len1, _ref1, _results1;

              _ref1 = data.data;
              _results1 = [];
              for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
                rec = _ref1[_j];
                _results1.push(rec[fldName] = this.IsoDateTextToDate(rec[fldName]));
              }
              return _results1;
            }).call(this));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      }
    };
    this.dynamicSort = function(property) {
      var sortOrder;

      sortOrder = 1;
      if (property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
      }
      return function(a, b) {
        var result;

        result = (a[property] < b[property] ? -1 : (a[property] > b[property] ? 1 : 0));
        return result * sortOrder;
      };
    };
    this.trunc = function(num, idp) {
      var mult;

      mult = Math.pow(10, idp);
      if (num >= 0) {
        return Math.floor(num * mult) / mult;
      } else {
        return Math.ceil(num * mult) / mult;
      }
    };
    this.clone = function(src) {
      var ret;

      if (src instanceof Date) {
        return new Date(src.getTime());
      }
      if ((src == null) || typeof src !== "object") {
        return src;
      }
      if (typeof src.clone === "function") {
        return src.clone(true);
      }
      if (src instanceof RegExp) {
        return new RegExp(src);
      }
      if (src.nodeType && typeof src.cloneNode === "function") {
        return src.cloneNode(true);
      }
      ret = jQuery.extend(true, {}, src);
      return ret;
    };
    this.stripLeadingZeroes = function(input) {
      if ((input.length > 1) && (input.substr(0, 1) === "0")) {
        return input.substr(1);
      } else {
        return input;
      }
    };
    this.floatToInt = function(value) {
      return value | 0;
    };
    this.arrayMax = function(array) {
      return Math.max.apply(Math, array);
    };
    this.arrayMin = function(array) {
      return Math.min.apply(Math, array);
    };
    this.dateToJulian = function(date) {
      var a, day, m, month, y, year;

      year = date.getFullYear();
      month = date.getMonth() + 1;
      day = date.getDate();
      a = Math.floor((14 - month) / 12);
      y = year + 4800 - a;
      m = month + 12 * a - 3;
      return day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045;
    };
    this.julianToDate = function(num) {
      var a, b, c, d, date, day, e, int, m, month, year;

      int = this.floatToInt(num);
      a = int + 32044;
      b = Math.floor((4 * a + 3) / 146097);
      c = a - Math.floor((146097 * b) / 4);
      d = Math.floor((4 * c + 3) / 1461);
      e = c - Math.floor((1461 * d) / 4);
      m = Math.floor((5 * e + 2) / 153);
      day = e - Math.floor((153 * m + 2) / 5) + 1;
      month = m + 3 - 12 * Math.floor(m / 10);
      year = 100 * b + d - 4800 + Math.floor(m / 10);
      date = new Date(0);
      date.setFullYear(year, month - 1, day);
      return date;
    };
    this.julianToWeek = function(jd) {
      var L, d1, d4, numberOfWeek;

      d4 = (jd + 31741 - (jd % 7)) % 146097 % 36524 % 1461;
      L = floor(d4 / 1460);
      d1 = ((d4 - L) % 365) + L;
      numberOfWeek = floor(d1 / 7) + 1;
      return numberOfWeek;
    };
    this.unixToDate = function(unix_time) {
      var theDate;

      theDate = new Date(unix_time * 1000);
      return theDate;
    };
    /* @dateToUnix = (inYear, inMon, inDay, inHr, inMin, inSec ) ->
      humDate = new Date(Date.UTC(inYear, inMon - 1, inDay, inHr, inMin, inSec))
      result = (humDate.getTime() / 1000.0)
      return result
    */

    this.dateToUnix = function(date) {
      var num;

      num = date.getTime() / 1000.0;
      return num;
    };
    this.dateToNum = function(date) {
      return this.dateToUnix(date);
    };
    this.numToDate = function(num) {
      return this.unixToDate(num);
    };
    this.dayDifference = function(time_start, time_end) {
      return Math.floor(time_end) - Math.floor(time_start);
    };
    this.numToWeek = function(num) {
      var dt, jd;

      dt = this.numToDate(num);
      jd = this.dateToJulian(dt);
      return this.julianToWeek(jd);
    };
    this.toSeconds = function(r, decimals) {
      /*if decimals
      		  return Math.round(r * 86400, decimals)
      	  return r * 86400
      */
      return r;
    };
    this.secondsBetween = function(start, end) {
      return Math.abs(end - start);
    };
    this.hoursToNum = function(hours) {
      return hours * 3600;
    };
    /*
    @JsonObjectCopy = (obj, deepCopy) ->
      if deepCopy
        newObject = jQuery.extend({}, obj) # deep copy
      else
        newObject = jQuery.extend(true, {}, obj) # shallow copy
      return newObject
    
    @LangCurrent = (engTxt) ->
      lang = "fin"
      langCust = lang+"-customer"
      if langArr[langCust]? and langArr[langCust][engTxt]?
        return langArr[langCust][engTxt]
      retTxt = engTxt
      # check langArr["cust"][] first
      if langArr[lang]? and langArr[lang][engTxt]?
        if langArr[lang][engTxt] isnt "" # added but not translated
          retTxt = langArr[lang][engTxt]
      else
        langArr[lang] = "" # create empty translation
      return retTxt
    */

    this.RemoveTimeFromDate = function(date) {
      var offset;

      offset = date.getTimezoneOffset() * 60 * 1000;
      date.setTime(date.getTime() - (date.getTime() % 86400000) - offset);
    };
    this.IsoDateTextToDate = function(txtDate) {
      var day, month, year;

      year = txtDate.substring(0, 4);
      month = txtDate.substring(5, 7) - 1;
      day = txtDate.substring(8, 10);
      return new Date(year, month, day);
    };
    this.JsonAttributesAdd = function(json, attribute, columnName) {
      var attr, attributeAppy, elem, _i, _j, _len, _len1, _results, _results1;

      attributeAppy = function(json, attr) {
        var apply, i, _results;

        apply = false;
        if (!attr.type) {
          apply = true;
        } else if (attr.type.search(json.type) > -1) {
          apply = true;
        }
        if (attr.field) {
          if (attr.field !== json.field) {
            apply = false;
          }
        }
        if (apply) {
          _results = [];
          for (i in attr) {
            if (!json[i]) {
              _results.push(json[i] = attr[i]);
            } else {
              _results.push(void 0);
            }
          }
          return _results;
        }
      };
      if (json.length > 0) {
        _results = [];
        for (_i = 0, _len = json.length; _i < _len; _i++) {
          elem = json[_i];
          _results.push(this.JsonAttributesAdd(elem, attribute));
        }
        return _results;
      } else {
        if (attribute && attribute !== 'undefined') {
          if (attribute.length > 0) {
            _results1 = [];
            for (_j = 0, _len1 = attribute.length; _j < _len1; _j++) {
              attr = attribute[_j];
              _results1.push(attributeAppy(json, attr));
            }
            return _results1;
          } else {
            return attributeAppy(json, attribute);
          }
        }
      }
    };
    this.JsonToSingleLevelArr = function(singleArr, json, dx, dy, newText, width, fillColor, strokeColor, info, textColor) {
      var elem, index, rec, _i, _len, _results;

      if (width != null) {
        if (width <= 0) {
          log("width <= 0 (JsonToSingleLevelArr)");
          return;
        }
      }
      if (json.length > 0) {
        _results = [];
        for (_i = 0, _len = json.length; _i < _len; _i++) {
          elem = json[_i];
          _results.push(this.JsonToSingleLevelArr(singleArr, elem, dx, dy, newText, width, fillColor, strokeColor, info, textColor));
        }
        return _results;
      } else {
        index = singleArr.length;
        rec = angular.copy(json);
        if (dx) {
          if (typeof rec.x !== "undefined") {
            rec.x += dx;
          }
        }
        if (dy) {
          if (typeof rec.y !== "undefined") {
            rec.y += dy;
          }
        }
        if (width) {
          if (typeof rec.width !== "undefined") {
            rec.width = width;
          }
        }
        if (newText) {
          if (typeof rec.text !== "undefined") {
            rec.text = newText;
          }
        }
        if (rec.type === "text" && textColor) {
          if (typeof rec.fill !== "undefined") {
            if (textColor !== "default") {
              rec.fill = textColor;
            }
          }
        } else if (fillColor) {
          if (typeof rec.fill !== "undefined") {
            if (fillColor !== "default") {
              rec.fill = fillColor;
            }
          }
        }
        if (strokeColor) {
          if (typeof rec.stroke !== "undefined") {
            if (strokeColor !== "default") {
              rec.stroke = strokeColor;
            }
          }
        }
        if (info) {
          if (typeof rec.data !== "undefined") {
            rec.data = info;
          }
        }
        return singleArr[index] = rec;
      }
    };
    this.SlickBooleanFormatter = function(row, cell, value, columnDef, dataContext) {
      var formatStr;

      formatStr = value + "";
      formatStr = lang.Current(formatStr);
      return formatStr;
    };
    this.SlickRealFormatter = function(row, cell, value, columnDef, dataContext) {
      var val;

      val = Number(value).toFixed(2);
      return val;
    };
    this.SlickDateFormatter = function(row, cell, value, columnDef, dataContext) {
      var formatStr;

      if (value <= new Date(1900, 1, 1)) {
        return "00.00.00";
      }
      formatStr = dateFormat(value, "dd.mm.yyyy");
      return formatStr;
    };
    this.SlickTimeFormatter = function(row, cell, value, columnDef, dataContext) {
      var formatStr;

      formatStr = dateFormat(value, "UTC:HH:MM");
      return formatStr;
    };
    this.SlickWeekdayFormatter = function(row, cell, value, columnDef, dataContext) {
      var dayName, formatStr;

      dayName = ['Su', 'Ma', 'Ti', 'Ke', 'To', 'Pe', 'La'];
      formatStr = value + " " + dayName[value - 1];
      return formatStr;
    };
    this.SlickWorkShiftFormatter = function(row, cell, value, columnDef, dataContext) {
      var formatStr, shiftName;

      shiftName = ['YV', 'AV', 'IV', 'EM'];
      formatStr = value + " " + shiftName[value - 1];
      return formatStr;
    };
    this.SlickColorFormatter = function(row, cell, value, columnDef, dataContext) {
      var formatStr;

      if (value) {
        formatStr = "<span style='color:" + value + "'>" + value + "</span>";
      } else {
        formatStr = "";
      }
      return formatStr;
    };
    this.SlickDefaultFormatterSet = function(data) {
      this.JsonAttributesAdd(data, {
        formatter: this.SlickDateFormatter,
        editor: Slick.Editors.Date,
        type: "ad"
      });
      this.JsonAttributesAdd(data, {
        formatter: this.SlickTimeFormatter,
        editor: this.TimeEditor,
        type: "ah"
      });
      this.JsonAttributesAdd(data, {
        formatter: this.SlickBooleanFormatter,
        type: "af"
      });
      return this.JsonAttributesAdd(data, {
        formatter: this.SlickRealFormatter,
        type: "ar"
      });
    };
    this.timeFormat = function(input) {
      return dateFormat(input, "UTC:HH:MM:ss");
    };
    this.dateParse = function(input) {
      var parts;

      parts = input.match(/(\d+)/g);
      return new Date(parts[0], parts[1] - 1, parts[2]);
    };
    this.timeParse = function(input) {
      var hours, mins, parts, secs, time, timeSecs;

      parts = input.match(/(\d+)/g);
      if (parts[0]) {
        hours = parseInt(parts[0].substr(0, 2), 10);
      } else {
        hours = parseInt(input.substr(0, 2), 10);
      }
      if (parts[1]) {
        mins = parseInt(parts[1], 10);
      } else {
        if (input.length <= 2) {
          mins = 0;
        } else {
          mins = parseInt(input.substr(2, 2), 10);
        }
      }
      if (parts[2]) {
        secs = parseInt(parts[2], 10);
      } else {
        if (input.length <= 4) {
          secs = 0;
        } else {
          secs = parseInt(input.substr(4, 2), 10);
        }
      }
      timeSecs = secs + (mins * 60) + (hours * 60 * 60);
      time = new Date(timeSecs * 1000);
      return time;
    };
    this.TimeEditor = function(args) {
      var $input, scope;

      scope = this;
      $input = jQuery("<INPUT type=text class='editor-text' />");
      $input.appendTo(args.container).bind("keydown.nav", scope.handleKeyDown);
      this.init = function() {};
      this.handleKeyDown = function(e) {
        if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
          return e.stopImmediatePropagation();
        }
      };
      this.destroy = function() {
        return $input.remove();
      };
      this.focus = function() {
        return $input.focus();
      };
      this.serializeValue = function() {
        var time;

        time = timeParse($input.val());
        return time;
      };
      this.applyValue = function(item, state) {
        var fldName;

        fldName = args.column.field;
        return item[fldName] = state;
      };
      this.loadValue = function(item) {
        var fldName, time, timeStr;

        fldName = args.column.field;
        time = item[fldName];
        timeStr = timeFormat(time);
        $input.val(timeStr);
        return $input.select();
      };
      this.isValueChanged = function() {
        var fldName, isChanged, time, timeStr1, timeStr2;

        fldName = args.column.field;
        time = timeParse($input.val());
        timeStr1 = time.toString();
        timeStr2 = args.item[fldName].toString();
        isChanged = timeStr1 !== timeStr2;
        return isChanged;
      };
      this.validate = function() {
        var time, timeStr;

        if ($input.val().length < 1) {
          return {
            valid: false,
            msg: "Please type in valid numbers."
          };
        }
        time = timeParse($input.val());
        timeStr = timeFormat(time);
        if (timeStr < "00:00:00" || timeStr > "24:00:00") {
          return {
            valid: false,
            msg: "'time' cannot be greater than '24:00:00'"
          };
        }
        return {
          valid: true,
          msg: null
        };
      };
      return this.init();
    };
    this.DateEditor = function(args) {
      var $input, calendarOpen, defaultValue, scope;

      $input = void 0;
      defaultValue = void 0;
      scope = this;
      calendarOpen = false;
      this.init = function() {
        $input = $("<INPUT type=text class='editor-text' />");
        $input.appendTo(args.container);
        $input.focus().select();
        $input.datepicker({
          showOn: "button",
          buttonImageOnly: true,
          buttonImage: "../images/calendar.gif",
          beforeShow: function() {
            return calendarOpen = true;
          },
          onClose: function() {
            return calendarOpen = false;
          }
        });
        return $input.width($input.width() - 18);
      };
      this.destroy = function() {
        $.datepicker.dpDiv.stop(true, true);
        $input.datepicker("hide");
        $input.datepicker("destroy");
        return $input.remove();
      };
      this.show = function() {
        if (calendarOpen) {
          return $.datepicker.dpDiv.stop(true, true).show();
        }
      };
      this.hide = function() {
        if (calendarOpen) {
          return $.datepicker.dpDiv.stop(true, true).hide();
        }
      };
      this.position = function(position) {
        if (!calendarOpen) {
          return;
        }
        return $.datepicker.dpDiv.css("top", position.top + 30).css("left", position.left);
      };
      this.focus = function() {
        return $input.focus();
      };
      this.loadValue = function(item) {
        defaultValue = item[args.column.field];
        $input.val(defaultValue);
        $input[0].defaultValue = defaultValue;
        return $input.select();
      };
      this.serializeValue = function() {
        return $input.val();
      };
      this.applyValue = function(item, state) {
        return item[args.column.field] = state;
      };
      this.isValueChanged = function() {
        return (!($input.val() === "" && (defaultValue == null))) && ($input.val() !== defaultValue);
      };
      this.validate = function() {
        return {
          valid: true,
          msg: null
        };
      };
      return this.init();
    };
    return this;
  });

}).call(this);

/*
//@ sourceMappingURL=ma_utility.map
*/
