define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'template'], function ($, undefined, Backend, Table, Form, Template) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'posts/sites/index',
                    add_url: 'posts/sites/add',
                    edit_url: 'posts/sites/edit',
                    del_url: 'posts/sites/del',
                    multi_url: 'posts/sites/multi',
                    table: 'sites',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'username', title: __('User_id'), operate:false},
                        {field: 'name', title: __('name'),operate: 'LIKE %...%',placeholder: '关键字，模糊搜索',},
                        {field: 'domain', title: __('Domain'),operate: 'LIKE %...%',placeholder: '关键字，模糊搜索',},
                        {field: 'lang', title: __('Lang'), operate:false},
                        {field: 'status', title: __('Status'),searchList: {normal: __('Normal'), hidden: __('Hidden')},  formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate: 'BETWEEN', type: 'datetime', addclass: 'datetimepicker', data: 'data-date-format="YYYY-MM-DD"', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
        	Controller.api.bindevent();
        },
        edit: function () {
        	
            $.validator.config({
                rules: {
                	domain: function(ele){
                    	_value = $.trim(ele.value.toString());
                    	if(_value==$('#c-domain-old').val()) return ;
                        if (!_value.match(/^[A-Za-z0-9]+$/)) {
                            return __('Please enter a valid URL');
                        }
                        return $.ajax({
                            url: 'posts/sites/check_element_available',
                            type: 'POST',
                            data: {"domain": _value},
                            dataType: 'json'
                        });
                	},
                    url: function (element) {
                    	_value = $.trim(element.value.toString());
                        if (!_value.match(/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_\.]+$/)) {
                            return __('Please enter a valid URL');
                        }
                        return $.ajax({
                            url: 'posts/sites/check_element_available',
                            type: 'POST',
                            data: {"domain": _value},
                            dataType: 'json'
                        });
                    }
                }
            });
            
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
	            $(document).on('change', '.ctype',function(){
	            	if($(this).val()=='') return false;
	            	$tarDiv = $(this).closest('.row').find('.custom-val');
	            	nodeName = $tarDiv.children(0).attr('name');
	            	switch($(this).val()){
	            		case "text":
	            			$tarDiv.html('<input type="text" name="'+nodeName+'" class="form-control">')
	            			break;
	            		case "file":
	            			
		            		var random = $(this).closest('dd').data('index');// Math.floor(Math.random()*(10000-1+1)+1);
		            		$tarDiv.html('<input id="c-file-'+random+'" class="form-control upfile" name="'+nodeName+'" type="text" value=""><span><button type="button" id="plupload-f'+random+'" class="btn btn-danger plupload" data-input-id="c-file-'+random+'" data-mimetype="*/*" data-multiple="false"><i class="fa fa-upload"></i>' + __("Upload") + '</button></span><span><button type="button" id="fachoose-f'+random+'" class="btn btn-primary fachoose" data-input-id="c-file-'+random+'" data-mimetype="*/*" data-multiple="false"><i class="fa fa-list"></i>' + __("Choose") + '</button></span><ul class="row list-inline plupload-preview" id="p-image"></ul>');
		            		Form.api.bindevent($tarDiv);
						    break;
	            		case "textarea":
	            			$tarDiv.html('<textarea name="'+nodeName+'" class="form-control" cols="50"></textarea>')
	            			break;
	            		default:
	            			break;
	            	}
	            	return false;
	            });
	            $(document).on("click", ".varlist .btn-append", function () {
	                var rel = parseInt($(this).closest("dl").children('dd').length)-2;
			        var html = Template('appendtpl', {key: rel});
	            	$tar=$(html).insertBefore($(this).parent());
	            	Form.api.bindevent($tar);
	            });
	            $(document).on("click", ".varlist dd .btn-remove", function (e) {
	            	e.preventDefault();
	        		$(this).closest(".form-inline").off();
	        		$(this).closest(".form-inline").remove();
	        		return false;
	            });
	            
	            $(document).on('click', 'input[name*="row[lang]"]', function(e){
	            	if($(this).val()=='zh-cn'){
	            		$(this).prop('checked', true);
	            		return false;
	            	}
	            	$('#extraLanguage').html('');
	            	if($('input[name*="row[lang]"]:checked').length>1){
	            		$('input[name*="row[lang]"]:checked').each(function(){
	            			if($(this).val()!='zh-cn'){
			            		var language = $(this).val();
			            		var languageText = $(this).closest('label').text();
			            		var html = Template('seotpl', {lang: language, langName: languageText});
			            		$('#extraLanguage').append(html)
		            		}
	            		});
	            	}
	            });
	            
	            
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});