if (jQuery.validator) {
	jQuery.validator.addMethod("validate", function(value, element, params) {
		var previous = this.previousValue(element);
		if (previous.old !== value) {
			previous.old = value;
			var validator = this;
			this.startRequest(element);
			if (params.data == undefined) {
				params.data = {};
			}
			params.data[element.name] = value;
			$.post(params.url, params.data, function(response) {
				if (response.result) {
					validator.stopRequest(element, true);
					previous.valid = true;
				} else {
					var errors = {};
					errors[element.name] = response.errorMessage;
					validator.showErrors(errors);
					previous.valid = false;
				}
			}, 'json');
			return "pending";
		} else if (this.pending[element.name]) {
			return "pending";
		}
		return previous.valid;
	}, '');
}

jQuery.aa = {
	/**
	 * @func replaceAll(value,value,value) return value
	 * @brief 문자열 치환
	 */
	replaceAll : function(val, str, change) {
		return val.split(str).join(change);
	},
	/**
	 * @func isEmpty(value) return boolean
	 * @brief 빈값 여부 확인
	 */
	isEmpty : function(val) {
		var is_type = typeof val;

		if (val == null || val == 'undefined' || typeof val == 'undefined') {
			return true;
		} else if (is_type == 'string') {
			val = this.replaceAll(val, /\s+/g, '');
			if (val == '') {
				return true;
			}
		}

		return false;
	},
	/**
	 * input type
	 */
	isEmptyText : function(element, message) {
		if (this.isEmpty(element.val())) {
			alert(message);
			element.focus();
			return true;
		}

		return false;
	},
	/**
	 * @func isRegnum(value) return boolean
	 * @brief 대한민국 주민등록번호가 올바른지 판단한다.
	 */
	isRegnum : function(val) {
		val = val.replace(/[^0-9]+/g, '');

		var count = 1;
		var total = 0;

		for ( var i = 0; i < 12; i++) {
			if (count > 8) {
				count = 1;
				count++;
			} else {
				count++;
			}

			total += parseInt(val.charAt(i)) * count;
		}

		var mod = total % 11;
		var check = 11 - mod;

		if (check == 10) {
			check = 0;
		}
		if (check == 11) {
			check = 1;
		}

		if (check == parseInt(val.charAt(12))) {
			return true;
		} else {
			return false;
		}
	},
	/**
	 * 재외국인 주민번호 체크
	 */
	checkForeignerSsn: function (fgnno) {
        var sum=0;
        var odd=0;
        buf = new Array(13);
        for(i=0; i<13; i++) { buf[i]=parseInt(fgnno.charAt(i)); }
        odd = buf[7]*10 + buf[8];
        if(odd%2 != 0) { return false; }
        if( (buf[11]!=6) && (buf[11]!=7) && (buf[11]!=8) && (buf[11]!=9) ) {
			return false;
        }
        multipliers = [2,3,4,5,6,7,8,9,2,3,4,5];
        for(i=0, sum=0; i<12; i++) { sum += (buf[i] *= multipliers[i]); }
        sum = 11 - (sum%11);
        if(sum >= 10) { sum -= 10; }
        sum += 2;
        if(sum >= 10) { sum -= 10; }
        if(sum != buf[12]) { return false; }
        return true;
	},
	/**
	 * @func isCount(min|max,number,value) return boolean
	 * @brief 문자열 최대 길이와 최소길이를 판단한다.
	 */
	isCount : function(mode, num, val) {
		val = new String(val);
		var len_val = val.length;

		if ((len_val < num && mode == 'min_length')
				|| (len_val > num && mode == 'max_length')) {
			return false;
		} else {
			return true;
		}
	},
	/**
	 * 앵커 값을 반환
	 */
	getAnchor : function(s) {
		var anchorRegExp = new RegExp(/#(.*)$/);
		var a = s.match(anchorRegExp);
		return (a && a[1]) ? a = a[1] : "";
	},
	noArticle: function(subject) {
		alert(subject +"이 없습니다.");
		return false;
	}
};

jQuery.fn.makeOutLink = function() {
	$(this).each(function (index) {
		$(this).attr("target","_blank");
	});
};

jQuery.fn.embedVideos = function(closed) {
	if (!Archeage.isFlashEnabled) {
		return;
	}

	closed = !!closed;

	var width = 600;
	var height = 365;

    var videos = [
                  {
                          name : "youtube",
                          urlfetcher : "a[href^='http://www.youtube.com/watch?']",
                          codeRegex : /[\?|&]v=([a-zA-Z0-9\-_]+)\b/,
                          generateTags : function(code) {
                                  return '<br/><iframe title="YouTube video player" width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/'
                                                  + code + '?wmode=transparent'
                                                  + '" frameborder="0" allowfullscreen></iframe>';
                          }
                  },
                  {
                          name : "youtu.be",
                          urlfetcher : "a[href^='http://youtu.be/']",
                          codeRegex : /youtu\.be\/([a-zA-Z0-9\-_]+)\b/,
                          generateTags : function(code) {
                                  return '<br class="b"/><iframe title="YouTube video player" width="' + width + '" height="' + height + '" src="http://www.youtube.com/embed/'
                                  + code + '?wmode=transparent'
                                  + '" frameborder="0" allowfullscreen></iframe>';
                          }
                  },
                  {
                          name : "daum tvpot",
                          urlfetcher : "a[href^='http://tvpot.daum.net/clip/ClipViewByVid.do?vid']",
                          codeRegex : /\?vid=([\$a-zA-Z0-9\-_]+)/,
                          generateTags : function(code) {
                                  return "<br/><object type='application/x-shockwave-flash' id='"
                                                  + code
                                                  + "' width='" + width + "px' height='" + height + "px' align='middle' classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'><param name='movie' value='http://flvs.daum.net/flvPlayer.swf?vid="
                                                  + code
                                                  + "' /><param name='allowScriptAccess' value='always' /><param name='allowFullScreen' value='true' /><param name='bgcolor' value='#000000' /><param name='wmode' value='transparent' /><embed src='http://flvs.daum.net/flvPlayer.swf?vid="
                                                  + code
                                                  + "' width='" + width + "px' height='" + height + "px' allowScriptAccess='always' type='application/x-shockwave-flash' allowFullScreen='true' bgcolor='#000000' wmode='transparent'></embed></object>";
                          }
                  },
                  {
                          name : "Vimeo",
                          urlfetcher : "a[href^='http://vimeo.com/']",
                          codeRegex : /vimeo.com\/([0-9]+)\b/,
                          generateTags : function(code) {
                                  return '<br/><iframe src="http://player.vimeo.com/video/' + code + '?portrait=0" width="' + width + '" height="' + height + '" frameborder="0"></iframe>';
                          }
                  },
                  {
                          name: "Naver",
                          urlfetcher : "a[href^='http://serviceapi.nmv.naver.com/flash/NFPlayer.swf']",
                          codeRegex : /(.*)/,
                          generateTags : function(code) {
                                  return "<br/><object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0'  id='NFPlayer40502' width='" + width + "' height='" + height + "'><param name='movie' value='" + code + "' /><param name='wmode' value='transparent' /><param name='allowScriptAccess' value='never' /><param name='allowFullScreen' value='true' /><embed src='" + code + "' wmode='transparent' width='" + width + "' height='" + height + "' allowScriptAccess='never' name='NFPlayer40502' id='NFPlayer40502' allowFullScreen='true' type='application/x-shockwave-flash' /></object>";
                          }
                  }
                  ];

    function getCode(url, regex) {
            var matches = url.match(regex);
            if (matches == null) {
                    return null;
            }
            return matches[1];
    }

    var $wrapper = $(this);

    for (i = 0; i < videos.length; i++) {

            var video = videos[i];
            var $videoTags = $(video.urlfetcher, $wrapper);

            $videoTags.each(function() {
                    var $videoTag = $(this);
                    var url = $videoTag.attr("href");
                    var code = getCode(url, video.codeRegex);
                    var $br = $videoTag.next("br");

                    var $embedTags = $(video.generateTags(code));

                    if (closed) {
                    	$embedTags.hide();

	                    var $fold = $(" <img class='video_toggle' src='/images/common/icon_toggle_video.png'/>");
	                    $fold.insertAfter($videoTag)

	                    $fold.filter(".video_toggle").click(function() {
	                    	$embedTags.toggle();
	                    	return false;
	                    });
                    }

                    if ($br.get().length == 1) {
                            $embedTags.insertBefore($br);
                    } else {
                            $embedTags.appendTo($videoTag.parent());
                    }

            });
    }
};

if (typeof Archeage == "undefined") {
	Archeage = {};
}

/** 플래시 활성화 여부 검사 */
Archeage.isFlashEnabled = (function() {
	try {
		var fo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
		if (fo) {
			return true;
		}
		return false;
	} catch(ex) {
		return !!((navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ?
					navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : false);
	}
})();


/**
 * OS를 판별한다.
 */
Archeage.getOS = function() {
    var ua = navigator.userAgent;

    if (ua.indexOf("NT 6.1") > -1 ) return "Windows 7";
    else if(ua.indexOf("NT 6.0") > -1) return "Windows Vista/Server 2008";
    else if(ua.indexOf("NT 5.2") > -1) return "Windows Server 2003";
    else if(ua.indexOf("NT 5.1") > -1) return "Windows XP";
    else if(ua.indexOf("NT 5.0") > -1) return "Windows 2000";
    else if(ua.indexOf("NT") > -1) return "Windows NT";
    else if(ua.indexOf("9x 4.90") > -1) return "Windows Me";
    else if(ua.indexOf("98") > -1) return "Windows 98";
    else if(ua.indexOf("95") > -1) return "Windows 95";
    else if(ua.indexOf("Win16") > -1) return "Windows 3.x";
    else if(ua.indexOf("Windows") > -1) return "Windows";
    else if(ua.indexOf("Linux") > -1) return "Linux";
    else if(ua.indexOf("Macintosh") > -1) return "Macintosh";
    else return "";
};

/**
 * 0 부터 지정된 수 보다 바로 1작은 수까지 랜덤으로 리턴한다.
 *
 * @param excludedMax 나올 수 있는 숫자의 갯수. 예) 3을 지정하면 0,1,2 가 리턴될 수 있다.
 * @returns 난수
 */
Archeage.random = function(excludedMax) {
	var size = ("" + excludedMax).length;
	var base = 1;
	for (var i = 0; i <= size; i++) {
		base *= 10;
	}

	return Math.floor(Math.random() * base) % excludedMax;
};

Archeage.isArray = function(value) {
	return value &&
		typeof value === 'object' &&
		typeof value.length === 'number' &&
		typeof value.splice === 'function' &&
		!(value.propertyIsEnumerable('length'));
};

