var dayNamesMin = ['일', '월', '화', '수', '목', '금', '토'];
var monthNames = ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월'];
var nextText = '다음 달';
var prevText = '이전 달';

//var urlPattern = new RegExp('^(https?:\\/\\/){1}((([a-z\d](([a-z\d-]*[a-z\d])|([ㄱ-힣]))*)\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$','i');
var urlPattern = /^(http|https):(\/\/)?(([-가-힣]|\w)+(?:[\/\.:@]([-가-힣]|\w)+)+)\/?(.*)?\s*$/i;
var datePattern =/^(19|20)\d{2}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[0-1])$/;
var numberPattern = /^[0-9]+$/;
function dateCheck(date) {
	return datePattern.test(date);
}
function urlCheck(url) {
	var ret =urlPattern.test(url);
	return ret;
}
function numberCheck(data) {
	return numberPattern.test(data);
}

function openNewWindow(url,name,w,h,options) {
	var left = Number((screen.width/2)-(w/2));
    var top = Number((screen.height/2)-(h/2))-100;
	return window.open(url, name, 'scrollbars=1,resizable=1,width='+w+',height='+h+',top='+top+',left='+left+','+options);
}

function openPopupView( url, did, width, height, top, left, scrollbars, status, resizable ) {
	window.open(url,"popupWin_"+did,"width="+width+",height="+height+",scrollbars="+scrollbars+",status="+status+",resizable="+resizable+",top="+top+",left="+left);
}

function humanFileSize(size) {
	if( size <= 0 ) {
		return "0";
	}
    var i = Math.floor( Math.log(size) / Math.log(1024) );
    return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + '' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
};

var $j = jQuery.noConflict();

function newWindow($atag) {
	var funcName = $atag.attr("data-func");
	var func = window[funcName];
	var ret = func ? func($atag) : true;
	if( ret ) {
		var width = $atag.attr("data-width") ? $atag.attr("data-width") : 400;
		var height = $atag.attr("data-height") ? $atag.attr("data-height") : 400;
		var popup = openNewWindow($atag.attr("href"), $atag.attr("data-name"),width,height, "");
		popup.focus();
	}
}
$j(document).ready(function() {
	$j("a[target='_blank'][data-role='newWin']").click(function() {
		newWindow($j(this));
		return false;
	});
	
	$j(document).on("click","a[target='_blank'][data-role='newWin']",function(){
		newWindow($j(this));
		return false;
	});
	
	$j(document).on("click", ".usm-btn-history-back", function () {
        history.back();
    });
    
    $j(document).on("click", ".usm-btn-reload", function (e) {
		e.preventDefault();
        window.location.reload();
    });
	
	$j("a[data-role='dataDel']").click(function(e) {
		var msg = $j(this).attr("data-msg") || "정말로 삭제하시겠습니까?";
		var funcName = $j(this).attr("data-func");
		
		if (confirm(msg)) {
			if (funcName && typeof window[funcName] === "function") {
				e.preventDefault();
				window[funcName]($j(this));
			} else {
				return true;
			}
		} else {
			return false;
		}
	});
	
	$j("a[data-role='msgConfirm']").click(function() {
		var msg = $j(this).attr("data-msg");
		if( confirm(msg) ) {
			return true;
		} else {
			return false;
		}
	});
	
	$j('#closeBtn').on('click', function(e) {
		e.preventDefault();
		window.close();
	});

	zoomIconControl();
});

function checkFile($file,allowExt,allowSize) {
	if( !$file[0].files.length ) {
		return false;
	}
	if($file[0].files[0].size > allowSize) {
		$file.val("");
		alert(humanFileSize(allowSize) + " 까지만 첨부할 수 있습니다.");
		return false;
	}
	
	var name = $file[0].files[0].name;
	var idx = name.lastIndexOf( "." );
	var ext = name.substr(idx+1).toLowerCase();
	if( $j.inArray(ext,allowExt) == -1 ) {
		$file.val("");
		alert("첨부할 수 없는 확장자입니다.확장자가" + allowExt.join(",")+ "만 가능합니다." );
		return false;
	}
	return true;
}

function imageLoader(src,loadFunc,errorFunc) {
	var img=$j('<img />');     
	img.attr('src',src);
     
	img.on('error',function() {		
		if ( errorFunc ) {
			errorFunc();
		}
	});
	 
	img.on('load',function() {
		var orgWidth = $j(this).width();
		var orgHeight = $j(this).height();
		$j(this).css("max-width", "100%");
		if( loadFunc ) {
			loadFunc(orgWidth, orgHeight);
		}
	});
	
	return img;
}

function imagePreview($file, $preview, allowExt, allowSize, loadFunc,errorFunc) {
	var filename;
	if( !$file[0].files.length ) {
		$preview.html("");
		return "";
	}
	var ret = checkFile($file, allowExt, allowSize);
	if( !ret ) return "";
	if(window.FileReader){  // modern browser
      filename = $file[0].files[0].name;
      if (!$file[0].files[0].type.match(/image\//)) return "";
      var reader = new FileReader();
      reader.onload = function(e){
          var src = e.target.result;
          var img = imageLoader(src, loadFunc, function() {$file.val("");$preview.html("정상적인 이미지가 아닙니다.");if(errorFunc){errorFunc();}});
          $preview.html(img);
      };
      reader.readAsDataURL($file[0].files[0]);
	} else {
		filename = $file.val().split('/').pop().split('\\').pop();  // 파일명만 추출
	}
	
	return filename;
}

function getFileName($file) {
	if( !$file[0].files.length ) {
		return "";
	}
	
    return $file[0].files[0].name;
}

function passwdCheck(id,$pass,$rePass,passMsg,rePassMsg,min,max) {
	if ( $pass.val().trim() == "" ) {
		alert(passMsg + "를 입력하세요");
		$pass.focus();
		return false;
	}
	
	if ( $rePass.val().trim() == "" ) {
		alert(rePassMsg + "을 입력하세요");
		$rePass.focus();
		return false;
	}
	
	if ( $pass.val().trim() != $rePass.val().trim() ) {
		alert("재입력한 " + passMsg + "가 틀립니다");
		$rePass.focus();
		return false;
	}
	
	if ( $pass.val().indexOf( id ) != -1 ) {
		alert( "아이디가 포함된 비밀번호는 사용하실 수 없습니다" );
		return false;
	}
	
	//var isPW = /^[A-Za-z0-9`\-=\\\[\];',\./~!@#\$%\^&\*\(\)_\+|\{\}:"<>\?]{8,20}$/;
	var isPW = new RegExp("^[A-Za-z0-9`\\-=\\\\\\[\\];',\./~!@#\\$%\\^&\\*\\(\\)_\\+|\\{\\}:\"<>\\?]{"+min+","+max+"}$");
	if( !isPW.test($pass.val()) ) {
		alert("비밀번호는 " + min + "~" + max + "자의 영문자와 숫자, 특수문자를 사용할 수 있습니다.");
		return false;
	}
	
	var chk_num = $pass.val().search(/[0-9]/g) > -1;
	var chk_eng = $pass.val().search(/[A-Za-z]/g) > -1;
	var chk_spec = $pass.val().search(/[`\-=\\\[\];',\./~!@#\$%\^&\*\(\)_\+|\{\}:"<>\?]/g) > -1;
	
	var chkCnt = 0;
	if ( chk_num ) chkCnt++;
	if ( chk_eng ) chkCnt++;
	if ( chk_spec ) chkCnt++;
	
	if ( chkCnt < 3 ){
		alert( "비밀번호는 영문자, 숫자 및 특수문자를 모두 조합하여야 합니다." );
		return false;
	}
	
	return true;
}

function generateUUID() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
};

function zoomIconControl() {
	var parentTag = ".usm-editor-view";
	var parentWidth = $j(parentTag).width();
	var imgs = $j(parentTag +" img");
	imgs.each(function() {
		var naturalWidth = $j(this).prop("naturalWidth");
		var width = $j(this).width();
		var height = $j(this).height();
		$span = $j(this).parents(".zoomIcon");
		/*
		if(width>100 && (naturalWidth>width||naturalWidth>parentWidth)) {
			$j(this).css("height","auto");
			if($j(this).parents(".zoomIcon").length == 0) {
				$span = $j("<span/>");
				$span.attr("class", "zoomIcon");
				//$span.width(parentWidth);

				$atag = $j("<a/>");
				$atag.attr("href",$j(this).attr("src"));
				$atag.attr("target","_blank");
	
				$zoom = $j("<span>크게보기</span>");
				
				$atag.append($zoom);
				
				$span.append($atag);
				$j(this).before($span);
				$j(this).appendTo($span);
			} else {
				$span.width(parentWidth);
				$atag = $span.children("a");
				$atag.show();
			}
			$atag.css("top", ($j(this).height()-$atag.height())+"px");
			$atag.css("left", (width-$atag.width())+"px");
		} else {
			$span.children("a").hide();
		}
		*/
	});
	
}
$j(window).resize(function() {
	zoomIconControl();
});

function sendSns(sns, txt) {
    var o;
    var _url = encodeURIComponent(location.href);
    var _txt = encodeURIComponent(txt);
    var _br  = encodeURIComponent('\r\n');

    switch(sns) {
        case 'facebook':
            o = {method:'popup',url:'http://www.facebook.com/sharer/sharer.php?u=' + _url};
            break;
        case 'twitter':
            o = {method:'popup',url:'http://twitter.com/intent/tweet?text=' + _txt + '&url=' + _url};
            break;
        case 'me2day':
            o = {method:'popup',url:'http://me2day.net/posts/new?new_post[body]=' + _txt + _br + _url + '&new_post[tags]=epiloum'};
            break;
        case 'kakaotalk':
			_url =location.href;
			Kakao.Link.sendDefault({
				objectType: 'feed',
			    content: {
			    	title: txt,
			        imageUrl: $j("meta[property='og:image']").attr("content"),
			        link: {
			        	mobileWebUrl: _url,
			            webUrl: _url
			        }
			    }
			});
			return;
        case 'kakaostory':
			_url =location.href;
			Kakao.Story.open({url: _url,text: txt});
			return;
        case 'band':
            o = {
                method:'web2app',
                param:'create/post?text=' + _txt + _br + _url,
                a_store:'itms-apps://itunes.apple.com/app/id542613198?mt=8',
                g_store:'market://details?id=com.nhn.android.band',
                a_proto:'bandapp://',
                g_proto:'scheme=bandapp;package=com.nhn.android.band'
            };
			break;
		case 'print':
			window.print();
            break;
        default:
            alert('지원하지 않는 SNS입니다.');
            return false;
    }
 
    switch(o.method) {
        case 'popup':
            window.open(o.url, sns, 'width=626,height=436');
            break;
        case 'web2app':
            if(navigator.userAgent.match(/android/i)) {
                setTimeout(function(){ location.href = 'intent://' + o.param + '#Intent;' + o.g_proto + ';end'}, 100);
            } else if(navigator.userAgent.match(/(iphone)|(ipod)|(ipad)/i)) {
                // Apple
                setTimeout(function(){ location.href = o.a_store; }, 200); 
                setTimeout(function(){ location.href = o.a_proto + o.param }, 100);
            } else {
                alert('이 기능은 모바일에서만 사용할 수 있습니다.');
            }
           break;
    }
}

function snsControl(txt) {
	if(!navigator.userAgent.match(/(android)|(iphone)|(ipod)|(ipad)/i)) {
		$j("#usm-sns > span.mob").hide();
	} else {
		$j("#usm-sns > span:last-child").hide();
	}
	$j("#usm-sns").show();
	$j("#usm-sns a").click(function(e) {
		var href = $j(this).attr("href");
		if( href.charAt(0) == "#") {
			e.preventDefault();
			sendSns($j(this).attr("href").substring(1), txt ? txt : document.title);
		}
	});
}
