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.setAccessControl();
	
	wmf.setKeydownHandler();
};

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);
	});
	
	$('.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');
};

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;
	var supersupercid;
	
	switch(level) {
    case '2':
		supercid = $(".listBox", "#category1").val();
        break;
	case '3':
		if ($(".listBox option:selected", "#category2").text()=="ALL") {
			supersupercid = $(".listBox", "#category1").val();
		} else {
			supercid = $(".listBox", "#category2").val();
		}
        break;
	}
	$.ajax({
		url: '/manager/fabric/category/getlist',
		type: 'POST',
		cache: false,
		data: {level: level, supercid:supercid, supersupercid:supersupercid},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var categoryList = $('Records', $(xml));			
			selector.empty();
			if (level > 1) {
				$("<option value='00' orderValue='00'>ALL</option>").appendTo(selector);
			}
			$('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'));
		}	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;
	}
	
	if (name == "ALL") {
		//alert('ALL 은 생성될 수 없습니다.');
		alert('ALLは、生成されることがありません');
		return false;
	}
	
	var level = form.attr('id').split('ategory')[1];
	var supercid ;
	if (level > 1) {
		var superlevel = level-1;
		var supercategory = "#category"+superlevel;
		if ($(".listBox", supercategory).val()=="00") {
			//alert("특정 상위 카테고리를 지정해 주십시오.");
			alert("特定の親カテゴリを指定してください。");
			return false;
		}
		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;
	}
	
	if (new_name == "ALL") {
		//alert('ALL 은 생성될 수 없습니다.');
		alert('ALLは、生成されることがありません');
		return false;
	}
	
	$.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.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;
	}
	
	if (selectedValue == '00' || dstOption.val() == '00') {
		//alert('ALL 항목의 위치는 변경될 수 없습니다.');
		alert('ALLアイテムの位置は変更されることがありません。');
		return false;
	}
	
	var level = form.attr('id').split('ategory')[1];
	if (level == '3') {
		if ($(".listBox", "#category2").val()=="00") {
			alert("특정 상위 카테고리를 지정해 주십시오.");
			alert("特定の親カテゴリを指定してください");
			return false;
		}
	}
	
	$.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();
	
	var level = 3;
	var uppercategory;
	
	if (categoryId == '-1') {
		return;
	} else if (categoryId == '00') {
		if ($(".listBox", '#category2').val()=="00") {
			uppercategory = $(".listBox", '#category1').val();
			level = 1;
		} else {
			uppercategory = $(".listBox", '#category2').val();
			level = 2;
		}
	}
	$.ajax({
		url: '/manager/fabric/getlist_by_manager',
		type: 'POST',
		cache: false,
		data: {
			categoryId: categoryId, level: level, uppercategory: uppercategory
		},
		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('-');
	
	$.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
		},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmf.getFabricGrid(categoryId, response['id']);
			}
			else {
				alert('Saving fabric has failed');
			}
		},
		error: function() {
			alert('Saving fabric has failed');
		}
	});
};

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');
				}
			}
			
			$('#fabricViewer').data('fid', fabricId);
		},
		error: function() {
			alert('Loading fabric information has failed');
		}
	});
};

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 = $('.categorySelector');
	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 = $('.categorySelector');
	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;
		}
	});
};