var JSON_FAIL = "0";
var JSON_SUCCESS = "1";
var JSON_NOT_LOGIN = "2";
var JSON_DATA_REQUIRED = "3";

var TOAST_FORM_ARR = [];
var MESSAGES= { 
    "required" : "필수항목을 입력하지 않았습니다. ", 
	"search required" : "검색어를 입력해 주세요. ",
	"double submit" : "처리중입니다",
	"number invalid" : "숫자만 입력가능합니다.",
	"max length" : "길이 제한을 초과하였습니다. 초과된 부분은 자동으로 삭제됩니다.",
	"not yet" : "error handle~~(not yet)"
};

try {document.execCommand('BackgroundImageCache', false, true)} catch(e){}

function getLength(value) {

	var total_len=0;
	for (i = 0; i<value.length; i++){
		total_len++;
		if (value.charCodeAt(i) > 127) total_len++;
	}

	return total_len;

};
function makeSubstr(value,len){

	var total_len = 0;
	var new_value = '';

    for (var i=0;i<value.length; i++) {
		total_len++;
		if (value.charCodeAt(i) > 127) total_len++;

        if (total_len>len) break;
        else new_value += value.charAt(i);
    }
    return new_value;
};

function toast_validate_form(obj, options) {

	options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);

	if (typeof obj == "string")
		obj = document.getElementById(obj);

	options.form_id = obj;
	for (var i = 0, element; element = obj.elements[i]; i++) 
		if (!toast_validate(element, options)) return false;

	return true;
};

function toast_validate(elem, options) {

	options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);

	var attr = jQuery.trim($(elem).attr("toast"));
	if (attr) {

		var arr = "{" + attr + "}";
		eval("arr = " + arr);
		var rules = [];

		jQuery.each(arr, function(elem, val) {
			rules[rules.length] = { method:elem, params:val }
		});

		return(toast_blur_validate(elem, rules, options));
	}
	return true;
}

jQuery.fn.toastValidate = function(options){

	options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);

	this.each(function(){
		var elem = $(this);
		var attr = elem.attr("toast");

		if (attr) {
			var arr = "{" + attr + "}";
			eval("arr = " + arr);

			var rules = [];
			jQuery.each(arr, function(elem, val) {
				rules[rules.length] = { method:elem, params:val }
			});

			elem.keyup(function(){  
				if (!elem.val()) return;
				for (var i = 0; i < rules.length; i++) {
					m = rules[i].method; p = rules[i].params;
					switch(m) {
					case 'maxLength':
						if (p < getLength(elem.val())){
							toast_invalid(elem, MESSAGES["max length"]);
							elem.val(makeSubstr(elem.val(), p));
						}
						break;
					case 'special':
                    	if (!p && /[~!@\#$%<>^&*\()\-=+_\']/gi.test(elem.val())){
                        	elem.val(elem.val().substr(0,elem.val().length-1));
                      		return toast_invalid(elem, MESSAGES["special invalid"], options);
                        }
                        break;
					}
				}
			})
		}
	});
}

function toast_blur_validate(element, rules, options) {
	var elem = $(element);
	for (var i = 0; i < rules.length; i++) {
		m = rules[i].method; p = rules[i].params;
		switch(m) {
			case 'required': 
				if (options.form_id) {
					if (typeof p == 'boolean' && p) {
						if (jQuery.fn.toastValidate.checkable(element)) {
							if (!$("input[name='"+element.name+"']:checked").length)
								return toast_invalid(elem,MESSAGES["required"],options);
						} 
						else
						if (getLength(elem.val().replace(/\s+/g,"")) == 0) 
							return toast_invalid(elem,MESSAGES["required"],options);
					}
					else
					if (typeof p == "string") {
						var checkable = jQuery(p).length > 0 ? true : false;
						if (checkable) {
							if (jQuery.fn.toastValidate.checkable(element)) {
								if (jQuery(document).find("[name='"+element.name+"']").filter(":checked").length == 0)
									return toast_invalid(elem,MESSAGES["required"],options);
							} 
							else 
							if (getLength(elem.val().replace(/\s+/g,"")) == 0) 
								return toast_invalid(elem,MESSAGES["required"],options);
						}
						if (!checkable && elem.val() != "") elem.val("");
					}
				}
				break;
			case 'alphanum':
                if(elem.val() != "" && p && !/^[A-Za-z0-9]+$/.test(elem.val()))
                 	return toast_invalid(elem, MESSAGES["alphanum invalid"], options);
                break;
			case 'number':
				if(elem.val() != "" && !/^[0-9]+$/.test(elem.val()))
					return toast_invalid(elem, MESSAGES["number invalid"], options);
				break;
			case 'equal':
				if (elem.val() != jQuery(p).val()) 
					return toast_invalid(elem, MESSAGES["equal invalid"], options);
				break;
			case 'rangeLength':
				var length = getLength(elem.val());
				if (elem.val() != "" && (length < p[0] || length > p[1])) 
					return toast_invalid(elem, MESSAGES["rangeLength invalid"], options);
				break;
			case 'maxNumber':
           		if(p && (!/^\d+$/.test(elem.val()) || elem.val()>p)){
                	elem.val(elem.val().substr(0,elem.val().length-1));
                	return toast_invalid(elem, p+MESSAGES['maxNumber invalid']);
          		}
               break;
            case 'minNumber':
            	if(p && (!/^\d+$/.test(elem.val()) || elem.val()<p)){
                	elem.val(p);
                    return toast_invalid(elem, p+MESSAGES['minNumber invalid']);
                }
                break;
		}
	}

	return true;
}

function toast_invalid(obj, msg, options) {

	var	message = obj.attr("title") || msg; 
	if (options && options.label_id && $(options.label_id).length) {
		$(options.label_id).html(message);
		if (typeof options.callback == "function") options.callback();
	}
	else alert(message);

	obj.focus();
	return false;
}

jQuery.extend(jQuery.fn.toastValidate, {
	defaults : {
		form_id  : this.form_id,
		label_id : this.lable_id,
		callback : this.callback
	},

	checkable: function (element) {
		return /radio|checkbox/i.test(element.type);
	}
});


function toast_validate_form_return(obj){
    if(typeof obj == "string")
        obj = document.getElementById(obj);

    var form_idx = $.inArray(obj, TOAST_FORM_ARR);
    if(form_idx != -1) TOAST_FORM_ARR[form_idx] = "";
};

function toast_validate_form(obj, options){

    options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);

    if(typeof obj == "string")
        obj = document.getElementById(obj);

    options.form_id = obj;

    for(var i = 0, element; element = obj.elements[i]; i++)
        if(!toast_validate(element, options))
            return false;

    if($.inArray(obj, TOAST_FORM_ARR) != -1)  {
        alert(MESSAGES["double submit"]);
        return false;
    }
    else {
        TOAST_FORM_ARR[TOAST_FORM_ARR.length] = obj;
        return true;
    }
};

function toast_ajax_error(response, text_status){

	if(response.status != "0" && response.status != "12029"){
		if(response.status == "404" ||
        response.status == "500" ||
        response.status == "503")
        alert(MESSAGES[response.status]);
    else
        alert(response.status + "::" + text_status);	
	}
}

function toast_error_handle(result){
	alert("[ERROR:"+result.status + "] ajax fail");
};

//* -------------------------- [ajaxfileupload plugin] --------------------*//
jQuery.extend({

    createUploadIframe: function(id, uri)
	{
		//create frame
        var frameId = 'jUploadFrame' + id;

        if(window.ActiveXObject) {
        	var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
           	if(typeof uri== 'boolean'){
            	io.src = 'javascript:false';
            }
            else if(typeof uri== 'string'){
            	io.src = uri;
            }
        }
        else {
        	var io = document.createElement('iframe');
            io.id = frameId;
            io.name = frameId;
        }
        io.style.position = 'absolute';
        io.style.top = '-1000px';
        io.style.left = '-1000px';

        document.body.appendChild(io);

        return io
    },
    createUploadForm: function(id, fileElementId, addElementId)
	{
		//create form
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);

		if (typeof addElementId != undefined) {
            var orgElement = $('#'+ addElementId);
            var addElement = $(orgElement).clone();
            $(orgElement).attr('id', 'jUploadAdd'+id);
			$(addElement).attr('name', $(orgElement).attr('name'));
            $(orgElement).before(addElement);
            $(orgElement).appendTo(form);
        }
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');
		return form;

    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
		s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
		var form = jQuery.createUploadForm(id, s.fileElementId, s.addElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;

        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}
        var requestDone = false;
        // Create the request object
        var xml = {}
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{
			var io = document.getElementById(frameId);
            try
			{
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;

				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout")
			{
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );

                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e)
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function(){
					try
					{
						$(io).remove();
						$(form).remove();
					} catch(e) {
						jQuery.handleError(s, xml, null, e);
					}

				}, 100)

                xml = null
            }
        }
        // Timeout checker
        if ( s.timeout > 0 )
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try
		{
           // var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
            if(form.encoding)
			{
                form.encoding = 'multipart/form-data';
            }
            else
			{
                form.enctype = 'multipart/form-data';
            }
            $(form).submit();

        } catch(e)
		{
            jQuery.handleError(s, xml, null, e);
        }
        if(window.attachEvent){
            document.getElementById(frameId).attachEvent('onload', uploadCallback);
        }
        else{
            document.getElementById(frameId).addEventListener('load', uploadCallback, false);
        }
        return {abort: function () {}};

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
			 eval( "data = " + data );
        // evaluate scripts within html
        if( type == "html" )
            jQuery("<div>").html(data).evalScripts();
        return data;
    }
})

/*----------------------------- smart ----------------------------------*/

$(function(){

	$("input[toast], textarea[toast]").toastValidate();

	$("img.help_button").mouseover(function(){
		var layer_id = $(this).attr("id");
		$("div#"+layer_id).show();
	});

	$('img.help_button').mouseout(function() {
		var layer_id = $(this).attr("id");
		$("div#"+layer_id).hide();
	});


	// 등록
	$("img#write_register").click(function(){
		var toast_form = "bbs_write_form";
        if (!toast_validate_form(toast_form)) return false;

		var queryString = $("#"+toast_form).serialize();
        $.ajax({
            type : "POST",
            url  : "makeWrite.jsp",
            data : 	queryString, 
			dataType : "json",
            success : function(data){
				if (data.result > '0')
					document.location.href = "list.jsp?"+data.go;
				else
					alert(data.message);
            },
            error : function (res, e) {
                toast_ajax_error(res, "[makeWrite]:"+e);
            },
            complete : function(res, e){
                toast_validate_form_return(toast_form);
            }
        });
        return false;
    });

	// 수정
	$("img#write_edit").click(function(){
		var toast_form = "bbs_update_form";
        if (!toast_validate_form(toast_form)) return false;

		var queryString = $("#"+toast_form).serialize();
        $.ajax({
            type : "POST",
            url  : "makeUpdate.jsp",
            data : 	queryString, 
			dataType : "json",
            success : function(data){
				if (data.result > '0')
					document.location.href = "con.jsp?"+data.go;
				else
					alert(data.message);
            },
            error : function (res, e) {
                toast_ajax_error(res, "[makeWrite]:"+e);
            },
            complete : function(res, e){
                toast_validate_form_return(toast_form);
            }
        });
        return false;
    });

	$("img#qna_replay").click(function(){
		var tmp = $(this).parents("tr.line").attr("id");

	});


	$("form#search_form").submit(function(){
		if ($.trim($("input[name='search']", this).val(), this) == '') {
            alert(MESSAGES['search required']);
            $('input[type=text]', this).focus();
            return false;
        } else {
			if ($.trim($("input[name='search']", this).val()).length < 2){
				alert('최소 두자 이상 입력하시기 바랍니다.');
            	return false;
			}
		}

		document.location.href ="search.jsp?"+$(this).serialize();
		return false;
	});
	$("img#search").click(function(){
		var f = $(this).parents("form").find("input[name='search']");
		if ($.trim(f.val()) == '') {
            alert(MESSAGES['search required']);
			f.focus();
            return false;
        } else {
			if ($.trim(f.val()).length < 2){
				alert('최소 두자 이상 입력하시기 바랍니다.');
            	return false;
			}
		}
		document.location.href ="search.jsp?"+f.serialize();
		return false;
	});


	$("img#write_cancel").click(function(){
		document.location.href = "list.jsp?bbs="+ $(this).parents("tr").attr("id");
	});

	$("#con_del").click(function(){
		$("#apDiv1").find("input[name='event']").val("delete");

		$.extend($.blockUI.defaults.overlayCSS, 
			{backgroundColor: '#000', opacity: '0.4'});

    	$.blockUI({
        	message: $("#apDiv3"),
        	css: {
            	top: '20%',
            	left: '30%',
            	textAlign: 'justify',
            	border: 'none',
            	backgroundColor: '#000'
        	}
    	});
	});
	$("#con_edit").click(function(){
		if ($("#apDiv1").find("input[name='event']").val() == "")
			$("#apDiv1").find("input[name='event']").val("update");

		$.extend($.blockUI.defaults.overlayCSS, 
			{backgroundColor: '#000', opacity: '0.4'});

    	$.blockUI({
        	message: $("#apDiv1"),
        	css: {
            	top: '20%',
            	left: '30%',
            	textAlign: 'justify',
            	border: 'none',
            	backgroundColor: '#000'
        	}
    	});
	});

	$("img#check_delete").click(function(){
		$("#con_edit").trigger("click");	
	});

	$("#password_check").submit(function(){
		if (!toast_validate_form(this)) return false;
		var toast_form = this;

		$.ajax({
			type : "POST",
			url  : "makeCheckPassword.jsp",
			data : $(this).serialize(),
			dataType : "json",
			success : function(data){
				if (data.result == '0' )
					$(toast_form).find("td#password_info").html("※ 설정하신 비밀번호와 일치하지 않습니다.<br /> 다시 입력해 주세요.");
				else
				if (data.result == '-1')
					alert(data.message);
				else {
					var submit_form = "form#"+ $(toast_form).find("input[name='event']").val()+"_form";
					if (submit_form.indexOf("delete"))
						$(submit_form).find("input[name='user_password']").val($(toast_form).find("input[type='password']").val());
					$(submit_form).submit();
				}
            },
            error : function (res, e) {
                toast_ajax_error(res, "[makeCheckPassword]:"+e);
            },
            complete : function(res, e){
                toast_validate_form_return(toast_form);
            }
		});
		return false;
	});

	$("img#check_password").click(function(){
		$("#password_check").trigger("submit");
	});

	$("img#cancel").click(function(){
		$.unblockUI();
		$("#apDiv1").find("input[name='event']").val(""); 
		$("#apDiv1").find("input[type='password']").val("");
		$("#apDiv1").find("td#password_info").text("※ 설정 하신 비밀번호를 입력해 주세요.");
	});

	// For Admin
	$("#login_form").submit(function(){
		if (!toast_validate_form(this)) return false;
		var toast_form = this;

		$.ajax({
			type : "POST",
			url  : "makeLogin.jsp",
			data : $(this).serialize(),
			dataType : "json",
			success : function(data){
				if (data.result <= 0) alert(data.message);
				else
					document.location.href ="list.jsp";	
			},
            error : function (res, e) {
                toast_ajax_error(res, "[makeLogin]:"+e);
            },
            complete : function(res, e){
                toast_validate_form_return(toast_form);
            }
		});
		return false;

	});
	$("img#admin_login").click(function(){
		$("#login_form").trigger("submit");
	});



	$("img#admin_delete").click(function(){
		if (confirm("삭제하시겠습니까?")){
			$("form#delete_form").submit();
		}
	});

	$("img#admin_delete_list").click(function(){

		if ($("input[type='checkbox']:checked").length == 0)
			alert("선택된 게시글이 없습니다.");
		else
		{
			var checked_list = "";
			$("input[type='checkbox']:checked").each(function(){
				checked_list += $(this).val()+",";
			});
			$("form#list_form").find("input[name='noList']").val(checked_list);

			if (confirm("삭제하시겠습니까?")){
				$("form#list_form").submit();
			}
		}
	});

	// 목록 - 페이지이동
	$("span.search").find("a").click(function(){
		var no = $(this).attr("id").split("_");
		document.location.href = "list.jsp?bbs="+no[0]+"&p="+no[1];
	});


	// 파일 - 업로드
	$("input[name='admin_image']").change(function(){
		var file_element ="admin_image";

		$.ajaxFileUpload({
			url : "makeFile.jsp",
			secureuri:false,
            fileElementId:file_element,
            dataType: "json",
            success: function (data)
            {
				if (data.result > 0) {
					$("input[name='phone_image']").val(data.image);
					$("span#admin_image_name").text(data.image);
				}
            },
            error: function (data, status, e)
            {
            	alert("fail..");
            }	
		});

		return false;
	});

	// Admin - Phone 등록
	$("img#phone_write").click(function(){
		var toast_form = "phone_write_form";
        if (!toast_validate_form(toast_form)) return false;

		var queryString = $("#"+toast_form).serialize();

        $.ajax({
            type : "POST",
            url  : "makePhone.jsp",
            data : 	queryString, 
			dataType : "json",
            success : function(data){
				if (data.result > '0')
					document.location.href = "main.jsp";
				else
					alert(data.message);
            },
            error : function (res, e) {
                toast_ajax_error(res, "[makeWrite]:"+e);
            },
            complete : function(res, e){
                toast_validate_form_return(toast_form);
			}
		});

		return false;
	});

	$("img#phone_update").click(function(){
		var queryString = $("#phone_list_form").serialize();
		if (queryString == '') {
			alert('폰을 선택하세요.');
			return false;
		}
		document.location.href = "main_update.jsp?"+queryString;
	});

	$("img#phone_delete").click(function(){
		var queryString = $("#phone_list_form").serialize();
		if (queryString == '') {
			alert('폰을 선택하세요.');
			return false;
		}
		queryString = "phone_no=";
		$("input[name='phone_no']:checked").each(function(){
			queryString += $(this).val()+",";
		});

		if (confirm("삭제하시겠습니까?")){
			$.ajax({
				type : "POST",
				url  : "makeDeletePhone.jsp",
				data : queryString,
				dataType : "json",
				success : function(data){
					if (data.result > '0')
						document.location.reload();
					else
						alert(data.message);
				},
            	error : function (res, e) {
                	toast_ajax_error(res, "[makeDelete]:"+e);
            	}
			});
		}
	});

	
})
function logout(){
	$.getJSON("makeLogout.jsp", function(data){
		if (data.result == 1)
			alert('로그아웃');
		document.location.href = "index.jsp";
	});
}

