var d_lat = 35.672768;
var d_lng = 139.658203;
function onNearSearch(text) {
  /*if( text == '') {
    alert(msg_search_noinputed());
    return false;
  }*/
  geocoder.getLocations(text, onLocationSearch);
}
function onLocationSearch(response){
   if (!response || response.Status.code != 200){
      alert("該当場所を検索できませんでした。");
      $("search_near_area").focus();
      return;
   } else {
    var place = response.Placemark[0];
    global_searchaction.soption.longitude = place.Point.coordinates[0];//100;
    global_searchaction.soption.latitude = place.Point.coordinates[1];//80;
    global_searchaction.soption.setMode('nearsearch');
    //reset_searchbox(global_searchaction.soption);
    jobSearch(global_searchaction.soption);
   }
}
function onInitialSearch(){
    if(!global_searchaction.soption.province){
        var location = google.loader.ClientLocation;
        if(location){
          global_searchaction.soption.longitude = location.longitude;
          global_searchaction.soption.latitude = location.latitude;
          global_searchaction.soption.neararea = location.address.country + location.address.city;
          global_searchaction.soption.sorttype = 4;//近い順
          global_searchaction.soption.setMode('nearsearch');
        } else {
          global_searchaction.soption.sorttype = 5;//最新順
          global_searchaction.soption.province = 13;
        }    
    }
    
    jobSearch(global_searchaction.soption);
    g_bInit = true;
}
function AddressLocationSearch(text, joblist) {
    jobs = joblist;
    geocoder.getLocations(text, onAddressLocationSearch);
}
function onAddressLocationSearch(response){
   if (!response || response.Status.code != 200){
       if(jobs){
         fjob = true;  
       } else {
          fjob = false; 
          if(!g_lat || !g_lng){
             g_lat = d_lat;
             g_lng = d_lng;
          } 
       }
   } else {
        var place = response.Placemark[0];
        g_lng = place.Point.coordinates[0];//100;
        g_lat = place.Point.coordinates[1];//80;
        if(jobs){
            fjob = true;  
        } else {
          fjob = false; 
          if(!g_lat || !g_lng){
             g_lat = lat;
             g_lng = lng;
          } 
        }
   }
   global_searchaction.soption.setMode('areasearch');
   onDrawMap(jobs, g_lat, g_lng, fjob);
}
function onDetailSearch() {
  
  // get pos infos from gmap 
  /*soption.longitude = 100;
  soption.latitude = 80;*/
  soption.setMode('nearsearch');
  reset_searchbox(soption); 
  // search start
  jobSearch(soption); 
}

// when it had been finished on job search
function onSearchcomplete(json) {
  //alert(json);
}
var newwindow;
// when it 's clicked on job link
function onJobClick(index) {
    if(index.match(/^http.+/)){
        newwindow = window.open(index+'?group_id=10061', null, "height=600, width=800,status=yes, toolbar=yes, menubar=yes, location=yes, scrollbars=yes, resizable=yes");    
        newwindow.focus();
        joburl = index.match(/^http:\/\/.+jobs\/(\d+)\.html$/);
        if(joburl[1]) searchservice.addTagClick(joburl[1], function(){});
        
    } else {
        if(JobMarks[index]){
            if(parseFloat(JobMarks[index]['jbp_lat']) && parseFloat(JobMarks[index]['jbp_lng']) ){
                var latlng = new GLatLng(
                parseFloat(JobMarks[index]['jbp_lat']),
                parseFloat(JobMarks[index]['jbp_lng'])
                );
                infoTabs = setJobTab(JobMarks[index], index);
                map.openInfoWindowTabsHtml(latlng, infoTabs);    
            } else {
                alert(msg_search_problem());
            }
            
        } else {
            alert(msg_search_problem());
        }   
    }
}

// when it ocures errors in comuniating with server.
function onNoDiagnotics() {
  alert(msg_search_problem());
}

function onBookmarkload(json) {
  //alert(json);
}
//only html validate
function loadswf(url)
{
   document.write('<embed src="'+ url + '" loop="true" quality="high" bgcolor="#ffffff" width="200" height="150" name="bt" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>');  
}
cookieManager = function(config) {
  
  this.setCookie = function(name, value, expires, path, domain, secure)  {
    //this.removeCookie(name, path, domain);
    
    // set time, it's in milliseconds
    var today = new Date();
    today.setTime( today.getTime() );
    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires ) {
      expires = expires * 1000 * 60 * 60 * 24;
    } else {
      expires = 1000 * 60 * 60 * 24; 
    }
    var expires_date = new Date( today.getTime() + (expires) );
                                              
    document.cookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
  },
  
  this.getCookie = function(name) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) &&
      ( name != document.cookie.substring( 0, name.length ) ) )
    {
      return null;
    }
    if ( start == -1 ) return null;
    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 ) end = document.cookie.length;
    return unescape( document.cookie.substring( len, end ) );
  },
  
  this.removeCookie = function(name, path, domain) {
    if ( this.getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
  }
}


function msg_bmlist_confirm() {
  return 'ブックマークを削除します。よろしいですか？';
}

function msg_bmlist_remove() {
  return 'ブックマークが削除されました。';
}  

function msg_bmlist_appendlimit() {
  return 'ブックマークの登録は１０件まで可能です。';
}  

function msg_bmlist_noselected() {
  return 'お仕事を選択してください。';
}

function msg_bmlist_complete() {
  return 'お仕事をブックマークしました。';
}

function msg_joblist_noselected() {
  return 'お仕事を選択してください。';
}

function msg_search_noinputed() {
  return '特定の場所を入力してください。';
}

function msg_search_problem() {
  return 'エラーが発生しました。もう一度操作してください。';
}

function msg_search_keyword_noinputed() {
  return 'キーワードを入力してください。';
}
function msg_sort(msg) {
  return '※初期表示の際、下記のリストは' + msg + 'にソートされています。';
}
seoManager = function(config) {
  this.initialize(config);
}

seoManager.prototype = {
  PRE_JOB         : "SEOJT",
  PRE_JOBROMA     : "JTR",
  PRE_PROVINCE    : "PN",
  PRE_TOWN        : "AN",     
  PRE_EMPLOYTYPE  : "EN",
  PRE_KEYWORD     : "KEY",
  PRE_NEARAREA    : "RN",
  
  title_format : null,
  subtitle_format : null,
  provincelist : null,
  townlist : null,
  employlist : null,

  initialize : function(config) {
    try {
      this.title_format = config['title_format']; 
      this.subtitle_format = config['subtitle_format'];
      this.jobtitle_format = config['jobtitle_format'];
      this.provincelist = config['provincelist'];
      this.townlist = config['townlist'];
      this.employlist = config['employlist'];
    } catch (e) {
    }
  },
  
  _assemText : function(rawText, data, breplace) {
    pattern = /\{([^\[\]\{\}]*)\[([A-Z]*)\]([^\[\]\{\}]*)\}/ig;  
    text = rawText.replace(pattern, function(str, p1, p2, p3) {
      if ( breplace) {
        replace = (data[eval("'" + p2 + "'")]) ? p1 + data[eval("'" + p2 + "'")] + p3 : '';
      } else {
        replace = (data[eval("'" + p2 + "'")]) ? p1 + data[eval("'" + p2 + "'")] + p3 : str; 
      }
      return replace;
   });
   return text;
  },
  
  getTitle : function(sopt) {
    var parsedParam = this.parseParam(sopt);
    var data = {};
      data[this.PRE_JOB] = sopt.job;
      data[this.PRE_JOBROMA] = sopt.jobroma;
      data[this.PRE_KEYWORD] = sopt.keyword;
      data[this.PRE_EMPLOYTYPE] = parsedParam.employtype;
    if ( sopt.sorttype == 4) { //近い順
       data[this.PRE_NEARAREA] = sopt.neararea;
    } else {　//都道府県順
       data[this.PRE_PROVINCE] = parsedParam.province;
       data[this.PRE_TOWN] = parsedParam.town; 
    }
    return this._assemText(this.title_format, data, true); 
  },
  
  getSubtitle : function(sopt) {
    var parsedParam = this.parseParam(sopt);
    var data = {};
      data[this.PRE_JOB] = sopt.job;
      data[this.PRE_JOBROMA] = sopt.jobroma;
      data[this.PRE_KEYWORD] = sopt.keyword;
      data[this.PRE_EMPLOYTYPE] = parsedParam.employtype;
    if ( sopt.sorttype == 4) { //近い順
       data[this.PRE_NEARAREA] = sopt.neararea;
    } else {　//都道府県順
       data[this.PRE_PROVINCE] = parsedParam.province;
       data[this.PRE_TOWN] = parsedParam.town; 
    }
    return this._assemText(this.subtitle_format, data, true); 
  },
  
  getJobtitle : function(sopt) {
    var parsedParam = this.parseParam(sopt);
    var data = {};
    data[this.PRE_PROVINCE] = parsedParam.province;
    data[this.PRE_TOWN] = parsedParam.town;
    data[this.PRE_EMPLOYTYPE] = parsedParam.employtype; 
    data[this.PRE_KEYWORD] = sopt.keyword;
    return this._assemText(this.jobtitle_format, data, true);
  },
  
  sopt2substitude : function(sopt) {
    var data = {};
    var sopt = this.parseParam(sopt);
    if (sopt.job) {
      data[this.PRE_JOB] = sopt.job;
    }
    if (sopt.jobroma) {
      data[this.PRE_JOBROMA] = sopt.jobroma;
    }
    if (sopt.province) {
      data[this.PRE_PROVINCE] = sopt.province;
    }    
    if (sopt.town) {
      data[this.PRE_TOWN] = sopt.town;
    }
    if (sopt.keyword) {
      data[this.PRE_KEYWORD] = sopt.keyword;
    }
    if (sopt.employtype) {
      data[this.PRE_EMPLOYTYPE] = sopt.employtype;
    }
    return data;
  },
  
  getTownlist : function() {
    return global_config_params['townlist'];
  },
  
  parseParam : function(sopt) {
    var parse_param = new searchOption();
    parse_param.job = sopt.job;
    parse_param.jobroma = sopt.jobroma;
    parse_param.keyword = sopt.keyword;
    try {
      if (sopt.province) {
        plist = this.provincelist;
        if(!sopt.town)
        {
          parse_param.town = plist[sopt.province] ? plist[sopt.province] : null;
        }
      }    
      if (sopt.town) {
        tlist = this.getTownlist();//this.townlist;
        parse_param.town = tlist[sopt.town] ? tlist[sopt.town] : null;
      }

      if (sopt.employtype) {
        elist = this.employlist;
        parse_param.employtype = elist[sopt.employtype] ? elist[sopt.employtype] : null;
      }      
    } catch(e) {
    }
    return parse_param;
  }
}

seoService = function() {
  this.setTitle = function(title) {
    $(document).attr('title', title); 
  }
  this.setSubtitle = function(title) {
    $('#subtitle').html(title);
  }
  this.doSeo = function(seo, sopt) {
    if(g_bInit)
    {
      this.setSubtitle(seo.getSubtitle(sopt));
      this.setTitle(seo.getTitle(sopt)); 
    }
  }

}

seoservice = new seoService();







$(window).load(function() { 
  $('.div_list_p_f img').click(function() {
    if (bmlist.getCheckedRowSize() == 0) {
      alert(msg_joblist_noselected())
      return false;
    }
    
    if( confirm(msg_bmlist_confirm())) {
      bmlist.removeChecked(); // delete removed
      bkservice.initCookie();
      bkservice.serialize(bmlist.getJobids());// push into cookie
      if ( bkservice.isEmpty() ) {
        bm_noresult();
      }
      $('#joblist_bm_chk_all').attr('checked', false);
      alert(msg_bmlist_remove());
    }
  });

  $('.div_list_b_f img').click(function() {
    if (joblist.getCheckedRowSize() == 0) {
      alert(msg_bmlist_noselected())
      return false;
    }
    
    if ( !bkservice.serialize(joblist.getCheckedJobids())) {
      alert(msg_bmlist_appendlimit());
      return false ;
    }
    bm_haveresult();
    bmlist.setUniqDataset(joblist.getCheckedRows());
    $("img[name='tablist_bm']").click();
    alert(msg_bmlist_complete());
  });
  var config = ['#joblist_bm', '#joblist_bm_chk_all', 'joblist_bm_rb_rowsize'];
  bmlist = new gridPanel(config);
  //if(searchservice == null) return;
  
  searchservice.getJoblist(bkservice.unserialize(), function(json) {
    var ds = [], dataset = [];
    for(var i=0;i<json.length;i++) {
      ds = [];
      ds.push(json[i]['job_id']);
      ds.push(json[i]['jbp_title']);
      ds.push(json[i]['employ_icon']);
      ds.push(json[i]['job_province']);
      ds.push(json[i]['jbp_pay_low']);
      ds.push(json[i]['jbp_cong_price']);
      ds.push(json[i]['job_url']);
      ds.push(json[i]['job_employtype']);
      ds.push(json[i]['all_pr']);
      dataset.push(ds);
    }
    onBookmarkload(json);
    bmlist.empty();
    if( dataset.length == 0) {
      $('#bmlist_status').append("<tr><td colspan=10 align=center><div class='nomessage'>ブックマークしたお仕事がありません。</div></td></tr>");
    } else {
      $('#bmlist_status').empty();
      bmlist.setDataset(dataset);    
    } 
  });
}); 


function bm_noresult() {
  bm_haveresult();
  $('#bmlist_status').append("<tr><td colspan=10 align=center><div class='nomessage'>ブックマークしたお仕事がありません。</div></td></tr>");
}

function bm_haveresult() {
  $('#bmlist_status').empty();
}


function joblist_noresult() {
  $('#joblist_status').empty();
  $('#joblist_status').append("<tr><td colspan=10 align=center><div class='nomessage'>検索結果がありません。</div></td></tr>");
}

$(window).load(function() {

  $("img[name='tablist'], img[name='tablist_bm']").click(function() {
    $("img[name='tablist'], img[name='tablist_bm']").each(function() {
      toggleInactive($(this));
    });
    $('.div_list_b, .div_list_p').hide();

    if ($(this).attr('name') == 'tablist') {
      toggleActive($("img[name='tablist']"));
      $('.div_list_b').show();
    } else {
      toggleActive($("img[name='tablist_bm']"));
      $('.div_list_p').show();
    }
  });
  if(!joblist){
    var config = ['#joblist', '#joblist_chk_all', 'joblist_rb_rowsize'];
    joblist = new gridPanel(config);    
  }

  $("input[name='joblist_rb_rowsize']").click(function(){
    //if ( $('#search_near').css('display') == 'block'){
    if ( global_searchaction.soption.searchmode == 'near'){
        global_searchaction.soption.longitude = g_lng?g_lng:'';
        global_searchaction.soption.latitude = g_lat?g_lat:'';
    } else {
        global_searchaction.soption.longitude = null;
        global_searchaction.soption.latitude = null;
    }
    global_searchaction.soption.maxsize = $(this).val();
    if(searchmode == global_searchaction.soption.searchmode){
        redrawMap = false;    
        waiting();  
        if(jobs.length < global_searchaction.soption.maxsize){
            global_searchaction.soption.underlimit = jobs.length;
            global_searchaction.soption.upperlimit = global_searchaction.soption.maxsize - 1 ;
            searchservice.jobSearch(global_searchaction.soption, function(json) {
                for(i =0; i < json.length; i++){
                    jobs.push(json[i]);
                }
                DrawingJob(global_searchaction.soption);
            });
          } else {
              jobs.splice(global_searchaction.soption.maxsize , jobs.length);
              DrawingJob(global_searchaction.soption);
              setTimeout(finish, 500);
          }    
    } else {
        searchmode = global_searchaction.soption.searchmode;
        jobSearch(global_searchaction.soption);
    }
        //jobSearch(global_searchaction.soption);
  });
  
});





var g_lat;
var g_lng;
var jobs;
var searchmode;
// set event handler for static html
$(window).load(function() {
  //select box
  
  //近い順
  $('#search_near_area').keyup(function(e) {
    if( e.keyCode == 13) {
      $('#search_near1').click();  
    }
  });
  $('#search_near1').click(function() {
    var text = $('#search_near_area').val();
    if(text == ''){
        alert(msg_search_noinputed());
        $('#search_near_area').focus();
        return ;  
    } 
    global_searchaction.soption.neararea = text;
    global_searchaction.soption.keyword = $('#keyword').val();
    global_searchaction.reset();
    onNearSearch(text);
  });
  $('#search_near2').click(function() {
    global_searchaction.soption.keyword = $('#keyword').val();
    global_searchaction.reset();
    onDetailSearch();
  });
  
  //都道府県
 
  $('#province').change(function() {
    //_town(global_searchaction.getOption());
    global_searchaction.soption.province = $('#province').val();
    global_searchaction.soption.town = null;
    global_searchaction.buildTown($('#province').val());
    global_searchaction.doAction();
  });

  $('#town').change(function() {
    global_searchaction.soption.town = $('#town').val();
    global_searchaction.doAction();
  });
  
  //採用タイプ
  $('#search_emp0').click(function() {
    global_searchaction.soption.employtype = 0;
    global_searchaction.doAction();
  });
  $('#search_emp1').click(function() {
      
    global_searchaction.soption.employtype = 1;
    global_searchaction.doAction();
  });
  $('#search_emp2').click(function() {
    global_searchaction.soption.employtype = 2;
    global_searchaction.doAction();
  });
  xor_select('#search_emp img');

  //勤務時間
  $('#search_timeband0').click(function() {
    global_searchaction.soption.timeband = 0;
    global_searchaction.doAction();
  });
  $('#search_timeband1').click(function() {
    global_searchaction.soption.timeband = 1;
    global_searchaction.doAction();
  });
  $('#search_timeband2').click(function() {
    global_searchaction.soption.timeband = 2;
    global_searchaction.doAction();
  });
  $('#search_timeband3').click(function() {
    global_searchaction.soption.timeband = 3;
    global_searchaction.doAction();
  });
  xor_select('#search_timeband img');

  //キーワード
  $('#keyword').keyup(function(e) {
    if( e.keyCode == 13) {
      $('#keyword_confirm').click();
    }
  });
  $('#keyword_confirm').click(function() {
    global_searchaction.soption.keyword = $('#keyword').val();
    global_searchaction.doAction();
  });
  
  //近い順から
  $('#search_near_link').click(function(){
    toggleActive($(this));
    toggleInactive($('#search_area_link'));
    $('.div_search_item12').setClass('div_search_item1');
    $('#search_area').hide();
    $('#search_near').show();
    global_searchaction.soption.sorttype = 4;
    global_searchaction.soption.searchmode = 'near';
  });
  
  //都道府県から
  $('#search_area_link').click(search_area_link_click);
  
  //検索条件
  $('#search_btab_link').click(function(){
    toggleActive($(this));
    toggleInactive($('#search_ptab_link'));

    $('.div_search_p_h').setClass('div_search_b_h');
    $('.div_search_p_b').setClass('div_search_b_b');
    $('.div_search_p_f').setClass('div_search_b_f');

    $('#search_partner').hide();
    $('#search_base').show();
  });
  
  //他の職種サイト
  $('#search_ptab_link').click(function(){
    toggleActive($(this));
    toggleInactive($('#search_btab_link'));

    $('.div_search_b_h').setClass('div_search_p_h');
    $('.div_search_b_b').setClass('div_search_p_b');
    $('.div_search_b_f').setClass('div_search_p_f');
    $('#search_partner').show();
    $('#search_base').hide();
  });  
  $('#search_partner a').click(function() {
    url = $(this).attr('href');
    window.open(url);
    return false;
  });

});

function search_area_link_click(){
  toggleActive($('#search_area_link'));
  toggleInactive($('#search_near_link'));
  $('.div_search_item1').setClass('div_search_item12');
  $('#search_area').show();
  $('#search_near').hide();
  global_searchaction.soption.sorttype = 5;
  global_searchaction.soption.searchmode = 'area';
  global_searchaction.render('areasearch');
}
//検索部
searchAction = function(config) {
  this.initialize(config);
}
searchAction.prototype = {
  soption : null,
  action : null, 
  
  initialize : function(config) {
    if (config['action']) {
      this.action = config['action'];
    }
    this.soption = new searchOption();
    if (config['soption']) {
      this.build(config['soption']);
    }
  },
  
  doAction : function() {
    if( this.action) {
        //if ( $('#search_near').css('display') == 'block'){
        if ( global_searchaction.soption.searchmode == 'near'){
            var text = $('#search_near_area').val();
            if(text == ''){
                alert(msg_search_noinputed());
                $('#search_near_area').focus();
                return false;  
            }else{
                if(global_searchaction.soption.neararea){
                    global_searchaction.soption.longitude = g_lng?g_lng:'';
                    global_searchaction.soption.latitude = g_lat?g_lat:'';
                    global_searchaction.soption.sorttype = 4;
                }
                if(global_searchaction.soption.province){
                    global_searchaction.soption.province = null;
                    global_searchaction.soption.town = null;
                }    
            }
        }
        if(global_searchaction.soption.underlimit) global_searchaction.soption.underlimit = null;
        if(global_searchaction.soption.upperlimit) global_searchaction.soption.upperlimit = null;
      this.action(this.soption);
      return true;
    }
    return false;
  },
  
  render : function(caller) { // adapt search page by search url
    if ( $('#search_area').css('display') != 'none' || caller == 'areasearch') {
      // 都道府県 
      if (!this.soption.province ) {
        $('#province').val('');
        this.appendEmpty($('#town'));
      } else if (this.soption.province != $('#province').val() ) {
        $('#province').val(this.soption.province);
        this.buildTown(this.soption.province, this.soption.town);
      } else if (!this.soption.town) {
        $('#town').val('');
      } else if (this.soption.town != $('#town').val()) {
        $('#town').val(this.soption.town);
      }
    }
    //キーワード
    $('#keyword').val(this.soption.keyword ? this.soption.keyword : '');
    // 採用タイプ
    $('#search_emp0, #search_emp1, #search_emp2').each(function() {
      toggleInactive($(this));
    });
    if (this.soption.employtype == 0 ) {
      toggleActive($('#search_emp0'));
    } else if(this.soption.employtype == 1) {
      toggleActive($('#search_emp1'));
    } else if (this.soption.employtype == 2){
      toggleActive($('#search_emp2'));
    } else {
      toggleActive($('#search_emp0'));
    }
    //近い順
    if (caller != 'loader') {
      $('#search_near_area').val(this.soption.neararea ? this.soption.neararea : '');
      if(this.soption.longitude) g_lng = this.soption.longitude;
      if(this.soption.latitude) g_lat = this.soption.latitude;
    } 
    
    if (caller == 'shortsearchbox') {
      $('#search_timeband0, #search_timeband1, #search_timeband2, #search_timeband3').each(function() {
        toggleInactive($(this));
      });
      toggleActive($('#search_timeband0'));
    }  
  },
  
  reset : function(mode) {
    if (mode == undefined) {  //近い順から検索
      this.soption.province = null;
      this.soption.town = null;
      this.soption.underlimit = null;
      this.soption.upperlimit = null;
      this.soption.sorttype = 4;
    }
  },
  resetprovince: function()
  {
    this.soption.province = null;
    this.soption.town = null;
  },
  
  build : function(url_info) {
    try {
      if( url_info['job']) this.soption.job = url_info['job']; 
      if( url_info['jobroma']) this.soption.jobroma = url_info['jobroma'];
      if( url_info['neararea']) this.soption.neararea = url_info['neararea']; 
      if( url_info['province']) this.soption.province = url_info['province'];
      if( url_info['town']) this.soption.town = url_info['town'];
      if( url_info['keyword']) this.soption.keyword = url_info['keyword'];
      if( url_info['employtype']) this.soption.employtype = url_info['employtype'];
      if( url_info['sorttype']) this.soption.sorttype = url_info['sorttype'];
    } catch(e) {
      return false;
    }
    return true;
  },
  
  buildbyobject : function(obj) {
      var job = this.soption.job;
      var job_roma = this.soption.jobroma;
      var pnames = obj.getpropertynames();
      for(var i=0; i<pnames.length; i++) {
        eval("if(obj." + pnames[i] + " != null) {this.soption." + pnames[i] + " = obj." + pnames[i] + "}");
      }
      this.soption.job = job;
      this.soption.jobroma = job_roma;
  },
  
  appendEmpty : function(obj) {
    obj.empty();
    obj.append("<option value=''>すべて</option>");
  },
  
  buildTown : function(province, town) {
    this.appendEmpty($('#town'));

    if (province == '' ) {
    } else {
      searchservice.searchTown(province, function(json) {
        if ( json) {
          for(key in json) {
              $selected = (town && town == key) ? 'selected = true' : '';
              $('#town').append("<option " + $selected + " value='" + key + "'>" + json[key] + "</option>"); 
          }
        }
      });
    }
  },
  
  getOption : function() {
    return this.soption;
  }
}

function jobSearch(arg, client) {
  waiting();  
  $('#div_link451039').empty();
  if(g_bInit)
  {
    ssearch.render(arg);
  }
  if ( client == 'shortsearchbox') {
    global_searchaction.buildbyobject(arg);
    seoservice.doSeo(seo, global_searchaction.getOption());
    global_searchaction.render('shortsearchbox'); 
  } else {
    global_searchaction.render();
    seoservice.doSeo(seo, arg);
  }
  searchservice.jobSearch(arg, function(json) {
      jobs = json;
      redrawMap = true;
      DrawingJob(arg);
  });
}
function DrawingJob(arg, mapflag){
  var ds = [], dataset = [];
  for(var i=0;i<jobs.length;i++) {
      ds = [];
      ds.push(jobs[i]['job_id']);
      ds.push(jobs[i]['jbp_title']);
      ds.push(jobs[i]['employ_icon']);
      ds.push(jobs[i]['job_province']);
      ds.push(jobs[i]['jbp_pay_low']);
      ds.push(jobs[i]['jbp_cong_price']);
      ds.push(jobs[i]['job_url']);
      ds.push(jobs[i]['job_employtype']);
      ds.push(jobs[i]['all_pr']);
      dataset.push(ds);
  }
  //マップに仕事を表示
    var fjob = true;
    if ( $('#search_near').css('display') == 'block'){
        if(arg.longitude && arg.latitude) fjob = false;    
    }
    onDrawMap(jobs, arg.latitude, arg.longitude, fjob);
  
  if(jobs.length){
        
       if(arg.sorttype == 4){
           $('#list_coment').html(msg_sort('「特定の場所」から近い順'));    
        } else if (arg.sorttype == 5){
            $('#list_coment').html(msg_sort('最新順'));    
        }else{
            $('#list_coment').html('');    
        }
        if(arg.maxsize == jobs.length){
            $('#search_count').html('<font color="red" ><b>&nbsp;&nbsp;'+jobs.length+'件以上</b></font>');
        } else {
            $('#search_count').html('<font color="blue" ><b>&nbsp;&nbsp;'+jobs.length+'件</b></font>');
        }
    } else {
        $('#list_coment').html('');    
            $('#search_count').html('<font color="blue"><b>&nbsp;&nbsp;0件</b></font>');
    }
    onSearchcomplete(jobs);
    onTableSortReset();
    $("img[name='tablist']").click();  // active joblisttab
    if(!joblist){
        var config = ['#joblist', '#joblist_chk_all', 'joblist_rb_rowsize'];
        joblist = new gridPanel(config);    
    }
    if(joblist) joblist.empty();
    if( dataset.length == 0) {
      joblist_noresult();
    } else {
      $('#joblist_status').empty();
      if(joblist) joblist.setDataset(dataset);
    }  
}




//google.load("maps", "2", {"language" : "ja"});
//google.load("search", "1");
var redrawMap = true;
var map;
var marker;
var time = 12;
var jobcurrent;
var JobMarks = new Array() ;
var JobTimerId;
var fjob;
var TimerId;

//googleマップオンロード    
function onDrawMap(json, ulat, ulng, fjobflag) {
    if (GBrowserIsCompatible()) {
        if(!map){
          map = new GMap2(document.getElementById("map"));
          map.addControl(new GLargeMapControl());
          map.addControl(new GMapTypeControl());
          map.addControl(new GOverviewMapControl(new GSize(100, 100)));
          map.addControl(new GScaleControl());
          //map.enableDoubleClickZoom();
         //map.enableScrollWheelZoom();  
        }
        if(map){
            map.clearOverlays();
            fjob = fjobflag;
            if(!fjob){
                //中心座標設定
                if(ulat && ulng){
                    latlng = new GLatLng(ulat, ulng);
                    setCrossMaker(latlng, redrawMap);           
                } else {
                    fjob = true;
                } 
                
            }
            //仕事表示
            if(json && json.length){
                createMarker(json, map);
            }    
        }
        
    }
}
function onDrawMark(){
    oneMarkDraw(jobcurrent);
    if (jobcurrent < JobMarks.length){
        TimerId  = setTimeout(onDrawMark, 50);
        jobcurrent++;
    }
}
function oneMarkDraw(i){
    if(JobMarks[i]){
        var latlng = new GLatLng(
            parseFloat(JobMarks[i]['jbp_lat']),
            parseFloat(JobMarks[i]['jbp_lng'])
        );
        if(i == 0 && fjob){
            if(redrawMap){
              //中心座標設定
              map.setCenter(latlng, time);            
            }
        }
        if(JobMarks[i]['centermark'] && (JobMarks[i]['centerindex'] == 0)){
            createhouseicon(JobMarks[i]['centermark']);
        }
        if(JobMarks[i]['centermark']){
            point_array = new Array();
            point_array[0] = JobMarks[i]['centermark'];
            point_array[1] = latlng;
            line = new GPolyline(point_array, "#0000ff", 4, 0.5);
            map.addOverlay(line);
        }
        var image = JobMarks[i]['employ_icon'] + ".png";
        size = new GSize(20, 32);
        anchor = new GPoint(10, 32);
        //ianchor = new GPoint(10, 5);
        ianchor = new GPoint(10, 32);
        simage = "icon_shadow.png";       
        ssize = new GSize(45, 39);
        sianchor= null;//new GPoint(10, 10);
        icon = createIcon(size, anchor, ianchor, image, ssize, sianchor, simage)
        //infoTabs = setJobTab(JobMarks[i], i);
        loadMarker(icon, latlng, JobMarks[i], i, JobMarks.length);    
    } 
}
//十子アイコン表示
function setCrossMaker(latlng, redrawMap){
    if(redrawMap){
        map.setCenter(latlng, time);    
    }
    image = "cross.gif";
    size = new GSize(28, 36);
    anchor = new GPoint(14, 28);
    ianchor = null;
    icon = createIcon(size, anchor, ianchor,  image)
    marker = new GMarker(latlng, icon);
    map.addOverlay(marker);
}           
//仕事がある地域を表示
function createMarker(json, map) {
    index = 0;
    var locators = new Array();
    for (i = 0; i < json.length; i++) {
        fFound = false;
        locators[index] = new Array();
        for (j = 0; j < index; j++){
            if (parseFloat(json[i]['jbp_lat']) == parseFloat(locators[j]['jbp_lat']) &&  parseFloat(json[i]['jbp_lng']) == parseFloat(locators[j]['jbp_lng'])) {
                locators[j]['ids'][locators[j]['count']] = i;
                locators[j]['count']++;
                fFound = true;
                break;
            }
        }
        
        if (!fFound){
            locators[index]['jbp_lat'] = parseFloat(json[i]['jbp_lat']);
            locators[index]['jbp_lng'] = parseFloat(json[i]['jbp_lng']);
            locators[index]['count'] = 1;
            locators[index]['ids'] = new Array();
            locators[index]['ids'][0] = i;
            index++;
        }
    }
    var r = 0.0002;
    var R = 0.00003;
    
    for (i = 0; i < locators.length; i++){
        var count = locators[i]['count'];
        if (count == 1){
        } else {
            var min_count = 3;
            var start_angle = -70*3.14/180;
            if (count < min_count) {
                var step_angle = 2*3.14/min_count;
            } else {
                var step_angle = 2*3.14/count;
            }
            if(locators[i]['jbp_lat'] && locators[i]['jbp_lng']){
                latlng = new GLatLng(locators[i]['jbp_lat'], locators[i]['jbp_lng']);
                for (j = 0; j < count; j++) {
                    index = locators[i]['ids'][j];
                    json[index]['centermark'] = latlng;
                    json[index]['centerindex'] = j;
                    json[index]['jbp_lat'] = locators[i]['jbp_lat']-R*Math.cos(step_angle*j+start_angle);
                    json[index]['jbp_lng'] = locators[i]['jbp_lng']-r*Math.sin(step_angle*j+start_angle);
                }
            }
        }
    }
    
    JobMarks = json;
    if(JobMarks.length){
        jobcurrent = 0;
        setTimeout(onDrawMark, 50);    
    }
}
function createhouseicon(latlng){
    image = "shadow.png";
    size = new GSize(10, 10);
    anchor = new GPoint(5, 5);
    ianchor = null;//new GPoint(0, 0);
    icon = createIcon(size, anchor, ianchor,  image)
    marker = new GMarker(latlng, icon);
    map.addOverlay(marker);
}
function createIcon(size, anchor, ianchor,  image, ssize, sianchor, simage){
    var icon = new GIcon();
    if(size) icon.iconSize = size;
    if(anchor) icon.iconAnchor = anchor;
    if(ianchor) icon.infoWindowAnchor = ianchor;
    if(image) icon.image = basedomain+"/images/" + image;
    if(simage) icon.shadow = basedomain+"/images/" + simage;
    if(ssize) icon.shadowSize = ssize;
    if(sianchor) icon.infoShadowAnchor= sianchor;
    return icon;
}
//googleタブ設定
function setJobTab(json, index){
    index = index - 0 + 1;
    var img_pay = (json['jbp_pay_type'] - 1)?"icon_month.gif":"icon_hour.gif";
    var img_kind = (json['jbp_employ_type_id']-1)?"icon_shain.gif":"icon_arbeit.gif";
    var Tab1 = "<div style='width:200;'><table cellpadding='0' cellspacing='5' border='0' width = '200px'><tr>";
        Tab1 += "<td align='left'><a href='#' onclick = 'onJobClick(\""+ json['job_url'] +"\")'>" + (index) + "." +json['jbp_title'] + "</a></td>";
        Tab1 += "</tr><tr><td align='left'>" + json['cpn_name'] + "</td></tr><tr><td align='left'>" + json['jbp_pr'] + "</td></tr>";
        Tab1 += "<tr><td align='left'><img src='" + basedomain + "/images/button/" + img_kind + "'>&nbsp;<img src='" + basedomain + "/images/button/";
        Tab1 += img_pay + "'>&nbsp;" + json['jbp_pay_low'] + "円 &nbsp; &nbsp; &nbsp; ";
        Tab1 += "<img src='" + basedomain + "/images/button/icon_celebrate.gif'>&nbsp;"
        Tab1 += json['jbp_cong_price'] + "円</td></tr></table></div>";
    Tab2 = "<div style='width:200;'><table  cellpadding='0' cellspacing='0' border='0' width = '200px'><tr>";
    if(json['jbp_img_main_comment']){
        Tab2 += "<td align='left'><a href='#' onclick = 'onJobClick(\""+ json['job_url'] +"\")'>"+ (index) + "." + json['jbp_title'] + "</a><br /><br /><a href='#' onclick = 'onJobClick(\""+ json['job_url'] +"\")'>";
        Tab2 += "<img style='border : 0px; padding-right:10px; padding-bottom:10px;' src='" + json['image_url'] + "' align = 'left' ></a>"+json['jbp_img_main_comment'] + "";    
    } else {
        Tab2 += "<td align='center'><a href='#' onclick = 'onJobClick(\""+ json['job_url'] +"\")'>"+ (index) + "." + json['jbp_title'] + "</a><br /><br /><a href='#' onclick = 'onJobClick(\""+ json['job_url'] +"\")'>";
        Tab2 += "<img style='border : 1px solid #979797;' src='" + json['image_url'] + "' align = 'center' ></a>";
    }
    Tab2 += "</td></tr></table></div>";
    
    var infoTabs = [
        new GInfoWindowTab("求人情報", Tab1),
        new GInfoWindowTab("写真", Tab2)
    ];
    return infoTabs;
}
//位置にアイコンとタブをロード
function loadMarker(icon, latlng, jobinfo, no, allcount) {
    var marker;  
    marker = new GMarker(latlng, icon);
    GEvent.addListener(marker, "click", function() {
      var infoTabs;
      oDiv = $('#div_list_b_b');
      selectjoblisttr(no);
      if(oDiv){
          oDiv.attr('scrollTop', Math.floor(oDiv.attr('scrollHeight') * (no/allcount))) ;
      }
      infoTabs = setJobTab(jobinfo, no);
      marker.openInfoWindowTabsHtml(infoTabs);
    });
    map.addOverlay(marker);
    return marker;
}
var  slide_status = 'area';
$(window).load(function() {
  
  $('#slide_open').click(function() {
    $('#tip').fadeIn();
    if(slide_status == 'area') {
      $("#slide_area, #slide_tab").slideDown("slow");
    } else {
      $("#slide_mkeyword, #slide_tab").slideDown("slow");
    }
    $('#slide_open').hide();
    $('#slide_close').show();
  });
  $('#slide_close').click(function() {
    $('#tip').fadeOut();
    $(".slide .tab, .slide .contents").slideUp("slow");
    $('#slide_open').show();
    $('#slide_close').hide();
  });
  
  // ununsed
  function toggleArea(areaname) {
    $("#slide_area div[name='slide_area_link']").hide();
    $('#slide_area_' + areaname).show();
  }

  $('#slide_area_tab').click(function() {
    $('#slide_area').show();
    $('#slide_mkeyword').hide();
    
    $('#tip').html(tip['area']);
    slide_status = 'area';
  });


  $('#slide_mkeyword_tab').click(function() {
    $('#slide_area').hide();
    $('#slide_mkeyword').show();
    
    $('#tip').html(tip['keyword']);
    slide_status = 'mkeyword';
  });
/*
  $('#slide_employ0').click(function() {
    onEmploy(0);
  });
  $('#slide_employ1').click(function() {
    onEmploy(1);  
  });
  $('#slide_employ2').click(function() {
    onEmploy(2);  
  });
*/  
  xor_select('#slide_area_tab, #slide_mkeyword_tab');
  xor_select('#slide_employ0, #slide_employ1, #slide_employ2');
});
/*
function onEmploy(etype) {
  ssearch.employtype = etype;
  jobSearch(ssearch.getoption(), 'shortsearchbox');
}
*/
function onShortlinkClick(url) {
  //簡単モードでクリックする時に検索ブロックをエリアサーチ方式に設定する。
  ssearch.sorttype = 5;
  searchmode = 'area';
  ssearch.searchmode = 'area';
  ssearch.maxsize = global_searchaction.soption.maxsize;
  search_area_link_click();
  ssearch.obj2populate(urlToolkit.parseUrlInfo(url));
  jobSearch(ssearch.getoption(), 'shortsearchbox');
}
searchOption = function(){
  this.version = '1.0';
  this.initialize();
}
searchOption.prototype = {
  job : null,
  jobroma : null,
  province: null,
  town: null,
  keyword: null,
  longitude: null,
  latitude: null,
  employtype: 0,
  timeband: 0,
  sorttype: 4,
  soptions: null,
  maxsize: 30,
  neararea: null,
  underlimit: null,
  upperlimit: null,
  searchmode: 'near',
  initialize: function() {
  },
  
  getpropertynames: function() {
    return ['province', 'town', 'keyword', 'longitude', 'latitude', 'neararea', 
    'employtype', 'timeband', 'sorttype', 'maxsize', 'underlimit', 'upperlimit', 'searchmode'];
  },
  
  initParams: function(mode) {
    if( mode == 'nearsearch') {
      this.province = null;
      this.town = null;
    } else if( mode == 'areasearch') {
      this.longitude = null;
      this.latitude = null;
      this.province = $('#province').val();
      this.town = $('#town').val();
    } else if( mode == 'shortsearch') {
      var _emptype = this.employtype;
      this.initParams();
      this.employtype = _emptype;
    } else {
      var pnames = this.getpropertynames();
      for(var i=0; i<pnames.length; i++) {
        eval("if(this." + pnames[i] + " != null) {this." + pnames[i] + " = null}");
      }
    }
  },
  
  serialize: function() {
    this.soptions = null;
    var pnames = this.getpropertynames();
    for(var i=0; i<pnames.length; i++) {
      var value = null;
      eval("if(this." + pnames[i] + " != null) {value = this." + pnames[i] + "}");
      if ( value != null) {
        if( !this.soptions ) {
          this.soptions = pnames[i] + '=' + value;
        } else {
          this.soptions += '&' + pnames[i] + '=' + value;
        }
      }
    }
    return this.soptions;
  },
  
  setMode : function(mode) {
    if ( mode == 'areasearch') {
      this.sorttype = null;
    } else if ( mode == 'nearsearch') {
      this.sorttype = 4;
      this.province = null;
      this.town = null;
    }
  },

  array2populate: function(arg) {
    if( arg['province']) this.province = arg['province'];
    if( arg['town']) this.town = arg['town'];
    if( arg['keyword']) this.keyword = arg['keyword'];
    if( arg['employtype']) this.employtype = arg['employtype'];
  },
  
  clone : function(src) {
    var pnames = src.getpropertynames();
    for(var i=0; i<pnames.length; i++) {
      eval("if(src." + pnames[i] + " != null) {this." + pnames[i] + " = src." + pnames[i] + "}");
    }  
  }               
}

searchService = function(config) {
  this.initialize(config);
  this.timeout = 30000;
  this.async = true;
}
searchService.prototype = {
  isfinished : null,
  soption : null,
  
  initialize: function(config) {
    
    this.searchProvinceUrl = config['provincesearch_url'] + ".html";
    this.searchTownUrl = config['townsearch_url'] + ".html";
    this.searchJobUrl = config['jobsearch_url'] + ".html";
    this.getJoblistUrl = config['getjoblist_url'] + ".html";
    this.searchMkeywordUrl = config['mkeywordsearch_url'] + ".html";
    this.getTagClickUrl = config['addtagclick_url'] + ".html";
    this.isfinished = false;
    //this.soption = new searchOption();
  },
  
  searchProvince: function(areaid, callback) {
    $.ajax({
        async : this.async,
        url: this.searchProvinceUrl,
        type: 'GET',
        dataType: 'json',
        data: "area=" + areaid ,
        success: function(json) {
          callback(json);
        },
        error : function() {
          onNoDiagnotics();
        }
    });
  },

  searchTown: function(provinceid, callback) {
    $.ajax({
        async : this.async,
        url: this.searchTownUrl,
        type: 'GET',
        dataType: 'json',
        data: "province=" + provinceid ,
        success: function(json) {
          global_config_params['townlist'] = json;
          callback(json);
        },
        error : function() {
          onNoDiagnotics();
        }
    });
  },

  searchMkeyword: function(callback) {
    $.ajax({
        async : this.async,
        url: this.searchMkeywordUrl,
        type: 'GET',
        dataType: 'json',
        //data: "province=" + provinceid ,
        success: function(json) {
          callback(json);
        },
        error : function() {
          onNoDiagnotics();
        }
    });
  },

  jobSearch: function(soption, callback) {
    $this = this;
    var params = new searchOption();
    params.clone(soption);
    if(params.keyword)
    {
      params.keyword = encodeURI(params.keyword);
    }
    //if (!$this.isfinished) { return null; }
    $.ajax({
      async : this.async,
      url: this.searchJobUrl,
      type: 'GET',
      dataType: 'json',
      data: params.serialize(),
      timeout: this.timeout,
      beforesend : function() {
        $this.isfinished = false;
        waiting();
      },
      error: function(){
        finish();
        //alert('Error');
        onNoDiagnotics();
      },
      success: function(json){
        callback(json);
      },
      complete: function() {
        $this.isfinished = true;
        finish();
        //alert('検索が完了しました。');
      }
    });
  },

  getJoblist: function(jobids, callback) {
    jobstr = '';
    for(var i=0; i<jobids.length; i++) {
      if( i==0) { jobstr = jobids[i]; }
      else {
        jobstr += "," + jobids[i];
      }
    }
    $.ajax({
      async : this.async,
      url: this.getJoblistUrl,
      type: 'GET',
      dataType: 'json',
      data: 'jobids='+jobstr,
      timeout: this.timeout,
      error: function(){
        onNoDiagnotics();
      },
      success: function(json){
        callback(json);
      },
      complete: function() {
      }
    });
  },
  
  addTagClick: function(jobid, callback){
    $.ajax({
      async : this.async,
      url: this.getTagClickUrl,
      type: 'GET',
      dataType: 'json',
      data: 'jobid='+jobid,
      timeout: this.timeout,
      error: function(){
        onNoDiagnotics();
      },
      success: function(){
              
      },
      complete: function() {
      }
    });
  }
  
}
bookmarkService = function(config) {
  this.cookieNamespace = '4510map';
  this.initialize(config);
}
bookmarkService.prototype = {
  cookieNamespace: null,
  cookiemanager: null,
  
  initialize: function(config) {
    this.cookiemanager = new cookieManager(); 
    if( config) {
      this.maxsize = config;
    } else {
      this.maxsize = 10;
    }
  },
  
  filter: function(dataset) {
    var newds = this.unserialize();
    for(var i=0;i<dataset.length;i++) {
      if( !this.isExisted(dataset[i], newds)) {
        newds.push(dataset[i]);
      }
    }
    var cn = 0;
    for(var i=0;i<newds.length;i++ ) {
      if( newds[i] != '') {
        cn ++;
      }
    }
    if(cn > this.maxsize) {
        return null;
    }
    return newds;
  },
  
  isExisted: function(value, ary) {
    for(var i=0;i<ary.length;i++) {
      if( value == ary[i]) return true;
    }
    return false;
  },
  
  isEmpty: function() {
    var data = this.unserialize();
    var cn = 0;
    for(var i=0;i<data.length;i++ ) {
      if( data[i] != '') {
        cn ++;
      }
    }
    if (cn == 0 ) {
      return true;
    }
    return false;
  },
  
  serialize: function(dataset) {
    dataset = this.filter(dataset);
    if(dataset == null) return false;
    
    var ck = '';
    for (var i=0; i<dataset.length; i++) {
      if(i == 0 ) {
        ck = dataset[i] ;        
      } else {
        ck += ',' + dataset[i] ;        
      }
    }
    if( ck != '') {this.cookiemanager.setCookie(this.cookieNamespace, ck);}
    return true;
  },
  
  initCookie: function() {
    this.cookiemanager.setCookie(this.cookieNamespace, '');
  },
  
  unserialize: function() {
    var ck = this.cookiemanager.getCookie(this.cookieNamespace);
    if( ck != null) {
      ck = ck.split(',');
      return ck
    }
    return [];
  }
  
}
shortSearch = function(config) {
  this.initialize(config);
}

shortSearch.prototype = {
  area: null,
  province: null,
  town: null,
  keyword: null,
  employtype: null,
  sorttype: null,
  maxsize: null,
  searchmode: null,
  actionmode : 'ajax',
  
  initialize: function(config) {
    this.defineConst();
    this.areas = config['areas'];
    this.mkeywords = config['mkeywords'];
    this.onShortlinkClick = onShortlinkClick;
  },
  
  defineConst: function() {
    this.htmlSpace = '&nbsp;';
    this.header = 'slide_area_link_header';
    this.content = 'slide_area_link_body';
    this.content1 = 'slide_area_link_body1';
    this.areabody = 'slide_area_link_header';
    this.arealinkpre = 'area_li_';
    this.areaAnchorPre = 'area_a_';

    this.layout = 'slide_area_link';
    this.employlink = 'td_employ_link'; 
    this.provincebody   = 'slide_province_body';
    this.provincelinkpre  = 'province_a_';
    this.provinceAnchorPre  = 'province_a_';
    this.townbody = 'slide_town_body';
    this.townlinkpre = 'town_li_';       
    this.townAnchorPre = 'town_a_';       
    this.mkeyword = 'slide_mkeyword';
  },
  
  array2populate: function(arg) {
    if( arg['province']) this.province = arg['province'];
    if( arg['town']) this.town = arg['town'];
    if( arg['keyword']) this.keyword = arg['keyword'];
    if( arg['employtype']) this.employtype = arg['employtype'];
  },

  obj2populate: function(soption) {
    if(soption.province)
    {
      this.area = this.getareabyprovince(soption.province);
    }
    this.province = soption.province;
    this.town = soption.town;
    this.keyword = soption.keyword;
    this.employtype = soption.employtype;
  },
  getareabyprovince: function(province)
  {
    var akey, pkey;
    if(!province) return 0;
    for( akey in this.areas)
    {
      for (pkey in this.areas[akey]['province'])
      {
        if( this.areas[akey]['province'][pkey]['id'] == province)
        {
          return this.areas[akey]['areaid'];
        }
      }
    }
    return 0;
  },  
  getoption : function() {
    var toption = new searchOption();
    toption.initParams();
    toption.province = this.province;
    toption.town = this.town;
    toption.employtype = this.employtype;
    toption.keyword = this.keyword;
    toption.sorttype = this.sorttype;
    toption.maxsize = this.maxsize;
    toption.searchmode = this.searchmode;
    return toption;
  },

  setoption : function(arg) {
    arg = arg.split('&');
    for (var i=0; i<arg.length; i++) {
      tmp = arg[i].split('=');
      eval("this." + tmp[0] + "= '" + tmp[1] + "'");
    }
  },
  
  initParams: function(mode) {
    this.province = null;
    this.town = null;
    this.keyword = null;
    this.employtype = null;
  },
  
  render: function(soption, $this) {
    if (!$this) $this = this;
    if ( soption) {
      $this.obj2populate(soption);
    }
    if($this.area)
    {
      $this.areahighlight($this.area);
    }
    else
    {
      $this.areahighlight(false);
      provincebody = $('#'+$this.provincebody);
      if(provincebody)
      {
        provincebody.hide();
      }
    }
    $this.buildMkeyword($this, $this.keyword);

/*    
    $('#slide_employ0, #slide_employ1, #slide_employ2').each(function() {
      toggleInactive($(this));
    });
    
    if ( $this.employtype == 0 ) {
      toggleActive($('#slide_employ0')); 
    } else if ($this.employtype == 1) {
      toggleActive($('#slide_employ1')); 
    } else if ($this.employtype == 2){
      toggleActive($('#slide_employ2')); 
    } else {
      toggleActive($('#slide_employ0'));  
    }
*/
    $this.buildEmploy($this);
  },
  
  /*
    set event handler to static html link when page loading.
  */
  build: function($this) {
    if (!$this) $this = this;
    
    if ($this.actionmode == 'ajax') {
      $('#' + this.areabody + ' a').click(function() {
        var areaid = getdataid($(this).attr('id'));
        if($this.area != areaid || $this.province )
        {
          var townbody = $('#' + $this.townbody);
          if(townbody.length != 0)
          {
            townbody.hide();
          } 
          $this.area = areaid;
          $this.areahighlight($this.area);
          return false;
        }
        return false;
      });
      $('#' + this.provincebody + ' a').click(function() {
        var provinceid = getdataid($(this).attr('id'));
        if($this.province != provinceid || $this.town)
        {
          $this.province = provinceid;
          global_searchaction.resetprovince();
          $this.onShortlinkClick($(this).attr('href'));
        }
        return false;  
      });
      $('#' + this.townbody + ' a').click(function() {
        var townid = getdataid($(this).attr('id'));
        if($this.town != townid)
        {
          $this.town = townid;
          $this.onShortlinkClick($(this).attr('href'));
        }
        return false;  
      });
      $('#' + this.mkeyword + ' a').click(function() {
        $this.onShortlinkClick($(this).attr('href'));
        return false;  
      });
      $('#' + this.employlink + ' a').click(function() {
        $this.onShortlinkClick($(this).attr('href'));
        return false;
      });
    }
  },
  
  buildArea: function($this) {
    return;
  },
  
  buildProvince: function($this, areaid) {
    if(!$this) $this = this;
    var provincebody = $('#' + $this.provincebody);
    var elem = '';
    var akey;
    
    if(provincebody.length == 0) 
    {
      htmlprovincebody = '<div id="slide_province_body" class="slide_area_sub"></div>';
      $('#' + $this.layout).append(htmlprovincebody);
      provincebody = $('#' + $this.provincebody);
    }
    if(provincebody.length == 0) return;
    
    for(akey in this.areas )
    {
      if(this.areas[akey]['areaid'] == areaid)
        break;
    }
    bFirst = true;
    bSelect = false;
    for ( var key in this.areas[akey]['province']) {
      var sopt = $this.getoption();
      sopt.town = null;
      sopt.province = this.areas[akey]['province'][key]['id'];
      var href = urlToolkit.publishUrl(sopt);
      var html = this.areas[akey]['province'][key]['name'];
      if(bFirst)
        bFirst = false;
      else
        elem+=' | ';

      if(this.province == sopt.province)
      {
        elem += $this.createProvinceAnchor(href, html, key, 'c');
        bSelect = true;        
      }
      else
        elem += $this.createProvinceAnchor(href, html, key, '');
    }
    provincebody.empty().append(elem);
    provincebody.show();
    if($this.province && bSelect ) 
    {
      $this.buildTown($this, $this.province);
    }
    else
    {
      townbody = $('#'+$this.townbody);
      if(townbody)
      {
        townbody.hide();
      }
    }
        
    $('#' + $this.provincebody + ' a').click(function() {
      var provinceid = getdataid($(this).attr('id'));
      if($this.province != provinceid || $this.town)
      {
        $this.province = provinceid;
        global_searchaction.resetprovince();
        $this.onShortlinkClick($(this).attr('href'));
      }
      return false;  
    });
  },
  
  buildTown: function($this, provinceid) {
    if(!$this) $this = this;

    searchservice.searchTown(provinceid, function(json) {
      var elem = '<ul>';
      var townbody = $('#' + $this.townbody);
      if(townbody.length == 0) 
      {
        htmltownbody = '<div id="slide_town_body" class="slide_area_city"></div>';
        $('#' + $this.layout).append(htmltownbody);
        townbody = $('#' + $this.townbody);
      }
      if(townbody.length == 0) return;

      for ( var key in json) {
        var sopt = $this.getoption();
        sopt.town = key;
        var href = urlToolkit.publishUrl(sopt);
        var html = json[key];
        if($this.town == key)
        {
          elem += $this.createRealAnchor(href, html, key, 'c');
        }
        else
        {
          elem += $this.createRealAnchor(href, html, key, '');
        }
      }
      elem += '</ul><div class="both"></div>';
      $('#' + $this.townbody).empty().append(elem);
      townbody.show();
      $('#' + $this.townbody + ' a').click(function() {
        var townid = getdataid($(this).attr('id'));
        if($this.town != townid)
        {
          $this.town = townid;
          $this.onShortlinkClick($(this).attr('href'));
        }
        return false;  
      });
      
    });  
  },
  
  buildMkeyword : function($this, keyword) {
    var elem = '<ul>';
    for ( var key in this.mkeywords) {
      var sopt = this.getoption();
      sopt.keyword = this.mkeywords[key];
      var href = urlToolkit.publishUrl(sopt);
      elem += this.createmkeywordAnchor(href, sopt.keyword); 
    }
    elem += '</ul><div class="both"></div>';

    $('#' + this.mkeyword).empty().append(elem);
    $('#' + this.mkeyword + ' a').click(function() {
      $this.onShortlinkClick($(this).attr('href'));
      return false;
    });
  },
  buildEmploy : function($this) {
    if(!$this) $this = this;

    var elem = '';
    var sopt = $this.getoption();
    var href;

    sopt.employtype = null;
    href = urlToolkit.publishUrl(sopt);
    if( $this.employtype != 1 && $this.employtype != 2 )
      html = '<img width="55" height="18" alt="すべての求人" border="0" src="' + basedomain + '/images/btn_all_1.gif" />';
    else
      html = '<img width="55" height="18" alt="すべての求人" border="0" src="' + basedomain + '/images/btn_all_0.gif" />';
    elem += $this.createEmployAnchor(href, html)+$this.htmlSpace; 

    sopt.employtype = 1;
    href = urlToolkit.publishUrl(sopt);
    if( $this.employtype == 1 )
      html = '<img width="85" height="18" alt="アルバイトの求人" border="0" src="' + basedomain + '/images/btn_arbeit_1.gif" />';
    else
      html = '<img width="85" height="18" alt="アルバイトの求人" border="0" src="' + basedomain + '/images/btn_arbeit_0.gif" />';
    elem += $this.createEmployAnchor(href, html)+$this.htmlSpace; 

    sopt.employtype = 2;
    href = urlToolkit.publishUrl(sopt);
    if( $this.employtype == 2 )
      html = '<img width="55" height="18" alt="社員の求人" border="0" src="' + basedomain + '/images/btn_shain_1.gif" />';
    else
      html = '<img width="55" height="18" alt="社員の求人" border="0" src="' + basedomain + '/images/btn_shain_0.gif" />';
    elem += $this.createEmployAnchor(href, html); 

    $('#'+$this.employlink).empty().append(elem);
    $('#' + this.employlink + ' a').click(function() {
      $this.onShortlinkClick($(this).attr('href'));
      return false;
    });
  },
  areahighlight : function(area) {
    var all = $('#' + this.areabody + ' li');
    all.removeClass();
    all.each(function(){
      var areaid = getdataid($(this).attr('id'));
      $(this).addClass("area"+areaid);
    });
    if(area)
    {
      var curObj = $('#' + this.arealinkpre + area);
      curObj.removeClass();
      curObj.addClass('area'+area+'s');
    }
    this.buildProvince(this, area);
  },

  createAnchor: function(html, value, cls) {
    if ( !cls) cls = 'anchor';
    return "<span class='" + cls +"' datafld='" + value + "'>" + html + "</span>";
  },
  
  createContainer: function(id, html) {
    return "<div id='" + id + "'>"+ html +"</div>";
  },
  createmkeywordAnchor : function(href, html, value, cls) {
     return "<li class='" + cls + "'><a href='" + href + "'>" + html + "</a></li>";
  },
  createRealAnchor : function(href, html, value, cls) {
     return "<li class='" + cls + "' id='" + this.townlinkpre + value +"'><a href='" + href + "' name='" + this.townAnchorPre + value + "' id='" + this.townAnchorPre + value + "'>" + html + "</a></li>";
  },
  createProvinceAnchor : function(href, html, value, cls) {
     return "<a href='" + href + "' class='" + cls + "' name='" + this.provinceAnchorPre + value  + "' id='" + this.provinceAnchorPre + value +"'>" + html + "</a>";
  },
  createEmployAnchor: function(href, html) {
    return "<a href='" + href + "'>" + html + "</a>";
  }
}
gridPanel = function(config) {
  this.initialize(config);
    
}
gridPanel.prototype = {
  dataset: [],
  rowsize: 50,
  config: null,
  listener: null,
  
  initialize: function(config) {
    this.config = config;
    this.listener = function(arg) {
      onJobClick(arg);
    }
    
    this.initGridPanel();
  },
  
  initGridPanel: function() {
    var config = this.config;
    var $this = this;
    $(config[0] + " input[type='checkbox']").attr('checked', false);
    $(config[1]).attr('checked', false);
    /* put handler to checkbox in header for check all method */
    $(config[1]).unbind();
    $(config[1]).click(function() {
      $(config[0] + " input[type='checkbox']").attr('checked', $(config[1]).attr('checked'));
    });
    
    /* put handler to radio box in header for setting rowsize */
    /*
    $("input[name="+ config[2] +"]").unbind();
    $("input[name="+ config[2] +"]").click(function() {
      this.rowsize = $(this).attr('value');
    });
    */
    /* reset tablesorter */
    /*
    
    */ 
    
   $.tablesorter.addParser({
      id: "money",
      is: function(s) {
        return false;
      },
      format: function(s, table, cell) {
        var monthpay;
        s = s.replace(',', '');
        ra = s.match(/>[^\d]*([\d]*)[^\d]*$/);
        if(!ra) return '';
        str = ra[1];
        monthpay = (str > 10000)? true:false;
        if (monthpay) 
          str = str / 170;
        return str;
      },
      type: "numeric"
    });
    $(config[0]).tablesorter({widgets:['zebra'], headers : {0:{sorter : false}, 4:{sorter : 'money'}, 5:{sorter: 'currency'}}});
    
    /* ignore natural a tag for job link */
    
    var func = this.listener;
    
    $(config[0]+' tbody tr').click(
      function(){
        ondiv = document.getElementById('div_list_p');//$('div_list_p');  
        if(ondiv.style.display == 'block'){
          //func($(this).attr('datafurl'));                       
        } else {
          $($this.config[0] + ' tbody tr').removeClass('joblist_tr_select');
          $(this).addClass('joblist_tr_select');
          func(getdataid($(this).attr('id')));    
        }
      }
    );
    $(config[0]+' tbody span').click(
      function(){
        ondiv = document.getElementById('div_list_p');//$('div_list_p');  
        if(ondiv.style.display == 'block'){
          func($(this).attr('datafurl'));                       
        }
      }
    );
    /* ignore span tag for job link */
    /*
    $(config[0] + " span.anchor").unbind();
    $(config[0] + ' span.anchor').click(function(){
      ondiv = document.getElementById('div_list_p');//$('div_list_p');  
      if(ondiv.style.display == 'block'){
        func($(this).attr('datafurl'));                       
      } else {
        func($(this).attr('datafindex'));    
      }
      return false;
    });
    */
  },
    
  getCheckedRows: function() {
    config = this.config;
    var records = [], active, cnt;
    var record = [];
    $(config[0] + ' tbody tr').each(function() {
      cnt = 0; 
      record = [];
      $(this).children().each(function() {
        if( cnt == 0) {
          active = $(this).children().attr('checked');
        }
        else if(active && cnt == 1) {
          record.push(getdataid($(this).children().attr('id')));
          record.push($(this).children().html());
        }
        else if(active){
          record.push($(this).html());
        }
        cnt ++;
      });
      if( active) { records.push(record); }
    });
    return records;
  },
  
  getCheckedRowSize : function() {
    var chr = this.getCheckedRows();
    return chr.length;
  },
  
  getCheckedJobids: function() {
    var jobids = [];
    var cds = this.getCheckedRows();
    
    for(var i=0; i<cds.length; i++) {
      jobids.push(cds[i][0]);
    }
    return jobids;
  },
  
  getJobids: function() {
    config = this.config;
    
    var record = [], cnt;

    $(config[0] + ' tbody tr').each(function() {
      cnt = 0; 
      $(this).children().each(function() {
        if(cnt == 1) {
          record.push(getdataid($(this).children().attr('id')));
        }
        cnt ++;
      });
    });
    return record;
  },
  
  getRowSize: function() {
    var config = this.config;
    var size = 0;
    $(config[0] + ' tbody tr').each(function() {
      size ++;
    });
    return size;
  },
  
  
  
  setDataset: function(ds) { 
    this.render(1, ds);
    this.initGridPanel();
  },
  
  setUniqDataset: function(ds) {
    var newds=[];
    var jobids = this.getJobids(); 
    if( jobids.length == 0 ) {
      newds = ds;
    } else {
      for(var i=0;i<ds.length;i++) {
          /*if(ds[i][1]){
            str = ds[i][1];
            str = str.substring(str.indexOf('.') + 1, str.length);      
            ds[i][1] = str;
          }*/
        if( !this.isExisted(ds[i][0], jobids)) {
          newds.push(ds[i]);
        }
      }
    }
    searchservice.getJoblist(bkservice.unserialize(), function(json) {
    var ds = [], dataset = [];
    for(var i=0;i<json.length;i++) {
      ds = [];
      ds.push(json[i]['job_id']);
      ds.push(json[i]['jbp_title']);
      ds.push(json[i]['employ_icon']);
      ds.push(json[i]['job_province']);
      ds.push(json[i]['jbp_pay_low']);
      ds.push(json[i]['jbp_cong_price']);
      ds.push(json[i]['job_url']);
      ds.push(json[i]['job_employtype']);
      ds.push(json[i]['all_pr']);
      dataset.push(ds);
    }
    onBookmarkload(json);
    bmlist.empty();
    if( dataset.length == 0) {
      $('#bmlist_status').append("<tr><td colspan=10 align=center><div class='nomessage'>ブックマークしたお仕事がありません。</div></td></tr>");
    } else {
      $('#bmlist_status').empty();
      bmlist.setDataset(dataset);    
    } 
    });
    //this.render(2, newds);
    //this.initGridPanel();
    
  },
  
  isExisted: function(value, ary) {
    for(var i=0;i<ary.length;i++) {
      if( value == ary[i]) return true;
    }
    return false;
  },
  
  emptyRender: function(msg) {
    $(this.config[0]).append("<tr><td colspan=10 align=center><span class='nomessage'>" + msg +"</span></td></tr>");
  },
  
  render: function(mode, ds) {
    first_rowsize = this.getRowSize();
    size = 6;
    
    for(var i=0;i<ds.length;i++) {
      var record = this.createElement(this.createCheckbox(i, ''), '');
      for(var j=1;j<size;j++) {
        if( j == 1 ) {
          var  str1 = (i+1);
          record += this.createElement(this.createAnchor(str1+'.'+ds[i][j], 'anchor', ds[i][0], ds[i][6], i), '', 'left', ds[i][8]); 
        } else if( j ==　4 ) {
          if ( mode == 1 ) {
            record += this.createElement(this.formatMoney(ds[i][j], ds[i][7]), '', 'right');      
          } else {
            record += this.createElement(this.formatMoney(ds[i][j]), '', 'right');      
          }
          
        } else if( j == 5) {
          record += this.createElement(this.formatMoney(ds[i][j]), '', 'center');  
        } else if( j == 3) {
          record += this.createElement(this.formatMoney(ds[i][j]), 'td_address');  
        } else if(j == 2) {
          img = "<img src='" + basedomain + "/images/" + ds[i][j] + ".gif' alt='" + ds[i][7] + "' width = '15' height ='25'>";
          record += this.createElement(img, '');  
        }
        
      }
      ((first_rowsize + i) % 2 == 0 )?cls='even':cls='odd';
      $(this.config[0]).append(this.createRecord(record, cls, i, ds[i][6], i));
    }
  },
  
  removeChecked: function() {
    config = this.config;
    
    $(config[0] + ' tbody tr').each(function() {
      var tr = $(this);
      if( tr.children().children().attr('checked')) {
        tr.remove();
      }
    });
    
    this.initGridPanel();
  },
  
  empty: function() {
    config = this.config;
    $(config[0] + ' tbody tr').each(function() {
      $(this).remove();
    });
    this.initGridPanel();
  },
  
  formatMoney: function(arg, viewmode) {
    if (!viewmode) return arg;
    var ret = [];
    for(var i=arg.length-1, j=1;i>=0;i--) {
      if ( arg.charAt(i) != ',') {
        ret.push(arg.charAt(i)); 
        if( j % 3 == 0 && i > 0) {
          ret.push(',');
        } 
        j ++;         
      }
    }
    ret.reverse();
    var str = ret.join('');
    //var str = arg;
    if (viewmode == 'ア') {
        
        img = "<img src='" + basedomain + "/images/button/icon_hour.gif' /><br />";
        //str = '(時)' + str;  
        str = img + str;  
    } else if (viewmode == '社') {
        img = "<img src='" + basedomain + "/images/button/icon_month.gif' /><br />";
        //str = '(月)' + str;
        str = img + str;   
    }
    return  str;
  },
  
  createRecord: function(html, css, no, url, index) {
    return ("<tr class='"+ css + "' id = 'job_row_" + index + "'>" + html + "</tr>");
  },
  
  createElement: function(html, css, align, pr) {
    align = (!align) ? 'center': align;
    pr = (!pr)? '':pr;
    return ("<td align='"+align+"' class='"+ css + "' title='" + pr +"'>" + html + "</td>");    
  },
  createCheckbox: function(value, css) {
    return ("<input type='checkbox' class='"+ css +"' value='"+ value  + "'>");
  },
  createAnchor: function(html, css, id, url, i) {
    result = "<span class='" + css + "' id='"+ "joblist_span_" + id +"' datafurl='" + url + "'>" + html + "</span>"
    return result;
  }
}

function selectjoblisttr(index){
  $('#joblist tbody tr').removeClass('joblist_tr_select');
  $('#job_row_'+index).addClass('joblist_tr_select');
}
function xor_select(meta) {
  $(meta).click(function() {
    $(meta).each(function(){
      toggleInactive($(this));
    });
    toggleActive($(this)); 
  });
}

function toggleActive(obj) {
  var src = obj.attr('src');
  if(src){
    param = src.split('/');
    param.reverse();  
    if ( param[0]) {
        param[0] = param[0].replace('0', '1');
    }
    param.reverse();
    src = param.join('/');
    obj.attr('src', src);
  } 
}

function toggleInactive(obj) {
   var src = obj.attr('src');
  if(src){
    param = src.split('/');
    param.reverse();
    if ( param[0]) {
        param[0] = param[0].replace('1', '0');
    }
    param.reverse();
    src = param.join('/');
    obj.attr('src', src);    
  } 
  
}
//文字ライトソート
function strright( str, n ) {
    l = str.length;
    if (n>l) n=l;
    return( str.substring(l-n,l) );
}
//文字レフトソート
function strleft( str, n ) {
    l = str.length;
    if (n>l) n=l;
    return( str.substring(l-n,l) );
    //return( str.substring(1,n) );
}

function onTableSortReset(){
    jobth = document.getElementById('joblist_th')
    if(!jobth) return;
    for(i = 0; i < jobth.childNodes.length; i++){
        if(jobth.cells[i] && jobth.cells[i].tagName == "TH" ){
            if(jobth.cells[i].innerHTML == '仕事名'){
                if(jobth.cells[i].className == 'header'){
                    jobth.cells[i].className = 'headerSortUp';
                }     
            }else{
                if(jobth.cells[i].className != 'header'){
                    jobth.cells[i].className = 'header';
                }
            }
        }
    }    
}

// 文字列からデータIDを取得する。area_li_5 から5を取得する。
function getdataid(szdata)
{
  var id, index;
  
  szdata = szdata+"";
  index = szdata.lastIndexOf("_");
  if(index!=-1)
    id = szdata.substr(index+1);
  else
    id = null;
  return id;
}

$(window).load(function() {
  $("<div id='waiter' class='waiter'></div>")
  .append("<img src='" + rootdomain + "/loading.gif'></img>")
  .css('left', ($(window).width() / 2 - 100))
  .css('top', $(window).height() / 2 - 25 + $(window).scrollTop())
  .css('width',246)
  .css('height', 50)
  //.css('border', '1px solid green')
  .css('position','absolute')
 // .css('background-color', '#ffffcc')
  .appendTo("body")
  .hide();
});

function waiting() {
  $('#waiter')
  .css('left', ($(window).width() / 2 - 120))
  .css('top', $(window).height() / 2 - 25 + $(window).scrollTop() - 120)
  .show()
}

function finish() {
  $('#waiter').hide();
}

urlToolkit = new function(config) {
  
  this.initialize = function(config) {
    
  }
  
  this.parseUrl = function(url) {
  
    var urlitem = this.getUrlitem(url);
    var parseparam = {};    
    for(var i=0; i<urlitem.length; i++) {
      re = /([ptek]{1})_([^\.]*)/i;
      m = re.exec(urlitem[i]);
      if ( !m || m[1] == undefined ) continue;
      switch(m[1]) {
        case 'p' :
          parseparam['province'] = decodeURI(m[2]);
          break;
        case 't' :
          parseparam['town'] = decodeURI(m[2]);
        break;
        case 'e' :
          parseparam['employtype'] = decodeURI(m[2]);
        break;
        case 'k' :
          parseparam['keyword'] = decodeURI(m[2]);
        break;
      }
    }
    return parseparam;
  }
  
  this.array2soption = function(arr) {
    var sopt = new searchOption();
    if (arr['province'] != undefined) sopt.province = arr['province'];
    if (arr['town'] != undefined) sopt.town = arr['town'];  
    if (arr['employtype'] != undefined) sopt.employtype = arr['employtype'];  
    if (arr['keyword'] != undefined) sopt.keyword = arr['keyword'];  
    return sopt;
  }
  
  this.parseUrlInfo = function(url) {
    return (this.array2soption(this.parseUrl(url)));
  }
  
  this.publishUrl = function(param) {
    if (param instanceof searchOption) {
       var item = [];
       if( param.province) item.push('p_' + param.province); 
       if( param.town) item.push('t_' + param.town);
       if( param.employtype) item.push('e_' + param.employtype);
       if( param.keyword) item.push('k_' + param.keyword);
       return this.fullPublishUrl(item.join('/'));
    } else {
      return null;
    }
  }
  
  this.fullPublishUrl = function(url) {
    return '/job/' + url + '.html'; 
  }
  
  this.getUrl = function() {
    return $(document).attr('location');
  }
  
  this.getUrlitem = function(url) {
    if ( url == undefined) {
      var url = new String(this.getUrl());
    }

    return url.split('/');
  }
  

}


