﻿(function ($) {

	$(document).ready(function (e) {

		if ($("#divMessage").length == 0) {
			$("<div id=\"divMessage\" title=\"확인\" style=\"display:none;\"><p style=\"font-size:9pt;\"></p></div>").appendTo("body");
		}

	});



	$.fn.CoCoFunCodeSelectBoxBinding = function (RefIdx, selectIdx, callback) {
		try {

			var $this = $(this[0]);

			$.ajax({
				type: "POST",
				url: "/Resource/Module/AJAX/CoCoFunCode?RefIdx=" + RefIdx,
				dataType: "text",
				success: function (data, status) {

					$this.children().remove();

					if ($this.attr("multiple") != "multiple") {
						$this.append("<option value=''>선택</option");
					}

					var results = data.split("\r\n");

					for (var i = 0; i < results.length; i++) {

						if ($.trim(results[i]) != "") {
							var row = results[i].split("\t");

							var idx = row[0];
							var title = row[1];

							if (selectIdx != null && eval(idx) == eval(selectIdx)) {
								$this.append("<option value='" + idx + "' selected>" + title.replace(/ /g, '') + "</option>");
							}
							else {
								$this.append("<option value='" + idx + "'>" + title.replace(/ /g, '') + "</option>");
							}
						}
					}

					if (callback != null) {
						callback('success');
					}
				},
				error: function (xhr, status, thr) {
					if (callback != null) {
						callback('error');
					} else {
						global.ShowMessage("/Resource/Module/AJAX/CoCoFunCode Ajax 호출에서 오류가 발생했습니다. : " + thr);
					}
				}
			});
		}
		catch (exception) {
			global.Messagealert("GetCoCoFunCode 오류 : " + exception.description);
			return false;
		}
	}

	$.fn.CoCoFunCodeSelectBoxBinding2 = function (RefIdx, selectIdx, callback) {
		try {

			var $this = $(this[0]);

			$.ajax({
				type: "POST",
				url: "/Resource/Module/AJAX/CoCoFunCode?RefIdx=" + RefIdx,
				dataType: "text",
				success: function (data, status) {

					$this.children().remove();

					if ($this.attr("multiple") != "multiple") {
						$this.append("<option value=''>선택</option");
					}

					var results = data.split("\r\n");

					for (var i = 0; i < results.length; i++) {

						if ($.trim(results[i]) != "") {
							var row = results[i].split("\t");

							var idx = row[0];
							var title = row[1];

							if (selectIdx != null && eval(idx) == eval(selectIdx)) {
								$this.append("<option value='" + title.replace(/ /g, '') + "' selected>" + title.replace(/ /g, '') + "</option>");
							}
							else {
								$this.append("<option value='" + title.replace(/ /g, '') + "'>" + title.replace(/ /g, '') + "</option>");
							}
						}
					}

					if (callback != null) {
						callback('success');
					}
				},
				error: function (xhr, status, thr) {
					if (callback != null) {
						callback('error');
					} else {
						global.ShowMessage("/Resource/Module/AJAX/CoCoFunCode Ajax 호출에서 오류가 발생했습니다. : " + thr);
					}
				}
			});
		}
		catch (exception) {
			global.Messagealert("GetCoCoFunCode 오류 : " + exception.description);
			return false;
		}
	}

	$.fn.RequiredFieldValueCheck = function (message) {

		try {

			if (this.length > 0) {

				var result = false;

				var typeName = this[0].type;

				var $this = this[0];

				switch (typeName) {

					case "text":
					case "password":
					case "hidden":
					case "textarea":
					case "select-one":
					case "file":
						if ($.trim($this.value) == "") {

							$("#divMessage > p").html(message);

							$("#divMessage").dialog({
								resizable: false,
								height: 150,
								modal: true,
								buttons: {
									확인: function () {
										$this.focus();
										$(this).dialog("close");
									}
								}
							});
						}
						else
							result = true;

						break;
				}

				return result;
			}
			else {
				return true;
			}

		}
		catch (exception) {
			global.Messagealert("RequiredFieldValueCheck 오류 : " + exception.description);
			return false;
		}
	}


	/// 숫자만 체크
	$.fn.RequiredFieldOnlyNumberCheck = function (message) {

		try {
			var result = false;
			var $this = this[0];

			//alert(isNaN('asdf'));

			if (isNaN($.trim($this.value))) {
				$("#divMessage > p").html(message);

				$("#divMessage").dialog({
					resizable: false,
					height: 150,
					modal: true,
					buttons: {
						확인: function () {
							$this.focus();
							$(this).dialog("close");
						}
					}
				});

			}

			else {
				result = true;
			}

			return result;


		}
		catch (exception) {
			global.Messagealert("RequiredFieldOnlyNumberCheck 오류 : " + exception.description);
			return false;
		}
	}


	$.extend({
		isNotBlank: function (sender, errMessage) {
			var senderObj = $('#' + sender);
			if (senderObj.val().length === 0) {
				alert(errMessage);
				senderObj.focus();
				return false;
			}

			return true;
		},
		post_goto: function (url, params, target) {
			var form = $('[name=popup_form]');
			if (form.length === 0) {
				var f = document.createElement('form');
				f.setAttribute('name', 'popup_form');
				f.setAttribute('method', 'post');
				document.body.appendChild(f);
				form = $(f);
			}
			form.attr('target', target);
			form.attr('action', url);
			form.html('');

			var objs, value;
			for (var key in params) {
				value = params[key];
				var input = '<input type="hidden" name="' + key + '" value="' + value + '">';
				form.append(input);
			}
			form.submit();
		},
		post_window: function (name, url, param, opt) {
			var temp_win = window.open('', name, opt);
			$.post_goto(url, param, name);
		},
		// <img name="popup_mail" src="" coupon_type="", sid="" cpno="" />
		// 페이지 내 테크의 name 이 popup_mail을 클릭 할 경우 발생 이벤트
		// coupon_type : store, free ...
		// sid : 샵 id
		// cpno : 쿠폰 번호
		popup_mail: function () {
			var popup_mail = $('[name=popup_mail]');
			popup_mail.css('cursor', 'pointer');
			popup_mail.unbind('click').click(function () {
				var mail_type = $(this).attr('mail_type');
				var sid = $(this).attr('sid');
				var coupon_code = $(this).attr('coupon_code');
				$.post_window('popup',
                    '/Resource/Common/popMailWrite',
                    { 'ctype': mail_type, 'sid': sid, 'couponcode': coupon_code },
                    'width=680, height=585');
			});
		},
		popup_print: function () {
			var popup_print = $('[name=popup_print]');
			popup_print.css('cursor', 'pointer');
			popup_print.unbind('click').click(function () {
				var print_type = $(this).attr('print_type');
				switch (print_type) {
					case 'social_coupon':
						var order_code = $(this).attr('order_code');
						if (order_code === '') return;
						$.post_window('popup',
                            '/ShopBlog/PrintSocialCoupon',
                            { 'order_code': order_code },
                            'width=700, height=700,scrollbars=yes');
						break;
					case 'coupon':
						var coupon_code = $(this).attr('coupon_code');
						if (coupon_code === '') return;
						$.post_window('popup',
                            '/FreeCoupon/PrintFreeCoupon',
                            { 'couponcode': coupon_code },
                            'width=700, height=700, scrollbars=yes');
						break;
					case 'mycoupon':
						var coupon_code = $(this).attr('coupon_code');
						if (coupon_code === '') return;
						$.post_window('popup',
                            '/FreeCoupon/PrintFreeCoupon',
                            { 'couponcode': coupon_code },
                            'width=700, height=700, scrollbars=yes');
						break;
					case 'minicoupon':
						var coupon_code = $(this).attr('coupon_code');
						if (coupon_code === '') return;
						$.post_window('popup',
                            '/Community/MiniCouponPrint',
                            { 'couponcode': coupon_code },
                            'width=600, height=400, scrollbars=no');
						break;
					case 'coupons':
						break;
				}
			});
		},		
		sendMeg: function () {
			$.ajax({
				type: "POST",
				url: "/Resource/Common/SendSMS.cshtml/",
				data: { code: code },
				success: function (result) {
					alert("삭제되었습니다.");
				}
			});
		},
		sns_Initialization: function () {
			$.sns_facebook();
			$.sns_twitter();
			$.sns_me2day();
			$.sns_yozm();
		},
		sns_facebook: function () {
			var sns_facebook = $('[name=sns_facebook]');
			if (sns_facebook.length === 0) return;
			sns_facebook.css('cursor', 'pointer');
			sns_facebook.unbind('click').click(function () {
				var title = $(this).attr('title');
				var ref_url = $(this).attr('ref_url');
				sendFaceBook(title, ref_url);
			});
		},
		sns_twitter: function () {
			var sns_twitter = $('[name=sns_twitter]');
			if (sns_twitter.length === 0) return;
			sns_twitter.css('cursor', 'pointer');
			sns_twitter.unbind('click').click(function () {
				var title = $(this).attr('title');
				var ref_url = $(this).attr('ref_url');
				sendTwitter(title, ref_url);
			});
		},
		sns_me2day: function () {
			var sns_me2day = $('[name=sns_me2day]');
			if (sns_me2day.length === 0) return;
			sns_me2day.css('cursor', 'pointer');
			sns_me2day.click(function () {
				var title = $(this).attr('title');
				var ref_url = $(this).attr('ref_url');
				var tags = $(this).attr('tags');
				sendMe2Day(title, ref_url, tags);
			});
		},
		sns_yozm: function () {
			var sns_yozm = $('[name=sns_yozm]');
			if (sns_yozm.length === 0) return;
			sns_yozm.css('cursor', 'pointer');
			sns_yozm.unbind('click').click(function () {
				var title = $(this).attr('title');
				var ref_url = $(this).attr('ref_url');
				var tags = $(this).attr('tags');
				goYozmDaum(title, null, ref_url);
			});
		},
		shareSns: function () {
			// 임은선 추가작업 공유기능 추가
			var share_sns = $('[name=share_sns]');
			if (share_sns.length > 0) {
				share_sns.css('cursor', 'pointer');
				share_sns.unbind('click').click(function () {
					var sender = $(this);
					var title = sender.attr('title');
					var ref_url = sender.attr('ref_url');
					var mail_type = sender.attr('mail_type');
					var sid = sender.attr('sid');
					var coupon_code = sender.attr('coupon_code');
					var print_type = sender.attr('print_type');

					if (mail_type == "store") {
						var liketemp = '<div class="toshare" style="position:relative;margin-top:3px;margin-bottom:5px;" id="divLikeTemp">'
				        + '		<ul class="icolist">'
				        + '			<li><img name="sns_facebook" src="/image/ico/ico_facebook.gif" alt="페이스북"/></li>'
				        + '			<li><img name="sns_twitter" src="/image/ico/ico_twitter.gif" alt="트위터"/></li>'
				        + '			<li><img name="sns_me2day" src="/image/ico/ico_sns01.gif" alt="미투데이"/></li>'
				        + '			<li><img name="sns_yozm" src="/image/ico/ico_sns02.gif" alt="요즘"/></li>'
				        + '		</ul>'
				        + '		<ul class="nice">'
				        + '			<li class="fir">'
				        + '                <div class="reTweet">'
                        + '                    <a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.cocofun.co.kr"  data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></' + 'script>'
                        + '                </div>'
				        + '			</li>'
				        + '			<li>'
				        + '				<iframe src="http://www.facebook.com/plugins/like.php?href=LikeURL&amp;layout=button_count&amp;show_faces=false&amp;width=92&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:92px; height:21px;" allowTransparency="true"></iframe>'
				        + '			</li>'
				        + '		</ul>'
				        + '		<ul class="icolist">'
				        + '			<li><img name="popup_mail" src="/image/btn/btn_smail.gif" alt="이메일 보내기" mail_type="" sid="" coupon_code=""/></li>'
				        + '		</ul>'
				        + '		<p class="cboth">'
				        + '			<img src="/image/coupon/txt_conn_dc.gif" alt="다음쿠폰에 연결" />'
				        + '			<input type="text" title="다음쿠폰에 연결 링크 주소" class="basic" />'
				        + '		</p>'
				        + '		<p class="btn"><img name="close_sns" src="/image/coupon/btn_share_clse.gif" alt="닫기" /></p>'
				        + '	</div>';
					}
					else {
						var liketemp = '<div class="toshare" style="position:relative;margin-top:3px;margin-bottom:5px;" id="divLikeTemp">'
				        + '		<ul class="icolist">'
				        + '			<li><img name="sns_facebook" src="/image/ico/ico_facebook.gif" alt="페이스북"/></li>'
				        + '			<li><img name="sns_twitter" src="/image/ico/ico_twitter.gif" alt="트위터"/></li>'
				        + '			<li><img name="sns_me2day" src="/image/ico/ico_sns01.gif" alt="미투데이"/></li>'
				        + '			<li><img name="sns_yozm" src="/image/ico/ico_sns02.gif" alt="요즘"/></li>'
				        + '		</ul>'
				        + '		<ul class="nice">'
				        + '			<li class="fir">'
				        + '                <div class="reTweet">'
                        + '                    <a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.cocofun.co.kr"  data-count="horizontal">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></' + 'script>'
                        + '                </div>'
				        + '			</li>'
				        + '			<li>'
				        + '				<iframe src="http://www.facebook.com/plugins/like.php?href=LikeURL&amp;layout=button_count&amp;show_faces=false&amp;width=92&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:92px; height:21px;" allowTransparency="true"></iframe>'
				        + '			</li>'
				        + '		</ul>'
				        + '		<ul class="icolist">'
				        + '			<li><img name="popup_mail" src="/image/btn/btn_smail.gif" alt="이메일 보내기" mail_type="" sid="" coupon_code=""/></li>'
				        + '			<li><img name="popup_print" src="/image/btn/btn_sprint.gif" alt="인쇄하기" print_type="" coupon_code="" /></li>'
				        + '		</ul>'
				        + '		<p class="cboth">'
				        + '			<img src="/image/coupon/txt_conn_dc.gif" alt="다음쿠폰에 연결" />'
				        + '			<input type="text" title="다음쿠폰에 연결 링크 주소" class="basic" />'
				        + '		</p>'
				        + '		<p class="btn"><img name="close_sns" src="/image/coupon/btn_share_clse.gif" alt="닫기" /></p>'
				        + '	</div>';
					}
					$('#divLikeTemp').remove();
					var $temp = $(liketemp);
					var faceurl = $temp.find('ul.nice iframe').attr('src').replace(/LikeURL/g, ref_url);

					$temp.find('div.reTweet>a').attr('data-url', ref_url)
					$temp.find('ul.nice iframe').attr('src', faceurl);
					$temp.find('input:text').val(ref_url);

					var popup_mail = $temp.find('[name=popup_mail]');
					popup_mail.attr('mail_type', mail_type);
					popup_mail.attr('sid', sid);
					popup_mail.attr('coupon_code', coupon_code);

					var popup_print = $temp.find('[name=popup_print]');
					popup_print.attr('print_type', print_type);
					popup_print.attr('coupon_code', coupon_code);

					var sns_facebook = $temp.find('[name=sns_facebook]');
					sns_facebook.attr('title', title);
					sns_facebook.attr('ref_url', ref_url);

					var sns_twitter = $temp.find('[name=sns_twitter]');
					sns_twitter.attr('title', title);
					sns_twitter.attr('ref_url', ref_url);

					var sns_me2day = $temp.find('[name=sns_me2day]');
					sns_me2day.attr('title', title);
					sns_me2day.attr('ref_url', ref_url);

					var sns_yozm = $temp.find('[name=sns_yozm]');
					sns_yozm.attr('title', title);
					sns_yozm.attr('ref_url', ref_url);

					sender.parents('div').eq(0).after($temp);

					$.sns_Initialization();
					$.popup_mail();
					$.popup_print();

					var close_sns = $('[name=close_sns]');
					close_sns.css('cursor', 'pointer');
					close_sns.unbind('click').click(function () {
						$('#divLikeTemp').slideUp('slow').remove();
					});
				});
			} else {
				$.sns_Initialization();
			}
		}
	});

	$(function () {
		$.shareSns();
		$.popup_mail();
		$.popup_print();
	});

})(jQuery);


function Global() {

    this.ToMoneyFormat = function (number) {

        var returnValue = 0;
        var temp1 = (number + "").replace(/,/g, "");   // 입력 데이터를 숫자 형태로 변환
        var temp = temp1.split('.');

        // 정수자리 원단위로 만들기
        var num1 = "";
        var comma = 1;
        for (var i = temp[0].length - 1; i >= 0; i--) {
            num1 += temp[0].charAt(i);

            if (comma % 3 == 0 && comma != 0) {
                num1 += ",";
            } // end if
            comma++;
        } // end for


        var num2 = "";
        for (var i = num1.length - 1; i >= 0; i--) {
            num2 += num1.charAt(i);
        } // end for

        // 소수점이 있다면...
        if (temp.length > 1) {

            // 소수점 자리 원 단위로 만들어서 리턴..!!
            var num3 = "";
            for (var i = 1; i <= temp[1].length; i++) {
                num3 += temp[1].charAt(i - 1);

                if ((i % 3 == 0) && (i != 0)) {
                    num3 += ",";
                }
            } // end for

            var num4 = num2 + "." + num3;
            returnValue = num4.replace(/(^,)|(,$)/g, "");
        } // end if
        else
            returnValue = num2.replace(/(^,)|(,$)/g, ""); ; // 앞,뒤 콤마 제거

        if (returnValue == "" || returnValue == ".")
            return ""
        else
            return returnValue;
    }

    this.SetCookie = function(name, value, expiredays) {
        var todayDate = new Date();
        todayDate.setDate(todayDate.getDate() + expiredays);
        document.cookie = name + "=" + escape(value) + "; path=/; expires=" + todayDate.toGMTString() + ";"
    }

    this.GetCookie = function(name) {
        var nameOfCookie = name + "=";
        var x = 0;
        while (x <= document.cookie.length) {
            var y = (x + nameOfCookie.length);
            if (document.cookie.substring(x, y) == nameOfCookie) {
                if ((endOfCookie = document.cookie.indexOf(";", y)) == -1)
                    endOfCookie = document.cookie.length;
                return unescape(document.cookie.substring(y, endOfCookie));
            }
            x = document.cookie.indexOf(" ", x) + 1;
            if (x == 0)
                break;
        }

        return "";   
    }

    this.ShowMessage = function (message) {
        
        $("#divMessage > p").html(message);

        $("#divMessage").dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: {
                확인: function () {
                    $(this).dialog("close");
                }
            }
        });
    }

    this.GotoPage = function (message, url) {
        
        $("#divMessage > p").html(message);

        $("#divMessage").dialog({
            resizable: false,
            height: 200,
            modal: true,
            buttons: {
                확인: function () {
                    location.href = url;
                    $(this).dialog("close");
                }
            }
        });
    }

    this.DialogOpen = function (url, name, width, height, enableScroll) {

        /// <summary>지정된 URL, 크기의 창을 중간에 표시 합니다.</summary>
        var properties = "width=" + width;
        properties += ", height=" + height;

        properties += ", left=" + ((document.body.clientWidth / 2) - (width / 2));
        properties += ", top=" + ((document.body.clientHeight / 2) - (height / 2));

        if (enableScroll)
            properties += ", scrollbars=1";

        var popWindow = window.open(url, name, properties);

        if (!popWindow)
            alert("팝업 대화상자가 차단되었습니다. 팝업 차단을 해제해 주시기 바랍니다.");
    }

    this.GetQueryString = function (valuename) {
        var rtnval = "";
        var nowAddress = unescape(location.href);
        var parameters = (nowAddress.slice(nowAddress.indexOf("?") + 1, nowAddress.length)).split("&");

        for (var i = 0; i < parameters.length; i++) {
            var varName = parameters[i].split("=")[0];
            if (varName.toUpperCase() == valuename.toUpperCase()) {
                rtnval = parameters[i].split("=")[1];
                break;
            }
        }

        if (rtnval.indexOf("#") > 0)
            rtnval = rtnval.split("#")[0];

        return rtnval;
    }
}

var global = new Global();


//스크랩 추가
function fn_scrap_add(code, val) {
    $.ajax({
        type: "POST",
        url: "/Resource/Common/ScrapAdd.cshtml",
        data: { code: code },
        success: function (result) {
            alert("스크랩 되었습니다.");
            if (val != null && val != "") {
                location.href = val;
            }
        }
    });
}

// 스크랩 복수 추가
function fn_scraps_add(cls) {
    var obj = ":checkbox[class=" + cls + "]";
    var codes = "";
    var j = 0;

    $(obj).each(function (i) {
        if ($(this).is(':checked')) {

            if (j > 0) {
                codes += ",";
            }

            codes += $(this).val();

            j++;
        }

    });

    if (j == 0) {
        alert('선택한 쿠폰이 없습니다.');
        return false;
    }

    $.ajax({
        type: "POST",
        url: "/Resource/Common/ScrapsAdd.cshtml/",
        data: { codes: codes },
        success: function (result) {
            alert("스크랩 되었습니다.");
        }
    });
}

// 쿠폰 복수 인쇄
function fn_print_add(cls) {
	var obj = ":checkbox[class=" + cls + "]";
	var codes = "";
	var j = 0;

	$(obj).each(function (i) {
		if ($(this).is(':checked')) {

			if (j > 0) {
				codes += ",";
			}

			codes += $(this).val();

			j++;
		}

	});

	if (j == 0) {
		alert('선택한 쿠폰이 없습니다.');
		return false;
	}

	if (j > 1) {
		Post_Window('/FreeCoupon/PrintFreeCouponMulti', { 'couponcode': codes }, 'popup', 'width=700, height=600');
	} else {
		Post_Window('/FreeCoupon/PrintFreeCoupon', { 'couponcode': codes }, 'popup', 'width=700, height=600');
	}
}


function Post_Window(url, params, target, opt) {
	var temp_win = window.open('', target, 'width=700, height=600,scrollbars=yes');

	var form = $('[name=popup_form]');
	if (form.length === 0) {
		var f = document.createElement('form');
		f.setAttribute('name', 'popup_form');
		f.setAttribute('method', 'post');
		document.body.appendChild(f);
		form = $(f);
	}
	form.attr('target', target);
	form.attr('action', url);
	form.html('');

	var objs, value;
	for (var key in params) {
		value = params[key];
		var input = '<input type="hidden" name="' + key + '" value="' + value + '">';
		form.append(input);
	}
	form.submit();
}

// 쿠폰코드 여러개 받아서 스크랩
// 콤마로 받음
function fn_scrap_each_add(codes) {
    $.ajax({
        type: "POST",
        url: "/Resource/Common/ScrapsAdd.cshtml/",
        data: { codes: codes },
        success: function (result) {
            alert("스크랩 되었습니다.");
        }
    });
}


// 스크랩 삭제
function fn_scrap_del(code) {
    $.ajax({
        type: "POST",
        url: "/Resource/Common/ScrapDel.cshtml/",
        data: { code: code },
        success: function (result) {
            alert("삭제되었습니다.");
        }
    });
}

// 스마트서치 온
function fn_smartSearch_on() {
    //    alert('스마트서치 오픈');
    $("#div_smartSearchContent").load("/smart/index.cshtml");
    $("#layerSearch").show();

}

// 스마트 서치 탭 클릭
function SmartSearchTab(objClass) {
    var url = "/SmartSearch/search0" + objClass + ".cshtml";
    $("#smartsearch").load(url);
}

// 스마트서치 오프
function fn_smartSearch_off() {
    $("#layerSearch").hide();
//    $("#smartsearch").attr("style", "display:none");
    //alert("off");
}


// ------------ 셀렉트 박스 불러오기 ---------------
/*
/// 대지점 콤보박스 로드
/// obj:대지점콤보박스id, objValue:selected 값, objTitle:대지점옵션텍스트
*/
function fn_area1_init(obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/AreaBox.cshtml",
        data: { level: 1, selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 대지점 onchange 중지점 불러오기
*/
function fn_area1_onchange(area1, obj, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/AreaBox.cshtml",
        data: { level: 2, area1: area1 },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 중지점 초기화 수정모드로 불러오기
*/
function fn_area2_init(area1, obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/AreaBox.cshtml",
        data: { level: 2, area1: area1, selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 업종코드 대업종 콤보박스 로드
*/
function fn_category1_init(obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/CategoryBox.cshtml",
        data: { level: "1", selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 대업종 onchange 중업종 불러오기
*/
function fn_category1_onchange(category1, obj, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/CategoryBox.cshtml",
        data: { level: 2, category1: category1, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}

/*
/// 중업종 초기화 수정모드에서 불러오기
*/
function fn_category2_init(category1, obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/CategoryBox.cshtml",
        data: { level: 2, category1: category1, selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 지역코드 대지역 콤보박스 로드
/// obj:대지역콤보박스id, objValue:selected 값, objTitle:대지역옵션텍스트
*/
function fn_place1_init(obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/PlaceBox.cshtml",
        data: { level: 1, selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 대지역 onchange 중지역 불러오기
*/
function fn_place1_onchange(place1, obj, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/PlaceBox.cshtml",
        data: { level: 2, place1: place1, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}

/*
/// 중지역 초기화 수정모드에서 불러오기
*/
function fn_place2_init(place1, obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/PlaceBox.cshtml",
        data: { level: 2, place1: place1, selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


/*
/// 중지역 onchange 소지역 불러오기
*/
function fn_place2_onchange(place1Obj, place2, obj, objTitle) {
    var place1 = $(place1Obj).val();

    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/PlaceBox.cshtml",
        data: { level: 3, place1: place1, place2: place2, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}

/*
/// 소지역 초기화 수정모드에서 불러오기
*/
function fn_place3_init(place1, place2, obj, objValue, objTitle) {
    $.ajax({
        type: "POST",
        url: "/Resource/AJAX/PlaceBox.cshtml",
        data: { level: 3, place1: place1, place2: place2, selectValue: objValue, Title: objTitle },
        success: function (result) {
            $(obj).empty().append(result);
        }
    });
}


function fn_login_confirm(url) {
    if (confirm("회원만 사용할 수 있는 기능입니다.\n로그인 하시겠습니까?")) {
        location.href = "/Member/Login.cshtml?return_url=" + url;
    }
}

function fn_login_confirm1(url) {
    if (confirm("회원만 사용할 수 있는 기능입니다.\n로그인 하시겠습니까?")) {
        location.href = "/Member/Login.cshtml?return_url=" + url;
    }
}

function fn_shopblog_add_confirm() {
//    alert("Shop 회원가입후 개설이 가능합니다.");
    location.href = "/Ctadvertise/cf_first";
}

// 사업자 등록번호 체크
function fn_bizNo_check(value) {
    var sumMod = 0;
    sumMod += parseInt(value.substring(0, 1));
    sumMod += parseInt(value.substring(1, 2)) * 3 % 10;
    sumMod += parseInt(value.substring(2, 3)) * 7 % 10;
    sumMod += parseInt(value.substring(3, 4)) * 1 % 10;
    sumMod += parseInt(value.substring(4, 5)) * 3 % 10;
    sumMod += parseInt(value.substring(5, 6)) * 7 % 10;
    sumMod += parseInt(value.substring(6, 7)) * 1 % 10;
    sumMod += parseInt(value.substring(7, 8)) * 3 % 10;

    sumMod += Math.floor(parseInt(value.substring(8, 9)) * 5 / 10);
    sumMod += parseInt(value.substring(8, 9)) * 5 % 10;
    sumMod += parseInt(value.substring(9, 10));

    if (sumMod % 10 != 0) {
        //alert('사업자등록번호가 잘못되었습니다.');
        return false;
    }
    else {
        return true;
    }
}

/// 달력 모듈 바인딩
function fn_DataPicker_init(objs) {
    $(objs).datepicker({
        showOn: "both",
        buttonImage: "/image/common/btncalendar.gif",
        buttonImageOnly: true
    }).css('margin-right', "4px");
}

/// 달력 모듈 바인딩
function fn_DataPickerLimit_init(objs) {
	$(objs).datepicker({
		showOn: "both",
		buttonImage: "/image/common/btncalendar.gif",
		buttonImageOnly: true,
		minDate: 0
	}).css('margin-right', "4px");
}

// 날짜비교해서 뒤에 날짜가 작은지 체크
function fn_start_end_date_check(obj1, obj2, msg) {

    if ($(obj1).val() > $(obj2).val()) {
        alert(msg);
        return false;
    }
    else {
        return true;
    }
}


// 검색 날짜 간격 버튼
function fn_dateSetting(obj1, obj2, e) {

    var _date1 = fn_addDate(1);
    var _date2;

    switch (e) {
        case 1:
        case 7:
        case 15:
        case 30:
            _date2 = fn_addDate(e);
            break;
        case 0:
            _date1 = "";
            _date2 = "";
            break;
    }

    $(obj1).val(_date1);
    $(obj2).val(_date2);

}

// 특정 이후 날짜 리턴
function fn_addDate(offset) {
    var today = new Date();
    var todayyear = today.getFullYear();
    var todaymonth = today.getMonth();
    var todayday = today.getDate();
    var temp;
    var tempyear;
    var tempmonth;
    var tempday;

    if (offset == 30) {
        temp = new Date(todayyear, todaymonth + 1, todayday);
        tempyear = temp.getFullYear();
        tempmonth = temp.getMonth() + 1;
        tempday = temp.getDate();
    }
    else {
        temp = new Date(todayyear, todaymonth, todayday + offset - 1);
        tempyear = temp.getFullYear();
        tempmonth = temp.getMonth() + 1;
        tempday = temp.getDate();
    }

    return tempyear + '-' + fn_addZero(tempmonth) + '-' + fn_addZero(tempday);
}

//날짜 월일 두자리 만들기
function fn_addZero(sender) {
    if ((sender + '').length == 1) return '0' + sender;
    else return sender;
}

/************************************************************************************************************
*숫자 체크 함수
************************************************************************************************************/
function OnCheckNumber(p_clientid) {

    var obj = document.getElementById(p_clientid);
    var m_value = obj.value;

    if (m_value != "") {
        if (!CheckNumber(m_value, obj, "")) {

        }
    }
}

function CheckNumber(p_value, p_object, p_default) {


    var sellFormat = /^\d+?$/

    if (!IsValidFormat(p_value, sellFormat)) {
        alert("숫자만 입력이 가능합니다.");
        p_object.value = p_default;
        p_object.focus();
        return false;
    }
    else {
        p_object.value = parseInt(p_object.value, 10);
    }

    return true;

}

/**********************************************************
* 스마트 서치 및 쿠폰맵 함수
**********************************************************/

function tmp_smartSearch_on() {
    $("#div_smartSearchBox").load("/smart/smart.cshtml?pageKind=1");
    $("#layerSearch").show();
}
function tmp_couponMap_on() {
    $("#div_smartSearchBox").load("/smart/smart.cshtml?pageKind=4");
    $("#layerSearch").show();
}



//글자수 제한
function LengthCal(str, Subj, len) {
	if (str.value.length > len) {
		alert(Subj + "는 " + len + "자까지만 입력할 수 있습니다.");
		return true;
	}
	return false;
}


//영문, 숫자, 글자수 범위, 영문-숫자 혼용, 같은문자 반복 
function CheckValue(val, min, max) {
	if (min == "" || max == "") {
		alert("글자수 범위 인자값을 입력하십시오");
		return false;
	}

	if (!/^[a-zA-Z0-9]{min,max}$/.test(val)) {
		alert("숫자와 영문자 조합으로 " + min + "~" + max + "자리를 사용해야 합니다.");
		return false;
	}


	var chk_num = val.search(/[0-9]/g);
	var chk_eng = val.search(/[a-z]/ig);

	if (chk_num < 0 || chk_eng < 0) {
		alert("숫자와 영문자를 혼용하여야 합니다.");
		return false;
	}

	if (/(\w)\1\1\1/.test(val)) {
		alert("같은 문자를 4번 이상 사용하실 수 없습니다.");
		return false;
	}

	return true;
}




/*
/// 구독_이북 지점 코드 대지역 콤보박스 로드
/// objKind:구분(M-매거진, E-이북), obj:대지점콤보박스id, objValue:selected 값, objTitle:대지역옵션텍스트
*/
function fn_SubscriptionArea1_init(objKind, obj, objValue, objTitle) {
	$.ajax({
		type: "POST",
		url: "/Resource/AJAX/SubscriptionAreaBox.cshtml",
		data: { objKind: objKind, Level: 1, SelectValue: objValue, Title: objTitle },
		success: function (result) {
			$(obj).empty().append(result);
		}
	});
}


/*
/// 대지점 onchange 중지역 불러오기
*/
function fn_SubscriptionArea1_onchange(objKind, Area1, obj, objTitle) {	
	$.ajax({
		type: "POST",
		url: "/Resource/AJAX/SubscriptionAreaBox.cshtml",
		data: { objKind: objKind, Level: 2, Area1: Area1, Title: objTitle },
		success: function (result) {
			$(obj).empty().append(result);
		}
	});
}

/*
/// 중지점 초기화 수정모드에서 불러오기
*/
function fn_SubscriptionArea2_init(objKind, Area1, obj, objValue, objTitle) {
	$.ajax({
		type: "POST",
		url: "/Resource/AJAX/SubscriptionAreaBox.cshtml",
		data: { objKind: objKind, Level: 2, Area1: Area1, SelectValue: objValue, Title: objTitle },
		success: function (result) {
			$(obj).empty().append(result);
		}
	});
}
