
// ============== INDEX LIST ==============
//
//  1: CHECK LIST
//  2: TANISHI-KUN
//  3: COMMON
//  4: MYPAGE
//  5: Thumbnail
//
// ========================================



// ========================================
//  1: CHECK LIST
// ========================================

// チェックリストを開く
function openCheckList(url) {

	var windowName = 'kouhouWindow';

	param = 'scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,width=700,height=800';

	w = window.open("", windowName, param);
	w.focus();
	w.document.write("読み込み中...");
	w.location.href=url;
}


// チェックした学校をまとめて資料請求する
function gotoMainWindow(url, window_name){
    var ele_window = window.opener;
    var ele_customerIds = document.getElementsByName('seikyuuParamDto.customerIds');

    try {
        // 親画面の有無
        if (ele_window == undefined) {
            ele_window = window.open('', window_name, '');
            ele_window.document.write('資料・願書確認画面読み込み中...');
        }

		var ele_form = ele_window.document.createElement('form');

        // フォーム設定
        ele_form.name = 'seikyuu_main';
        ele_form.action = url;
        ele_form.method = 'post';

        for (var i = 0; i < ele_customerIds.length; i++) {
        	if(ele_customerIds[i].checked)
        	{
	            var ele_input = ele_window.document.createElement('input');
	            ele_input.type = 'hidden';
	            ele_input.name = 'seikyuuParamDto.customerIds';
	            ele_input.value = ele_customerIds[i].value;
	            ele_form.appendChild(ele_input);
	        }
        }

        var ele_route_type = ele_window.document.createElement('input');
        ele_route_type.type = 'hidden';
        ele_route_type.name = 'seikyuuParamDto.routeType';
        ele_route_type.value = '1';
        ele_form.appendChild(ele_route_type);
        // 親画面にフォームを作成
        var ele_window_body = ele_window.document.getElementsByTagName('body')[0];
        ele_window_body.appendChild(ele_form);

        // フォームsubmit()
        ele_form.submit();
    } catch (e) {
		// alert(e.description);
		// alert(e.number);
        //alert('スクリプトエラーです。大変申し訳ありませんが画面を一旦閉じた後、最初から操作を行ってください。');
    }
}


// ========================================
//  2: TANISHI-KUN
// ========================================

// 今日のタニシ君を開く
function openTanishi(){
	window.open('tanishi/top/','_blank','scrollbars=no,width=610,height=420');
}

// ========================================
//  3: COMMON
// ========================================

// メインウィンドへ遷移
function GoMainWindow(url, window_name) {
	if (opener.closed) {
		NewWin=window.open("",window_name);
		NewWin.location.href=url;
		NewWin.focus();
	}
	else {
		opener.location.href=url;
		opener.focus();
	}
}

// 指定URLへ画面遷移
function move(url){
    document.location.href=url;
}

// formのactionを指定してsubmitを実行
function execute(form, url){
	form.action = url;
	form.submit();
}

// submitの実行(SSL)
function executeSSL(form, url){
	//↓これは相対パス使うときの方法の為、
	//　絶対パスでアクセスする方法に変更
	//var fullurl = getFullURL(url)
	//if(fullurl.indexOf('http://')!=-1){
	//	fullurl = 'https' + fullurl.substr(4,fullurl.length);
	//}

	var fullurl = 'https://' + location.host + url;
	execute(form,fullurl);

}

// actionとmethodとhiddenのinputを指定してsubmitを実行。
// formは勝手に作る。paramObjが汚染されているとおかしくなるので注意。
function executeWithParam(action, method, paramObj){
	_executeWithParam(action, method, paramObj, document);
}
function _executeWithParam(action, method, paramObj, document){

	var form = $(document.createElement("form")).attr({
	  "action" : action,
      "method" : method,
      "name" : "form"
    });
	for(var key in paramObj){
		$(document.createElement("input")).attr({
			"type" : "hidden",
			"name" : key,
			"value" : paramObj[key]
		}).appendTo(form);
	}
	form.appendTo(document.body).submit();
}

// ログアウトする。
// ログアウト後のリダイレクト先URLは、各画面でgetLogoutAfterUrl関数を定義することで指定する。
// 基本はm:id="shingakuJs"をヘッダに含めることで、beforeRewriteUrlが入るので個別に定義する必要なし。
// 検索や各種完了画面など、帰ってきてほしくない画面の場合は独自に定義する。
function logout(){
	executeWithParam(contextPath + "/logout/", "post", {"redirectUrl" : getLogoutAfterUrl()});
}

function toggleDisabled(name, disabled){
	if(disabled){
		$("[name=" + name + "]").attr("disabled", "true");
	}else{
		$("[name=" + name + "]").removeAttr("disabled");
	}
}

function toggleDisabled2(name, disabled) {
	var elements = document.getElementsByName(name);
	if( disabled ){
		for(var i = 0; i < elements.length; i++){
			elements[i].disabled = true;
		}
	} else {
		for(var i = 0; i < elements.length; i++){
			elements[i].disabled = false;
		}
	}
}

// 検索画面での一括チェック
var onoroff = false;
function toggleCheck(form, name){

	if(form[name] != undefined){
		if(onoroff){
			if(form[name].length == undefined){
				toggleCheckItem(form[name],false);
			}else{
				for(i = 0;i < form[name].length;i++){
					toggleCheckItem(form[name][i],false);
				}
			}
			onoroff = false;
		}else{
			if(form[name][0] == undefined){
				toggleCheckItem(form[name],true);
			}else{
				for(i = 0;i < form[name].length;i++){
					toggleCheckItem(form[name][i],true);
				}
			}
			onoroff = true;
		}
	}

}

function toggleCheckItem(chekcbox,checked){
	if(!chekcbox.disabled){
		chekcbox.checked = checked;
	}
}
function toggleCheck2(cb, name){
	onoroff = !cb.checked;
	toggleCheck(cb.form, name);
}


// ポップアップウィンドウ
function openWindow(url, window_name, param) {
	param = param || 'scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no,width=850,height=800';

	window.open(url, window_name, param);
	return false;
}

// ポップアップウィンドウ2
function openPopupWindow(url, name, param) {

	var windowName = name;

	param = param || 'scrollbars=yes,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,titlebar=no,width=700,height=800';

	w = window.open("", windowName, param);
	w.focus();
	w.document.write("読み込み中...");
	w.location.href=url;
}

// 候補リストOPEN
function openKouhoWindow(url) {
	//url = '/seikyuu/seikyuu_kouho.html';
	param = 'scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=yes,width=650,height=800';

	w = window.open("", "kouhoWindow", param);
	if(w.document.cookie.length > 0)
	{
		w.close();
		w = window.open("", "kouhoWindow", param);
	}
	//w = window.open("", "", param);
	w.focus();
	w.document.write("\u5019\u88DC\u30EA\u30B9\u30C8\u8AAD\u307F\u8FBC\u307F\u4E2D...");
	// 候補リスト読み込み中...
	w.location.href=url;
}



// 同意チェック(submit)
function consentSubmit(form, name, url){
	var V;
	for(i = 0; i < form.elements.length; i++) {
		if(form.elements[i].name == name && form.elements[i].checked) {
			V = form.elements[i].value;
			break;
		}
	}
	if(V){
		javascript:form.action=url;
		form.submit();
	}else{
		alert("\u540C\u610F\u3057\u3066\u304B\u3089\u30DC\u30BF\u30F3\u3092\u62BC\u4E0B\u3057\u3066\u304F\u3060\u3055\u3044");
		// 同意してからボタンを押下してください
		//location.href=url;
	}
}
function consentOpenBlank(form, name, url){
	var V;
	for(i = 0; i < form.elements.length; i++) {
		if(form.elements[i].name == name && form.elements[i].checked) {
			V = form.elements[i].value;
			break;
		}
	}
	if(V){
		window.open(url,'_blank');
	}else{
		alert("\u540C\u610F\u3057\u3066\u304B\u3089\u30DC\u30BF\u30F3\u3092\u62BC\u4E0B\u3057\u3066\u304F\u3060\u3055\u3044");
		// 同意してからボタンを押下してください
		//location.href=url;
	}
}

// ページ上にあるコントロールの活性・非活性化
// 2007/01/11 T.Soga
function controlDisabled(flag){
	for( var i = 0 ; i < document.forms.length ; i++ ){
		var f = document.forms[i];
		for( var j = 0 ; j < f.elements.length ; j++ ){
			var e = f.elements[j];
			e.disabled = flag;
		}
	}
}

// URLをフルパスで取得
function getFullURL(fileName){
          var locationPath = location.href.substr(0,location.href.lastIndexOf('/'));
          var fileNameMin = fileName.substr(fileName.lastIndexOf('/')+1,fileName.length);
          var filname2    = fileName.substr(fileName.indexOf('/')+1,fileName.length);
          var dirLen   = fileName.split('../').length;
          if(fileName.indexOf('https://')!=-1||
             fileName.indexOf('http://')!=-1) return fileName;
          else if(dirLen==1)return locationPath+'/'+filname2;
          else if(dirLen>1){for(i=0;i<dirLen;i++){
              locationPath = locationPath.substr(0,locationPath.lastIndexOf('/'));
            }
            return locationPath+'/'+fileNameMin;
          }
}

// 指定フォーム内に指定した名前のエレメントで
// チェックされた項目があるかどうかチェックする
// 戻り値 true/false
// 呼び出し例
//
// [指定した名前を持つcheckbox/radioが1個以上チェックされている]
//    checkedCheck('form1','checkbox_hoge',true);
//
// [指定した名前を持つcheckbox/radioで1個以上未チェックの物がある]
//    checkedCheck('form1','checkbox_hoge',false);
function checkedCheck(formName,elementName,flagTrueOrFalse){

	return ( getCheckBoxMatchCount(formName, elementName, flagTrueOrFalse) > 0 ) ? true : false;
}

function getCheckBoxMatchCount(formName, elementName, flagTrueOrFalse){
	var elementCount = 0;
	var matchCount = 0;
	var formObj = document.forms[formName];

	for( var i = 0 ; i < formObj.elements.length ; i++ ){
		var e = formObj.elements[i];
		if( e.type == "checkbox" || e.type == "radio" ){
			if( e.name == elementName ){
				elementCount++;
				if( e.checked == flagTrueOrFalse ){
					matchCount++;
				}
			}
		}
	}
	return matchCount;
}


//
// SHLサイトへSHL_IDをPOST送信 (別ウインドウ)
//
function openTekigakuTekishoku(shlID){

	// JAVAスクリプトから直接POSTは出来ないので
	// 一時的にPOSTメソッドのページを作成してsubmit()してSHLのサイトへPOST送信する
	if( shlID == null || shlID == "" ){
		alert( "SHL_ID\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093");
		// SHL_IDが設定されていません
		return ;
	}
	w = window.open("","");
	w.document.writeln("<html><head></head><body><form name=\"shl\" action=\"https://secure1.shl.ne.jp/shingaku/auth.asp\" method=\"post\">");
	w.document.writeln( "<input type=\"hidden\" name=\"entry_id\" value=\"" + shlID + "\"/>" );
	w.document.writeln("</form></body></html>" );
	w.document.forms['shl'].submit();
}

function accessNumWin(url){
	var accessNumWin=window.open(url,"accessNum","width=276,height=285,toolbar=no,scrollbars=yes,resizable=no,menubar=no,status=yes");
	accessNumWin.window.focus();
}

function sslHelpWin(url){
	var sslHelpWin=window.open(url,"sslHelp","width=276,height=415,toolbar=no,scrollbars=yes,resizable=no,menubar=no,status=yes");
	sslHelpWin.window.focus();
}

//========================================
// 4: MYPAGE
//========================================

// 志望校リスト削除確認
function delete_confirm(){
	if(!checkedCheck("mypage","mypageWishedSchoolDto.deleteIdList",true)){
		alert("削除する学校が選択されていません");
		return false;
	}
	return true;
}

// 資料・願書選択判定
function seikyu_confirm(){
	var cnt = getCheckBoxMatchCount("mypage","seikyuuParamDto.customerIds",true);
	if(cnt <= 0){
		alert("資料願書を請求する学校が選択されていません\n（画面左側のチェックボックスはリストからの削除用です）");
		return false;
	}else if(cnt > 30){
		alert("一度にまとめて資料請求できるのは30件までです。");
		return false;
	}
	else {
		return true;
	}
}

// 志望校リスト削除、資料請求選択、願書選択のチェックボックス選択用
function shiboukouListToggleCheck(clickname, targetname){

	var clickEleName = '#block-mypage-list input.' + clickname;
	var targetEleName = '#block-mypage-list input.' + targetname;

	$(targetEleName).each(function(i){
		 $(targetEleName).attr('checked', $(clickEleName).attr('checked'));
	});
}

// マイスケジュール スケジュール削除確認
function delete_scheule_confirm(){
	return confirm( '削除してもよろしいですか？\r\n\r\n＜入試日程を削除する場合の注意＞\r\n「エントリー開始」「エントリー締切」「出願開始」「出願締切」のいずれかを\r\n削除すると、その入試に関わる日程はすべて削除されます。' );
}

// メッセージボックス(受信） メッセージ削除確認
function delete_message_confirm(){
	if(!checkedCheck("mypage","mypageMessageReceiveExtendDto.delIdList",true)){
		alert("削除するメッセージが選択されていません");
		return false;
	}
	else {
		if(confirm("削除してもよろしいですか？")){
			return true;
		}
	}
	return false;
}

//メッセージボックス(送信） メッセージ削除確認
function delete_messege_send_confirm(){
	if(!checkedCheck("mypage","mypageMessageSendExtendDto.delIdList",true)){
		alert("削除するメールが選択されていません");
		return false;
	}
	else {
		if(confirm("削除してもよろしいですか？")){
			return true;
		}
	}
	return false;
}


// マイページ広告　学校情報へ
function submitMypageAdToGakkou(form, accessNumber, advertiseId, contextPath) {
	$('#input_access_number').attr('value', accessNumber);
	$('#mypage_ad_routeType').attr('name', 'customerCommonDto.routeType');
	var url = '';;
	if($('#mypage_ad_routeType').attr('value') == '11'){
		// 都道府県広告の場合。
		url = contextPath + '/uma/' + advertiseId + '/';
	}else{
		url = contextPath + '/ums/' + advertiseId + '/';
	}
	execute(form, url);
}

//マイページ広告　資料請求へ
//
// 志望校リストで使用する場合は、すでに経路区分のhiddenが指定されているので、その値を変更します。したがって「mypage_ad_routeType」の指定は必要ありません。
function submitMypageAdToSeikyu(form, customerId, contextPath) {
	$('#input_customer_id').attr('value', customerId);
	$('#mypage_ad_routeType').attr('name', 'seikyuuParamDto.routeType');
	$('#wished_route_type').attr('name', '');
	$('#wished_route_type').attr('value', '');
	var url = contextPath + '/seikyuu/sentaku/';
	execute(form, url);
}

//受信しないリスト メッセージ削除確認
function delete_unwanted_messege_confirm(){
	if(!checkedCheck("mypage","mypageUnwantedMessageDto.deleteIdList",true)){
		alert("「受信しないリスト」から削除する学校が選択されていません");
		return false;
	}
	else {
		return true;
	}
}




//========================================
// 5: Thumbnail
//========================================

jQuery.fn.thumbs = function() {
	return this.wrap('<div></div>');
}

jQuery.fn.thumbImage = function() {
	var orgImgWidth = 0;
	var orgImgHeight = 0;
	var dispImgWidth = $(this).attr("width");
	var dispImgHeight = $(this).attr("height");

	if ( typeof $(this).attr("naturalWidth") != 'undefined'  ) {
		// Firefox, Google chrome
		orgImgWidth = $(this).attr("naturalWidth");
		orgImgHeight = $(this).attr("naturalHeight");
	}
	else if ( typeof $(this).attr("runtimeStyle") != 'undefined' ) {
		// IE
		var runs = $(this).attr("runtimeStyle");
		runs.width  = "auto";
		runs.height = "auto";
		orgImgWidth = $(this).attr("width");
		orgImgHeight = $(this).attr("height");
	}

	// リンク要素
	//$(this).parent().parent().css("width", dispImgWidth);
	//$(this).parent().parent().css("height", dispImgHeight);
	//$(this).parent().parent().css("display", "block");

	if ( orgImgWidth < dispImgWidth && orgImgHeight < dispImgHeight ) {
		// 写真背景（親要素）
		$(this).parent().css("width", dispImgWidth);
		$(this).parent().css("height", dispImgHeight);
		$(this).parent().css("background-color", "#FFFFFF"); // 背景色

		// 写真（子要素）
		$(this).css("position", "relative");
		$(this).css("width", orgImgWidth);
		$(this).css("height", orgImgHeight);
		$(this).css("top", (dispImgHeight/2 - orgImgHeight/2));
		$(this).css("left", (dispImgWidth/2 - orgImgWidth/2));
	}
}


