﻿/// <reference path="/Common/JS/jquery-1.4.1.js" />
/// <reference path="/Common/JS/json2.js" />
/// <reference path="/Common/JS/jquery.validity.js" />
/// <reference path="/Common/JS/jquery.HotKey.MouseR.js" />

/************************************************************************
작성목적	    : jQuery.validity 의 메세지 및 Output 모드 기능 확장.
작 성 자	    : (주)아이스파티윰 - 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
$(document).ready(function () {

    //마우스 오른쪽 버튼 방지
    //$("html").rightClick(function(e){}).noContext();

    //ctrl+a, ctrl+c 방지   
    //$(document).bind('keydown', 'ctrl+a', function(){return false;}).bind('keydown', 'ctrl+c', function(){return false;});   
    
    //드래그 방지  
    //$(document).mousedown(function(){$(document).mousemove(function(e){return false;});});   


    // validity 스타일  초기화 --> 각 사이트마다 바꿔줘야함, 텍스트 박스에 스타일이 틀릴경우 사용못함 : 추후 업그레이드 할것!!!!!!!!!!!!!!!!!!!!!
    $('input[type=text]').keyup(function () {
        if ($(this).css("borderColor") == 'red' && $(this).val() != "") {
            $(this).css("borderColor", "#cdcdcd");
        }
    });

    $('input[type=password]').keyup(function () {
        if ($(this).css("borderColor") == 'red' && $(this).val() != "") {
            $(this).css("borderColor", "#cdcdcd");
        }
    });

});

if ($.validity != null) {

    (function () {
        $.validity.outputs.custom = {

            start: function () {
                /*
                $("input:text")
                .css({ border: '1px solid black' })
                */
            },

            end: function (results) {

                // If not valid and scrollTo is enabled, scroll the page to the first error. 
                if (!results.valid && $.validity.settings.scrollTo) {
                    location.hash = $(".fail:eq(0)").attr('id')
                }

            },

            raise: function ($obj, msg) {
                alert(msg);
                $obj
                .css({ border: '1px solid red', background: '#fff', padding: '1px' })
                .focus()
            },

            // Just raise the error on the last input.
            raiseAggregate: function ($obj, msg) {

                this.raise($($obj.get($obj.length - 1)), msg);
            }
        }

        $.validity.setup({ outputMode: 'custom' });
    })();



    $.extend({ getUrlVars: function () { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }, getUrlVar: function (name) { return $.getUrlVars()[name]; } });

    $.extend($.validity.messages, {
        require: "#{field} 필수 입력값입니다.",
        // Format validators:    
        match: "#{field} 형식에 맞지 않습니다.",
        integer: "#{field} Int형이어야 합니다.",
        date: "#{field} 날짜형식이어야 합니다.",
        email: "#{field} 메일 주소 형식이어야 합니다.",
        usd: "#{field} must be formatted as a US Dollar amount.",
        url: "#{field} URL 형식이어야 합니다.",
        number: "#{field} 숫자만 입력하십시요!",
        zip: "#{field} must be formatted as a zipcode ##### or #####-####.",
        phone: "#{field}  ###-###-####와 같은 전화 번호 형식이어야 합니다.",
        guid: "#{field} must be formatted as a guid like {3F2504E0-4F89-11D3-9A0C-0305E82C3301}.",
        time24: "#{field} must be formatted as a 24 hour time: 23:00.",
        time12: "#{field} must be formatted as a 12 hour time: 12:00 AM/PM",
        // Value range messages:    
        lessThan: "#{field} #{max} 보다 작아야 합니다.",
        lessThanOrEqualTo: "#{field} 는 #{max} 보다 작거나 같아야 합니다.",
        greaterThan: "#{field} #{min} 보다 커야 합니다.",
        greaterThanOrEqualTo: "#{field} 는 #{min} 보다 크거나 같아야 합니다.",
        range: "#{field} #{min} 와 #{max} 사이의 값이어야 합니다.",
        // Value length messages:
        tooLong: "#{field} #{max} 글자를 넘을 수 없습니다.",
        tooShort: "#{field} 최소 #{min} 글자는 되어야 합니다.",
        // Aggregate validator messages:
        equal: "값이 다릅니다.",
        distinct: "값은 유일해야 합니다.",
        sum: "Values don't add to #{sum}.",
        sumMax: "The sum of the values must be less than #{max}.",
        sumMin: "The sum of the values must be greater than #{min}.",
        nonHtml: "#{field} cannot contain Html characters.",
        generic: "유효하지 않습니다."
    });

    $.validity.patterns.userName = /^([a-zA-Z][a-zA-Z0-9_\-\.]+)$/;
    $.validity.messages.userName = "#{field} 영문자로 시작하여야 하며 숫자 및 영문자만 가능합니다.";
    $.validity.patterns.koreaPhone = /^0\d{1}(\d{1})?-\d{3}(\d{1})?-\d{4}$/;
    $.validity.messages.koreaPhone = "#{field} '-' 부호를 포함한 '지역번호-국번-번호' 형식이어야 합니다.";
    $.validity.patterns.koreaDate = /^\d{1,4}\-([012]?\d|30|31)\-([01]?\d)$/;
    $.validity.messages.koreaDate = "#{field} yyyy-mm-dd 형식이어야 합니다.";
    $.validity.patterns.ipAddress = /^(1|2)?\d?\d([.](1|2)?\d?\d){3}$/;
    $.validity.messages.ipAddress = "#{field} 형식에 맞지 않습니다.";
}


/************************************************************************
작성목적	    : Calendar 기능 확장.
작 성 자   	: 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
if ($.datepicker != null) {
    (function () {

        $.datepicker.regional['ko'] = {
            closeText: '닫기',
            prevText: '이전달',
            nextText: '다음달',
            currentText: '오늘',
            monthNames: [' 1월', ' 2월', ' 3월', ' 4월', ' 5월', ' 6월', ' 7월', ' 8월', ' 9월', ' 10월', ' 11월', ' 12월'],
            dayNames: ['일', '월', '화', '수', '목', '금', '토'],
            dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
            dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
            weekHeader: 'Wk',
            dateFormat: 'yy-mm-dd',
            firstDay: 0,
            isRTL: false,               // 이미지 좌우 위치(true : 오른쪽, false : 왼쪽)
            showMonthAfterYear: true,
            yearSuffix: '년'
        };

        $.datepicker.setDefaults($.datepicker.regional['ko']);

    })();
}


/************************************************************************
함수명		: AjaxRequest
작성목적	    : jquery의 ajax함수 호출
작 성 자	    : 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function AjaxRequest(url, pars, success, error, async, type) {
    $.ajax({
        type: "POST",
        url: url,
        data: pars,
        dataType: type != null ? "text" : "json",
        async: (async == null || async == true) ? true : false,
        error: error != null ? error : function (req, s, e) {
            alert(req.responseText);
        },
        success: success,
        beforeSend: function () {

        },
        complete: function () {

        }
    });
}


/************************************************************************
함수명		: AjaxRequestToJson
작성목적	    : *.cs function 직접 호출시 JSON data type 통신
작 성 자	    : 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function AjaxRequestToJson(url, pars, success, async) {
    $.ajax({
        type: "POST",
        url: url,
        data: pars,
        async: (typeof async != "undefined" ? async : true),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-type",
            "application/json; charset=utf-8");
        },
        complete: function () {


        },
        success: success,
        error: function (req, s, e) {
            alert("AJAX ERROR : " + req.responseText);
        }
    });
}


/************************************************************************
함수명		: fnNumberOnly
작성목적	    : 숫자만 입력 가능 
작 성 자	    : 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
예제        :    $(document).ready(function() {
                 
// 숫자만 입력
fnNumberOnly($('input:text[name*=txt_AMT]'));

});
*************************************************************************/
function fnNumberOnly(selector) {

    //한글입력을 받지 않는다.
    $(selector).css("ime-mode", "disabled");

    // 숫자만 입력
    $(selector).keypress(function (event) {
        if (event.which && (event.which > 47 && event.which < 58 || event.which == 8)) {
        } else {
            event.preventDefault();
        }
    });
}


/************************************************************************
함수명		: fnNumberFormat
작성목적	    : 천단위 쉼표 생성
작 성 자	    : 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function fnNumberFormat(num) {

    num = fnUnNumberFormat(num);
    var pattern = /(-?[0-9]+)([0-9]{3})/;

    while (pattern.test(num)) {
        num = num.replace(pattern, "$1,$2");
    }

    return num;
}

// 쉼표제거
function fnUnNumberFormat(num) {
    return (num.replace(/\,/g, ""));
}


/************************************************************************
함수명		: fnWindowOpenCenter
작성목적	    : 팝업창 화면 가운데 오픈
작 성 자	    : 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function fnWindowOpenCenter(url, winName, width, height, fstate) {

    var features = "width=" + width + ",height=" + height;

    var state = "";

    if (fstate == "") {
        state = features + ", left=" + (screen.width - width) / 2 + ",top=" + (screen.height - height) / 2;
    } else {
        state = fstate + ", " + features + ", left=" + (screen.width - width) / 2 + ",top=" + (screen.height - height) / 2;
    }

    var win = window.open(url, winName, state);

    win.focus();
}


/************************************************************************
함수명		: fnWindowOpenCenter_Post
작성목적	    : 팝업창에 포스트로 넘기기 (화면 가운데 오픈)
작 성 자	    : 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function fnWindowOpenCenter_Post(target, action, width, height, fstate) {

    var features = "width=" + width + ",height=" + height;

    var state = "";

    if (fstate == "") {
        state = features + ", left=" + (screen.width - width) / 2 + ", top=" + (screen.height - height) / 2;
    } else {
        state = fstate + ", " + features + ", left=" + (screen.width - width) / 2 + ", top=" + (screen.height - height) / 2;
    }

    var win = window.open('', target, state);
    var oldAction = $("form").attr("action");

    $("form").attr("target", target);
    $("form").attr("action", action);
    $("form").submit();

    win.focus();

    $("form").attr("action", oldAction);
    $("form").attr("target", "");

}



/************************************************************************
함수명		: fnGalleryViewerOpen
작성목적	    : 갤러리 뷰어 오픈 (화면 가운데 오픈)
작 성 자   	: 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function fnGalleryViewerOpen(seq) {

    if ($("input:hidden[name*=hid_Gallery_Seq]").length == 0)
        $("form").append("<input type='hidden' name='hid_Gallery_Seq' />");

    $("input:hidden[name*=hid_Gallery_Seq]").val(seq);

    // 사이즈로 오픈
    //fnWindowOpenCenter_Post('GalleryViewer', '/Common/Popup/GalleryViewer.aspx', 1000, 850, 'resizable=no,menubars=no,status=no');

  
    // 전체화면으로 오픈
    var win = window.open('', 'GalleryViewer', "fullscreen=yes, menubars=no, status=no, resizable=yes, scrollbars=yes");
    var oldAction = $("form").attr("action");

    var oldAction = $("form").attr("action");

    $("form").attr("target", "GalleryViewer");
    $("form").attr("action", "/Common/Popup/GalleryViewer.aspx");
    $("form").submit();

    win.focus();

    $("form").attr("action", oldAction);
    $("form").attr("target", "");
    
}



/************************************************************************
함수명		: fnRealEstateViewerOpen
작성목적	    : 부동산 뷰어 오픈 (화면 가운데 오픈)
작 성 자   	: 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function fnRealEstateViewerOpen(seq) {

    if ($("input:hidden[name*=hid_RealEstate_Seq]").length == 0)
        $("form").append("<input type='hidden' name='hid_RealEstate_Seq' />");

    $("input:hidden[name*=hid_RealEstate_Seq]").val(seq);

    fnWindowOpenCenter_Post('RealEstateViewer', '/Common/Popup/RealEstateViewer.aspx', 720, 850, 'scrollbars=yes,resizable=no,menubars=no,status=no');
}



/************************************************************************
함수명		: fnAuctionMapNaverMap
작성목적	: 사업자소재 검증업체 지도 오픈 (화면 가운데 오픈)
작 성 자   	: 김상백
최초작성일	:
최종작성일	:
수정내역	:
*************************************************************************/
function fnAuctionMapNaverMap(UserId) {
    var strUrl = "/Common/Popup/Map.aspx?UserId=" + UserId;
    fnWindowOpenCenter(strUrl, 'NaverMap', 512, 412, '');
}


/************************************************************************
함수명		: fnOrderInfo
작성목적	: 무통장 입금 내역 정보 (화면 가운데 오픈)
작 성 자   	: 김상백
최초작성일	:
최종작성일	:
수정내역	:
*************************************************************************/
function fnOrderInfo(Seq) {
    var strUrl = "/Common/Popup/OrderInfo.aspx?Seq=" + Seq;
    fnWindowOpenCenter(strUrl, 'OrderInfo', 700, 320, '');
}


/************************************************************************
함수명		: fnImageSizeFix
작성목적	    : 이미지 사이즈 조절
작 성 자   	: 이윤재
최초작성일	:
최종작성일	:
수정내역	    :
*************************************************************************/
function fnImageSizeFix(imgObj, fixSize) {

    $(imgObj).each(function () {

        var imgWidth = $(this).attr("width");
        var imgHeight = $(this).attr("height");

        // 넓이 높이 모두 기준값을 초과 할때
        if (imgWidth > fixSize && imgHeight > fixSize) {
            if (imgWidth > imgHeight) {
                var ratio = imgWidth / imgHeight;
                var newHeight = Math.round(fixSize / ratio);
                
                $(this).attr({ width: fixSize, height: newHeight });
            }
            else {
                var ratio = imgHeight / imgWidth;
                var newWidth = Math.round(fixSize / ratio);
             
                $(this).attr({ width: newWidth, height: fixSize });
            }
        }
        // 넓이가 기준값을 초과할 때
        else if (imgWidth > fixSize) {

            var ratio = imgWidth / imgHeight;
            var newHeight = Math.round(fixSize / ratio);

            $(this).attr({ width: fixSize, height: newHeight });
        }
        // 높이가 기준값을 초과할 때
        else if (imgHeight > fixSize) {
            var ratio = imgHeight / imgWidth;
            var newWidth = Math.round(fixSize / ratio);

            $(this).attr({ width: newWidth, height: fixSize });
        }

    });

}


/************************************************************************
함수명		: fnIsNumber
작성목적	    : 숫자여부 판단
작 성 자   	: 이윤재
최초작성일	:
최종작성일	:
수정내역	:
*************************************************************************/
function fnIsNumber(s) {
    s += ''; // 문자열로 변환
    s = s.replace(/^\s*|\s*$/g, ''); // 좌우 공백 제거
    if (s == '' || isNaN(s)) return false;
    return true;
}


