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

var wmp = w3d.manager.product;

wmp.initManageProduct = function() {
	// set drop item ( by drag & drop )
	wmp.setDropItem();
	
	// set product functions ( delete/new/save )
	wmp.setProductFunctions();
	
	var categoryForms = $('.categorySelector');
	
	// set category functions ( create/modify/delete )
	wmp.setCategoryFunctions(categoryForms);
	
	// init categorySelector
	wmp.getCategoryList(categoryForms.first().data('parentId', '0'));
	
	// init product information
	wmp.initProductInfo();
	
	wmp.setAccessControl();
};

wmp.setDropItem = function() {
	$('#productImageViewer')
		.drop("start",function(){
			$( this ).addClass("active");
		})
		.drop(function( ev, dd ){
			wmp.getProductInfo({
				pid: $(dd.drag).data('pid'),
				image_url: $(dd.drag).data('image_url'),
				name: $(dd.drag).data('name'),
				code: $(dd.drag).data('code'),
				url: $(dd.drag).data('url'),
				type: $(dd.drag).data('type'),
        valid: $(dd.drag).data('valid'),
				allowed_group_ids: $(dd.drag).data('allowed_group_ids')
			});
			$(dd.drag).addClass('showing');
		})
		.drop("end",function( ev, dd ){
			$( this ).removeClass("active");
		});
	
	$.drop({ mode:"intersect" });
};

wmp.setCategoryFunctions = function(forms) {
	forms.each(function(i) {
		var form = $(this);
		$('select.listBox', form).change(function() {
			// 크롬에서 <select/>의 빈 공간을 클릭해도 change 이벤트가 발생하는 것을 막기 위해 선택된 값을 저장하여 비교한다
			var formerValue = $(this).data('selectedId');
			var nowSelected = $(this).val();
			if (formerValue == nowSelected) {
				return false;
			}
			
			wmp.selectCategory(form, nowSelected);
		});
		
		$('.categoryFunc.create', form).click(function() {
			wmp.createCategory(form);
		});
		
		$('.categoryFunc.modify', form).click(function() {
			wmp.modifyCategory(form);
		});
		
		$('.categoryFunc.delete', form).click(function() {
			wmp.deleteCategory(form);
		});
		
		$('.categoryUpDown', form).click(function() {
			wmp.switchCategory(form, $(this).hasClass('orderUp'));
		});
	});
};

wmp.setProductFunctions = function() {
	/* // 선택 모드
	$('#select_mode_btn').click(function() {
		if ($(this).data('selectmode')) {
			// 선택 모드 해제
			$('.productItem input:checkbox').removeAttr('checked').hide();
			$(this).data('selectmode', false);
			$(this).text('선택');
		}
		else {
			// 선택 모드 설정
			$('.productItem input:checkbox').show();
			$(this).data('selectmode', true);
			$(this).text('해제');
		}
	});
	*/
	$('#delete_product_btn').click(wmp.deleteProduct);
	
	//$('#new_product_btn').click(wmp.initProductInfo);
	
	$('#save_product_btn').click(wmp.saveProduct);
};

wmp.initProductInfo = function() {
	var infoForm = $('.productInfo');
	
	$('#productImageViewer', infoForm).empty();
	$('.detail_input input:text', infoForm).val('');
	$('.detail_input textarea', infoForm).val('');
	$('.detail_input input:radio', infoForm).removeAttr('checked');
	$('.client_group input:checkbox', infoForm).removeAttr('checked').attr('disabled', 'disabled');
	$('#rd_allow_to_all', infoForm).attr('checked', 'checked');
	
	$('.productItem.showing').removeClass('showing');
	
	infoForm.data('pid', '-1');
};

wmp.getCategoryList = function(form, selectedId, noPropagation) {
	// noPropagation(default: false) 값이 true이면 다음 레벨의 카테고리 폼 또는 그리드를 변경하지 않는다
	noPropagation = noPropagation || false;
	
	var selector = $('select.listBox', form);
	var parentId = form.data('parentId');
	var level = form.attr('level');
	
	if (parentId == '-1') {
		selector.empty();
		wmp.selectCategory(form);
		return;
	}
	
	$.ajax({
		url: '/manager/product/category/getlist',
		type: 'POST',
		cache: false,
		data: {CID: parentId},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var categoryList = $('Records', $(xml));
			
			if (categoryList.attr('Count') > 0 && level !== categoryList.attr('Level')) {
				alert('Loading category list has Failed');
				return false;
			}
			
			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);
			});
			wmp.selectCategory(form, selectedId, noPropagation);
		},
		error: function() {
			alert('Loading category list has Failed');
		}
	});
};

wmp.selectCategory = function(form, selectedId, noPropagation) {
	// noPropagation(default: false) 값이 true이면 다음 레벨의 카테고리 폼 또는 그리드를 변경하지 않는다
	noPropagation = noPropagation || false;
	
	var selector = $('select.listBox', form);
	var nameInput = $('input.categoryName', form);
	var level = form.attr('level');
	var next_form = form.next('.categorySelector');
	
	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());
		// 하위 카테고리에 parentId로 전달
		selectedId = selectedOption.val();
	}
	else {
		nameInput.val('');
		// 하위 카테고리에 parentId로 -1을 전달 ( 선택된 카테고리가 없음을 의미 )
		selectedId = '-1';
	}
	
	// 크롬에서 <select/>의 빈 공간을 클릭해도 change 이벤트가 발생하는 것을 막기 위해 선택된 값을 저장하여 비교한다
	selector.data('selectedId', selectedId);
	
	if (noPropagation) {
		return;
	}
	else {
		if (next_form.length) {
				next_form.data('parentId', selectedId);
				wmp.getCategoryList(next_form);
		}
		else {
			// 그리드 리셋 - 선택 카테고리 : selectedId
			wmp.getProductGrid(selectedId);
		}
	}
};

wmp.createCategory = function(form) {
	var parentId = form.data('parentId');
	var name = $('input.categoryName', form).val();
	var level = form.attr('level');
	
	if (name.length == 0) {
		return;
	}
	else if (name.length < 2) {
		alert('Category name must be at least 2 characters long.');
		return;
	}
	
	$.ajax({
		url: '/manager/product/category/create',
		type: 'POST',
		cache: false,
		data: {parentId: parentId, level: level, name: name},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmp.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');
		}
	});
};

wmp.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/product/category/modify',
		type: 'POST',
		cache: false,
		data: {cid: selectedValue, name: new_name},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmp.getCategoryList(form, selectedValue, false);
			}
			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');
		}
	});
};

wmp.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/product/category/delete',
		type: 'POST',
		cache: false,
		data: {cid: selectedValue},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmp.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');
		}
	});
};

wmp.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;
	}
	
	$.ajax({
		url: '/manager/product/category/switchorder',
		type: 'POST',
		cache: false,
		data: {scid: selectedValue, dcid: dstOption.val()},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmp.getCategoryList(form, selectedValue, noPropagation = true);
			}
			else {
				alert('Switching category order has Failed');
			}
		},
		error: function() {
			alert('Switching category order has Failed');
		}
	});
};

wmp.getProductGrid = function(categoryId, showingProductId) {
	showingProductId = showingProductId || $('.productInfo').data('pid');
	$('#productImageViewer').removeClass("active available");
	
	var productGrid = $('#productGrid');
	productGrid.empty();
	//$('#select_mode_btn').data('selectmode', false).text('선택'); // 선택 모드
	wmp.initProductInfo();
	
	if (categoryId == '-1') {
		return;
	}
	
	$.ajax({
		url: '/manager/product/getlist',
		type: 'POST',
		cache: false,
		data: {
			CID: categoryId
		},
		dataType: 'xml',
		async: false,
		success: function(xml) {
			var ProductListXML = $('Records', $(xml));
			
			$('Record', ProductListXML).each(function(i) {
				var thumbSrc = $(this).attr('thumb_url');
				var imgSrc = $(this).attr('path');
				var productId = $(this).attr('ID');
				var productName = $(this).attr('Name');
				var productNo = $(this).attr('StyleNO');
				var productPath = $(this).attr('URL');
				var productType = $(this).attr('Type');
				var productValid = $(this).attr('Visible');
				var allowed_group_ids = $(this).attr('allowed_group_ids');
				
				var productItem = $("<div class='productItem' style='background-image: url(" + thumbSrc + ");'></div>")
					.data({
						pid: productId,
						image_url: imgSrc,
						name: productName,
						code: productNo,
						url: productPath,
						type: productType,
						valid: productValid,
						allowed_group_ids: allowed_group_ids
					})
					.append("<input type='checkbox' class='checkbox'/>")
					.appendTo(productGrid);
					
					var nameLabel = $("<div class='label name'>" + productName + "</div>")
						.appendTo(productItem);
						
					if (productValid == 'False') {
						$("<div class='label background'></div>")
							.css('opacity', 0.7)
							.css('height', nameLabel.height())
							.css('background-color', 'lightgrey')
							.appendTo(productItem);
					}
					else {
						$("<div class='label background'></div>")
							.css('opacity', 0.7)
							.css('height', nameLabel.height())
							.appendTo(productItem);					
					}

					if (parseInt(productId, 10) === parseInt(showingProductId, 10)) {
						wmp.getProductInfo({
							pid: productItem.data('pid'),
							image_url: productItem.data('image_url'),
							name: productItem.data('name'),
							code: productItem.data('code'),
							url: productItem.data('url'),
							type: productItem.data('type'),
              valid: productItem.data('valid'),
							allowed_group_ids: productItem.data('allowed_group_ids')
						});
						productItem.addClass('showing');
					}
			});
			
			wmp.setItemsDragDrop(productGrid);
		},
		error: function() {
			alert('Loading Product list has failed');
		}
	});
};

wmp.setItemsDragDrop = function(grid) {
	$('.productItem', 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:'#productImageViewer, .productItem' })
		.drop("start",function(){
			$( this ).addClass("active");
			$( this ).append($("<div class='caret'></div>"));
		})
		.drop(function( ev, dd ){
			if ( this != dd.drag )
				wmp.insertProductBefore($(dd.drag).data('pid'), $(this).data('pid'));
		})
		.drop("end",function( ev, dd ){
			$( this ).removeClass("active");
			$('.caret', this).remove();
		});
		
	$("<div class='productItem null'></div>")
		.drop("start",function(){
			$( this ).addClass("active");
			$( this ).append($("<div class='caret'></div>"));
		})
		.drop(function( ev, dd ){
			if ( this != dd.drag )
				wmp.insertProductBefore($(dd.drag).data('pid'), '0');
		})
		.drop("end",function( ev, dd ){
			$( this ).removeClass("active");
			$('.caret', this).remove();
		}).appendTo(grid);
};

wmp.saveProduct = function() {
	var infoForm = $('.productInfo');
	var productId = infoForm.data('pid');
	var categoryForm = $('.categorySelector:last');
	var categoryId = $('select.listBox', categoryForm).val();
	
	if (productId < 0 || !confirm('Save changes?')) {
		return
	}
	
	var productName = $('input#inp_productName', infoForm).val();
	var productNo = $('input#inp_productNo', infoForm).val();
	var productPath = $('textarea#inp_productPath', infoForm).val();
	var typeRadios = $('div#typeRadios', infoForm);
	var productType = $('input:checked', typeRadios).val();
	var productValid = $('input[name=valid]:checked', infoForm).val();     
	
	if (!productType) {
		alert('Select product type.');
		return;
	}
	
	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/product/modify',
		type: 'POST',
		cache: false,
		data: {
			pid: productId,
			name: productName,
			code: productNo,
			type: productType,
			url: productPath,
      Visible: productValid,
			allowed_group_ids: allowed_group_ids
		},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmp.getProductGrid(categoryId, response['id']);
			}
			else {
				alert('Modifying product information has failed');
			}
		},
		error: function() {
			alert('Modifying product information has failed');
		}
	});
};

wmp.getProductInfo = function(info) {
	var infoForm = $('.productInfo');
	var imageViewer = $('#productImageViewer', infoForm);
	
	wmp.initProductInfo();
	
	var productId = info.pid;
	var imageURL = info.image_url;
	var productName = info.name;
	var productNo = info.code;
	var productPath = info.url;
	var productType = info.type;
  var productValid = info.valid;
	var str_allowed_group_ids = info.allowed_group_ids;
	
	var mainImage_element = $("<div class='mainImage_element'></div>").appendTo(imageViewer);
	var mainImage_element_img = $("<img src='" + imageURL + "' />").hide().appendTo(mainImage_element);
	w3d.fn.fitImageIntoParent(mainImage_element_img);
	
	$('input#inp_productName', infoForm).val(productName);
	$('input#inp_productNo', infoForm).val(productNo);
	$('textarea#inp_productPath', infoForm).val(productPath);
	
	var typeRadios = $('div#typeRadios');
	$(':radio', typeRadios).removeAttr('checked');
	$(':radio[value=' + productType + ']', typeRadios).attr('checked', 'checked');
  
  if (productValid == 'True')
    $('input#chk_valid', infoForm).attr('checked', 'checked');
  else
    $('input#chk_valid', infoForm).removeAttr('checked');
	
	var allowed_group_ids = str_allowed_group_ids.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');
		}
	}
	
	infoForm.data('pid', productId);
};

wmp.setAccessControl = function() {
	var infoForm = $('.productInfo');
	
	$('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');
		}
	});
};

wmp.deleteProduct = function() {
	var categoryForm = $('.categorySelector:last');
	var categoryId = $('select.listBox', categoryForm).val();
	var productGrid = $('#productGrid');
	var selectedItems = $('input:checkbox:checked', productGrid);
	
	if (selectedItems.length == 0) {
		return
	}
	
	if (!confirm('Delete selected ' + selectedItems.length + ' Products?')) {
		return
	}
	
	selectedItems.each(function() {
		var productId = $(this).parent('.productItem').data('pid');
		
		$.ajax({
			url: '/manager/product/delete',
			type: 'POST',
			cache: false,
			data: {
				ID: productId
			},
			dataType: 'json',
			async: false,
			success: function(response) {
				if (response['success']) {
					
				}
				else {
					switch (response['reason']) {
						case 'DoesNotExist':
							alert('Deleting product has failed : Does not exist');
							break;
						default:
							alert('Deleting product has failed : ' + response['reason']);
					}
				}
			},
			error: function() {
				alert('Deleting product has failed');
			}
		});
	});
	wmp.getProductGrid(categoryId);
};

wmp.insertProductBefore = function(srcpid, dstpid) {
	var categoryForm = $('.categorySelector:last');
	var categoryId = $('select.listBox', categoryForm).val();
	
	$.ajax({
		url: '/manager/product/changeorder',
		type: 'POST',
		cache: false,
		data: {
			srcpid: srcpid,
			dstpid: dstpid
		},
		dataType: 'json',
		async: false,
		success: function(response) {
			if (response['success']) {
				wmp.getProductGrid(categoryId);
			}
			else {
				alert('Changing product order has failed : ' + response['reason']);
			}
		},
		error: function() {
			alert('Changing product order has failed');
		}
	});
};