//マイページ・ミニページ関連Javascript
var sendFlg = false;

function miniprof(id) {
	document.formminiprof.accountId.value = id;
	document.formminiprof.submit();
}

function exec(aPath) {
	var rFrame = parent.document.getElementById("main");

	rFrame.src = aPath;
}

function sendFriendRegMail( nickname ) {

}

function jump_otherpage(pageNumber, index) {
	if (index == 0) {
		changePage(pageNumber, 'wishListPage');
	}
	if (index == 1) {
		changePage(pageNumber, 'pageNum');
	}
}

function changePage(pageNumber, id) {
	document.getElementById(id).value = pageNumber;

	document.formpagelink.submit();
}

function delItem(id,kbn) {
	document.formdelitem.itemId.value = id;
	document.formdelitem.itemKbn.value = kbn;

	document.formdelitem.submit();
}


function ExecuteView(aUrl, aId) {
	document.formcirclepage.circleId.value = aId;
	document.formcirclepage.submit();
}

function jump_circlelist(page) {
	document.formcirclelist.pageNum.value = page;
	document.formcirclelist.submit();
}



function del_wishitem(id) {
	document.formdelwish.itemId.value = id;
	document.formdelwish.submit();
}

function editRegInfo( isEnable, url ) {
	if ( !isEnable ) {
		return;
	}

	var form = document.createElement('form');
	form.method = 'POST';
	form.action = url;

	document.getElementsByTagName('body')[0].appendChild(form);
	form.submit();
}

var isExistMailAddressFlg;
function isExistMailAddress( mailAddress ) {
	DWREngine.setTimeout(1000);
	DWREngine.setAsync(false);

	//LoginChk.existId( callBackMailAddressCheck, mailAddress, 2 );
	LoginChk.existIdMail( callBackMailAddressCheck, mailAddress );
	return isExistMailAddressFlg;
}

function callBackMailAddressCheck( result )
{
	isExistMailAddressFlg = result;
}

function updateReginfo(isGungho)
{
	if (isGungho == 0) {
		// 外部ブログURLのチェック
		if(!feedUrlCheck()) {
			return;
		}
	}
	document.formreginfoupdate.submit();
}

function viewDiaryComment( aId, aDate )
{
	document.formdiarycomment.authorId.value = aId;
	document.formdiarycomment.diaryDate.value = aDate;
	document.formdiarycomment.submit();
}

function jump_mypage( accountid , myaccountid)
{
	if (accountid == myaccountid) {
		top.ChangeWithMyAvatar('', '/tinierme/subMenuDisp.do', null);
	} else {
		top.ChangeWithMyAvatar(accountid, '/tinierme/subMenuDisp.do?accountId=' + accountid, null);
	}
	document.formfriendpage.accountId.value = accountid;
	document.formfriendpage.submit();
}

function gotoDiaryMore( )
{
	document.formdiarymore.submit();
}

function gotoOldDiary()
{
	document.formolddiary.submit();
}

function gotoNewDiary()
{
	document.formnewdiary.submit();
}

function viewCircleBBS ( aCircleId, aThreadId )
{
	document.formcircleBBS.circleId.value = aCircleId;
	document.formcircleBBS.threadId.value = aThreadId;
	document.formcircleBBS.pageNumber.value = 0;
	document.formcircleBBS.submit();
}

function gotoCircle ( aCircleId )
{
	document.formcircle.circleId.value = aCircleId;
	document.formcircle.submit();
}

function gotoCircleMore()
{
	document.formcirclemore.submit();
}

function gotoCommentMore()
{
	document.formcommentmore.submit();
}

function profileDetail( isEnable, url, accountId ) {
	if ( !isEnable ) {
		return;
	}

	var form = document.createElement('form');
	form.method = 'POST';
	form.action = url;

	input = document.createElement('input');
	input.name = 'accountId';
	input.type = 'hidden';
	input.value = accountId;
	form.appendChild(input);

	document.appendChild(form);
	form.submit();
}

function profileEdit( isEnable, url ) {
	if ( !isEnable ) {
		return;
	}

	var form = document.createElement('form');
	form.method = 'POST';
	form.action = url;

	document.appendChild(form);
	form.submit();
}

function validateUpdateProfile( form ) {
	if ( form.birthMonth ) {
		var birthMonth = form.birthMonth.value;
		if ( birthMonth.isEmpty() ) {
			//alert( '必須項目部分をご記入ください' );
			alert( 'Please fill in all required fields.' );
			return false;
		}
		if ( !birthMonth.match( /^[0-9]+$/ ) ) {
			alert( getMessage( 'errors.integer', new Array( 'Date of Birth' ) ) );
			return false;
		}
	}
	if ( form.birthDay ) {
		var birthDay = form.birthDay.value;
		if ( birthDay.isEmpty() ) {
			//alert( '必須項目部分をご記入ください' );
			alert( 'Please fill in all required fields.' );
			return false;
		}
		if ( !birthDay.match( /^[0-9]+$/ ) ) {
			alert( getMessage( 'errors.integer', new Array( 'Date of Birth' ) ) );
			return false;
		}
	}
	if ( form.birthYear ) {
		var birthYear = form.birthYear.value;
		if ( birthYear.isEmpty() ) {
			//alert( '必須項目部分をご記入ください' );
			alert( 'Please fill in all required fields.' );
			return false;
		}
		if ( !birthYear.match( /^[0-9]+$/ ) ) {
			alert( getMessage( 'errors.integer', new Array( 'Birth Year' ) ) );
			return false;
		}
		if ( birthYear.length > 4 ) {
			alert( getMessage( 'errors.maxlength', new Array( 'Birth Year', 4 ) ) );
			return false;
		}
	}
	if ( form.birthYear && form.birthMonth && form.birthDay ) {
		if ( !isValidDate( form.birthYear.value, form.birthMonth.value, form.birthDay.value ) ) {
			//alert( '誕生日、生まれた年に存在しない日付が入力されています。もう一度お確かめください' );
			alert( 'The values entered are not possible birth year and birth date values. \nPlease try again.' );
			return false;
		}
		if ( !isValidAge(form.birthYear.value, form.birthMonth.value, form.birthDay.value, (form.timezone.value*-1)*60) ){
			alert( 'You must be at least 13 to register for TinierMe. Registration by those under 13 years of age is prohibited.\nPlease try again.' );
			return false;
		}
	}

	var selfIntroduction = form.selfIntroduction.value;
	if ( selfIntroduction.isEmpty() ) {
		//alert( '必須項目部分をご記入ください' );
		alert( 'Please fill in all required fields.' );
		return false;
	}
	// for cafesta ---------------------------------------------------
	if ( selfIntroduction.byteLength() > 100000 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'About Me', '100,000' ) ) );
		return false;
	}
//	if ( selfIntroduction.byteLength() > 4096 ) {
//		alert( getMessage( 'errors.maxlength', new Array( '自己紹介文', '全角2048(半角4096)' ) ) );
//		return false;
//	}
	// for cafesta ---------------------------------------------------

	var blogUrl = form.blogUrl.value;
	if(blogUrl.byteLength() > 0) {
		// URL構文チェックを行う
		if(!URLStructureChk(blogUrl)) {
			//alert('入力されたURLの内容が正しくありません。');
			alert('The URL content entered is not correct.');
			return false;
		}

		// 禁止URLチェックを行う
		if(!URLChk(blogUrl)) {
			//alert('このURLはブログURLとして、登録できません。');
			alert('This URL cannot be registered as a Blog.');
			return false;
		}
	}

	var blogProfile = form.blogProfile.value;
	if(blogProfile.byteLength() > 256) {
		alert( getMessage( 'errors.maxlength', new Array( 'About My Blog', '256' ) ) );
		return false;
	}

	var free1Title = form.free1Title.value;
	if ( free1Title.byteLength() >  24 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'Free Field 1 Title', '24' ) ) );
		return false;
	}

	var free1Body = form.free1Body.value;
	if ( free1Body.byteLength() > 256 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'Free Field 1 Details', '256' ) ) );
		return false;
	}

	var free2Title = form.free2Title.value;
	if ( free2Title.byteLength() >  24 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'Free Field 2 Title', '24' ) ) );
		return false;
	}

	var free2Body = form.free2Body.value;
	if ( free2Body.byteLength() > 256 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'Free Field 2 Details', '256' ) ) );
		return false;
	}

	var free3Title = form.free3Title.value;
	if ( free3Title.byteLength() >  24 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'Free Field 3 Title', '24' ) ) );
		return false;
	}

	var free3Body = form.free3Body.value;
	if ( free3Body.byteLength() > 256 ) {
		alert( getMessage( 'errors.maxlength', new Array( 'Free Field 3 Details', '256' ) ) );
		return false;
	}

	return true;
}

function updateProfile( form ) {
	if ( !validateUpdateProfile( form ) ) {
		return;
	}
	if ( !confirm( 'Are you sure you would like to save your changes?' ) ) {
		return;
	}

	form.submit();
}

function confirmDeleteVisitHistory() {
	return confirm( 'Are you sure you would like to delete your visitor history?' );
}

function deleteVisitHistory( isEnable, url, accountId ) {
	if ( !isEnable ) {
		return;
	}

	var form = document.createElement('form');
	form.method = 'POST';
	form.action = url;

	input = document.createElement('input');
	input.name = 'accountId';
	input.type = 'hidden';
	input.value = accountId;
	form.appendChild(input);

	document.getElementsByTagName('body')[0].appendChild(form);
	form.submit();
}

var isBadURLFlg;

function URLChk( url ){
	DWREngine.setTimeout(1000);			// DWRタイムアウト時間設定
	DWREngine.setAsync(false);			// 同期的に実行(trueで同期)

	// 禁止ブログURLを指定しているかチェックする
	NGURL.checkURL(URLchkcallback, url);

	return isBadURLFlg;
}

function URLchkcallback(result){
	isBadURLFlg = result;
}

function URLStructureChk(url) {
	if(!url.match(/(http|https):\/\/.+/)) {
		return false;
	}
	return true;
}

function gotoVoiceCloset() {
	document.formvoicecloset.submit();
}

var feedUrlFlg;

// 外部ブログURLのチェックを行う
function feedUrlCheck() {
	var feedUrl = document.getElementById("feedUrl").value;
	if(feedUrl == null || feedUrl == '') {
		return true;
	}

	// DWRのタイムアウト時間を設定する
	DWREngine.setTimeout(1000);
	// 同期するように設定
	DWREngine.setAsync(false);

	OutsideBlog.validFeedUrl(feedUrlCheckCallBack, feedUrl);

	if(!feedUrlFlg) {
		//alert("入力された外部ブログのRSSのURLが正しくありません。");
		alert("The RSS URL of your external blog is not valid.");
		return false;
	} else {
		return true;
	}
}

// 外部ブログURLチェックのコールバック
function feedUrlCheckCallBack(result) {
	feedUrlFlg = result;
}

function mypageDispCircle(circleId) {
	document.dispForm.circleId.value = circleId;
	document.dispForm.submit();
}

/**
 * パスワード変更画面 入力値チェック
 */
function checkAndSubmitPassword() {
	var oldPassword = document.passwordForm.password.value.toLowerCase();
	var newPassword = document.passwordForm.newPassword.value;
	var retryNewPassword = document.passwordForm.retryNewPassword.value;
	var userID = document.passwordForm.userID.value;
	var nickname = document.passwordForm.nickname.value;

	// 新パスワードフォーマットチェック
	if (!passwordErrorCheck(newPassword, 'new password')) {
		return;
	}

	// 新パスワードと確認用新パスワードが一致するか
	if (newPassword != retryNewPassword) {
		alert(getMessage('errors.notsame', new Array('password', 'Confirm New Password')));
		return;
	}

	// 新パスワードと古いパスワードが異なっているか
	if (newPassword == oldPassword) {
		alert(getMessage('errors.notreuse', null));
		return;
	}

	// Exampleとパスワードが異なっているか
	if ("s3lfyt0wn!" == newPassword) {
		alert(getMessage('errors.example', null));
		return;
	}

	// ユーザIDとニックネームが同一の場合はエラー
	if (newPassword.toLowerCase() == nickname.toLowerCase()) {
		alert(getMessage('errors.same.nickname', null));
		return
	}

	// 以前のパスワードが正しいか
	if (!existAccount(userID, oldPassword)) {
		alert(getMessage('errors.notmatch', new Array('Current Password')));
		return;
	}

	document.passwordForm.submit();
}

/**
 * 入力されたパスワードからエラー内容を判定し、
 * エラー内容に対応するメッセージを画面に表示します。
 *
 * @param password パスワード
 * @param errMes エラーメッセージ
 * @return エラーなし:true / エラーあり:false
 */
function passwordErrorCheck(password, errMes) {
	var errNum = validatePassword(password);

	if (errNum == -1) {
		alert(getMessage('errors.required', new Array(errMes)));
		return false;
	}
	if (errNum == -2) {
		alert(getMessage('errors.minlength', new Array(errMes, 8)));
		return false;
	}
	if (errNum == -3) {
		alert(getMessage('errors.maxlength', new Array(errMes, 16)));
		return false;
	}
	if (errNum == -4) {
		alert(getMessage('errors.invalid', new Array(errMes)));
		return false;
	}
	if (errNum == -5) {
		alert(getMessage('errors.notdifferent', null));
		return false;
	}

	return true;
}

/**
 * パスワード再設定用validator
 *
 * @param password
 * @return エラーなし:0 / 未入力:-1 / 入力文字数不足:-2 / 入力文字数超過:-3 / 入力禁止文字列:-4 / 組合せ種類不足:-5
 */
function validatePassword(password) {
	if (!objnullchk(password))
		return -1;

	var errNum = betweenchk(password, 8, 16);

	if (errNum == -1)
		return -2;
	if (errNum == -2)
		return -3;
    if (!password.match(/^[-0-9a-z\!\"\'\#\$\%\&\(\)\*\+\,\.\/\:\;\<\>\=\?\@\[\]\\\^\_\`\{\}\|\~]+$/))
		return -4;
    if (!checkTypeCount())
    	return -5;

    /**
     * パスワードに含まれている文字の種類が、3種類以上存在するか判定します。
     *
     * @return 判定結果(存在する:true / 存在しない:false)
     */
    function checkTypeCount() {
        var numeric = false;
        var lowerCaseAlphabet = false;
        var symbol = false;
        var type = 0;

    	for (var i = 0; i < password.length; i++) {
        	var word = password.substring(i, i+1);

        	if (word.match("^[0-9]+$")) numeric = true;
        	if (word.match("^[a-z]+$")) lowerCaseAlphabet = true;
        	if (word.match("^[\\!\"'#$%&()*+,./:;<>=?@\\[\\]\\\\^_`{}|~]+$")) symbol = true;
        }

    	if (numeric) type++;
    	if (lowerCaseAlphabet) type++;
    	if (symbol) type++;

        return type >= 3;
    }

	return 0;
}

/**
 * ログインアカウントが存在するか判定する。
 *
 * 注意:使用するhtmlで、以下のタグを宣言すること。
 * <p>
 * <script type="text/javascript" src="http://www.tinierme.com/tinierme/dwr/interface/LoginChk.js"></script>
 *
 * @param userID ユーザID
 * @param password パスワード
 * @return true:存在する / false:存在しない
 */
function existAccount(userID, password) {
	var result = false;

	DWREngine.setTimeout(1000);		// DWR実行タイムアウト
	DWREngine.setAsync(false);		// 同期的に実行(false で同期)

    // アカウントチェック
    LoginChk.existAccount(callbackExistAccount, userID, password);

	function callbackExistAccount(data) {
		result = data;
	}

	return result;
}

function checkMailAddress(mailAddress, mailAddress_re) {

	if ( mailAddress.isEmpty() ) {
		//alert( 'メールアドレスが入力されていません' );
		alert( 'Please enter an E-mail address.' );
		return false;
	}
	if ( mailAddress.byteLength > 256 )
	{
		//alert('メールアドレスは半角256文字以内で入力してください。');
		alert('Please enter an E-mail address that is within 256 characters.');
		return false;
	}
	if ( !mailAddress.match( /.+@.+/ ) || mailAddress.isContainTwoByteChar() )
	{
		//alert('メールアドレスは正しくご入力ください。');
		alert('Please correctly enter an E-mail address.');
		return false;
	}
	if ( mailAddress.match( /@.*(ezweb\.ne\.jp|docomo\.ne\.jp|vodafone\.ne\.jp|pdx\.ne\.jp|softbank\.ne\.jp).*/ ) )
	{
		//alert('ケータイアドレスではご登録できません。');
		alert('A mobile phone E-mail address cannot be used.');
		return false;
	}
	if((mailAddress.match( /[^a-zA-Z0-9@\.\!\#\$\%\&\'\*\+\-\/\=\?\^\_\`\{\|\}\~]+/ ))){
		alert( getMessage( 'errors.mailaddr', null ) );
		return false;
	}
	if ( mailAddress != mailAddress_re )
	{
		//alert('メールアドレスが一致しません。入力内容を再度ご確認ください。');
		alert('The E-mail addresses you entered do not match. \nPlease re-enter your E-mail addresses.');
		return false;
	}
	if (isExistMailAddress( mailAddress ) ) {
		//alert( 'すでに登録されているメールアドレスです' );
		alert( 'This E-mail address has already been registered.' );
		return false;
	}

	return true;
}

function isValidAge(year, month, day, offset) {
	var result = false;

	DWREngine.setTimeout(1000);		// DWR実行タイムアウト
	DWREngine.setAsync(false);		// 同期的に実行(false で同期)

    // アカウントチェック
    TimeZone.getAge(callbackGetAge, year, month, day, offset);

	function callbackGetAge(data) {
		if(data>=13) {
			result = true;
		}
	}

	return result;
}