/**
 * This file contains the functions of Controlling Searching.
 *
 * @package     webroot
 * @subpackage  js
 * @author      GMG
 * @created     2009/3/2
 */

var cmbIndex = new Object();
var salaryInfo = new Object();
var selectedArea = -1;

$(document).ready(function() {

    if( initializeCookie() == false ) {
        return;
    }

    countOfCommunication = 0;
    initForIE();
    setStaticJob();
    initComboItems();
    initDetailView();
    //loadSpecialsInfo(jQuery('[name=job]').val());
    
//    $('input#keywordBox').bind('keypress', function(e) {
//        if (e.keyCode==13)
//        {
//            return false;
//        }
//    });
    
    $("div#specialtyForm a.btnOpe").hover(
     function (){
         $("tr#specialtyListCoverTable").show();
     
     },
     function(){}
    );
    $("div#specialtyListCover div.closeBtn").click(
     function (){
         $("tr#specialtyListCoverTable").hide();
     }
    );
    $("div#subjectForm a.btnOpe").hover(
     function (){
          $("tr#subjectListCoverTable").show();
     },
     function(){}
    );
    $("div#subjectListCover div.closeBtn").click(
     function (){
         $("tr#subjectListCoverTable").hide();
     }
    );
    
    $('ul#subjectListCoverUL').children('li').children('span').children('input').click(
          function(){
              var txtSpecialities = $('input#specialitiesTXT').val();
              var txtSelected = $(this).parent().parent().children('span').children('label').text();
              var result = '';
              if ($(this).attr('checked')) {
                  if (txtSpecialities.indexOf(txtSelected) == -1)
                  {
                      result = txtSpecialities == '' ? txtSelected : txtSpecialities + ',' + txtSelected;
                  }
              } else {
                  var splits = txtSpecialities.split(',');
                  for (var i = 0; i < splits.length; i++) {
                      result += splits[i] == txtSelected ? '' : splits[i]+',';
                  }
                  result = result == '' ? '' : result.substr(0, result.length-1);
              }
              $('input#specialitiesTXT').val(result);
              $('input#specialitiesTXT').css("color","#000000");
          }
    );
    
    $('ul#specialtyListCoverUL').children('li').children('span').children('input').click(
          function(){
              var txtSpecialities = $('input#specialistsTXT').val();
              var txtSelected = $(this).parent().parent().children('span').children('label').text();
              var result = '';
              if ($(this).attr('checked')) {
                  if (txtSpecialities.indexOf(txtSelected) == -1)
                  {
                      result = txtSpecialities == '' ? txtSelected : txtSpecialities + ',' + txtSelected;
                  }
              } else {
                  var splits = txtSpecialities.split(',');
                  for (var i = 0; i < splits.length; i++) {
                      result += splits[i] == txtSelected ? '' : splits[i]+',';
                  }
                  result = result == '' ? '' : result.substr(0, result.length-1);
              }
              $('input#specialistsTXT').val(result);
              $('input#specialistsTXT').css("color","#000000");
          }
    );

    //  refresh ad
    var job_id = getCookie('job_type', 1);
    var emptyAd = new Array();
    if( job_id != -1 && job_id != null ) {
        loadAdData(job_id);
    } else {
        refreshAdver(emptyAd);
    }
});

function initComboItems() {
    var numberOfCombobox = $('ul.navOne').size()+1;
    for ( var i=0; i<numberOfCombobox; i++) {
        var thisUl = 'ul#nav' + i;              
        var thisNth = "li:nth-child(1)";
        var thisID = $(thisUl).children(thisNth).attr('ID');
        var thisLi = "li#" + thisID;
        
        var masterComboCondition = $(thisLi).children('input#' + thisID + 'Value').val();
        if (masterComboCondition == "" || masterComboCondition == 0 || masterComboCondition == -1)
        {
            masterComboCondition = getCookie(thisID, 1);
        }
        
        var relationComboCondtion = -1;
        cmbIndex[thisID] = i;

        if (thisID == 'placesub' || thisID == 'employment' || thisID == 'business') {
            relationComboCondtion = getRelationComboCondition(thisID);
            initRelationComboItems(thisID, masterComboCondition, relationComboCondtion);
        } else {
            initMasterComboItems(thisID, masterComboCondition);
        }
    }
}

function initMasterComboItems(comboID, masterComboCondition) {
    if (comboID === undefined || comboID == null || comboID == "")
    {
        return;
    }
    var thisJson = getJsonURL(comboID);

    //  check whether job is static or not
    if( isStatisJob == true && comboID == 'job' )
    {
        loadSalaryInfo(masterComboCondition);
        loadSpecialsInfo( masterComboCondition );
        _insertChangeTR( masterComboCondition, true );
        return;
    }

    showAjaxStatus(1);

    $.ajax({
        type: 'POST',
        url: thisJson,
        data:{'comboID':comboID,'masterComboCondition':masterComboCondition},
        success: function(data) {
            refreshMasterComboItems(data);
            showAjaxStatus(2);
        }
    });
}

function refreshMasterComboItems(data)
{
    eval("var jsonData="+data);
    var comboID = jsonData.comboID;
    var masterComboCondition = jsonData.masterComboCondition;
    var thisLi = "li#" + comboID;

    var new_text = new Array();
    var allLength = jsonData.point.length;
    for (v=0; v<allLength; v++) {
        var thisLID = jsonData.point[v].key;
        if (thisLID == masterComboCondition || isValueIncluded(masterComboCondition, thisLID) ) {
            new_text[v] = ('<li class="bgOrange" id="' + thisLID + '"><a class="bgOrange" href="#">' + jsonData.point[v].title + '</a></li>');
            //$(thisLi).children('input#' + comboID + 'Txt').val(jsonData.point[v].title);            
        } else {
            new_text[v] = ('<li class="grayHover" id="' + thisLID + '"><a class="grayHover" href="#">' + jsonData.point[v].title + '</a></li>');
        }
    }
    var new_html = new_text.join("");
    new_html = '<ul class="navTwo" id="nt' + cmbIndex[comboID] + '">' + new_html + '</ul>';
    $(thisLi).append(new_html);
    
    var clickedText = getSelectedString( $(thisLi).children('ul'), masterComboCondition );
    if (masterComboCondition == -1 || masterComboCondition == '' || clickedText == '' ) {
        $(thisLi).children('input#' + comboID + 'Txt').attr("disabled","true");
        $(thisLi).children('input#' + comboID + 'Txt').val(getDefaultComboText(comboID));
        if (comboID == 'job') {
            masterComboCondition = 0;
        }
    } else {
        $(thisLi).children('input#' + comboID + 'Txt').attr("disabled","");
        $(thisLi).children('input#' + comboID + 'Txt').val(clickedText);
    }
    $(thisLi).children('input#' + comboID + 'Value').val(masterComboCondition);

    if( comboID == 'job' )
    {
        //  load salary info for selected job.
        loadSalaryInfo( masterComboCondition );
        loadSpecialsInfo( masterComboCondition );
        _insertChangeTR( masterComboCondition, true );
    }

    if( comboID == 'place' )
    {
        selectedArea = masterComboCondition;
    }

    //  append onclicked-handler & hover-handler
    settingClickEffect($(thisLi));
    settingHoverEffect($(thisLi));
}

function initRelationComboItems(comboID, masterComboCondition, relationComboCondtion)
{
    //  show ajax-communication status
    showAjaxStatus(1);

    //  compose Ajax url
    var ajaxURL = "";
    if (comboID == 'placesub') {
        if (relationComboCondtion == -1) {
            relationComboCondtion = 0;
        }
        ajaxURL = '/ajax/location_city?areaID=' + relationComboCondtion;
    } else if( comboID == 'business' ) {
        ajaxURL = '/ajax/business_job?jobID=' + relationComboCondtion;
    } else if( comboID == 'employment' ) {
        ajaxURL = '/ajax/employment_job?jobID=' + relationComboCondtion;
    }

    //  send request
    $.ajax({
        type: 'POST',
        url: ajaxURL,
        data:{'comboID':comboID,'masterComboCondition':masterComboCondition, 'relationComboCondtion':relationComboCondtion},
        success: function(data) {
            refreshRelationComboItems(data);
            showAjaxStatus(2);
        }
    });
}

function refreshRelationComboItems(data)
{
    eval("var jsonData="+data);

    //  get sended parameters 
    var comboID = jsonData.comboID;
    var masterComboCondition = jsonData.masterComboCondition;
    var relationComboCondtion = jsonData.relationComboCondtion;
    var thisLi = "li#" + comboID;

    //  compose items' html according to selected status.
    var new_text = new Array();
    var allLength = jsonData.point.length;
    var thisLID = "";
    for (var v=0; v<allLength+1; v++) {
        if(v == 0)
        {
            if( comboID == 'business' || comboID == 'employment' )
            {
                new_text[v] = ('<li class="grayHover" id="0"><a class="grayHover" href="#">こだわらない</a></li>');
            }            
            continue;
        }
        thisLID = jsonData.point[v-1].key;
        if (thisLID == masterComboCondition || isValueIncluded(masterComboCondition, thisLID) ) {
            new_text[v] = ('<li class="bgOrange" id="' + thisLID + '"><a class="bgOrange" href="#">' + jsonData.point[v-1].title + '</a></li>');
        } else {
            new_text[v] = ('<li class="grayHover" id="' + thisLID + '"><a class="grayHover" href="#">' + jsonData.point[v-1].title + '</a></li>');
        }
    }
    
    //  redraw menu
    var new_html = new_text.join("");
    if( $(thisLi).children('ul').is('ul') == false )
    {
        new_html = '<ul class="navTwo" id="nt' + cmbIndex[comboID] + '">' + new_html + '</ul>';
        $(thisLi).append(new_html);
    }
    else
    {
        $(thisLi).children('ul').html(new_html);
    }
    settingHoverEffect($(thisLi));
    
    //  refresh selected items
    if( comboID == 'business' || comboID == 'employment' )
    {
        masterComboCondition = refreshValues( $(thisLi).children('ul'), masterComboCondition );
        setCookie(comboID, masterComboCondition, 1);
    }

    //  show selected items' text & store selected items' id
    var clickedText = getSelectedString( $(thisLi).children('ul'), masterComboCondition );
    if (masterComboCondition == -1 || masterComboCondition == '' || clickedText == '') {
        $(thisLi).children('input#' + comboID + 'Txt').attr("disabled","true");
        $(thisLi).children('input#' + comboID + 'Txt').val(getDefaultComboText(comboID));
    } else {
        $(thisLi).children('input#' + comboID + 'Txt').attr("disabled","");
        $(thisLi).children('input#' + comboID + 'Txt').val(clickedText);
    }
    $(thisLi).children('input#' + comboID + 'Value').val(masterComboCondition);

    if ( comboID == 'placesub' ) {
        setCookie('placesubname', clickedText, 1);
    }

    //  append onclicked, hover-handler
    if( comboID == 'business' || comboID == 'employment' ) {
        settingClickEffect2($(thisLi));
    } else {
        settingClickEffect($(thisLi));
    }
}

function settingClickEffect(elementObj) {
    if (elementObj == null) {
        elementObj = $('ul.navOne').children('li');
    }
    elementObj.children('ul').children('li').click(function(){
        var clickedValue = $(this).attr('ID');
        var oldSelectedValue = getCookie($(this).parent('ul').parent('li').attr('ID'), 1);
        
        if( $(this).parent('ul').parent('li').attr('ID') == 'place' )
        {
            oldSelectedValue = selectedArea;
        }

        if ((oldSelectedValue != -1) && (clickedValue == oldSelectedValue)) {
            return false;//disableCombo($(this));
        } else {
            var comboID = $(this).parent('ul').parent('li').attr('ID');
            var clickedText = $(this).children('a').text();
            $(this).parent('ul').parent('li').children('input#' + comboID + 'Txt').val(clickedText);
            $(this).parent('ul').parent('li').children('input#' + comboID + 'Value').val(clickedValue);
            
            chGrayBg($(this).parent('ul').children('li.bgOrange'));
            chOrangeBg($(this));
            $(this).parent('ul').parent('li').children('input#' + comboID + 'Txt').attr("disabled","");
            //設定を保存するタイミングは検索ボタンを押したとき
            //setCookieCombo($(this));
            
            if( comboID == 'place' )
            {
                selectedArea = clickedValue;
            }
            
            changeRelationCombo($(this));

            //  refresh ad
            if( comboID == 'job' ) {
                loadAdData(clickedValue);
            }
        }        
        return false;
    });
}

function settingClickEffect2(elementObj) {
    if (elementObj == null) {
        elementObj = $('ul.navOne').children('li');
    }
    elementObj.children('ul').children('li').click(function(){
        if (($(this).parent('ul').parent('li').attr('ID') == 'employment' || $(this).parent('ul').parent('li').attr('ID') == 'business') && $(this).attr('ID') == 0)
        {
            $(this).parent('ul').parent('li').children("input[@type='text']").val(getDefaultComboText($(this).parent('ul').parent('li').attr('ID')));
            $(this).parent('ul').parent('li').children("input[@type='text']").attr('disabled', 'true');       
            $(this).parent('ul').parent('li').children("input[@type='hidden']").val(-1);
            setCookie($(this).parent('ul').parent('li').attr('ID'), -1, 1);
            $(this).parent('ul').children('li').each(function() {
                chGrayBg($(this));
            });
            return false;
        }
        
        var clickedValue = $(this).attr('ID');
        var oldSelectedValue = getCookie($(this).parent('ul').parent('li').attr('ID'), 1);
        var included = isValueIncluded( oldSelectedValue, clickedValue );
        var newValue = "";

        if( included == true ) {
            newValue = removeValue( oldSelectedValue, clickedValue );
        } else {
            newValue = addValue( oldSelectedValue, clickedValue );
        }
        
        if( newValue.length == 0 )
        {
            disableCombo($(this));
            return false;
        }
        if ($(this).parent('ul').parent('li').attr('ID') == 'employment' || $(this).parent('ul').parent('li').attr('ID') == 'business')
        {
            setCookie($(this).parent('ul').parent('li').attr('ID'), newValue, 0);
        }

        var comboID = $(this).parent('ul').parent('li').attr('ID');
        var clickedText = getSelectedString($(this).parent('ul'), newValue);
        $(this).parent('ul').parent('li').children('input#' + comboID + 'Txt').val(clickedText);
        $(this).parent('ul').parent('li').children('input#' + comboID + 'Value').val(newValue);
        
        if( included == false)
        {
            //chGrayBg($(this).parent('ul').children('li.bgOrange'));
            chOrangeBg($(this));
            $(this).parent('ul').parent('li').children('input#' + comboID + 'Txt').attr("disabled","");
        }
        else
        {
            //chGrayBg(elementObj.parent('ul').children('li.bgOrange'));
            chGrayBg($(this));
        }
        //設定を保存するタイミングは検索ボタンを押したとき
        //setCookieCombo($(this), newValue);
        changeRelationCombo($(this));            
        return false;
    });
}

function disableCombo(elementObj) {
    var comboID = elementObj.parent('ul').parent('li').attr('ID');
    if (comboID != 'job') {
        setCookie(comboID, -1, 1);
        if (comboID == 'place')
        {
            setCookie('placename', '', 1);
        }
        if (comboID == 'placesub')
        {
            setCookie('placesubname', '', 1);
        }

        chGrayBg(elementObj.parent('ul').children('li.bgOrange'));
        elementObj.parent('ul').parent('li').children('input#' + comboID + 'Txt').attr("disabled","true");
        elementObj.parent('ul').parent('li').children('input#' + comboID + 'Txt').val(getDefaultComboText(comboID));
        elementObj.parent('ul').parent('li').children('input#' + comboID + 'Value').val(-1);
    }
}

function changeRelationCombo(elementObj) {
    var comboID = elementObj.parent('ul').parent('li').attr('ID');

    if( comboID != "place" && comboID != "job" ) {
        return;
    }
    
    var masterComboCondition = "";
    var relationComboCondtion = getCookie(comboID, 1);
    if (relationComboCondtion == -1) {
        relationComboCondtion = 0;
    }

    if( comboID == "place" )
    {
        masterComboCondition = getCookie('placesub', 1);
        //initRelationComboItems('placesub', masterComboCondition, relationComboCondtion);
    } else if( comboID == "job" ) {
        masterComboCondition = getCookie('business', 1);
        initRelationComboItems('business', masterComboCondition, relationComboCondtion);

        masterComboCondition = getCookie('employment', 1);
        initRelationComboItems('employment', masterComboCondition, relationComboCondtion);

        //  load salary info for selected job.
        loadSalaryInfo( relationComboCondtion );
        loadSpecialsInfo( relationComboCondtion );
        _insertChangeTR( relationComboCondtion, false);
    }
}

function setCookieCombo(elementObj, value) {
    var param = elementObj.parent('ul').parent('li').attr('ID');
    var cookieValue = "";
    
    if( value == null ) {
        cookieValue = elementObj.attr('ID');
    } else {
        cookieValue = value;
    }
    
    setCookie( param, cookieValue, 1 );
    if (param == 'job')
    {
        setCookie('jobname', elementObj.children('a').text(), 1);
    }
    if (param == 'place')
    {
        setCookie('placename', elementObj.children('a').text(), 1);
    }
    if (param == 'placesub')
    {
        setCookie('placesubname', elementObj.children('a').text(), 1);
    }
}

//function keywordFocus(){
//    $("input.keywordBox").focus(function(){
//        if(this.value == msg){
//            $(this).val("").css("color","#000");
//        }
//    });
//    $("input.keywordBox").blur(function(){
//        if(this.value == ""){
//            $(this).val(msg).css("color","#969696");
//        }
//        if(this.value != msg){
//            $(this).css("color","#000");
//        }
//    });
//}

function loadSalaryInfo( jobID )
{
    //  show ajax-communication status
    showAjaxStatus(1);

    // compose url
    var ajaxURL = '/ajax/salary_job?jobID=' + jobID;

    //  send request
    $.ajax({
        type: 'POST',
        url: ajaxURL,
        data:{'jobID':jobID},
        success: function(data) {
            // store loaded data
            eval("var jsonData="+data);

            // recomposing salary info & enable/disable radio
            salaryInfo = new Object();

            var salaryType = 0;
            var enableStatus = new Array("true", "true", "true", "true", "true");
            for( var i = 0; i < jsonData.records.length; i ++ )
            {
                salaryType = jsonData.records[i].salary_type;
                if( salaryType > 4 ) {
                    continue;
                }
                
                salaryInfo[salaryType] = { low : jsonData.records[i].limit_low, high : jsonData.records[i].limit_high };
                enableStatus[salaryType] = "";
            }

            for( i = 1; i < 5; i ++ )
            {
                $('td.kibouRadioTd').children("input#m"+i).attr('disabled', enableStatus[i]);
            }

            // init cookie （initializeCookie関数を参考…）
            var moneyclass = getCookie('moneyclass', 1);
            var moneyvalue = getCookie('moneyvalue', 1);
            var value = $('td.kibouRadioTd').children("input[@checked='1']").attr('id');
            if( value != moneyclass && value != 'm0' )
            {
                setCookie('moneyclass', value, 0);
                moneyclass = value;
            
                value = $('span#mValue1').text();
                if (value != '' || parseInt(value+'0') > 0 )
                {
                    setCookie('moneyvalue', value, 0);
                    moneyvalue = value;
                }
            }

            if ((moneyclass == null) || (moneyclass == '') || (moneyclass == 'm0') || (moneyclass == -1)) {
                setCookie('moneyclass', 'm0', 0);
            }
            
            if ((moneyvalue == null) || (moneyvalue == '') || (moneyvalue == -1)) {
                setCookie('moneyvalue', '', 0);
            }
            
            initSlider();
            showAjaxStatus(2);
        }
    });

}

function _insertChangeTR( jobID, isFirst )
{
    var context = "";
    if (!isFirst)
    {
        //コンボボックスで職種を選択する際に、初期化する
        $('input#specialitiesTXT').val("");
        $('input#specialistsTXT').val("");
        $('ul#subjectListCoverUL').children('li').children('span').children('input').each(function(index) {
                $(this).attr('checked', 0);
            }
        );
        $('ul#specialtyListCoverUL').children('li').children('span').children('input').each(function(index) {
                $(this).attr('checked', 0);
            }
        );
        $('input#nurse').attr('checked', 0);
    }
    
    $("tr#ns1").hide();
    $("tr#specialities_box").hide();
    $("tr#subjectListCoverTable").hide();
    $("tr#specialists_box").hide();
    $("tr#specialtyListCoverTable").hide();
    
    if (jobID == 2) 
    {
        $("tr#ns1").show();
    } 
    if (jobID == 1) 
    {
        $("tr#specialities_box").show();
        $("tr#specialists_box").show();
        _setWidthOfspecialities();
        _setWidthOfSpecialists();
    }
}

function _setWidthOfspecialities() {
    var maxItemLength = 0;
    var curLen = 0;
    var pxLength = maxItemLength * 1.15;
    var minCount = 0;
    
    maxItemLength = 0;
    $('div#subjectListCover').children('ul').children('li').each(function() {
        curLen = $(this).children('span').children('label').text().length;
        if( curLen > maxItemLength ) {
            maxItemLength = curLen;
        }
    }
    );

    //  reset all items' length
    if (maxItemLength != 0) 
    {
        minCount = parseInt(60/(maxItemLength+2));
        if (minCount > $('div#subjectListCover').children('ul').children('li').size())
        {
           minCount = $('div#subjectListCover').children('ul').children('li').size();
        }
        pxLength = Math.round(parseInt($('div#searchBox').width(), 10) * 0.97 / minCount) - 1;/* 0.97 : ul ' width is 98% of entire div */
        $('div#subjectListCover').children('ul').children('li').each(function() {
                $(this).css("width", pxLength + "px");
            }
        );
    }
}

function _setWidthOfSpecialists() {
    var maxItemLength = 0;
    var curLen = 0;
    var pxLength = maxItemLength * 1.15;
    var minCount = 0;
    
    maxItemLength = 0;
    $('div#specialtyListCover').children('ul').children('li').each(function() {
        curLen = $(this).children('span').children('label').text().length;
        if( curLen > maxItemLength ) {
            maxItemLength = curLen;
        }
    }
    );

    //  reset all items' length
    if (maxItemLength != 0) 
    {
        minCount = parseInt(60/(maxItemLength+2));
        if (minCount > $('div#specialtyListCover').children('ul').children('li').size())
        {
            minCount = $('div#specialtyListCover').children('ul').children('li').size();
        }
        pxLength = Math.round(parseInt($('div#searchBox').width(), 10) * 0.97 / minCount) - 1;
        $('div#specialtyListCover').children('ul').children('li').each(function() {
                $(this).css("width", pxLength + "px");
            }
        );
    }
}

function loadSpecialsInfo( jobID )
{
    //  show ajax-communication status
    showAjaxStatus(1);

    // compose url
    var ajaxURL = '/ajax/specials_job?jobID=' + jobID;

    //  send request
    $.ajax({
        type: 'POST',
        url: ajaxURL,
        data:{'jobID':jobID},
        success: function(data) {
            // store loaded data
            eval("var jsonData="+data);

            var htmlcontext = "<ul>";
            for( var i = 0; i < jsonData.records.length; i ++ )
            {
                htmlcontext += "<li><span><a href='" + jsonData.records[i].url + "'>" + jsonData.records[i].title + "</a></span></li>"
            }
            
            htmlcontext += "</ul>";
            $('div.eventListArea').html(htmlcontext);

            showAjaxStatus(2);
            //内容がなければ、表示部分を隠す。
            if( jsonData.records.length > 0 ) {
                $('div#eventArea').show();
            } else {
                $('div#eventArea').hide();
            }
        }
    });

}

function initSlider() {
//    var conditionValue = getCookie('moneyvalue', 1);
//    if (conditionValue == -1) {
//        conditionValue = '';
//    }
    if (jQuery('#hopeSalaryCheck').attr('checked')) {
        sliderEnable($('div#mSlider'));
    } else {
        sliderDisable($('div#mSlider'));
    }
//    var conditionClass = getCookie('moneyclass', 1);
//    if (conditionClass != -1) {
//        $('td.kibouRadioTd').children("input#"+conditionClass).attr('checked', 1);
//        if (conditionClass == 'm0') {
//            sliderDisable($('div#mSlider'));
//        } else {
//            getMinMax($('td.kibouRadioTd').children("input#"+conditionClass).next('label').text(), $('div#mSlider'), conditionValue);
//            sliderEnable($('div#mSlider'));
//        }
//    }
    
    clickSlider();
}

function clickSlider() {
    $('input[name=salary]').click(function(){
        var m_type = $(this).next('label').text();
        var thisSlider = $('div#mSlider');
        if (m_type != "こだわらない") {
            getMinMax(m_type, thisSlider);
            sliderEnable(thisSlider);
        } else {
            sliderDisable(thisSlider);
        }
        
        setCookie('moneyclass', $('td.kibouRadioTd').children("input[@checked='1']").attr('id'), 1);
    });
}

function getMinMax(m_type, thisSlider, defaultStartValue){
    thisSlider.slider('destroy');
    
    var thisMax = 1000;
    var thisMin = 100;
    switch (m_type) {
        case '年収':
            thisMax = jQuery('#salaryLimitRange1 span.high').text();
            thisMin = jQuery('#salaryLimitRange1 span.low').text();
            $('#mValue2').text("万円");
            break;
        case '月給':
            thisMax = jQuery('#salaryLimitRange2 span.high').text();
            thisMin = jQuery('#salaryLimitRange2 span.low').text();
            $('#mValue2').text("万円");
            break;
        case '日給':
            thisMax = jQuery('#salaryLimitRange3 span.high').text();
            thisMin = jQuery('#salaryLimitRange3 span.low').text();
            $('#mValue2').text("円");
            break;
        case '時給':
            thisMax = jQuery('#salaryLimitRange4 span.high').text();
            thisMin = jQuery('#salaryLimitRange4 span.low').text();
            $('#mValue2').text("円");
            break;
    }

    var thisStart = (parseInt(thisMin) + parseInt(thisMax)) / 2;
    if ((defaultStartValue != null) && (defaultStartValue != '')) {
        thisStart = defaultStartValue;
    }
    
    setCookie('moneyvalue', thisStart, 1);
    
    makeSlider(thisSlider, m_type, thisMax, thisMin, thisStart);
}

function makeSlider(thisSlider, m_type, thisMax, thisMin, thisStart){
    var slider_value = $('#mValue1');
    var slider_step = 1;

    /*if( thisMax - thisMin > 100 )
        slider_step = Math.round((thisMax - thisMin) / 100);
    else
        slider_step = 1;*/

    slider_value.text(thisStart);
    thisSlider.slider({
        min: thisMin,
        max: thisMax,
        startValue: thisStart,
        stepping: slider_step,
        slide: function (event, ui)
        {
            slider_value.text(ui.value);
            setCookie('moneyvalue', ui.value, 1);
        },
        change: function (event, ui)
        {
            slider_value.text(ui.value);
            setCookie('moneyvalue', ui.value, 1);
        }
    });
    return false;
}

function sliderEnable(thisSlider){
    thisSlider.children('a').css('visibility', 'visible');
    thisSlider.slider('enable');
    thisSlider.parent('div').parent('td').parent('tr').parent('tbody').parent('table').removeClass('grayTable');
    thisSlider.parent('div').parent('td').parent('tr').parent('tbody').parent('table').addClass('wTable');
    thisSlider.removeClass('uiSliderGout');
    thisSlider.removeClass('uiSliderDisabled');
    thisSlider.addClass('uiSliderFirst');
}

function sliderDisable(thisSlider){
    thisSlider.children('a').css('visibility', 'hidden');
    $('span#mValue1').text('');
    $('span#mValue2').text('円');
    thisSlider.slider('disable');
    thisSlider.parent('div').parent('td').parent('tr').parent('tbody').parent('table').removeClass('wTable');
    thisSlider.parent('div').parent('td').parent('tr').parent('tbody').parent('table').addClass('grayTable');
    thisSlider.removeClass('uiSliderFirst');
    thisSlider.addClass('uiSliderGout');
    thisSlider.addClass('uiSliderDisabled');
}

function initDetailView(){
    initDetailButton();
    //initGrayTexts();
    _initKeywordAndSalaryMoney();
}

//var msg = '必要に応じてキーワード・求人情報Noを入力してください';

function _initKeywordAndSalaryMoney() {
   var moneyclass = getCookie('moneyclass', 1);
   
   if ((moneyclass != null) && (moneyclass != '') && (moneyclass != -1))
   {
       $('td.kibouRadioTd').children("input#"+moneyclass).attr('checked', 1);
       if (moneyclass != 'm0')
       {
           $('span#mValue1').text(getCookie('moneyvalue'), 1);
       }
   }
//
//   var condition = getCookie('keyword', 1);
//    if (condition != -1) {
//        $("input.keywordBox").val(condition);
//    }
//    if($("input.keywordBox").val() == msg) {
//        $("input.keywordBox").css("color","#969696");
//    }
//
//    keywordFocus();
}

function initDetailButton() {
    var condition = getCookie('detailview', 1);
    if ((condition == null) || (condition == 0) || (condition == -1)) {
        $('div#detailField').hide();
        $('input#toggleValue').val(0);
        $('a#divToggle').removeClass('dtOpen');
    } else {
        $('div#detailField').show();
        $('input#toggleValue').val(1);
        $('a#divToggle').addClass('dtOpen');
    }
    
    $('a#divToggle').click(function(){
        $(this).toggleClass("dtOpen");
        $(this).next('div#detailField').slideToggle('slow');
        
        if ($('input#toggleValue').val() == 0) {
            $('input#toggleValue').val(1);
        } else {
            $('input#toggleValue').val(0);
        }
        setCookie('detailview', $('input#toggleValue').val(), 1);
    });
}

function initCheckBox() {
    var condition;
    $("input.marR10[@type='checkbox']").each(function(index) {
        condition = getCookie($(this).attr('id'), 1);
        if ((condition != false) && (condition != null) && (condition != '') && (condition != -1)) {
            $(this).attr('checked', 1);
        } else {
            $(this).attr('checked', 0);
        }
    });
}

function initRadios() {
    var condition;
    $("input.marR10[@type='radio']").each(function(index) {
        condition = getCookie($(this).attr('id'), 1);
        if ((condition != false) && (condition != null) && (condition != '') && (condition != -1)) {
            $(this).attr('checked', 1);
        } else {
            $(this).attr('checked', 0);
        }
    });
}

function saveSearchConditions() {
    setCookie('keywordBox', $("input.keywordBox").val(), 1);
    setCookie('moneyclass', $('td.kibouRadioTd').children("input[@checked='1']").attr('id'), 1);
    setCookie('moneyvalue', $('span#mValue1').text(), 1);    
}

function resetConditions() {
    var comboID;
    $("ul.navOne").each(function(index) {
        comboID = $(this).children('li').attr('id');
        
        if (comboID == 'placesub' || comboID == 'business' || comboID == 'employment')
        {
            $(this).children('li').children("input[@type='text']").val(getDefaultComboText(comboID));
            $(this).children('li').children("input[@type='text']").attr('disabled', 'true');
            $(this).children('li').children("input[@type='hidden']").val(-1);
            $(this).children('li').children('ul').css('visibility', 'hidden');
            chGrayBg($(this).children('li').children('ul').children('li.bgOrange'));
        }
    });
    
    executeReset(0);
    
    $("input#specialitiesTXT").val('');
    $("input#specialistsTXT").val('');
    
    //$("input.keywordBox").val(msg);
    //$("input.keywordBox").css("color","#969696");
    
    $('td.kibouRadioTd').children("input").attr('checked', 0);
    $('td.kibouRadioTd').children("input#m0").attr('checked', 1);
    sliderDisable($('div#mSlider'));
    
    $('span#mValue1').text('');
    
    $("input.marR10[@type='checkbox']").each(function(index) {
        $(this).attr('checked', 0);
    });
    
    $("input.marR10[@type='radio']").each(function(index) {
        $(this).attr('checked', 0);
    });
    
    $("select#holiday").val(0);
//    $("input.fukuriField").val(msg1);
//    $("input.fukuriField").css("color","#969696");
    $("input.marR3").val('');
//    $("input.setubiField").val(msg2);
//    $("input.setubiField").css("color","#969696");
}

function form_submit() {
    return false;
    if (!checkJobValue($("input#jobValue").val()))
    {
        displayAlert();
        return;
    }
    
    $('div#detailAllListArea').html("<p class='textCenter'><img src='/img/common/bg/bg_loadingS.gif' alt='' width='20' height='20' /><span class='loadingText'>検索中です...</span></p>");
    
    var conditions = new Array();
    
    //  エリア、職種、希望条件、キーワード、最低希望給与
    conditions['pref'] = $("select#prefValue").val();
    conditions['city'] = $("input#placesubValue").val();
    conditions['job'] = $("input#jobValue").val();
    conditions['busi'] = $("input#businessValue").val();
    conditions['employ'] = $("input#employmentValue").val();
    
    //検索の際に設定を保持する
    //setCookie('place', $("input#placeValue").val(), 1);
    //setCookie('placename', $("input#placeTxt").val(), 1);
    
    if ($("input.keywordBox").hasClass('placeholder')) { // テキスト
        conditions['key'] = encodeURI( $("input.keywordBox").val() );
    }

    conditions['money_c'] = $('td.kibouRadioTd').children("input[@checked='1']").attr('id').replace("m","");
    var moneyValue = $('span#mValue1').text();
    if (moneyValue == '') {
        moneyValue = 0;
    }
    conditions['money_v'] = moneyValue;

    //  詳細検索条件
    var itemID = '';
    var itemValue = '';
    if ($('input#toggleValue').val() == 1) {

        //  チェックバックスの検索条件
        $("form#formTreat input.marR10[@type='checkbox'][@checked='1']").each(function(index) {
            if( $(this).parent().is('td') == true )
            {
                itemID = $(this).attr('id');
                conditions[itemID] = 1;
            }
        });
        
        // ラジオボタン検索条件（転勤など）
        $("form#formTreat input.marR10[@type='radio'][@checked='1']").each(function(index) {
            itemID = $(this).attr('id');
            itemValue = itemID.substr( itemID.length-1 );
            itemID = itemID.substr( 0, itemID.length-1 );

            if( isNaN( parseInt(itemValue) ) == false ) {
                conditions[itemID] = itemValue;
            }
        });
        
        // 福利厚生（テキスト）
        itemValue = $("input.fukuriField").val();
        if (itemValue != msg1) {
            conditions['welfare'] = encodeURI(itemValue);
        }

        // 休日休暇
        itemValue = $("select#holiday").val();
        if (itemValue > 0) {
            conditions['holiday'] = itemValue;
        }

        // 年間休日（テキスト）
        itemValue = $("input#holiday2").val();
        conditions['holiday2'] = encodeURI(itemValue);

        // 設備（テキスト）
        itemValue = $("input.setubiField").val();
        if (itemValue != msg2) {
            conditions['equip'] = encodeURI(itemValue);
        }

        // 募集科目（職種が医師の場合）
        itemValue = '';
        $("form#formTreat ul#subjectListCoverUL input[@type='checkbox'][@checked='1']").each(function(index) {
            itemID = $(this).attr('id');
            if( itemValue.length > 0 ) {
                itemValue = itemValue + 'x';
            }
            itemValue = itemValue + itemID.substr(8);  // 8 : subjects.length
        });
        conditions['subject'] = itemValue;

        // 専門医（職種が医師の場合）
        itemValue = '';
        $("form#formTreat ul#specialtyListCoverUL input[@type='checkbox'][@checked='1']").each(function(index) {
            itemID = $(this).attr('id');
            if( itemValue.length > 0 ) {
                itemValue = itemValue + 'x';
            }
            itemValue = itemValue + itemID.substr(11);  // 11 : specialists.length
        });
        conditions['spec'] = itemValue;
    }
    
    // 補助条件の初期化（ページナビ関連）
    conditions['sort'] = $("input#sort").val();
    conditions['jobCode'] = $("input#job_code").val();
    conditions['page'] = 1;

    // 一部の検索条件をクッキーに保存する。
    saveSearchConditions();

    // パラメータを構成する。
    var params = '';
    for( itemID in conditions )
    {
        if ( params.length > 0 ) {
            params = params + "&";
        }
        params = params + itemID + "=" + conditions[itemID];
    }

    // 検索条件を発信する。
    location.href = $('form#formTreat').attr('action') + "?" + params;

    return false;
}

function initializeCookie()
{
    var value = '';
    
    /*
    // エリア
    value = $("input#placeValue").val();
    cookie_value = getCookie('place', 0);
    if( value.length > 0 && value != '-1' && value != cookie_value )
        setCookie('place', value, 0);
    // 都道府県
    value = $("input#placesubValue").val();
    cookie_value = getCookie('placesub', 0);
    if( value.length > 0 && value != '-1' && value != cookie_value )
        setCookie('placesub', value, 0);
    // 職種
    value = $("input#jobValue").val();
    cookie_value = getCookie('job', 0);
    if( value.length > 0 && value != '-1' && value != cookie_value )
        setCookie('job', value, 0);
    // 希望条件ー業種
    value = $("input#businessValue").val();
    cookie_value = getCookie('business', 0);
    if( value.length > 0 && value != cookie_value )
        setCookie('business', value, 0);
    // 希望条件ー雇用形態
    value = $("input#employmentValue").val();
    cookie_value = getCookie('employment', 0);
    if( value.length > 0 && value != cookie_value )
        setCookie('employment', value, 0);
    // キーワード
    value = $("input#keywordBox").val();
    cookie_value = getCookie('keyword', 0);
    if( value.length > 0 && value != cookie_value )
        setCookie('keyword', value, 0);
    */    

    // 新着求人ページの場合、エリアと職種がクッキーに設定されていないとTOPページに変移させる。
    /*//
    if( location.pathname.indexOf('search') != -1 )
    {
        //var area_cookie = parseInt(getCookie('place', 0));
        if( isNaN(area_cookie) || area_cookie < 1 )
        {
        //displayAlert();
        alert("test");
        //return false;
        }
	}

    //*/
    if( location.pathname.indexOf('new') != -1 )
    {
        var area_cookie = parseInt(getCookie('place', 0));
        var job_cookie = parseInt(getCookie('job', 0));
        var bUndefined = false;

        if( isNaN(area_cookie) || area_cookie < 1 ) {
            bUndefined = true;
        }
        if( isNaN(job_cookie) || job_cookie < 1 ) {
            bUndefined = true;
        }
        if( bUndefined )
        {
            displayAlert();
            return false;
        }
    }

    return true;
}

function goToPage(page)
{
    var query = location.search;
    query = _deleteParam( query, 'page' );
    
    if( query == '' ) {
        query = '?';
    }
    if( query.length > 1 ) {
        query = query + '&';
    }
    query = query + 'page=' + page;
    location.href = $('form#formTreat').attr('action') + query;
    //location.href = $('form#formTreat').attr('action') + "?_mode=page&page=" + page;
    //gotoURL(page, 'search_treat');
}

function sort(param)
{
    var query = location.search;
    query = _deleteParam( query, 'sort' );
    
    if( query == '' ) {
        query = '?';
    }
    if( query.length > 1 ) {
        query = query + '&';
    }
    query = query + 'sort=' + param;
    location.href = $('form#formTreat').attr('action') + query;
    //location.href = $('form#formTreat').attr('action') + "?_mode=sort&sort=" + param;
    //common_sort(param, 'formTreat');
}
