
// POSTするフォームで重複送信防止のためボタンを非表示にする
// 重複送信を防止したいform要素に preventDuplicateForm クラスを付ける
// 重複送信を防止するために隠したい要素に preventDuplicateTarget クラスを付ける
function preventDuplicatePost() {
    $('form.preventDuplicateForm').submit(function(){
        $('.preventDuplicateTarget').css('visibility', 'hidden');
    });
}

function setClassBtn() {
	$(".setButton img, .setButton input, ul#localNav li a img, div#pageTitle p a img,table.inputList td img, ul.stepFlow a img, div#homeNav a img, div#pointSummary a img, ul#secondNav a img").each(function() {
		$(this).addClass("btn");
	});
}

function setTableAddSpan() {
	$("table.viewDetail th, table.inputDetail th" ).each(function() {
	    var theading = jQuery(this).html();
    	jQuery(this).html("<span>" + theading + "</span>");
	});
}
function setTableFormAddMust() {
	$("table.inputDetail th").each(function() {
		var th_text = jQuery(this).html();
		th_text = th_text.replace(/（必須）/g, "<img src='/img/common/ic_must.gif' alt='必須' width='25' height='11' />");
		jQuery(this).html(th_text);
	});
}

function setCheckBoxAddClass() {
	$("table.inputList td  input[type=checkbox]").click(function() {
		jQuery(this).parent().parent().toggleClass('select');
	});
}



function initsetButtonImages() {
	var image_cache = new Object();
	//$("a img.btn,input[type=image].btn").not("[@src*='_o.'],[@src*='_d.']").each(function(i) {
	$("a img.btn, input:image").not("[@src*='_o.'],[@src*='_d.']").each(function(i) {
		$(this).hover(
			function() {
                            if (this.src.lastIndexOf('_o.') !== -1) {
                                return;
                            }
                            var dot = this.src.lastIndexOf('.');
                            this.src = this.src.substr(0, dot) + '_o' + this.src.substr(dot, 4);
                        },
			function() {
                            this.src = this.src.replace('_o.', '.');
                        }
		);
	});
}

function pageScroll() {
	$('a[href*=#]').click(function() {
                // href が # で終わる場合はアンカーを指してないのでなにもしない
                if ($(this).attr('href').match(/#$/)) {
                    return false;
                }
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
			var $target = $(this.hash);
			$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
			if ($target.length) {
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 500);
				return false;
			}
		}
	});
}
function popUpForSupportSite() {
	$(function(){
		$('a').each(function(){
			var support_site_pattern = /^(https?:\/\/[-a-zA-Z.]*)?\/support/;
			if (!(this.href.match(support_site_pattern))) {
				return;
			}
			$(this).click(function(){
				window.open(this.href, "support","width=780,height=600,menubar=yes,scrollbars=yes,resizable=yes");
				return false;
			});
		});
	});
}

function setCorner() {
	$('ul#localNav,div.formBox,div.aggregateBox,dl.colorSelectBox,div#messageFinish').corner("round");
}

// 職種をリセットする
function resetJobType() {
    var options, parsed;
    parsed = location.host.match(/^([a-z0-9-]+?\.)([a-z0-9-.]+)$/);
    options = {
        path: '/',
        expires: 1
    };
    if (parsed && parsed.length == 3) {
        options.domain = '.' + parsed[2];
    }

    $.cookie('CakeCookie[job_type]', '', options);
}

// 左上のサイトロゴをクリックした場合、職種をリセットする
function attachResetJobType() {
    $('div#header p#siteName a').click(resetJobType)
}

/**
 * ページ最上部の会員登録促進メッセージの表示制御
 */
function hideRegisterNotice() {
    if (jQuery("div#headerAdd").size() == 0) {
        return false;
    }
    if (!($(jQuery.cookie))) {
        return false;
    }

    if (jQuery.cookie('hide_register_notice') === '1') {
        jQuery("div#headerAdd").remove();
    }

    jQuery("div#headerAdd a.close").click(function(){
        jQuery("div#headerAdd").remove();
        jQuery.cookie('hide_register_notice', '1', {
            path: '/'
        });
    });
}

/**
 * 職種を開く、職種を閉じるボタンで職種選択の表示on/offを切り替える。
 */
function toggleJobTypes() {
    var anchor = $("a#toggleJobTypes");
    anchor.click( function() {
        if ( anchor.parent("p#jobTypeChangeBtn").attr("class") == "open" ) {
            anchor.html("<img src=\"/img/search/btn_job_open.gif\" alt=\"職種を選択\" width=\"90\" height=\"22\" class=\"btn\" />");
            anchor.parent("p#jobTypeChangeBtn").attr("class", "close");
            $("div#unitJobtypeList").hide();
        } else {
            anchor.html("<img src=\"/img/search/btn_job_close.gif\" alt=\"職種を閉じる\" width=\"90\" height=\"22\" class=\"btn\" />");
            anchor.parent("p#jobTypeChangeBtn").attr("class", "open");
            $("div#unitJobtypeList").show();
        }
    });
}

/**
 * スカウトと転職活動を切り替える
 *
 */
function changeScoutStatus() 
{
    var processing;
    // 切り替えステータス(連続切り替えによるちらつき防止)
    processing = {
        scout: 0,
        job_information: 0
    };
    // class に「star」が付いた画像をクリック
    $('img[class*="setting_"]').click(function(){
        // 
        switch ($(this).attr('class')) {
        case 'setting_scout_on':
        case 'setting_scout_off':
            // 処理中ならなにもしない
            if (processing.scout) {
                break;
            } else {
                processing.scout = 1;
            }
            var _thisImg = $(this);var newStatus;
            if (_thisImg.attr('class') == 'setting_scout_on') {
                newStatus = 1;
            } else {
                newStatus = 0;
            }
            // 応答を待たずに見た目を変更する
            updateScoutDisplayStatus(newStatus);
            $.post('/user/change_scout/', {dummy:'dummy'}, function(returned){
                // 応答後に見た目を正しくする
                updateScoutDisplayStatus(returned.scout);
                processing.scout = 0;
            }, 'json');
            break;
        case 'setting_jobinfo_on':
        case 'setting_jobinfo_off':
            // 処理中ならなにもしない
            if (processing.job_information) {
                break;
            } else {
                processing.job_information = 1;
            }
            var _thisImg = $(this);var newStatus;
            if (_thisImg.attr('class') == 'setting_jobinfo_on') {
                newStatus = 1;
            } else {
                newStatus = 0;
            }
            // 応答を待たずに見た目を変更する
            updateJobInfoDisplayStatus(newStatus);
            $.post('/user/change_job_information/', {dummy:'dummy'}, function(returned){
                // 応答後に見た目を正しくする
                updateJobInfoDisplayStatus(returned.job_information);
                processing.job_information = 0;
            }, 'json');
            break;
        }
    });
}

/**
 * スカウト状態の表示を切り替える
 */
function updateScoutDisplayStatus(status) {
    if (status == 1) {
        $('img#scout_on_button')
            .attr('src', '/img/side/btn_setting_on_01.gif')
            .attr('class', 'setting_scout_now');
        $('img#scout_off_button')
            .attr('src', '/img/side/btn_setting_off_02.gif')
            .attr('class', 'setting_scout_off');
    } else {
        $('img#scout_on_button')
            .attr('src', '/img/side/btn_setting_on_02.gif')
            .attr('class', 'setting_scout_on');
        $('img#scout_off_button')
            .attr('src', '/img/side/btn_setting_off_01.gif')
            .attr('class', 'setting_scout_now');
    }
}

/**
 * 転職活動設定の変更
 */
function updateJobInfoDisplayStatus(status) {
    if (status == 1) {
        $('img#jobinfo_on_button')
            .attr('src', '/img/side/btn_setting_on_01.gif')
            .attr('class', 'setting_jobinfo_now');
        $('img#jobinfo_off_button')
            .attr('src', '/img/side/btn_setting_off_02.gif')
            .attr('class', 'setting_jobinfo_off');
    } else {
        $('img#jobinfo_on_button')
            .attr('src', '/img/side/btn_setting_on_02.gif')
            .attr('class', 'setting_jobinfo_on');
        $('img#jobinfo_off_button')
            .attr('src', '/img/side/btn_setting_off_01.gif')
            .attr('class', 'setting_jobinfo_now');
    }
}

/**
 * 転職活動設定の変更
 */
function changeJobInformation() {
	//データ更新 
	$.ajax({
        type: 'GET',
        url: '/user/change_job_information'
    });
}

/**
 * ツールチップを設定
 */
function showTooltip() {
    // ログイン領域
    if (!($.tooltip)) {
        return;
    }
    $('div#blockSubLogin ul li.tipIcon img[title]').tooltip({
        showURL: false
    });
}

//
// 利用規約確認をチェックするまでフォームに入力できないようにする
// @param {Object} conf 設定 処理対象のjQuery Expression
//     conf.checkAgreement 規約確認のためのチェックボックス
//     conf.targetBlock    ブロックする領域
//     conf.targetForm     ブロックするフォーム要素
//     conf.targetButton   ブロックするsubmitボタン
//
function attachBlockUI2Form(conf){
    var checkAgreement, targetBlock, targetForm, targetButton;
    checkAgreement = $(conf.checkAgreement);
    targetBlock = $(conf.targetBlock);
    targetForm = $(conf.targetForm);
    targetButton = $(conf.targetButton);
    $.blockUI.defaults.css = {
        padding:        10,
        margin:         0,
        width:          '55%',
        top:            '10%',
        left:           '35%',
        textAlign:      'center',
        color:          '#000',
        border:         '3px solid #FF6600',
        backgroundColor:'#fff',
        cursor:         'default'
    };
     $.blockUI.defaults.overlayCSS = {
        backgroundColor: '#fff',
        opacity:         '0.7',
        cursor:         'default'
    };
    $.blockUI.defaults.centerY = false;

    function blockForm(){
        targetBlock.block({message:false});
        // submitボタンを無効に
        targetForm.bind('submit.requireAgreement', function(){
            return false;
        })
        targetButton.css('opacity', '0.5');
    }
    function unblockForm(){
        targetBlock.unblock();
        // submitボタンを有効に
        targetForm.unbind('submit.requireAgreement');
        targetButton.css('opacity', '1');
    }
    checkAgreement.bind('click', function(){
        if ($(this).attr('checked')) {
            unblockForm();
        } else {
            blockForm();
        }
    }).triggerHandler('click');
}

/**
 * 画面上部の非課金表示の位置を画面リサイズに合わせて調整する
 */
function positioningCenterNoChargeMessage() {
    var $container = $('div#container'),
        $noCharge = $('div#noCharge'),
        // div#container からの位置決め
        leftFromContainer = ($container.width() - $noCharge.width()) / 2;
    
    if ($noCharge.length === 0) {
        return;
    }
    jQuery(window).bind('resize', function(){
        var left;
        // リサイズ時に変化する div#container の left に併せて
        // $noCharge を調整
        left = leftFromContainer + $container.offset().left;
        $noCharge.css('left', left);
    });
    jQuery(window).triggerHandler('resize');
}

$(document).ready(setClassBtn);
$(document).ready(setTableAddSpan);
$(document).ready(setTableFormAddMust);
$(document).ready(initsetButtonImages);
$(document).ready(pageScroll);
//$(document).ready(setCorner);
$(document).ready(setCheckBoxAddClass);
$(document).ready(popUpForSupportSite);
$(document).ready(attachResetJobType);
$(document).ready(hideRegisterNotice);
$(document).ready(toggleJobTypes);
$(document).ready(preventDuplicatePost);
$(document).ready(changeScoutStatus);
$(document).ready(showTooltip);
$(document).ready(positioningCenterNoChargeMessage);
