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

var cmbIndex = new Object();

$(document).ready(function() {
    initializeCookie();

    countOfCommunication = 0;
    _setWidthOfStationList();
    initForIE();
    setStaticJob();
    initComboItems();

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

/**
 * 路線検索 - 駅検索画面で、1行に何駅配置するかを設定する
 */
function _setWidthOfStationList() {
    var maxItemLength = 0;
    var curLen = 0;
    var pxLength = maxItemLength * 1.15;
    var itemsPerLine = 0;
    var searchBoxWidth = 0;

    maxItemLength = 0;
    $('ul.stationList').children('li').each(function() {
        curLen = $(this).children('span').children('label').text().length;
        if( curLen > maxItemLength )
        maxItemLength = curLen;
    }
    );

    //  reset all items' length
    if( maxItemLength != 0 )
    {
        itemsPerLine = parseInt(50/(maxItemLength+4));
        if (itemsPerLine > $('ul.stationList').children('li').size())
        {
           itemsPerLine = $('ul.stationList').children('li').size();
        }
        searchBoxWidth = $('div#blockSearchBody').width();
        
        pxLength = Math.round(searchBoxWidth * 0.97 / itemsPerLine) - 1;    /* ul.width = 98% of div */
        
        $('ul.stationList').children('li').each(function() {
                $(this).css("width", pxLength + "px");
        });
    }
}

function initComboItems() {
    var numberOfCombobox = $('ul.navOne').size();
    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;
        
        cmbIndex[thisID] = i;
        var masterComboCondition = $(thisLi).children('input#' + thisID + 'Value').val();
        if (masterComboCondition == "" || masterComboCondition == 0 || masterComboCondition == -1)
        {
            masterComboCondition = getCookie(thisID, 1);
        }
        initMasterComboItems(thisID, masterComboCondition);
    }
}

function initMasterComboItems(comboID, masterComboCondition) {
    if( comboID == "place" )     //  2009/03/19 : get area name from PHP.
        return;
        
    //最寄駅選択のページの条件の変更不可(0201691)
    return;     
    //  check whether job is static or not
    if( isStatisJob == true && comboID == 'job' )
    {
        return;
    }

    var thisJson = getJsonURL(comboID);
    
    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;
    if (comboID == 'place') {
        if ((masterComboCondition == -1) || (masterComboCondition == null)) {
            $(thisLi).children('input#' + comboID + 'Txt').val(getDefaultComboText(comboID));
        } else {
            for (k=0; k<allLength; k++) {
                if (jsonData.point[k].key == masterComboCondition) {
                    $(thisLi).children('input#' + comboID + 'Txt').val(jsonData.point[k].title);
                    break;
                }
            }
        }
    } else {
        for (v=0; v<allLength; v++) {
            var thisLID = jsonData.point[v].key;
            if (thisLID == masterComboCondition) {
                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("");
        var new_html = '<ul class="navTwo" id="nt' + cmbIndex[comboID] + '">' + new_html + '</ul>';
        $(thisLi).append(new_html);
        
        if (masterComboCondition == -1) {
            $(thisLi).children('input#' + comboID + 'Txt').attr("disabled","true");
            $(thisLi).children('input#' + comboID + 'Txt').val(getDefaultComboText(comboID));
            masterComboCondition = getDefaultComboValue(comboID);    
        } else {
            $(thisLi).children('input#' + comboID + 'Txt').attr("disabled","");
        }
        $(thisLi).children('input#' + comboID + 'Value').val(masterComboCondition);
    }

    //  append onclicked-handler & hover-handler
    settingClickEffect($(thisLi));
    settingHoverEffect($(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 ((oldSelectedValue != null) && (clickedValue == oldSelectedValue)) {
            return false;
        } 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","");
            //設定を保存するタイミングは検索ボタンを押したとき
            //setCookie($(this).parent('ul').parent('li').attr('ID'), $(this).attr('ID'), 1);
            
            if (comboID == 'job') {
                $('input#job_name').val(clickedText);
                $('input#job_id').val(clickedValue);

                //  refresh ad
                loadAdData(clickedValue);
            }
        }
        return false;
    });
}

function selectAll() {
    $("input.station[@type='checkbox']").attr('checked', 'true');
}

function clearAll() {
    $("input.station[@type='checkbox']").attr('checked', '');
}


function form_submit()
{
    var isCheckedAnyone = $("input.station[@type='checkbox'][@checked='1']").size();
    if (isCheckedAnyone == 0) {
        alert(ERROR_NOT_SELECTED_STATION);
        return;
    } else if (!checkAreaAndJob($("input#area_id").val(), $("input#job_id").val())) {
        displayAlert();
        return;
    }
    //$('div#detailAllListArea').html("<p class='textCenter'><img src='/img/common/bg_loadingS.gif' alt='' width='20' height='20' /><span class='loadingText'>検索中です...</span></p>");
    // 検索条件を集める。（ エリア、職種、選択された路線）
    var conditions = new Array();
    conditions['pref'] = $("input#area_id").val();
    conditions['job'] = $("input#job_id").val();
    conditions['railway'] = $("input#railway_id").val();

    // 募集科目（職種が医師の場合）
    var itemID = '', itemValue = '';
    $("form#formStation ul#stationList_ul input[@type='checkbox'][@checked='1']").each(function(index) {
        itemID = $(this).attr('id');
        if( itemValue.length > 0 )
            itemValue = itemValue + 'x';

        itemValue = itemValue + itemID.substr(7);  // 7 : 'station'.length
    });
    conditions['station'] = itemValue;

    // 補助条件の初期化（ページナビ関連）
    conditions['sort'] = $("input#sort").val();
    conditions['jobCode'] = $("input#job_code").val();
    conditions['page'] = 1;

    // パラメータQUERY文字列を構成する。
    var params = 'from=station';
    for( var itemID in conditions )
    {
        if( params.length > 0 )
            params = params + "&";

        params = params + itemID + "=" + conditions[itemID];
    }

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

function initializeCookie()
{
    var value = '';
    /*
    // エリア
    value = $("input#area_id").val();
    cookie_value = getCookie('place', 0);
    if( value.length > 0 && value != '-1' && value != cookie_value )
    {
        //setCookie('place', value, 0);
        value = $("input#area_name").val();
        //setCookie('placename', value, 0);
    }
    // 職種
    value = $("input#job_id").val();
    cookie_value = getCookie('job', 0);
    if( value.length > 0 && value != '-1' && value != cookie_value )
    {
        setCookie('job', value, 0);
        value = $("input#job_name").val();
        setCookie('jobname', value, 0);
    }
    //refreshCookieArea();    
    // 路線
    value = $("input#railway_id").val();
    cookie_value = getCookie('railway', 0);
    if( value.length > 0 && value != '-1' && value != cookie_value )
        setCookie('railway', value, 0);
    */
}

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#formStation').attr('action') + query;
    //location.href = $('form#formStation').attr('action') + "?_mode=page&page=" + page;
    //gotoURL(page, 'search_station');
}

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#formStation').attr('action') + query;
    //location.href = $('form#formStation').attr('action') + "?_mode=sort&sort=" + param;
    //common_sort(param, 'formStation');
}

