if (!w3d) var w3d = {};
if (!w3d.manager) w3d.manager = {};
if (!w3d.manager.fabric) w3d.manager.fabric = {};

var wmf = w3d.manager.fabric;

wmf.initManageFabric = function () {
    // set laundrytags ui
    wmf.setLaundryTags();

    // set drop item ( by drag & drop )
    wmf.setDropItem();

    // set fabric image functions ( one-repeat/detail image )
    wmf.setImageFunctions();

    // set fabric functions ( delete/new/save )
    wmf.setFabricFunctions();

    // set category functions ( create/modify/delete )
    wmf.setCategoryFunctions($('#category1'));
    wmf.setCategoryFunctions($('#category2'));
    wmf.setCategoryFunctions($('#category3'));

    // init category list
    wmf.getCategoryList($('#category1'));

    // init fabric information
    wmf.initFabricInfo();

    wmf.initLaundry();

    wmf.setAccessControl();

    wmf.setKeydownHandler();
};

wmf.initLaundry = function () {
    var infoForm = $('.fabricInformation');
    
    $('.laundryTag .tagDiv > .init-select', infoForm).prop('checked', true);
}

wmf.setLaundryTags = function () {
    $('.tagDiv').each(function () {
        $(this).click(function () {
            $('input:checkbox', $(this)).click();
        });
        $('input:checkbox', $(this)).click(function (e) {
            e.stopPropagation();
        });
    });
};

wmf.setDropItem = function () {
    $('#fabricViewer')
        .drop("start", function () {
            $(this).addClass("active");
        })
        .drop(function (ev, dd) {
            wmf.getFabricInfo($(dd.drag).data('fid'));
            $(dd.drag).addClass('showing');
        })
        .drop("end", function (ev, dd) {
            $(this).removeClass("active");
        });

    $.drop({
        mode: "intersect"
    });
};

wmf.setCategoryFunctions = function (form) {
    $('select.listBox', form).change(function () {
        // 크롬에서 <select/>의 빈 공간을 클릭해도 change 이벤트가 발생하는 것을 막기 위해 선택된 값을 저장하여 비교한다
        var formerValue = $(this).data('selectedId');
        var nowSelected = $(this).val();
        if (formerValue == nowSelected) {
            return false;
        }
        wmf.selectCategory(form, nowSelected);
    });

    $('.categoryFunc.create', form).click(function () {
        wmf.createCategory(form);
    });

    $('.categoryFunc.modify', form).click(function () {
        wmf.modifyCategory(form);
    });

    $('.categoryFunc.delete', form).click(function () {
        wmf.deleteCategory(form);
    });

    $('.categoryFunc.copy', form).click(function () {
    $('#loading_mask').show();
		setTimeout(function(){wmf.copyCategory(form);}, 100);
	});
    
    $('.categoryUpDown', form).click(function () {
        wmf.switchCategory(form, $(this).hasClass('orderUp'));
    });
};

wmf.setImageFunctions = function () {
    // set uploader (detail image)
    var detailUploader = new qq.FileUploaderBasic({
        params: {
            imgSizeLimit: '10000x10000'
        },
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff'],
        element: $('.detailImages .qqUploader')[0],
        button: $('#add_detail_btn')[0],
        text: '',
        action: '/manager/fabric/uploadtempfabric',
        onComplete: function (id, filename, response) {
            if (response['success']) {
                var image_url = response['filepath'];
                var detailImageWrapper = $('.detailImageWrapper');

                // append image to list
                var detailImage_element = $("<div class='detailImage_element'></div>")
                    .data('src', image_url)
                    .appendTo(detailImageWrapper)
                    .click(function () {
                        wmf.viewImageFull($(this).data('src'));
                    });

                var detailImage_element_img = $("<img src='" + image_url + "' />").hide().appendTo(detailImage_element);
                w3d.fn.fitImageIntoParent(detailImage_element_img);

                var closeBtn = $("<div class='close_btn'>X</div>").appendTo(detailImage_element);

                detailImage_element.hover(function () {
                    closeBtn.show();
                }, function () {
                    closeBtn.hide();
                });
                closeBtn.click(function (evt) {
                    detailImage_element.hide('fast', callback = function () {
                        $(this).remove();
                    });
                    evt.stopPropagation();
                });
            } else {
                switch (response['reason']) {
                case 'FileSizeExceeded':
                    alert('File size can not exceed 10MB.');
                    break;
                case 'NotAllowedExtension':
                    alert('Not allowed extension.');
                    break;
                default:
                    alert('File upload Failed');
                    break;
                }
            }
        }
    });
    $('#add_detail_btn').click(function () {
        if ($('.detailImage_element').length < 5) {
            return true;
        } else {
            alert('You can add Detail images up to 5.');
            return false;
        }
    });

    // set uploader (one-repeat image)
    var onerepeatUploader = new qq.FileUploaderBasic({
        params: {
            imgSizeLimit: '10000x10000'
        },
        allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'tif', 'tiff'],
        element: $('.mainImage .qqUploader')[0],
        button: $('#change_oneRepeat_btn')[0],
        text: '',
        action: '/manager/fabric/uploadtempfabric',
        onComplete: function (id, filename, response) {
            if (response['success']) {
                var image_url = response['filepath'];
                var mainImageViewer = $('.mainImageViewer').empty();

                var mainImage_element = $("<div class='mainImage_element'></div>")
                    .data('src', image_url)
                    .appendTo(mainImageViewer)
                    .click(function () {
                        wmf.viewImageFull($(this).data('src'));
                    });

                var mainImage_element_img = $("<img src='" + image_url + "' />").hide().appendTo(mainImage_element);
                w3d.fn.fitImageIntoParent(mainImage_element_img);
            } else {
                switch (response['reason']) {
                case 'FileSizeExceeded':
                    alert('File size can not exceed 10MB.');
                    break;
                case 'NotAllowedExtension':
                    alert('Not allowed extension.');
                    break;
                default:
                    alert('File upload Failed');
                    break;
                }
            }
        }
    });
};

wmf.setFabricFunctions = function () {
    /* // 선택 모드
    $('#select_mode_btn').click(function () {
    	if ($(this).data('selectmode')) {
    		// 선택 모드 해제
    		$('.fabricItem input:checkbox').removeAttr('checked').hide();
    		$(this).data('selectmode', false);
    		$(this).text('선택');
    	} else {
    		// 선택 모드 설정
    		$('.fabricItem input:checkbox').show();
    		$(this).data('selectmode', true);
    		$(this).text('해제');
    	}
    });*/

    $('#delete_fabric_btn').click(wmf.deleteFabric);

    $('#new_fabric_btn').click(wmf.initFabricInfo);

    $('#save_fabric_btn').click(function () {
        wmf.saveFabric(false);
    });

    $('#saveAs_fabric_btn').click(function () {
        wmf.saveFabric(true);
    });
};

wmf.initFabricInfo = function () {
    var infoForm = $('.fabricInformation');

    $('.mainImageViewer', infoForm).empty();
    $('.detailImageWrapper', infoForm).empty();
    $('input:text', infoForm).val('');
    $('textarea', infoForm).val('');
    $('.laundryTag input:checkbox', infoForm).removeAttr('checked');
    $('.client_group input:checkbox', infoForm).removeAttr('checked').attr('disabled', 'disabled');
    $('#rd_allow_to_all', infoForm).attr('checked', 'checked');
    $('.detail_input input:checkbox', infoForm).removeAttr('checked');

    $('.fabricItem.showing').removeClass('showing');

    $('#fabricViewer').data('fid', '-1');
    $('.select2').val(null).trigger("change");
};

wmf.getCategoryList = function (form, selectedId, noPropagation) {
    // noPropagation(default: false) 값이 true이면 다음 레벨의 카테고리 폼 또는 그리드를 변경하지 않는다
    noPropagation = noPropagation || false;

    var selector = $('select.listBox', form);

    var level = form.attr('id').split('ategory')[1];
    var supercid;

    if (level == '2') {
        supercid = $(".listBox", "#category1").val();
    } else if (level == '3') {
        supercid = $(".listBox", "#category2").val();
    }

    $.ajax({
        url: '/manager/fabric/category/getlist',
        type: 'POST',
        cache: false,
        data: {
            level: level,
            supercid: supercid
        },
        dataType: 'xml',
        async: false,
        success: function (xml) {
            var categoryList = $('Records', $(xml));
            selector.empty();
            $('Record', categoryList).each(function (i) {
                var categoryId = $(this).attr('ID');
                var categoryName = $(this).attr('Name');
                var orderValue = $(this).attr('OrderValue');
                $("<option value='" + categoryId + "' orderValue='" + orderValue + "'>" + categoryName + "</option>").appendTo(selector);
            });
            wmf.selectCategory(form, selectedId, noPropagation);
        },
        error: function () {
            alert('Loading category list has Failed');
        }
    });
};

wmf.selectCategory = function (form, selectedId, noPropagation) {
    // noPropagation(default: false) 값이 true이면 다음 레벨의 카테고리 폼 또는 그리드를 변경하지 않는다
    noPropagation = noPropagation || false;

    var selector = $('select.listBox', form);
    var nameInput = $('input.categoryName', form);

    if ($('option', selector).length > 0) {
        var selectedOption;
        if (selectedId)
            selectedOption = $('option[value=' + selectedId + ']', selector);
        else
            selectedOption = $('option:first', selector);

        $('option', selector).removeAttr('selected');
        selectedOption.attr('selected', 'selected');
        nameInput.val(selectedOption.text());
        // 그리드에 categoryId로 전달
        selectedId = selectedOption.val();
    } else {
        nameInput.val('');
        // 그리드에 categoryId로 -1을 전달 ( 선택된 카테고리가 없음을 의미 )
        selectedId = '-1';
    }

    // 크롬에서 <select/>의 빈 공간을 클릭해도 change 이벤트가 발생하는 것을 막기 위해 선택된 값을 저장하여 비교한다
    selector.data('selectedId', selectedId);

    if (noPropagation) {
        return;
    } else {
        // 그리드 리셋 - 선택 카테고리 : selectedId
        if (form.attr('id') == 'category1') {
            wmf.getCategoryList($('#category2'));
        } else if (form.attr('id') == 'category2') {
            wmf.getCategoryList($('#category3'));
            // 선택된 category2에 따라서 other information의 option 변경
            wmf.categoryAccessInformation();
        } else {
            wmf.getFabricGrid(selectedId);
        }
    }
};

wmf.createCategory = function (form) {
    var name = $('input.categoryName', form).val();

    if (name.length == 0) {
        return;
    } else if (name.length < 2) {
        alert('Category name must be at least 2 characters long.');
        return;
    }

    var level = form.attr('id').split('ategory')[1];
    var supercid;
    if (level > 1) {
        var superlevel = level - 1;
        var supercategory = "#category" + superlevel;
        supercid = $(".listBox", supercategory).val();
    }

    $.ajax({
        url: '/manager/fabric/category/create',
        type: 'POST',
        cache: false,
        data: {
            name: name,
            level: level,
            supercid: supercid
        },
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response['success']) {
                wmf.getCategoryList(form, response['id']);
            } else {
                switch (response['reason']) {
                case 'NameAlreadyExists':
                    alert('Creating category has Failed : Already Exists');
                    break;
                default:
                    alert('Creating category has Failed : ' + response['reason']);
                }
            }
        },
        error: function () {
            alert('Creating category has Failed');
        }
    });
};

wmf.modifyCategory = function (form) {
    var selector = $('select.listBox', form);
    var selectedValue = selector.val();
    var selectedOption = $('option[value=' + selectedValue + ']', selector);
    var new_name = $('input.categoryName', form).val();

    if (selectedOption.length == 0) {
        return;
    }
    if (new_name.length == 0) {
        return;
    } else if (new_name.length < 2) {
        alert('Category name must be at least 2 characters long.');
        return;
    }
    var old_name = selectedOption.text();
    if (old_name === new_name || !confirm("Modify [ " + old_name + " ] to [ " + new_name + " ]?")) {
        return;
    }

    $.ajax({
        url: '/manager/fabric/category/modify',
        type: 'POST',
        cache: false,
        data: {
            cid: selectedValue,
            name: new_name
        },
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response['success']) {
                wmf.getCategoryList(form, selectedValue);
            } else {
                switch (response['reason']) {
                case 'DoesNotExist':
                    alert('Modifying category has Failed : Does not exist');
                    break;
                case 'NameAlreadyExists':
                    alert('Modifying category has Failed : Already Exists');
                    break;
                default:
                    alert('Modifying category has Failed : ' + response['reason']);
                }
            }
        },
        error: function () {
            alert('Modifying category has Failed');
        }
    });
};

wmf.deleteCategory = function (form) {
    var selector = $('select.listBox', form);
    var selectedValue = selector.val();
    var selectedOption = $('option[value=' + selectedValue + ']', selector);

    if (selectedOption.length == 0 || !confirm("Delete [" + selectedOption.text() + "]?")) {
        return;
    }
    $.ajax({
        url: '/manager/fabric/category/delete',
        type: 'POST',
        cache: false,
        data: {
            cid: selectedValue
        },
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response['success']) {
                wmf.getCategoryList(form);
            } else {
                switch (response['reason']) {
                case 'DoesNotExist':
                    alert('Deleting category has Failed : Does not exist');
                    break;
                default:
                    alert('Deleting category has Failed : ' + response['reason']);
                }
            }
        },
        error: function () {
            alert('Deleting category has Failed');
        }
    });
};

wmf.copyCategory = function (form) {
    var name = $('input.categoryName', form).val();
    
    if (name.length == 0) {
        return;
	} else if (name.length < 2) {
		alert('Category name must be at least 2 characters long.');
		return;
	}
    
    var level = form.attr('id').split('ategory')[1];
    var supercid;
    if (level > 1) {
		var superlevel = level-1;
		var supercategory = "#category"+superlevel;
		supercid = $(".listBox", supercategory).val();
	}
    
    var existName = false;
    var nowSelected = $('select.listBox', form).val();
    $.ajax({
		url: '/manager/fabric/category/getlist',
		type: 'POST',
		cache: false,
		data: {
            level: level,
            supercid:supercid
        },
		dataType: 'xml',
		async: false,
		success: function (xml) {
			var categoryList = $('Records', $(xml));
			$('Record', categoryList).each(function (i) {
				var categoryName = $(this).attr('Name');
                if (name == categoryName) {
                    existName = true;
                }
			});
		},
		error: function () {
			alert('Comparing category list has Failed');
		}
	});
    
    if (!existName) {
        alert('This category name Does not exist');
        return;
    }
    
    var copyname = name.concat("2");
    
    var sub = false;
    if (level == '2' && $('option', '#category3').length > 0) {
        sub = true;
    }
    
    var newcid;
	$.ajax({
		url: '/manager/fabric/category/create',
		type: 'POST',
		cache: false,
		data: {
            name: copyname,
            level: level,
            supercid: supercid
        },
		dataType: 'json',
		async: false,
		success: function (response) {
			if (response['success']) {
                newcid = response['id'];
                if (sub) {
                    wmf.sublevelcopy(nowSelected, newcid);
                } else {
                    wmf.fabriccopy(nowSelected, newcid);
                }
                wmf.getCategoryList(form, response['id']);
			} else {
                switch (response['reason']) {
                case 'NameAlreadyExists':
                    alert('Creating category has Failed : Already Exists');
                    break;
                default:
                    alert('Creating category has Failed : ' + response['reason']);
				}
			}
		},
		error: function () {
			alert('Creating category has Failed');
		},
        complete: function () {
            $('#loading_mask').hide();
        }
	});
    $('input.categoryName', form).focus();
};

wmf.sublevelcopy = function (nowSelected, newcid) {
    var level = 3;
    var superlevel = 2;
    
    $.ajax({
		url: '/manager/fabric/category/getlist',
		type: 'POST',
		cache: false,
		data: {
            level: level,
            supercid: nowSelected
        },
		dataType: 'xml',
		async: false,
		success: function (xml) {
			var categoryList = $('Records', $(xml));
			$('Record', categoryList).each(function (i) {
				var subCId = $(this).attr('ID');
				var subCName = $(this).attr('Name');
                
                var newsubcid;
				$.ajax({
					url: '/manager/fabric/category/create',
					type: 'POST',
					cache: false,
					data: {
                        name: subCName,
                        level: level,
                        supercid: newcid
                    },
					dataType: 'json',
					async: false,
					success: function (response) {
                        if (response['success']) {
                            newsubcid = response['id'];
						} else {
							switch (response['reason']) {
							case 'NameAlreadyExists':
								alert('Creating Subcategory has Failed : Already Exists');
								break;
							default:
								alert('Creating Subcategory has Failed : ' + response['reason']);
							}
						}
					},
					error: function () {
						alert('Creating Subcategory has Failed');
					}
				});
                wmf.fabriccopy(subCId, newsubcid);
			});
		},
		error: function () {
			alert('Loading Subcategory list has Failed');
		}
	});    
};

wmf.fabriccopy = function (nowSelected, newcid) {
    var fabricId;
    
    $.ajax({
		url: '/manager/fabric/getlist_by_manager',
		type: 'POST',
		cache: false,
		data: {
            categoryId: nowSelected
        },
		dataType: 'xml',
		async: false,
		success: function (xml) {
			var FabricListXML = $('Records', $(xml));			
			$('Record', FabricListXML).each(function (i) {
				fabricId = $(this).attr('id');
                wmf.copydataload(fabricId, newcid, nowSelected);
            });
			wmf.getFabricGrid(newcid);
		},
		error: function () {
			alert('Loading fabric list has failed');
		}
	});
};

    var name;
	var code;
	var weight;
	var width;
	var composition;
	var price;
	var size;
	var text;
	var fabricValid;
    
wmf.copydataload = function (fabricId, newcid, origincid) {
    var test = true;
    
    $.ajax({
		url: '/manager/fabric/getinfo',
		type: 'POST',
		cache: false,
		data: {
            fid: fabricId
        },
		dataType: 'xml',
		async: false,
		success: function (xml) {
            var FabricInfoXML = $('fabricinformation', $(xml));
            var detailInfo = $('detailinfo', FabricInfoXML);
            
			name = $('name', detailInfo).text();
			code = $('code', detailInfo).text();
			weight = $('weight', detailInfo).text();
			width = $('width', detailInfo).text();
			composition = $('composition', detailInfo).text();
			price = $('price', detailInfo).text();
			size = $('size', detailInfo).text();
			text = $('text', detailInfo).text();
            fabricValid = $('valid', detailInfo).text();
            
            var onerepeatImg = $('onerepeatimage', FabricInfoXML);
            var oneRptImg = $('image_url', onerepeatImg).text();
            
            var detailImg = [];
            $('detailimage', FabricInfoXML).each(function () {
                detailImg.push($('image_url', $(this)).text());
            });
            if (detailImg.length === 0) {
                detailImg = "";
            } else {
                detailImg = detailImg.join(';');
            }
            
            wmf.getFabricInfo(fabricId);
            var infoForm = $('.fabricInformation');
            
            var laundryTags = [];
            $('.laundryTag input:checkbox', infoForm).each(function () {
                if ($(this).is(':checked')) {
                    laundryTags.push('1');
                } else {
                    laundryTags.push('0');
                }
            });
            laundryTags = laundryTags.join(';');
            
            var allowed_group_ids = [];
            $('.client_group input:checkbox', infoForm).each(function () {
                if ($(this).is(':checked')) {
                    allowed_group_ids.push($(this).val());
                }
            });
            allowed_group_ids = allowed_group_ids.join('-');
            
            var fabricFunction = [];
            $('#inputSearchFunction option').each(function () {
                if ($(this).is(':selected')) {
                    fabricFunction.push('1');
                } else {
                    fabricFunction.push('0');
                }
            });
            fabricFunction = fabricFunction.join(';');
            
            var fabricImage = [];
            $('#inputSearchImage option').each(function () {
                if ($(this).is(':selected')) {
                    fabricImage.push('1');
                } else {
                    fabricImage.push('0');
                }
            });
            fabricImage = fabricImage.join(';');
            
            var fabricColor = [];
            $('#inputSearchColor option').each(function () {
                if ($(this).is(':selected')) {
                    fabricColor.push('1');
                } else {
                    fabricColor.push('0');
                }
            });
            fabricColor = fabricColor.join(';');
            
            wmf.loaddatasave(newcid,name,code,weight,width,composition,price,size,text,fabricValid,oneRptImg,detailImg,laundryTags,allowed_group_ids,fabricFunction,fabricImage,fabricColor);
        },
		error: function () {
            wmf.loadfaildataset(fabricId, newcid, origincid);
		}
	});
};

wmf.loadfaildataset = function (fabricId, newcid, origincid) {
    $.ajax({
		url: '/manager/fabric/getlist_by_manager',
		type: 'POST',
		cache: false,
		data: {
			categoryId: origincid
		},
		dataType: 'xml',
		async: false,
		success: function (xml) {
			var FabricListXML = $('Records', $(xml));
			$('Record', FabricListXML).each(function (i) {
                if ($(this).attr('id') == fabricId) {
                    name = $(this).attr('Name');
                    code = "";
                    weight = "";
                    width = $(this).attr('width');
                    composition = "";
                    price = "";
                    size = "";
                    text = "";
                    fabricValid = $(this).attr('Visible');
                    
                    oneRptImg = $(this).attr('thum_url');
                    detailImg = "";
                    
                    laundryTags = "";
                    allowed_group_ids = "";
                    
                    fabricFunction = "";
                    fabricImage = "";
                    fabricColor = "";
                    
                    wmf.loaddatasave(newcid,name,code,weight,width,composition,price,size,text,fabricValid,oneRptImg,detailImg,laundryTags,allowed_group_ids,fabricFunction,fabricImage,fabricColor);
                }
			});
		},
		error: function () {
			alert('Loading fabric information has failed');
		}
	});
};

wmf.loaddatasave = function (newcid,name,code,weight,width,composition,price,size,text,fabricValid,oneRptImg,detailImg,laundryTags,allowed_group_ids,fabricFunction,fabricImage,fabricColor) {
    //var newfabricId = $('#fabricViewer').data('fid');
    var newfabricId = $('#fabricViewer').data('fid') + 1;
    
    $.ajax({
		url: '/manager/fabric/create_by_manager',
		type: 'POST',
		cache: false,
		data: {
			cid: newcid,
			fid: newfabricId,
			name: name,
			code: code,
			weight: weight,
			width: width,
			composition: composition,
			price: price,
			size: size,
			text: text,
			Visible: fabricValid,
			onerptimg: oneRptImg,
			detailimg: detailImg,
            laundryTags: laundryTags,
			allowed_group_ids: allowed_group_ids,
            fabricFunction: fabricFunction,
            fabricImage: fabricImage,
            fabricColor: fabricColor
		},
		dataType: 'json',
		async: false,
		success: function (response) {
			if (response['success']) {
			} else {
				alert('Saving fabric has failed_1');
			}
		},
		error: function () {
            alert('Saving fabric has failed_2');

		}
	});
};

wmf.switchCategory = function (form, is_up) {
    var selector = $('select.listBox', form);
    var selectedValue = selector.val();
    var selectedOption = $('option[value=' + selectedValue + ']', selector);
    var dstOption = is_up ? selectedOption.prev() : selectedOption.next();

    if (selectedOption.length == 0 || dstOption.length == 0) {
        return;
    }

    var level = form.attr('id').split('ategory')[1];

    $.ajax({
        url: '/manager/fabric/category/switchorder',
        type: 'POST',
        cache: false,
        data: {
            scid: selectedValue,
            dcid: dstOption.val()
        },
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response['success']) {
                wmf.getCategoryList(form, selectedValue, noPropagation = true);
            } else {
                alert('Switching category order has Failed');
            }
        },
        error: function () {
            alert('Switching category order has Failed');
        }
    });
};

wmf.getFabricGrid = function (categoryId, showingFabricId) {
    showingFabricId = showingFabricId || $('#fabricViewer').data('fid');
    $('#fabricViewer').removeClass("active available");

    var fabricGrid = $('#fabricGrid');
    fabricGrid.empty();
    //$('#select_mode_btn').data('selectmode', false).text('선택'); // 선택 모드

    wmf.initFabricInfo();
    wmf.initLaundry();

    if (categoryId == '-1') {
        return;
    }
    $.ajax({
        url: '/manager/fabric/getlist_by_manager',
        type: 'POST',
        cache: false,
        data: {
            categoryId: categoryId
        },
        dataType: 'xml',
        async: false,
        success: function (xml) {
            var FabricListXML = $('Records', $(xml));

            $('Record', FabricListXML).each(function (i) {
                var imgSrc = $(this).attr('thum_url');
                var fabricId = $(this).attr('id');
                var fabricName = $(this).attr('Name');
                var fabricValid = $(this).attr('Visible');

                var fabricItem = $("<div class='fabricItem' style='background-image: url(" + imgSrc + ");'></div>")
                    .data('fid', fabricId)
                    .append("<input type='checkbox' class='checkbox'/>")
                    .appendTo(fabricGrid);

                var nameLabel = $("<div class='label name'>" + fabricName + "</div>")
                    .appendTo(fabricItem);

                if (fabricValid == 'False') {
                    $("<div class='label background'></div>")
                        .css('opacity', 0.9)
                        .css('height', nameLabel.height())
                        .css('background-color', 'lightgrey')
                        .appendTo(fabricItem);
                } else {
                    $("<div class='label background'></div>")
                        .css('opacity', 0.7)
                        .css('height', nameLabel.height())
                        .appendTo(fabricItem);
                }

                if (parseInt(fabricId, 10) === parseInt(showingFabricId, 10)) {
                    wmf.getFabricInfo(fabricId);
                    fabricItem.addClass('showing');
                }
            });
            wmf.setItemsDragDrop(fabricGrid);
        },
        error: function () {
            alert('Loading fabric list has failed');
        }
    });
};

wmf.setItemsDragDrop = function (grid) {
    $('.fabricItem', grid)
        .drag("start", function (ev, dd) {
            $(dd.available).addClass("available");
            return $(this).clone()
                .css("opacity", .5)
                .addClass('clone')
                .appendTo(this.parentNode);
        })
        .drag("end", function (ev, dd) {
            $(dd.available).removeClass("available");
            $(dd.proxy).remove();
        })
        .drag(function (ev, dd) {
            dd.update();
            $(dd.proxy).css({
                top: dd.offsetY,
                left: dd.offsetX
            });
        }, {
            drop: '#fabricViewer, .fabricItem'
        })
        .drop("start", function () {
            $(this).addClass("active");
            $(this).append($("<div class='caret'></div>"));
        })
        .drop(function (ev, dd) {
            if (this != dd.drag) {
                wmf.insertFabricBefore($(dd.drag).data('fid'), $(this).data('fid'));
            }
        })
        .drop("end", function (ev, dd) {
            $(this).removeClass("active");
            $('.caret', this).remove();
        });

    $("<div class='fabricItem null'></div>")
        .drop("start", function () {
            $(this).addClass("active");
            $(this).append($("<div class='caret'></div>"));
        })
        .drop(function (ev, dd) {
            if (this != dd.drag) {
                wmf.insertFabricBefore($(dd.drag).data('fid'), '0');
            }
        })
        .drop("end", function (ev, dd) {
            $(this).removeClass("active");
            $('.caret', this).remove();
        }).appendTo(grid);
};

wmf.saveFabric = function (saveAs) {
    var infoForm = $('.fabricInformation');
    var fabricId = $('#fabricViewer').data('fid');
    var categoryForm = $('#category3');
    if ($('.listBox', categoryForm).val() == '00') {
        //alert('원단이 속할 특정 category를 level3에서 선택하여 주십시오.');
        alert('生地が属する特定のcategoryをlevel3で選択してください');
        return false;
    }
    var categoryId = $('select.listBox', categoryForm).val();
    var fabricValid = $('input[name=fabicValid]:checked', infoForm).val();

    if (!categoryId) {
        alert('Select category first.');
        return;
    }

    if (saveAs) {
        fabricId = '-1';
    }

    if (fabricId > 0 && !confirm('Save changes?')) {
        return;
    }

    var splitResult;

    var oneRptImg;
    if ($('.mainImage_element').length === 0) {
        alert('One repeat image must be set.');
        return;
    } else {
        oneRptImg = $('.mainImage_element').data('src');
    }

    var detailImg = [];
    $('.detailImage_element').each(function () {
        detailImg.push($(this).data('src'));
    });
    detailImg = detailImg.join(';');

    var laundryTags = [];
    $('.laundryTag input:checkbox', infoForm).each(function () {
        if ($(this).is(':checked')) {
            laundryTags.push('1');
        } else {
            laundryTags.push('0');
        }
    });
    laundryTags = laundryTags.join(';');

    var allowed_group_ids = [];
    $('.client_group input:checkbox', infoForm).each(function () {
        if ($(this).is(':checked')) {
            allowed_group_ids.push($(this).val());
        }
    });
    allowed_group_ids = allowed_group_ids.join('-');
    
    var fabricFunction = [];
	$('#inputSearchFunction option').each(function () {
		if ($(this).is(':selected')) {
			fabricFunction.push('1');
		} else {
			fabricFunction.push('0');
		}
	});
	fabricFunction = fabricFunction.join(';');
    
    var fabricImage = [];
	$('#inputSearchImage option').each(function () {
		if ($(this).is(':selected')) {
			fabricImage.push('1');
		} else {
			fabricImage.push('0');
		}
	});
	fabricImage = fabricImage.join(';');
    
    var fabricColor = [];
	$('#inputSearchColor option').each(function () {
		if ($(this).is(':selected')) {
			fabricColor.push('1');
		} else {
			fabricColor.push('0');
		}
	});
	fabricColor = fabricColor.join(';');

    $.ajax({
        url: '/manager/fabric/create_by_manager',
        type: 'POST',
        cache: false,
        data: {
            cid: categoryId,
            fid: fabricId,
            name: $('input#inp_fabricName', infoForm).val(),
            code: $('input#inp_fabricCode', infoForm).val(),
            weight: $('input#inp_fabricWeight', infoForm).val(),
            width: $('input#inp_fabricWidth', infoForm).val(),
            composition: $('input#inp_fabricComposition', infoForm).val(),
            price: $('input#inp_fabricPrice', infoForm).val(),
            size: $('input#inp_fabricSize', infoForm).val(),
            text: $('textarea#inp_fabricMemo', infoForm).val(),
            onerptimg: oneRptImg,
            detailimg: detailImg,
            laundryTags: laundryTags,
            Visible: fabricValid,
            allowed_group_ids: allowed_group_ids,
            fabricFunction: fabricFunction,
            fabricImage: fabricImage,
            fabricColor: fabricColor
        },
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response['success']) {
                wmf.getFabricGrid(categoryId, response['id']);
            } else {
                alert('Saving fabric has failed_3');
            }
        },
        error: function () {
            alert('Saving fabric has failed_4');
        }
    });
};

wmf.getFabricInfo = function (fabricId) {
    var infoForm = $('.fabricInformation');
    var mainImageViewer = $('.mainImageViewer', infoForm);
    var detailImageWrapper = $('.detailImageWrapper', infoForm);

    wmf.initFabricInfo();

    $.ajax({
        url: '/manager/fabric/getinfo',
        type: 'POST',
        cache: false,
        data: {
            fid: fabricId
        },
        dataType: 'xml',
        async: false,
        success: function (xml) {
            var FabricInfoXML = $('fabricinformation', $(xml));

            var onerepeatImg = $('onerepeatimage', FabricInfoXML);

            var mainImage_element = $("<div class='mainImage_element'></div>")
                .data('src', $('image_url', onerepeatImg).text())
                .appendTo(mainImageViewer)
                .click(function () {
                    wmf.viewImageFull($(this).data('src'));
                });

            var mainImage_element_img = $("<img src='" + $('thumb_url', onerepeatImg).text() + "' />").hide().appendTo(mainImage_element);
            w3d.fn.fitImageIntoParent(mainImage_element_img);

            $('detailimage', FabricInfoXML).each(function () {
                var detailImg = $(this);

                // append image to list
                var detailImage_element = $("<div class='detailImage_element'></div>")
                    .data('src', $('image_url', detailImg).text())
                    .appendTo(detailImageWrapper)
                    .click(function () {
                        wmf.viewImageFull($(this).data('src'));
                    });

                var detailImage_element_img = $("<img src='" + $('thumb_url', detailImg).text() + "' />").hide().appendTo(detailImage_element);
                w3d.fn.fitImageIntoParent(detailImage_element_img);

                var closeBtn = $("<div class='close_btn'>X</div>").appendTo(detailImage_element);

                detailImage_element.hover(function () {
                    closeBtn.show();
                }, function () {
                    closeBtn.hide();
                });
                closeBtn.click(function (evt) {
                    detailImage_element.hide('fast', callback = function () {
                        $(this).remove();
                    });
                    evt.stopPropagation();
                });
            });

            var detailInfo = $('detailinfo', FabricInfoXML);
            $('input#inp_fabricName', infoForm).val($('name', detailInfo).text());
            $('input#inp_fabricCode', infoForm).val($('code', detailInfo).text());
            $('input#inp_fabricWeight', infoForm).val($('weight', detailInfo).text());
            $('input#inp_fabricWidth', infoForm).val($('width', detailInfo).text());
            $('input#inp_fabricComposition', infoForm).val($('composition', detailInfo).text());
            $('input#inp_fabricPrice', infoForm).val($('price', detailInfo).text());
            $('input#inp_fabricSize', infoForm).val($('size', detailInfo).text());
            $('textarea#inp_fabricMemo', infoForm).val($('text', detailInfo).text());

            var fabricValid = $('valid', detailInfo).text();
            if (fabricValid == 'True') {
                $('.detail_input input:checkbox', infoForm).attr('checked', 'checked');
            } else {
                $('.detail_input input:checkbox', infoForm).removeAttr('checked');
            }

            var laundryTags = $('landrytags', FabricInfoXML).text();
            $('.laundryTag input:checkbox', infoForm).each(function (i) {
                if (laundryTags[i] == '1') {
                    $(this).attr('checked', 'checked');
                }
            });

            var allowed_group_ids = $('allowed_group_ids', FabricInfoXML).text().split('-');
            if (allowed_group_ids.length !== 0 && allowed_group_ids[0] !== '') {
                $('#rd_allow_to_limited', infoForm).attr('checked', 'checked');
                $('.client_group input:checkbox', infoForm).removeAttr('disabled');
            }
            for (var i = 0; i < allowed_group_ids.length; i += 1) {
                if (allowed_group_ids[i] !== '') {
                    $('.client_group input:checkbox[value=' + allowed_group_ids[i] + ']', infoForm).attr('checked', 'checked');
                }
            }
            
            var searchFunction = $('searchfunction', FabricInfoXML).text().toString().split('');
			var searchImage = $('searchimage', FabricInfoXML).text().toString().split('');
            var searchColor = $('searchcolor', FabricInfoXML).text().toString().split('');
            
            $("#inputSearchFunction").val(searchFunction).trigger("change");
            $("#inputSearchImage").val(searchImage).trigger("change");
            $("#inputSearchColor").val(searchColor).trigger("change");
            
            /*$("#inputSearchFunction option").removeAttr('disabled');
            
            if ($(".listBox","#category1").val()=='6'){
                $("#inputSearchColor").prop("disabled", false);
                $("#inputSearchFunction option[value=4]").attr('disabled', 'disabled');
                $("#inputSearchFunction option[value=5]").attr('disabled', 'disabled');
                $("#inputSearchFunction option[value=6]").attr('disabled', 'disabled');
                $("#inputSearchFunction option[value=7]").attr('disabled', 'disabled');
                $("#inputSearchFunction").select2()
            } else if ($(".listBox","#category1").val()=='7') {
                $("#inputSearchColor").prop("disabled", true);
                $("#inputSearchFunction option[value='0']").attr('disabled', 'disabled');
                $("#inputSearchFunction option[value='1']").attr('disabled', 'disabled');
                $("#inputSearchFunction").select2()
            }*/

            $('#fabricViewer').data('fid', fabricId);
        },
        error: function () {
            alert('Loading fabric information has failed');
        }
    });
};

wmf.categoryAccessInformation = function() {
    var categoryId = $(".listBox", "#category1").val();
    
    $("#inputSearchFunction option").removeAttr('disabled');
    
    if (categoryId == '6'){
        $("#inputSearchColor").prop("disabled", false);
        $("#inputSearchFunction option[value=4]").attr('disabled', 'disabled');
        $("#inputSearchFunction option[value=5]").attr('disabled', 'disabled');
        $("#inputSearchFunction option[value=6]").attr('disabled', 'disabled');
        $("#inputSearchFunction option[value=7]").attr('disabled', 'disabled');
        $("#inputSearchFunction").select2()
    } else if (categoryId == '7') {
        $("#inputSearchColor").prop("disabled", true);
        $("#inputSearchFunction option[value='0']").attr('disabled', 'disabled');
        $("#inputSearchFunction option[value='1']").attr('disabled', 'disabled');
        $("#inputSearchFunction").select2()
    }
}

wmf.setAccessControl = function () {
    var infoForm = $('.fabricInformation');

    $('input[type=radio][name=allow_to]', infoForm).change(function (e) {
        var mode = $(this).val();

        if (mode === 'to_all') {
            $('.client_group input:checkbox', infoForm).removeAttr('checked').attr('disabled', 'disabled');
        } else {
            $('.client_group input:checkbox', infoForm).removeAttr('disabled');
        }
    });
};

wmf.deleteFabric = function () {
    var categoryForm = $('#category3');
    var categoryId = $('select.listBox', categoryForm).val();
    var fabricGrid = $('#fabricGrid');
    var selectedItems = $('input:checkbox:checked', fabricGrid);

    if (selectedItems.length == 0) {
        return;
    }

    if (!confirm('Delete selected ' + selectedItems.length + ' fabrics?')) {
        return;
    }

    selectedItems.each(function () {
        var fabricId = $(this).parent('.fabricItem').data('fid');

        $.ajax({
            url: '/manager/fabric/delete',
            type: 'POST',
            cache: false,
            data: {
                fid: fabricId
            },
            dataType: 'json',
            async: false,
            success: function (response) {
                if (response['success']) {

                } else {
                    switch (response['reason']) {
                    case 'DoesNotExist':
                        alert('Deleting fabric has failed : Does not exist');
                        break;
                    default:
                        alert('Deleting fabric has failed : ' + response['reason']);
                    }
                }
            },
            error: function () {
                alert('Deleting fabric has failed');
            }
        });
    });
    wmf.getFabricGrid(categoryId);
};

wmf.insertFabricBefore = function (srcfid, dstfid) {
    var categoryForm = $('#category3');
    var categoryId = $('select.listBox', categoryForm).val();

    $.ajax({
        url: '/manager/fabric/changeorder',
        type: 'POST',
        cache: false,
        data: {
            srcfid: srcfid,
            dstfid: dstfid
        },
        dataType: 'json',
        async: false,
        success: function (response) {
            if (response['success']) {
                wmf.getFabricGrid(categoryId);
            } else {
                alert('Changing fabric order has failed : ' + response['reason']);
            }
        },
        error: function () {
            alert('Changing fabric order has failed');
        }
    });
};

wmf.viewImageFull = function (imgSrc) {
    removeFullViewer();
    var body = $('body');

    var mask = $("<div id='imageFullViewer_mask'></div>")
        .css('opacity', 0.5)
        .appendTo(body)
        .click(function () {
            removeFullViewer();
        });

    var wrapper = $("<div id='imageFullViewer_wrapper'></div>")
        .appendTo(body)
        .click(function () {
            removeFullViewer();
        });

    var outline = $("<div id='imageFullViewer_outline'></div>").appendTo(wrapper);
    var imageFullViewer_img = $("<img src='" + imgSrc + "' />").hide().appendTo(outline);
    w3d.fn.fitImageIntoParent(imageFullViewer_img);

    function removeFullViewer() {
        $('#imageFullViewer_wrapper').remove();
        $('#imageFullViewer_mask').remove();
    }
};

wmf.setKeydownHandler = function () {
    $('body').keydown(function (evt) {
        var key = evt.which;

        switch (key) {
        case 27: // escape
            $('#imageFullViewer_wrapper').remove();
            $('#imageFullViewer_mask').remove();
            break;
        default:
            break;
        }
    });
};