/**
 * 
 * 
 */
google.load('jquery', '1');
google.setOnLoadCallback(function() {
	disable('#sel_city',false);
	disable('#sel_line',false);
	$("#recruit_work_type").attr("disabled", false);
	$("#pref").attr("disabled", false);
	$("#salt").attr("disabled", false);
	//disable('#keyword',false);
	$("recruit_work_type").attr("disabled", false);
	$("#salary_type").attr("disabled", false);
	$("salary_money").attr("disabled", false);

    var prefId = $('#pref').val();
    if (prefId != '') {
        $('#sel_city, #sel_line').attr('disabled',false);
    }    // 他のセレクトタグに影響を与えないものは値の変更時にカウント取得

    $('.search:not(.getList)').change(function() {
        searchCount();
    });
    // 都道府県
    $('#pref').change(function() {
        initOption('.area:not(input, #pref, #rail)');
        disable('.area:not(#pref)');
        var prefId = $('#pref').val();
        if (prefId == '') {
            $('#sel_city, #sel_line').removeAttr('checked');
        } else {
            $.ajax({
                url:'/api/select-pref',
                type:'POST',
                cache:true,
                data:{prefId:prefId},
                dataType:'json',
                success:function(res) {
                    for(key in res.city) {
                        $('#city').append('<option value="' + key + '">' + res.city[key] + '</option>');
                    }
                    for(key in res.line) {
                        $('#line').append('<option value="' + key + '">' + res.line[key] + '</option>');
                    }
                }
            });
            // デフォルトで市区町村の設定を解除
            enable('#sel_city, #sel_line, #city');
            $('#sel_city').attr('checked', 'checked');
        }
        searchCount();
    });
    // 検索ボタン押下
    $('#btn_search').click(function() {
    var pref_top = $('#pref_top').val();
    var param = 'prefecture_id=' + pref_top;
    var area = $("input[name=area]:checked").val();
    var city = $('#city').val();
    if(area != '2'){
    	param += '&city_id=' + city;
    }else{
    	param += '&line_id=' + city;
    }
    var employment_form = $('#employment_form').val();
    param += '&employment_form' + employment_form + '=1';
    var office_system = $('#office_system').val();
    param += '&office_system' + office_system + '=1';
    //GETパラメータ作成
    var url = "/recruit/search?"+param;
	$("#search_link").attr("href",url);
    });
    // 都道府県
    $('#pref_top').change(function() {
        initOption('.area:not(input, #pref_top, #rail)');
        disable('.area:not(#pref_top)');
        var prefId = $('#pref_top').val();
        if (prefId == '') {
            $('#sel_city, #sel_line').removeAttr('checked');
        } else {
            $.ajax({
                url:'/api/select-pref',
                type:'POST',
                cache:true,
                data:{prefId:prefId},
                dataType:'json',
                success:function(res) {
                    for(key in res.city) {
                        $('#city').append('<option style="white-space:normal;" value="' + key + '">' + res.city[key] + '</option>');
                    }
                }
            });
            // デフォルトで市区町村の設定を解除
            enable('#sel_city_top, #sel_line_top, #city');
            $('#sel_city_top').attr('checked', 'checked');
        }
    });
    
    // フリーワード
    $('#wordsearch').click(function() {
    	var param = $('#freeword').val();
	    //GETパラメータ作成
	    var url = "/recruit/search/keyword/"+encodeURIComponent(param);
		$("#wordsearch").attr("href",url);
    });
    // エリア - 市区町村
    $('#sel_city_top').change(function() {
    	var prefId = $('#pref_top').val();
        if ($(this).is(':checked')) {
            $("#city").children().remove();
            $.ajax({
                url:'/api/select-pref',
                type:'POST',
                cache:true,
                data:{prefId:prefId},
                dataType:'json',
                success:function(res) {
                    $('#city').append('<option value="" class="noSelect">こだわらない</option>');
                    for(key in res.city) {
                        $('#city').append('<option style="width:150px;" value="' + key + '">' + res.city[key] + '</option>');
                    }
                }
            });
        }
    });
    // エリア - 路線
    $('#sel_line_top').change(function() {
    	var prefId = $('#pref_top').val();
        if ($(this).is(':checked')) {
            $("#city").children().remove();
            $.ajax({
                url:'/api/select-pref',
                type:'POST',
                cache:true,
                data:{prefId:prefId},
                dataType:'json',
                success:function(res) {
                    $('#city').append('<option value="" class="noSelect">こだわらない</option>');
                    for(key in res.line) {
                        $('#city').append('<option style="width:150px;" value="' + key + '">' + res.line[key] + '</option>');
                    }
                }
            });
        }
    });
    // エリア - 市区町村
    $('#sel_city').change(function() {
        if ($(this).is(':checked')) {
            $('.line').val('');
            enable('#city');
            disable('.line');
        }
    });
    // エリア - 路線
    $('#sel_line').change(function() {
        if ($(this).is(':checked')) {
            $('#city').val('');
            enable('#rail, #line');
            disable('#city');
        }
    });
    // 路線会社
    $('#rail').change(function() {
        initOption('.line:not(#rail)');
        disable('.line:not(#rail)');
        var prefId = $('#pref').val();
        var railId = $(this).val();
        $.ajax({
            url:'/api/select-rail',
            type:'POST',
            cache:true,
            data:{prefId:prefId, railId:railId},
            dataType:'json',
            success:function(res) {
                for(key in res) {
                    $('#line').append('<option value="' + key + '">' + res[key] + '</option>');
                }
            }
        });
        enable('#line');
        searchCount();
    });
    // 路線
    $('#line').change(function() {
        initOption('.stat:not(#rail)');
        var prefId = $('#pref').val();
        var lineId = $(this).val();
        if (lineId == '') {
            disable('.stat');
        } else {
            $.ajax({
                url:'/api/select-line',
                type:'POST',
                cache:true,
                data:{prefId:prefId, lineId:lineId},
                dataType:'json',
                success:function(res) {
                    for(key in res) {
                        $('.stat').append('<option value="' + key + '">' + res[key] + '</option>');
                    }
                }
            });
            enable('.stat:not(#statt)');
        }
        searchCount();
    });
    // 駅区間 - 始点
    $('#statf').change(function() {
        if ($(this).val() == '') {
            $('#statt').val('');
            disable('#statt');
        } else {
            enable('#statt');
        }
        searchCount();
    });
    // 給与形態
    $('#salt').change(function() {
        initOption('#salm');
        var typeId = $(this).val();
        if (typeId == '') {
            disable('#salm');
        } else {
            $.ajax({
                url:'/api/select-salt',
                type:'POST',
                cache:true,
                data:{typeId:typeId},
                dataType:'json',
                success:function(res) {
                    for(key in res) {
                        $('#salm').append('<option value="' + key + '">' + res[key] + '</option>');
                    }
                }
            });
            enable('#salm');
        }
        searchCount();
    });
    // 検索ボタン
    $('#area-btn').click(function() {
    	//検索に不要な項目は送信不可
    	disable('#sel_city');
    	disable('#sel_line');
//    	disable('#recruit_work_type');
//    	disable('#pref');
//    	disable('#salt');
    	if($('#recruit_work_type').val() == "" ){
	    	$("#recruit_work_type").attr("disabled", true);
    	}
    	if($('#pref').val() == "" ){
	    	$("#pref").attr("disabled", true);
    	}
    	if($('#salt').val() == "" ){
	    	$("#salt").attr("disabled", true);
    	}
    	
    	if($("input[name=recruit_work_type]:checked").val() == ""){
	    	$("recruit_work_type").attr("disabled", true);
    	}
    	if($('#salary_type').val() == "" ){
	    	$("#salary_type").attr("disabled", true);
    	}
    	if($('#salary_money').val() == "" ){
	    	$("salary_money").attr("disabled", true);
    	}

    	//こだわり
    	var rf = $("input[id=rf]:checked");
    	var param = new Array();
    	var i=0;
		rf.each(function(){
			param[i] = this.value;
			i++;
		});
		//サーバでの処理用
		if(param.length > 0){
			$("input[name=rf]").val(param.join("_"));
		}else{
			$("input[name=rf]").attr("disabled", true);
		}
    	$("input[id=rf]:checked").attr('checked', false);

        searchSubmit();
    });

    // 求人件数取得
    function searchCount()
    {
        // リクエストを投げて求人件数を取得。
        var search = getTerms();
        $.ajax({
            url:'/api/search-count',
            type:'POST',
            cache:true,
            data:search,
            success:function(res) {
                $('#searchCount').html(res);
            }
        });
    }

    // 送信
    function searchSubmit()
    {
        // GETで遷移するように修正
        $('#searchForm').submit();
        return true;

        var search = getTerms();
        var query = '';
        var param = {};
        // 検索条件から階層構造でパラメータを得る。
        for(var s in search) {
            if (s == '') {
                continue;
            }
            // 配列になっているものは分解
            if (s.indexOf('[') != -1) {
                var key = s.split('[')['0'];
                var val = s.split('[')['1'].replace(']', '');
                if (param[key] === undefined) {
                    param[key] = new Array();
                }
                param[key].push(val);
            } else {
                if (param[s] === undefined) {
                    param[s] = new Array();
                }
                if (typeof search[s] == 'string' && search[s].indexOf('-') != -1) {
                    // 配列を文字列化しているものは再度配列に直して統合
                    param[s].concat(search[s].split('-'));
                } else {
                    param[s].push(search[s]);
                }
            }
        }

        // キーワード検索数カウント
        if ('keyword' in param) {
            var word = param['keyword'];
            $.ajax({
                url:'/api/increment-word',
                type:'POST',
                cache:true,
                data:{keyword:word}
            });
        }

        // 特定のURLの場合分け
        var url = location.protocol + '//' + location.host + '/recruit';
        var path = location.pathname.split('/');
        var action = path.slice(2,3);
        if (action == 'newarrival') {
            url += '/newarrival';
            delete param['new'];
        } else {
            url += '/search';
        }

        // パラメータを文字列に変換
        for(var p in param) {
            query += '/' + p + '/' + param[p].join('-');
        }

        url += query;
        // フォームの飛び先を変更してサブミット
        $('#searchForm').attr('action', url).submit();
    }

// ---- フォーム操作用関数
    function enable(selecter)
    {
        $(selecter).removeAttr('disabled');
    }

    function disable(selecter)
    {
        $(selecter).attr('disabled', 'disabled');
    }

    function initOption(selecter)
    {
        $(selecter).html('<option value="" class="noSelect">こだわらない</option>');
    }

    function getTerms()
    {
        var terms = {};

        // URLの階層構造からパラメータを得る。
        var path = location.pathname.split('/');
        var param = path.slice(3);

        // 特定のURLの場合分け
        var action = path.slice(2,3);
        if (action == 'newarrival') {
            terms['new'] = 1;
        }

        for(var i=0,n=param.length; i < n; i+=2) {
            var k = param[i];
            var v = param[i+1];
            var objName = $('.search[name*="' + k + '["]').attr('name');
            if (objName === undefined) {
                terms[k] = v;
            } else if (objName.indexOf('[') != -1) {
                // 文字列化している配列要素を分解
                if (v.indexOf('-') != -1) {
                    v = v.split('-');
                    for(var j=0,n=v.length; i < n; ++i) {
                        terms[k + '[' + v[i] + ']'] = 1;
                    }
                } else {
                    terms[k + '[' + v + ']'] = 1;
                }
            }
        }

        // フォームの値を検索値に反映
        $('.search').each(function() {
            var objName = $(this).attr('name');
            if ($(this).is('select')) {
                // プルダウン
                var val = $(this).val();
                if (checkNum(val)) {
                    terms[objName] = val;
                } else {
                    delete terms[objName];
                }
            } else if ($(this).is(':radio:checked')) {
                // ラジオボタン
                var val = $(this).val();
                if (checkNum(val)) {
                    terms[objName] = val;
                } else {
                    delete terms[objName];
                }
            } else if ($(this).is(':checkbox')) {
                // チェックボックス
                if ($(this).is(':checked')) {
                    if (terms[objName] === undefined) {
                        terms[objName] = {};
                    }
                    terms[objName] = $(this).val();
                } else {
                    delete terms[objName];
                }
            } else if ($(this).is(':text')) {
                if ($(this).val() != '') {
                    terms[objName] = $(this).val();
                } else {
                    delete terms[objName];
                }
            } else if ($(this).is(':hidden')) {
                if ($(this).val() != '') {
                    terms[objName] = $(this).val();
                } else {
                    delete terms[objName];
                }
            }
        });
        return terms;
    }

// ---- 関数
    function checkNum(value){
      return (value != null && value.match(/[0-9]+/g) == value);
    }

});

