
function makeSubList(parent, child, isSubselectOptional, childVal) {
	$("body").append("<select style='display:none' id='" + parent + child + "'></select>");
	$('#' + parent + child).html($("#" + child + " option"));

	var parentValue = $('#' + parent).attr('value');
	
	if (parentValue) {
		$('#' + child).html($("#" + parent + child + " .sub_" + parentValue).clone());
		if ($('#' + child + ' option:first').attr('value')) {
			$('#' + child).prepend("<option value=''> -- Select -- </option>");
		}
		$('#' + child).val(childVal);
	}
	else {
		$('#' + child).html($("#" + parent + child + " option").clone());
	}

	childVal = (typeof childVal == "undefined") ? "" : childVal;
	$("#" + child + ' option[value="' + childVal + '"]').attr('selected', 'selected');

	$('#' + parent).change( function() {
		var parentValue = $('#' + parent).attr('value');
		
		if (parentValue) {
			$('#' + child).html($("#" + parent + child + " .sub_" + parentValue).clone());
		}
		else {
			$('#' + child).html($("#" + parent + child + " option").clone());
		}
		if (isSubselectOptional) {
			if ($('#' + child + ' option:first').attr('value')) {
				$('#' + child).prepend("<option value=''> -- Select -- </option>");
			}
			$('#' + child).val('');
		}
		$('#' + child).trigger("change");
		$('#' + child).focus();
	});
}

$(function() {
	makeSubList('area1', 'area2', true);
	makeSubList('ctg2', 'ctg3', true, $('#ctg3').val());
	
	$('.addCollectionBtn').bind('mouseenter',
		function() { $(this).attr('src', TP_path + 'img/common/addTp_over.gif');}
	);
	$('.addCollectionBtn').bind('mouseleave',
		function() { $(this).attr('src', TP_path + 'img/common/addTp.gif');}
	);
	
	$('.addCollectionBtn').bind('click', function(){
		var id = $(this).attr('id');
		var codes = id.split('_');
		var code = codes[1];
		var obj = this;
		
		code = parseInt(code);
		
		var elm;
		
		$.ajax({
			dataType: 'json',
			type: 'POST',
			data: {
				code: code
			},
			url: TP_path + 'myPage/addMyCollection.php',
			beforeSend: function() {
				elm = (codes[2]) ? '.addCollectionBtn' : obj;
				$(elm).unbind('click').unbind('mouseenter').unbind('mouseleave')
					.attr('src', TP_path + 'img/common/addTp_working.gif')
					.css('cursor', 'default');
			},
			success: function (json) {
				if (json.status == 1) {
					$(obj).effect("transfer", {
						to: "#tp_nofCollection",
						className: 'ui-effects-transfer'
						},
						800,
						function() {
							$(elm).attr('src', TP_path + 'img/common/addTp_comp.gif');
							$('#tp_nofCollection').html(json.count);
						}
					);
				}
				else {
					$(obj).attr('src', TP_path + 'img/common/addTp.gif');
				}
			},
			timeout: 10000
		});
	});
});


