// 初期設定
jQuery(function(){
    initToggleDetail();
    // ドロップダウンチェックリストの初期化
    initDropdownPref();
    // テキストフィールド(プレースホルダ)の初期化
    initTextField();
    // 検索実行時に送信するクエリを短くする
    attachSearchQueryOptimize();

    attachHopeSalary();
    attachEffectOnSearchExec();

    jumpTopIfNotSettingJobTypeArea();
    attachFormResetButton();
});

// 都道府県用ドロップダウンスクリプト
function initDropdownPref(){
    var jQselect, uaDefault;

    $("table#searchBoxBase select[multiple]").each(function(){
        var height, maxHeights;
        maxHeights = {
            EstablishmentPrefectureId: 260,
            EstablishmentBusinessType: 260,
            JobEmploymentType: 200,
            JobSpecialities: 190,
            EstablishmentsSpecialistSpecialistId: 190
        };
        // 選択肢が少ないときは、少ないなりに高さ調整
        height = jQuery(this).find('option').length * 23;

        if (height > maxHeights[this.id]) {
            height = maxHeights[this.id];
        }

        jQuery(this).dropdownchecklist( { maxDropHeight: height, width: 200 } );
    });
}

function initTextField(){
    var target;
    target = jQuery('input:text[title]');
    target.each(function(){
        // 戻るボタン対策
        if (jQuery(this).attr('title') === jQuery(this).val()) {
            jQuery(this).val('');
        }
        
        options = {
            word: jQuery(this).attr('title')
        }
        jQuery(this).placeholder(options);
    });
    // リロード時に文字列がのこってしまうものの対策
    jQuery(window).unload(function(){
        target.each(function(){
            if (jQuery(this).hasClass('placeholder')){
                jQuery(this).val('');
            }
        });
    });
}

// セレクトボックスのvaluesをinput[type=hidden]にカンマ区切りで置き換える
function attachSearchQueryOptimize(){
    var selectBoxes;
    // 短縮するセレクトボックスのデータ(URLクエリのキー: select要素のjQueryオブジェクト)
    selectBoxes = {
        pref: jQuery('#prefValue'),
        busi: jQuery('#businessValue'),
        employ: jQuery('#employmentValue'),
        subjects: jQuery('#specialityValue'),
        spec: jQuery('#specialistValue')
    };

    // セレクトボックスを短縮できるURLに変換する
    selectBoxes.pref.parents('form:first').submit(function(){
        jQuery.each(selectBoxes, function(name, selectBox){
            var hidden, values;
            hidden = jQuery('<input name="'+name+'" type="hidden" />');
            values = selectBox.val();
            if (values == null) {
                values = [];
            }
            hidden.val(values.toString());
            selectBox.replaceWith(hidden);
        });
    });
}

function attachEffectOnSearchExec() {
    jQuery('form#JobSearchTreat').submit(function(){
        /*jQuery('div#detailAllListArea').html("<p class='textCenter'>"+
            "<img src='/img/common/bg_loadingS.gif' alt='' width='20' height='20' />"+
            "<span class='loadingText'>検索中です...</span></p>");*/
        showAjaxStatus(1);
    });
}

// 給与の条件を指定するチェックボックスの振る舞い
function readySalaryForms(){
    var disableArea, salarySlider, salaryValue, valueLabel, choiceableTypes;
    disableArea = jQuery('div#notSalary'); // スライダーが使えないことを可視化する
    // スライダーのガワ
    salarySlider = jQuery('#mSlider');
    // 隠しフィールド
    salaryValue = jQuery('input[name=money_v]');
    // 最低給与表示用
    valueLabel = jQuery('#mValue1');
    // 選択可能な給与タイプ(年収、月給...)
    choiceableTypes = jQuery('input[name=salary_type][class!=nochoice]');
    if (jQuery('#JobExpectedSalary').attr('checked')) {
        choiceableTypes.removeAttr('disabled');
        disableArea.hide();
    } else {
        choiceableTypes
            .attr('disabled', 'disabled')
            .attr('checked', 0);
        disableArea.show();
        valueLabel.html('&nbsp;');
        salaryValue.val(0);
        salarySlider.slider('destroy');
    }
}

function attachHopeSalary() {
    var salarySlider, salarySliderClone, scales, salaryValue, valueLabel, choiceableTypes;
    scales = {
        1: '万円',
        2: '万円',
        3: '円',
        4: '円'
    };
    // スライダーのガワ
    salarySlider = jQuery('#mSlider');

    // スライダーをdestroyしたあとでまたスライダーにすると
    // 数字が狂うので、先にコピーしておいて、切り替えるときに取り出す。
    salarySliderClone = salarySlider.clone();
    // 隠しフィールド
    salaryValue = jQuery('input[name=money_v]');
    // 最低給与表示用
    valueLabel = jQuery('#mValue1');
    // 選択可能な給与タイプ(年収、月給...)
    choiceableTypes = jQuery('input[name=salary_type][class!=nochoice]');

    // スライダーの初期化
    // @param salaryTypeOption 給与の種類のラジオボタン要素
    // @param options オプション
    function initSlider(salaryTypeOption, options) {
        var range, salaryType, max, min;
        options = jQuery.extend({
            resetValue: true // スライダーの値を最小値にリセットするか
        }, options);
        // 埋め込んだスライダーの上限と下限を取得するキー
        salaryType = jQuery(salaryTypeOption).attr('id').match(/^JobSalaryType([0-9]+)$/)[1];
        range = jQuery('#salaryLimitRange'+salaryType);
        jQuery('#mValue2').text(scales[salaryType]+'以上');
        salarySlider.replaceWith(salarySliderClone.clone());
        salarySlider = jQuery('#mSlider');

        max = range.find('span.high').text();
        min = range.find('span.low').text();
        salarySlider.slider({
            max: max,
            min: min,
            slide: function(ev, ui) {
                valueLabel.text(ui.value);
                salaryValue.val(ui.value);
            }
        }).slider('enable');
        if (options.resetValue) {
            salarySlider.slider('moveTo', min);
        } else {
            salarySlider.slider('moveTo', salaryValue.val());
        }
    }

    choiceableTypes.click(function(){
        initSlider(this);
    });
    // ページ読み込みのスライダー有効化
    if (jQuery('[id^=JobSalaryType]:checked').length) {
        initSlider(jQuery('[id^=JobSalaryType]:checked'), { resetValue: false });
    }
    // 希望給与を設定チェックボックスの振る舞い
    jQuery('#JobExpectedSalary').click(function(){
        // 年収を最初に選択された状態にする
        jQuery('#JobSalaryType1').attr('checked','checked').click();
        readySalaryForms();
    });
    readySalaryForms();
}

function initToggleDetail() {
    //クエリdetail_searchで詳細検索divを開くかどうかを引き継いでいる
    if (jQuery('[name=detail_search]').val()=="0") {
        toggleDetail();
    }
}

function toggleDetail() {
    jQuery('#searchBoxMore').toggle();
    if (jQuery('#searchBoxMore:visible').length == 0) {
        jQuery('[name=detail_search]').val(0);
        jQuery('#button-switch-detail').find('img').attr('src', '/img/btn/btn_toggle_open_o.gif');
    } else {
        jQuery('[name=detail_search]').val(1);
        jQuery('#button-switch-detail').find('img').attr('src', '/img/btn/btn_toggle_close_o.gif');
    }
    return false;
}

function formReset() {
    var form;
    form = jQuery('form#JobSearchTreat');
    form.find('input:checked').attr('checked', 0);
    form.find('input:text').val('').blur();
    jQuery('.ui-dropdownchecklist-dropcontainer').find('input:checkbox:checked').next('span').click();
    form.find('#JobExpectedSalary').attr('checked', false);
    readySalaryForms();
    return false;
}

// 条件リセットボタンに処理を付ける
function attachFormResetButton() {
    jQuery('#JobSearchTreat p.reset a').click(function(){
        formReset();
    });
}

function jumpTopIfNotSettingJobTypeArea(){
    if (jQuery('[name=job]').val() === '-1') {
        alert('職種と勤務地を設定してください');
        location.href = '/';
    }
}

/**
 * 検索結果の表示順を変更する。
 * @param string param famous=>人気順, display_date=>更新順
 */
function sort(param) {

    var query = location.search;
    query = _deleteParam( query, 'sort' );
    query = _deleteParam( query, 'disable_offset' );
    query = _deleteParam( query, 'page' );
    
    if( query == '' ) {
        query = '?';
    }
    if( query.length > 1 ) {
        query = query + '&';
    }
    query = query + 'sort=' + param;
    location.href = query;
}

