var LP = {};

// {{{

/**
 * 簡易デバッグ
 */
LP.debug = function(obj){
  var str = '';
  for( var p in obj ){
    str += "\n" + p + " ： "+ obj[p];
  }
  return str;
}

// }}}
// {{{ string

/**
 * 文字列の前後にある空白を取り除きます
 */
LP.trim = function( obj ){
  // 文字列の場合
  if( typeof( obj ) == "string" ){
    return obj.replace( /^[ 　\t\r\n]+|[ 　\t\r\n]+$/g, "" );
  }
  // エレメントの場合
  else if( typeof( obj ) == "object" ){
    obj.value = obj.value.replace( /^[ 　\t\r\n]+|[ 　\t\r\n]+$/g, "" );
    return;
  }
}

LP.ltrim = function( obj ){
  // 文字列の場合
  if( typeof( obj ) == "string" ){
    return obj.replace( /^[ 　\t\r\n]+/, "" );
  }
  // エレメントの場合
  else if( typeof( obj ) == "object" ){
    obj.value = obj.value.replace( /^[ 　\t\r\n]+/, "" );
    return;
  }
}

LP.rtrim = function( obj ){
  // 文字列の場合
  if( typeof( obj ) == "string" ){
    return obj.replace( /[ 　\t\r\n]+$/, "" );
  }
  // エレメントの場合
  else if( typeof( obj ) == "object" ){
    obj.value = obj.value.replace( /[ 　\t\r\n]+$/, "" );
    return;
  }
}

/**
 * 分割表示している項目を連結します。
 * 連結する値を持つエレメントのIDは、連結した値をセットするエレメントのID＋1から始まる連番が振られている必要があります
 *
 * @param string id  連結した値を格納するエレメントのID
 * @param int    num 連結するエレメント数
 * @param string sep 区切り文字
 */
LP.join = function(id, sep){

  id = String(id);
  if( sep == null )
    sep = "";

  var vars = new Array();
  var i=1;

  while( true ){
    var elem = document.getElementById( id + i );
    if( elem == null )
      break;

//    vars.push( elem.value );
    regexp = new RegExp( sep, 'g' );
    vars.push( elem.value.replace( regexp, '' ) );
    i++;
  }

  var elem = document.getElementById( id );
  if( elem != null )
    elem.value = vars.join( sep );
}

/**
 * エレメントを受け取り，値から数字以外を取り除きます．
 */
LP.validateNumeric = function( elem ){
  if( elem.value == '' )
    return;

  num = LP.convertDigitToHarf( elem.value ); // 数字を半角にする

  minus = ( num.match( /^-/, num ) != null ); // マイナス値かどうか
  num = num.replace( /[^0-9.]/g, "" );        // 数字と[.]以外を削除
  num = num.replace( /^0+/, "0" );            // 先頭からの０の連続を一つにまとめる
  num = ( minus ? -num : num );               // 符号を付ける

  elem.value = ( num != "" ? num : 0 );
}

/**
 * 特定の規則の文字列を連想配列に変換します。
 *
 * @param string [キー]:[値],[キー]:[値],...といった文字列
 */
LP.convertHashForCSV = function(csv){
  var hash = new Array();

  var cols  = csv.split(",");
  for(var i=0; i<cols.length; i++){
    var cells = cols[i].split(":");
    hash[ cells[0] ] = cells[1];
  }

  return hash;
}

/**
 * 文字列に含まれる数字を全て半角にします．
 * @param string
 * @return string 全角数字が半角になった文字列
 */
LP.convertDigitToHarf = function( num ){
  var _full_nums = new Array( "０", "１", "２", "３", "４", "５", "６", "７", "８", "９" );

  for( i=0; i<10; i++ ){
    reg = new RegExp( _full_nums[i], "g" );
    num = num.replace( reg, i );
    num = num.replace( /－/, "-" );
    num = num.replace( /．/, "." );
  }
  return num;
}

/**
 * ３桁位取りカンマを付加した文字列を取得します。
 */
LP.unitCurrency = function( value ){
  value = String( value );
  minus = ( value.match( /^-/, value ) != null ); // マイナス値かどうか
  value = value.replace( /^[-+]/, "" );        // 符号を除去

  var res = "";
  var count = value.length;

  for( var i=0; i<count; i++ ){

    // 3桁ごとにカンマを付加
    if( i % 3 == 0 && res != "" )
      res = "," + res;

    // 右の文字から追加
    res = value.charAt( count - 1 - i ) + res;
  }
  return ( minus ? "-"+res : res );
}

// }}}
// {{{ select

/**
 * 選択されたセレクトボックスのオプションを、別のセレクトボックスへ移動します。
 *
 * @param string 移動元のセレクトボックス名
 * @param string 移動先のセレクトボックス名
 * @param bool   移動元のオプションを削除するかどうかを示す値
 */
LP.moveSelectOptions = function(sel1, sel2, is_remove) {
  var elemS1 = document.getElementById( sel1 );
  var elemS2 = document.getElementById( sel2 );
  if( is_remove == null )
    is_remove = false;

  for(var i=0; i<elemS1.length; i++) {
    if (elemS1.options[i].selected && elemS1.options[i].value != null && elemS1.options[i].value != '') {
      elemS2.options[elemS2.length] = new Option(elemS1.options[i].text, elemS1.options[i].value);
      if( is_remove ){
        elemS1.options[elemS1.selectedIndex] = null;
        i--;
      }
    }
  }
}

/**
 * 選択されたセレクトボックスのオプションを削除します
 */
LP.removeSelectOptions = function(sel){
  var elem = document.getElementById( sel );
  for(var i=0; i<elem.length; i++) {
    if (elem.options[i].selected) {
      elem.options[elem.selectedIndex] = null;
      i--;
    }
  }
}

/**
 * セレクトボックスの値をカンマ区切りで取得します。
 *
 * @param string 対象となるセレクトボックスのID
 * @param bool   選択されている値だけ取得するかどうかを示す値
 */
LP.getSelectOptions = function(sel, is_selected){
  var ops = new Array();
  var elem = document.getElementById( sel );

  for(var i=0; i<elem.length; i++){

    // 選択されているものだけの場合
    if( is_selected ){
      if( elem.options[i].selected )
        ops[i] = elem.options[i].value;
    }
    // 全て設定
    else{
      ops[i] = elem.options[i].value;
    }
  }
  return ops.join(",");
}

/**
 * セレクトボックスのオプションを全て選択または、解除します。
 */
LP.selectAllOptions = function(sel, is_select){
  var elem = document.getElementById( sel );
  for(var i=0; i<elem.options.length; i++) {
    elem.options[i].selected = is_select;
  }
} 

/**
 * 
 */
LP.selectSubmit = function( elem, id, msg ){

    if( msg != null ){
    if( !confirm( msg ) )
      return;
    }

    //elem.disabled = true;
    document.getElementById( id ).value = 't';
    elem.form.submit();
    //elem.disabled = false;
}

// }}}
// {{{ date

/**
 * 日付を加算します。
 */
LP.addDay = function( datetime, addday ){
  var timestamp = LP.getTimeStamp( datetime );
  if( !LP.isNumeric( timestamp ) )
    return null;

  var add_timestamp = addday * ( 24 * 60 * 60 * 1000 );
  return LP.getDateTimeString( timestamp + add_timestamp );
}

/**
 * タイムスタンプを取得します。
 */
LP.getTimeStamp = function( datetime ){
  if( !LP.isDateTime( datetime ) )
    datetime += " 00:00:00";

  if( !LP.isDateTime( datetime ) )
    return null;

  var tmp = datetime.replace( /-/g, "/" );
  return new Date( tmp ).getTime();
}

/**
 * タイムスタンプの現す日付文字列を取得します。
 */
LP.getDateString = function( timestamp ){
  var date = new Date();

  if( timestamp != null )
    date.setTime( timestamp );

  var year = date.getFullYear();
  var mon  = date.getMonth() + 1;
  var day  = date.getDate();

  mon = ( mon < 10 ? "0"+mon : mon );
  day = ( day < 10 ? "0"+day : day );

  return ( year + '-' + mon + '-' + day );
}

/**
 * タイムスタンプの現す時間文字列を取得します。
 */
LP.getTimeString = function( timestamp ){
  var date = new Date();

  if( timestamp != null )
    date.setTime( timestamp );

  var hour = date.getHours();
  var min  = date.getMinutes();
  var sec  = date.getSeconds();

  hour = ( hour < 10 ? "0"+hour : hour );
  min  = ( min  < 10 ? "0"+min  : min  );
  sec  = ( sec  < 10 ? "0"+sec  : sec  );

  return ( hour + ':' + min + ':' + sec );
}

/**
 * タイムスタンプの現す日時文字列を取得します。
 */
LP.getDateTimeString = function( timestamp ){
  var date = LP.getDateString( timestamp );
  var time = LP.getTimeString( timestamp );
  return ( date + ' ' + time );
}

/**
 * 日時の差をミリ秒単位で取得します。
 *
 * @param string datetime1 比較元となる日時文字列
 * @param string datetime2 比較対象となる日時文字列
 */
LP.getDiffTimeStamp = function( datetime1, datetime2 ){

  if( !LP.isDateTime( datetime1 ) )
    datetime1 += " 00:00:00";

  if( !LP.isDateTime( datetime2 ) )
    datetime2 += " 00:00:00";

  if( !LP.isDateTime( datetime1 ) || !LP.isDateTime( datetime2 ) )
    return null;

  var tmp = '';

  tmp = datetime1.replace( /-/g, "/" );
  var ts1 = new Date( tmp ).getTime();

  tmp = datetime2.replace( /-/g, "/" );
  var ts2 = new Date( tmp ).getTime();

  return ( ts1 - ts2 );
}

// }}}
// {{{

/**
 * タブを選択します。
 * タブのタグに付ける命名規則：[prefix][タブの名前][0から始まる連番]
 * タブの内容に付ける命名規則：[タブの名前][0から始まる連番]
 *
 * @param string タブの名前
 * @param string 選択するタブの名前
 * @param string 選択状態を表すスタイル
 * @param string 非選択状態を表すスタイル
 * @param string タブのサフィックス
 */
LP.selectTab = function( tabgroup_name, select_tab_id, on_style, off_style, suffix ){

  if( suffix == null )
    suffix = '_tag';
  if( on_style == null )
    on_style = 'active';
  if( off_style == null )
    off_style = 'disable';

  var i = 0;
  var childs = new Array();

  // タブのスタイルを変更する
  childs = new Array();
  i = 0;
  while( child = document.getElementById( tabgroup_name + i + suffix ) )
    childs[i++] = child;

  if( childs.length > 0 ){
    for( i=0; i<childs.length; i++){
      if( childs[i].id == ( select_tab_id + suffix ) )
        childs[i].className = on_style;
      else
        childs[i].className = off_style;
    }
  }

  // 内容表示を切り替える
  childs = new Array();
  i = 0;
  while( child = document.getElementById( tabgroup_name + i ) )
    childs[i++] = child;

  if( childs.length > 0 ){
    for( i=0; i<childs.length; i++){
      if( childs[i].id == select_tab_id )
        childs[i].style.display = ''; // block, inline, table-row
      else
        childs[i].style.display = 'none';
    }
  }
}

// }}}
// {{{

/**
 * クッキーを取得します。
 */
LP.getCookie = function(name) {
  if( name == '' || !document.cookie )
    return;

  var cookies = document.cookie.split("; ");
  for( var i=0; i<cookies.length; i++ ){
    var str = cookies[i].split( '=' );
    if( str[0] != name )
      continue;

    return unescape( str[1] );
  }
}
/**
 * クッキーを設定します。
 */
LP.setCookie = function(name, value, domain, path, expires, secure) {
  if( name == '' )
    return;

  var str = name + "=" + escape( value );
  if( domain ){
    if( domain == 1 )
      domain = location.hostname.replace( /^[^\.]*/, '' );
    str += "; domain=" + domain;
  }
  if( path ){
    if( path == 1 )
      path = location.pathname;
    str += "; path=" + path;
  }
  if( expires ){
    var nowtime = new Date().getTime();
    expires = new Date( nowtime + ( 60 * 60 * 24 * 1000 * expires ) );
    expires = expires.toGMTString();
    str += "; expires=" + expires;
  }
  if( secure && location.protocol == "https:" ){
    str += "; secure";
  }

  document.cookie = str;
}

// }}}
// {{{ bool

/**
 * 数字かどうかを示す値を取得します。
 */
LP.isNumeric = function( num ){
  return ( num != null && num != "" && !isNaN( num ) );
}

/**
 * 日付文字列かどうかを示す値を取得します。
 */
LP.isDate = function( value ){
  return ( value.match( /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/ ) != null )
}

/**
 * 日時文字列かどうかを示す値を取得します。
 */
LP.isDateTime = function( value ){
  return ( value.match( /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$/ ) != null )
}

/**
 * 日時をが大きいかどうかを示す値を取得します。
 *
 * @param string datetime1 比較元となる日時文字列
 * @param string datetime2 比較対象となる日時文字列
 */
LP.isDateTimeDiff = function( datetime1, datetime2 ){

  if( !LP.isDateTime( datetime1 ) )
    datetime1 += " 00:00:00";

  if( !LP.isDateTime( datetime2 ) )
    datetime2 += " 00:00:00";

  if( !LP.isDateTime( datetime1 ) || !LP.isDateTime( datetime2 ) )
    return false;

  var tmp = '';

  tmp = datetime1.replace( /-/g, "/" );
  var ts1 = new Date( tmp ).getTime();

  tmp = datetime2.replace( /-/g, "/" );
  var ts2 = new Date( tmp ).getTime();

  return ( ts1 < ts2 );
}

// }}}
// {{{ button

/**
 * 通常のボタンを押した時に、ボタンを無効にしてからサブミットします。
 */
LP.submitButton = function( elem, id, msg ){

  if( msg != null ){
    if( !confirm( msg ) )
      return;
  }

  elem.disabled = true;
  document.getElementById( id ).value = 't';
  elem.form.submit();
  elem.disabled = false;
}

/**
 * アンカーを押した時に、無効にしてからサブミットします。
 */
LP.submitAnchor = function( elem, id, formid, msg ){

  if( msg != null ){
    if( !confirm( msg ) )
      return;
  }

  elem.disabled = true;
  document.getElementById( id ).value = 't';
  document.getElementById( formid ).submit();
  elem.disabled = false;
}

/**
 * DIV追加クリック
 */
LP.addDivClick = function( area, formName ) {

  var htmlDiv   = document.getElementById( "div_" + area );//入れるところ
  var htmlTemp  = document.getElementById( "div_" + area + "_template" );//入れるもの
  var elemCount = document.getElementById( area + "_count" );//番号
  var element = document.createElement('div');
  elemCount.value++;
  element.name = elemCount.value;
  element.innerHTML = htmlTemp.innerHTML.replace( /__count__/g, elemCount.value );
  element.innerHTML = element.innerHTML.replace( /__form__/g, formName );

  htmlDiv.appendChild(element);

}

/**
 * 【追加】クリック
 */
LP.addElementClick = function( area, formName, type ){

  var elem = $('#elem_'+area);
  var text = $('#elem_'+area+'_template' ).html();//入れるもの
  var count = document.getElementById( area + "_count" );//番号
  text = text.replace( /__count__/g, count.value ).replace( /__form__/g, formName );
  count.value++;

  if(type=='before')
    elem.before(text);
  else
    elem.after(text);
    
}

/**
 * 【登録】クリック時に子フレームのフォームを取得し、送信する
 */
LP.getIFrameContents = function( elem, divName ){

  var div = document.getElementById(divName);
  var children = elem.childNodes;
  
  for(var k in children ){
    
    var e = children[k];
    
    if( elem.childNodes.length )
      LP.getIFrameContents( e, divName );
    
    if( e.tagName == null || e.tagName.search( /INPUT|SELECT|TEXTAREA/i ) < 0 )
      continue;
    
    if(e.tagName.search( /SELECT/i ) >= 0 && e.multiple){
      for(var i=0;e.options.length>i;i++){
      var o = e.options[i];
        if(o.selected){
          var element = document.createElement('input');
          element.type = 'hidden';
          element.name = e.name+'[]';  
          element.value = o.value;
          div.appendChild(element);
        }
      }
    }
    else{
      var value;
      if(e.type.search( /CHECKBOX|RADIO/i ) >= 0 ){
        value = (e.checked) ? e.value : '';
      }
      else{
        value = e.value;
      }
      var element = document.createElement('input');
      element.type = 'hidden';
      element.name = e.name;  
      element.value = value;
      div.appendChild(element);
    }
  }

}

// }}}
// {{{ check

/**
 * すべてチェックします。
 * 連結する値を持つエレメントのIDは、連結した値をセットするエレメントのID＋1から始まる連番が振られている必要があります
 *
 * @param string id  エレメントのID
 * @param bool is_checked 
 */
LP.checkAllBoxes = function(id,is_checked){

  id = String(id);
  if( is_checked == null )
    is_checked = true;

  var i=0;

  while( true ){
    var elem = document.getElementById( id + i );
    if( elem == null )
      break;

    elem.checked = is_checked;
    i++;
  }
}

// }}}
// {{{ toggle

/**
 * 指定IDの子エレメント全ての display を 切り替えます。
 *
 * @param string elem_id 子エレメントの表示非表示を切り替えるエレメントID
 * @param string closeimage_path 閉じている時に表示する画像パス
 * @param string openimage_path 開いている時に表示する画像パス
 */
LP.toggleTree = function( elem_id, closeimage_path, openimage_path ){

  elem = document.getElementById( elem_id );
  childs = new Array();

  i = 0;
  while( child = document.getElementById( elem_id + '_' + i ) )
    childs[i++] = child;

  if( childs.length > 0 ){
    for( i = 0; i < childs.length; i++ ){
      if( childs[i].style.display == 'none' )
        childs[i].style.display = ''; // block, inline, table-row
      else
        childs[i].style.display = 'none';
    }
  }

  if( childs[0].style.display == 'none' )
    elem.innerHTML = '<img src="' + closeimage_path + '" alt="" />';
  else
    elem.innerHTML = '<img src="' + openimage_path + '" alt="" />';
}

/**
 * 指定IDエレメントの表示非表示を設定します。
 */
LP.changeDisplay = function( elem_id, is_visible ){
  var elem = document.getElementById( elem_id );
  if( is_visible == true )
    elem.style.display = ''; // block, inline, table-row
  else
    elem.style.display = 'none';
}

/**
 * 指定IDのエレメント内にある項目全ての disabled を設定します。
 *
 * @param element elem 指定のエレメント
 * @param bool is_disabled 無効にするかどうかを示す値
 */
LP.changeDisabled = function( elem, is_disabled ){
  var children = elem.childNodes;
  for(var i=0; i<children.length; i++ ){
    var e = children[i];
    if( elem.childNodes.length )
      LP.changeDisabled( e, is_disabled );
    if( e.tagName == null || e.tagName.search( /INPUT|SELECT/i ) < 0 )
      continue;
    e.disabled = is_disabled;
  }
}

/**
 * iframe の高さを表示されているHTMLの高さに設定します。
 */
LP.resetIFrameSize = function( iframe_id, margin ){
  if( !LP.isNumeric( margin ) )
    margin = 0;

  var iframe = document.getElementById( iframe_id );
  var doc = iframe.contentDocument;
  if( doc == null ){
    doc = iframe.contentWindow.document;
  }

  iframe.height = 1;
  iframe.height = iframe.contentWindow.document.documentElement.scrollHeight + margin;
}

/**
 * Enterキーが押された場合にフォーカスを移動させます。
 *
 * @param string elem_id フォーカスの移動先となるエレメントのID
 */
LP.setFocusOnEnter = function( elem_id ){
  if( event.keyCode != 13 )
    return;
  document.getElementById( elem_id ).focus();
}

/**
 * エレメントが指定IDのエレメント内に含まれているのかを示す値を取得します。
 */
LP.isChildElement = function ( elemChild, parentId ){
  if( elemChild.id == parentId )
    return true;

  var elemParent = elemChild.parentNode;
  if( elemParent != null )
    return LP.isChildElement( elemParent, parentId );
  else
    return false;
}

// }}}
// {{{ ajax

/**
 * XMLHttpRequestオブジェクトを生成します．
 */
LP.createXMLHttpRequest = function(){
  var ajax;

  // IE以外
  if( window.XMLHttpRequest ){
    ajax = new XMLHttpRequest();
  }
  // IE用
  else if( window.ActiveXObject ){
    try{
      ajax = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch( e ){
      ajax = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  if( !ajax && typeof XMLHttpRequest!='undefined' ){
    ajax = new XMLHttpRequest();
  }

  return ajax;
}


$( function () {
  function prevent_submit_on_enter( event ) {
    if( event.keyCode == 13 )
      return false;
  }
  $( 'input' ).each( function () {
    if( this.id != 'keyword_search' )
      $( this ).bind( 'keypress', prevent_submit_on_enter );
  } );
} );


