(function() {
define(['v/store', 'v/moment', 'shared/product', 'shared/utils', 'v/jquery.click-edit'], function(_store, _moment, _sharedProduct, _sharedUtils) {
var CURRENCY, LANGUAGE, UTILS;
window.console = window.console || function() {};
LANGUAGE = 'en';
CURRENCY = '$';
(function() {
var lang;
if (/^(cn|en)\./i.test(location.host)) {
LANGUAGE = RegExp.$1;
} else {
lang = (navigator.languages && navigator.languages[0]) || navigator.language || navigator.browserLanguage;
LANGUAGE = /^[(zh)|(cn)]/i.test(lang) ? 'cn' : 'en';
}
if (LANGUAGE === 'cn') {
return CURRENCY = '¥';
}
})();
UTILS = {
inputDateFormatter: 'YYYYMMDD',
dateFormatter: 'YYYY-MM-DD',
language: LANGUAGE,
currency: CURRENCY,
MAXRANGE: 999999999,
KINDEDITORBUTTONS: ['fullscreen', 'undo', 'redo', 'print', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', '|', 'selectall', '-', 'title', 'fontname', 'fontsize', 'forecolor', 'hilitecolor', '|', 'textcolor', 'bgcolor', 'bold', 'italic', 'underline', 'strikethrough', 'removeformat', '|', 'image', 'flash', 'media', 'advtable', 'hr', 'emoticons', 'link', 'unlink', '|', 'table', 'about'],
isChineseEnv: function(env) {
return /cn/i.test(env || LANGUAGE);
},
resetForm: function($form) {
$form.find("input[type='text'], input[type='textarea']").map(function() {
return this.setAttribute('value', '');
});
return $form.find("select").map(function() {
return this.selectedIndex = 0;
});
},
checkAll: function($o, allExpr, itemExpr) {
return $o.find(allExpr || 'input[data-field="all"]').bind('click', function() {
var $list, isChecked;
isChecked = $(this).is(':checked');
$list = $o.find(itemExpr || 'input[data-field="item"]');
return $list.prop('checked', isChecked);
});
},
toFixed: function(num, digit) {
var defDigit;
num = num || 0;
defDigit = num > 1 ? 2 : 3;
return num.toFixed(typeof digit === 'number' ? digit : defDigit);
},
textToDate: function(text, formatter) {
return moment(text, formatter || this.inputDateFormatter);
},
dateToText: function(dateValue, formatter) {
return moment(dateValue).format(formatter || this.inputDateFormatter);
},
isValidDate: function(text) {
if (!text) {
return false;
}
return /^\d{4}-\d{2}-\d{2}$/.test(text) || /^\d{8}$/.test(text);
},
formatDate: function(date, formatter) {
if (typeof formatter !== 'string') {
formatter = UTILS.dateFormatter;
}
return moment(date).format(formatter);
},
defToFloat: function(value, def) {
if (def == null) {
def = 0;
}
value = parseFloat(value);
if (isNaN(value)) {
value = def;
}
return value;
},
defToInt: function(value, def) {
if (def == null) {
def = 0;
}
value = parseInt(value);
if (isNaN(value)) {
value = def;
}
return value;
},
dataFieldInput: function($o, fieldName) {
return this.dataField($o, fieldName).find('input,textarea,select');
},
dataField: function($o, fieldName) {
return $o.find("[data-field='" + fieldName + "']");
},
disableOperation: function(expr) {
return $(expr).bind('contextmenu', function() {
return false;
}).bind('selectstart', function() {
return false;
});
},
getUrlParam: function(key) {
var current, list, match, pair, pattern, result, search, _i, _len;
search = window.location.search;
search = search.substr(1, search.length);
if (key) {
pattern = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
match = window.location.search.substr(1).match(pattern);
if (match) {
return decodeURI(match[2]);
} else {
return null;
}
} else {
result = {};
list = search.split('&');
for (_i = 0, _len = list.length; _i < _len; _i++) {
current = list[_i];
pair = current.split('=');
result[pair[0]] = decodeURI(pair[1]);
}
return result;
}
},
store: function(key, value) {
if (value === void 0) {
return _store.get(key);
}
if (value === null) {
return _store.remove(key);
}
return _store.set(key, value);
},
pageItems: function(pag, max) {
if (max == null) {
max = 5;
}
return _sharedUtils.pageItems(pag, max);
},
paginationEvent: function($o) {
return $o.find('li').bind('click', function(e) {
e.preventDefault();
return $o.trigger('page:change', {
pageIndex: $(this).attr('data-page')
});
});
},
subHandler: function(text) {
return text.replace(/\[(.+)\]/, '$1');
},
renderPagination: function(pagination) {
var $page, template, tmplString;
pagination.items = this.pageItems(pagination);
tmplString = "
{{#each items}} - {{index}}
{{/each}}
";
template = Handlebars.compile(tmplString);
$page = $(template(pagination));
this.paginationEvent($page);
return $page;
},
selectedOption: function($o, value) {
return $o.find("option[value='" + value + "']").attr('selected', 'selected');
},
setEditorHeader: function($header, isEdit, name) {
var prefix;
prefix = isEdit ? '编辑' : '新建';
return $header.text(prefix + name);
},
cache: function($o, data, key) {
var cache;
key = key || 'cache';
cache = $o.data(key) || {};
if (data) {
_.extend(cache, data);
$o.data(key, cache);
}
return cache;
},
format: function() {
var args, text;
args = arguments;
text = args[0];
return text.replace(/\{(\d+)\}/g, function(m, i) {
var value;
value = args[parseInt(i) + 1];
if (value === void 0) {
value = m;
}
return value;
});
},
extractTemplate: function(expr, template) {
return $(template).find(expr).val();
},
trim: function(text) {
return text && text.replace(/(^\s*)|(\s*$)/g, '');
},
setCookie: function(name, value, days) {
var date, expires;
if (days) {
date = new Date;
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expires = '; expires=' + date.toGMTString();
} else {
expires = '';
}
return document.cookie = name + '=' + value + expires + '; path=/';
},
getCookie: function(name) {
var c, ca, i, nameEQ;
nameEQ = name + '=';
ca = document.cookie.split(';');
i = 0;
while (i < ca.length) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
i++;
}
return null;
},
simpleValidate: function(type, value, def) {
var date, floatValue, intValue;
switch (type) {
case 'date':
date = this.textToDate(value);
if (date.isValid()) {
return date.valueOf();
} else {
return def;
}
break;
case 'int':
intValue = parseInt(value);
if (isNaN(intValue)) {
return def;
} else {
return value;
}
break;
case 'float':
floatValue = parseFloat(value);
if (isNaN(floatValue)) {
return def;
} else {
return value;
}
break;
default:
return value;
}
},
initFriendlyKey: function(expr) {
return $(expr).bind('keydown', function(event) {
var $this, type;
$this = $(this);
type = (function() {
switch (event.keyCode) {
case 13:
return 'enter';
case 38:
return 'up';
case 40:
return 'down';
case 39:
return 'right';
case 37:
return 'left';
default:
return false;
}
})();
if (type) {
return $this.trigger('onFriendlyKey', [$this, type]);
}
});
},
initClickPrompt: function(expr) {
var self;
self = this;
return $(expr).bind('click', function(event) {
var $this, message, origin, type, value;
$this = $(event.target);
origin = $this.attr('data-origin');
type = $this.attr('data-type');
message = (function() {
switch (type) {
case 'date':
return '请输入日期,如20141213';
case 'currency':
return '请输入金额,如12.34';
case 'int':
return '请输入整数,如1034';
case 'float':
return '请输入小数,如12.34';
default:
return '请输入内容';
}
})();
if (type === 'date' && origin) {
origin = self.dateToText(parseInt(origin));
}
value = window.prompt(message, origin);
if (value === null) {
return;
}
value = self.simpleValidate(type, value, origin);
if (value === origin) {
return;
}
return $this.trigger('onPromptChange', value, type, origin);
});
},
analyzeFilterRules: function(text) {
var line, match, result, ruleText, rules, titles, _i, _len;
if (!text) {
return false;
}
rules = text.split('\n');
result = [];
for (_i = 0, _len = rules.length; _i < _len; _i++) {
line = rules[_i];
if (!/(.+?),(.+)/i.test(line)) {
continue;
}
titles = RegExp.$1.split('/');
ruleText = this.trim(RegExp.$2);
match = _sharedProduct.filterRuleMatcher(ruleText);
if (match.length === 0) {
continue;
}
result.push({
title_cn: titles[0],
title_en: titles[1] || '',
rule: ruleText
});
}
return result;
},
xPathMapValue: function(xPath, data) {
var value;
value = data;
xPath.split('.').forEach(function(key) {
if (!value || !(value = value[key])) {
}
});
return value;
},
inlineEditor: function($objs, type) {
var changeDate, changeFloat, changeInt, options;
type = type || 'text';
changeDate = function(before, changed) {
var date;
date = moment(changed, 'YYYYMMDD');
if (date.isValid()) {
return date.format('YYYY-MM-DD');
} else {
return before;
}
};
changeInt = function(before, changed) {
if (isNaN(parseInt(changed))) {
return before;
} else {
return changed;
}
};
changeFloat = function(before, changed) {
if (isNaN(parseFloat(changed))) {
return before;
} else {
return changed;
}
};
options = {
finishButton: true,
cancelButton: true,
afterShow: function($this, $input, value) {
$this.attr('data-origin', value);
if (type === 'date') {
$input.val(value.replace(/\-/ig, ''));
}
return $input.focus();
},
afterChangeVal: function($this, before, changed) {
var value;
value = (function() {
switch (type) {
case 'date':
return changeDate(before, changed);
case 'int':
return changeInt(before, changed);
case 'float':
return changeFloat(before, changed);
}
})();
$this.text(value);
return $this.trigger('inline:changed', value);
}
};
return $objs.ce(options);
}
};
(function() {
Handlebars.registerHelper('i18nMix', function(xPath, value, data) {
var key, result;
key = xPath + value;
result = UTILS.xPathMapValue(key, data);
if (result === void 0) {
result = value;
}
return result;
});
Handlebars.registerHelper('getFieldClass', function(field, header) {
var index, _ref;
index = parseInt(field.replace(/[^\d]/g, ''));
if (((_ref = header.index) != null ? _ref.weight : void 0) === index) {
return 'weight';
} else {
return '';
}
});
Handlebars.registerHelper('specialWeightField', function(field, header, uow) {
var index, _ref;
index = parseInt(field.replace(/[^\d]/g, ''));
if (((_ref = header.index) != null ? _ref.weight : void 0) === index) {
return uow;
} else {
return '';
}
});
Handlebars.registerHelper('getModelFieldClass', function(field, header, options) {
var index, _ref;
index = parseInt(field.replace('f', ''));
if (index === ((_ref = header.index) != null ? _ref.weight : void 0)) {
return "float";
}
return header.fields[index].type;
});
Handlebars.registerHelper('print', function(value, options) {
console.log(value);
return JSON.stringify(value);
});
Handlebars.registerHelper('ifEqual', function(left, right, isBlock, options) {
var isMatch;
if (!options) {
options = isBlock;
isBlock = false;
}
isMatch = left === right;
if (!isBlock) {
return isMatch;
}
if (isMatch) {
return options.fn(options.data.root);
}
});
Handlebars.registerHelper('toFixed', function(num, digit) {
return UTILS.toFixed(num, digit);
});
Handlebars.registerHelper('toCurrency', function(num, digit) {
return _sharedUtils.toCurrency(num, digit);
});
Handlebars.registerHelper('toKilogram', function(num) {
return (num / 1000) + " kg";
});
Handlebars.registerHelper('categoryLink', function(node) {
return _sharedProduct.categoryLink(node);
});
Handlebars.registerHelper('i18n', function(name, options) {
return this[name + "_" + LANGUAGE];
});
Handlebars.registerHelper('date', function(date, formatter, options) {
return UTILS.formatDate(date, formatter);
});
Handlebars.registerHelper('or', function(value1, value2, options) {
return value1 || value2;
});
Handlebars.registerHelper('pageLink', function(link, page) {
return _sharedUtils.format(link || '', page);
});
Handlebars.registerHelper('import', function(name, context, options) {
var html, template;
template = Handlebars.templates[name];
html = template(context || this);
return new Handlebars.SafeString(html);
});
return Handlebars.registerHelper('filesize', function(size, options) {
if (size < 1024 * 1024) {
return ((size / 1024).toFixed(2)) + " KB";
}
if (size < 1024 * 1024 * 1024) {
return ((size / 1024 / 1024).toFixed(2)) + " MB";
}
return size;
});
})();
return UTILS;
});
}).call(this);