/* option */
(function ($, LOGA) {

function formIsDirty(form) {
	for(var i = 0; i < form.elements.length; i++) {
		var element = form.elements[i];
		var type = element.type;
		if(type == "checkbox" || type == "radio") {
			if (element.checked != element.defaultChecked) {
				return true;
			}
		}
		else if(type == "hidden" || type == "password" || type == "text" || type == "textarea") {
			if(element.value != element.defaultValue) {
				return true;
			}
		}
		else if(type == "select-one" || type == "select-multiple") {
			for(var j = 0; j < element.options.length; j++) {
				if (element.options[j].selected	!= element.options[j].defaultSelected) {
					return true;
				}
			}
		}
	}
	return false;
}

$(window).on('beforeunload', function(e){
	e = e || window.event;
	if(formIsDirty(document.forms["formEdit"])) {
		// IE and Firefox
		if(e) {
			e.returnValue = LOGA.L('OPTION_NOT_SAVED_TIP');
		}
		// Safari
		return LOGA.L('OPTION_NOT_SAVED_TIP');
	}
});

$(document).on('submit', 'form', function() {
	$(window).off('beforeunload');
});

function randomString(len) {
	len = len || 32;
	/* except oOLl,9gq,Vv,Uu,I1 */
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
	var maxPos = $chars.length;
	var pwd = '';
	for(i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

$(document).on('click', '.generate_security_code', function() {
	$('#security_code').val(randomString(16));
});

$(document).on('click', '#add_custom_option', function() {
	$.FEA.dialog({
		title : LOGA.L('ADD_CUSTOM_OPTION'),
		content : document.getElementById('form_add_custom_option'),
		id : 'FACO',
		button : [
			{
				value : LOGA.L('OK'),
				callback : function() {
					$('#formAdd').submit();
					return false;
				}
			},
			{
				value : LOGA.L('CANCEL')
			}
		]
	}).showModal();
})
.on('click', '#sort_custom_option', function() {
	var sortOpt = {
		maxDepth: 1,
		rootClass: 'co_set_root',
		listClass: 'co_set',
		itemClass: 'co_item',
		listNodeName: 'tbody',
		itemNodeName: 'tr',
		normalBtnHTML: ''
	};
	$('.co_set_root').tree(sortOpt).on('change', updateOrder);

	$.FEA.dialog({
		title : LOGA.L('SORT_CUSTOM_OPTION'),
		content : document.getElementById('form_sort_custom_option'),
		id : 'FSCO',
		button : [
			{
				value : LOGA.L('OK'),
				callback : function() {
					$('#formSort').submit();
					return false;
				}
			},
			{
				value : LOGA.L('CANCEL')
			}
		]
	}).showModal();
});

var updateOrder = function() {
	$('.co_sort').each(function() {
		$(this).val($(this).parent().parent().index());
	});
};

})(jQuery, LOGA);
