/*
********************** CHANGES *********************
2006.11.24 CREATED; getStyleById;
2006.11.25 !NEW! extractNumber; extracts number from object's style length property
2006.11.28 !NEW! setEventHandler; sets given event handler (e.g. onClick) both for IE and non-IE UAs.
2007.03.12 !NEW! my_getElementById; cross-browser getElementById gets object from id
2007.04.01 !NEW! mySetClass; sets class name for given obj
2007.04.09 setEventHandler() modified to handle object passed as first arg.
2008.02.03 CREATED setPopup(), showPopup(), hidePopup();
2008.03.16 !NEW! $N returns array of the elements of given name;
2010.06.05 !NEW! pathToUri(), setAnchorImages(), dec2hex()
2010.06.05 !NEW! qw() // Perl qw() compatible (no bare words though)
******************* END OFCHANGES ******************
*/

function getStyleById () {
 var myID = arguments[0];
 var myProp = arguments[1];
 var myObj = document.getElementById(myID);

 if (myObj) {
  if (myObj.currentStyle) {
   return myObj.currentStyle[myProp];
  }
  else if (document.defaultView.getComputedStyle) {
   return document.defaultView.getComputedStyle(myObj,null).getPropertyValue(myProp);
  }
 }
}
// Taken from http://www.quirksmode.org/dom/getstyles.html

/*
String.prototype.camelize = function( ) {
  return this.replace( /-([a-z])/g,
      function( $0, $1 ) { return $1.toUpperCase( ) } );
}
String.prototype.deCamelize = function( ) {
  return this.replace( /[A-Z]/g,
      function( $0 ) { return "-" + $0.toLowerCase( ) } );
}

function getActiveStyle( element, property, pseudo ) {
// var element = document.getElementById(elementID);
  if( element.currentStyle ) { //IE or Opera
      if( property.indexOf( "-" ) != -1 ) property = property.camelize( );
      return element.currentStyle[ property ];
  }
  else if( getComputedStyle ) { //Mozilla or Opera
      if( property.indexOf( "-" ) == -1 ) property = property.deCamelize( );
      return getComputedStyle( element, pseudo ).getPropertyValue( property );
  }

  return "";
}
*/

function setEventHandler(sh_id, sh_handler, sh_event) {
 var element;
 if (typeof sh_id == typeof 'a') {
  element = document.getElementById(sh_id);
 }
 else if (typeof sh_id == typeof (new Object)) {
  element = sh_id;
 }
 else { return false };
 element.setAttribute(sh_handler, sh_event);
 if (element.getAttribute(sh_handler) == null) { // for IE
  element.setAttribute(sh_handler, new Function(sh_event), 0)
 }
}

function extractNumber(str) {
 var RE = new RegExp("^[0-9]+");
 return Number(str.match(RE));
 return false;
}

//----------------------------
//kl_getelem(id)
// returns 0 or undefined when failed
// id regards object ID
//----------------------------
function my_getElementById() {
 var id = arguments[0];
 if (!isString(id)) { return id; };

 if (document.getElementById){ //IE5+,NS6+,Opera
  if (document.getElementById(id)) { return document.getElementById(id); }
 }
 else if (document.all) { //IE4+,Opera
  if (document.all(id)) { return document.all(id); }
  }
  else if (document.layers) { //Netscape4.x
  return kl_getelem_ns4(id,document);
  }
 return 0;
}
// recursive search (for Netscape4.x )
function kl_getelem_ns4(id,doc) {
 if (!doc.layers) { return 0; }
 for(var i=0;i<doc.layers.length;i++){
  if(doc.layers[i].id==id) { return doc.layers[i]; }
  if(doc.layers[i].document) {
   var t=kl_getelem_ns4(id,doc.layers[i].document);
   if(t) return t;
  }
 }
 return 0;
}

function isStr() {
 return isString(arguments[0]);
}
// Thanks! from http://www.keynavi.net/ja/tipsj/getelem.html

function isString() {
 return(typeof(arguments[0]) == typeof(""));
}
function isArray(array) {
/**
 return !!(array && array.constructor &&
   array.constructor.toString().indexOf(" Array(") >= 0);
*/
 return array instanceof Array;
}
function isObject() {
 return(typeof(arguments[0]) == typeof({}));
}



function mySetClass(msc_obj, msc_value) {
 if (typeof(msc_obj) != "object") { return false };
 msc_obj.className = msc_value;
 return msc_obj;
}
 
function isMSIE() {
 return (document.documentElement.getAttribute("style") ==
            document.documentElement.style);
}



//////// popup script /////////
// usage: 
// <a href="#" id="popup_id">pops onMouseOver</a>
// <div id="popup_id_popup" style="background-color:white; border:1px solid #666; width:12em; margin:-24px 0; padding:3px;">some description</div>
// <script type="text/javascript">setPopup("popup_id");</script>
///////////////////////////////

function setPopup() {
 var triggerID = arguments[0];
 var popupID = arguments[1] ? arguments[1] : triggerID + '_popup';

 var triggerObj = document.getElementById(triggerID);
 var popupObj = document.getElementById(popupID);

 var js_onMouseOut = 'javascript:hidePopup(' + "'" + popupID + "'" + ')';
 var js_onMouseOver = 'javascript:showPopup(' + "'" + popupID + "'" + ')';
// var js_onMouseOut = 'javascript:setTimeout(' + "'" + 'hidePopup(' + "\"" + popupID + "\"" + ')' + "'" + ', 500)';
// var js_onMouseOver = 'javascript:setTimeout(' + "'" + 'showPopup(' + "\"" + popupID + "\"" + ')' + "'" + ', 500)';

 setEventHandler(
  popupID, 'onClick',
 'javascript:location.href = ' + "'" + triggerObj.href + "'"
 );

 setEventHandler(triggerID, 'onMouseOut', js_onMouseOut);
 setEventHandler(popupID, 'onMouseOut', js_onMouseOut);
 setEventHandler(triggerID, 'onMouseOver', js_onMouseOver);
 setEventHandler(popupID, 'onMouseOver', js_onMouseOver);
 popupObj.style.display = 'none';

}
function showPopup() {
 var popupID = arguments[0];
 var popupObj = document.getElementById(popupID);
 popupObj.style.display = 'block';
 popupObj.style.position = 'absolute';
}
function hidePopup() {
 var popupID = arguments[0];
 document.getElementById(popupID).style.display = 'none';
}

function set_imemode(myobj, mymode){
    switch(mymode){
        case 0: myobj.style.imeMode = "inactive"; break;
        case 1: myobj.style.imeMode = "active"; break;
        default: break;
    }
}



function setReplaceContent(triggerID, targetID, contentID, addnScript) {
 document.getElementById(contentID).style.display = 'none';
 setEventHandler(
  triggerID,
  'onClick',
  'document.getElementById(\'' + targetID + '\').innerHTML = document.getElementById(\'' + contentID + '\').innerHTML;' + addnScript
 );
}

function createElementWithAttrs(el_name,attrs) {
 var obj = document.createElement('div');

 if (isArray(el_name)) {
  var tmp1 = el_name[0];
  var tmp2 = el_name[1];
  el_name = tmp1;
  attrs = tmp2;
 }
 attrs = attrs? attrs : {};
 if (isString(el_name)) {
  obj = document.createElement(el_name);
 }
;
 if (typeof(attrs) != typeof({})) {
  return obj;
 }
;
 if (attrs.colspan && !attrs.colSpan) { attrs.colSpan = attrs.colspan; }
 if (attrs.rowspan && !attrs.rowSpan) { attrs.rowSpan = attrs.rowspan; }

 for (key in attrs) {
  if (key == 'innerHTML') {
   obj.innerHTML = eval("attrs." + key);
  }
  else if (key == 'innerText') {
   obj.innerText = eval("attrs." + key);
  }
  else if (key == "className") {
   mySetClass(obj, attrs.className);
  }

  else if (key == 'children') {
   if (isArray(attrs.children)) {
    if (isString(attrs.children[0])) {
     obj.appendChild(
      createElementWithAttrs(attrs.children[0], attrs.children[1])
     );
    }
    else {
     for (var i = 0; i < attrs.children.length; i++) {
      obj.appendChild(
       createElementWithAttrs(attrs.children[i])
      );
     }
    }
   }
   else {
    obj.appendChild(attrs.children);
   }
  }
  else if (key == 'style') {
//   attrs.style = new String(attrs.style);
   var styles = attrs.style.strip().replace(/;$/, '').split(/;/);
   for (var s = 0; s < styles.length; s++) {
    var p = styles[s].strip().split(/:/);
    eval('obj.style.' + p[0].camelize() + ' = "' + p[1] + '"');
   }
  }
  else if (typeof(jsonValue(attrs, key)) == 'string' || !isNaN(jsonValue(attrs, key)) )
 {
    obj.setAttribute(key, jsonValue(attrs, key)); 
  };
 };
 return obj;
}


function addCSSFile() {
 for (var i = 0; i < arguments.length; i++) {
  var css = createElementWithAttrs("link",
   {
    href:arguments[i],
    rel :'stylesheet',
    type:'text/css'
    }
  );
  document.getElementsByTagName("head")[0].appendChild(css);
 }
}

function addStyles(s) {
 var e = createElementWithAttrs("style",
   {
    type:'text/css',
    innerHTML:s
   }
 );
 document.getElementsByTagName("head")[0].appendChild(e);
}


function DOMNode_insertAfter(newChild,refChild)
//Post condition: if childNodes[n] is refChild, than childNodes[n+1] is newChild.
{
  var parent=refChild.parentNode;
  if(parent.lastChild==refChild) return parent.appendChild(newChild);
  else return parent.insertBefore(newChild,refChild.nextSibling);
}


function $N (element) {
  var elms = document.getElementsByName(element);

  elmArray = Array();

  for(i = 0; i < elms.length; i++){
    elmArray.push(Element.extend(elms.item(i)));
  }

  return elmArray;
}


function roundDecimal(n, p) {
 p = p? parseInt(p) : 0;
 var place = Math.pow(10, p);
 return(parseInt(Math.round(n*place)/place));
}

function asciiizeAlpha(str) {
  var r = '';
  for (var lp = 0; lp < str.length; lp++) {
    var unicode = str.charCodeAt(lp);
    if ((0xff0f < unicode) && (unicode < 0xff1a)) {
      r+=String.fromCharCode(unicode-0xfee0);
    } else if ((0xff20<unicode) && (unicode<0xff3b)) {
      r+=String.fromCharCode(unicode-0xfee0);
    } else if ((0xff40<unicode) && (unicode<0xff5b)) {
      r+=String.fromCharCode(unicode-0xfee0);
    } else {
      r+=String.fromCharCode(unicode);
    }
  }
  return r;
}


//http://homepage3.nifty.com/aokura/jscript/
function z2h_ascii(src) {
 if (!isNaN(src)) { src += ''; }
 var str = new String;
 var len = src.length;
 for (var i = 0; i < len; i++) {
  var c = src.charCodeAt(i);
  if (c >= 65281 && c <= 65374 && c != 65340) {
   str += String.fromCharCode(c - 65248);
  } else if (c == 8217) {
   str += String.fromCharCode(39);
  } else if (c == 8221) {
   str += String.fromCharCode(34);
  } else if (c == 12288) {
   str += String.fromCharCode(32);
  } else if (c == 65507) {
   str += String.fromCharCode(126);
  } else if (c == 65509) {
   str += String.fromCharCode(92);
  } else {
   str += src.charAt(i);
  } 
 }
 return str;
}


function addFigure(str) {
 var num = new String(str).replace(/,/g, "");
 while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
 return num;
}


function isTrue(d) {
 if ((d === undefined) || (d === null) || (d === 0) || (d === false) || d === "") {
  return false;
 }
 return d;
}


function cleanNumInput(str) {
 if (!isTrue(str)) { str = 0 };
 
 str = z2h_ascii(str);
 str.replace(/[^0-9]+/, '');
 str.replace(/^0/, '');
 if (str == '') { return(0); }
 return parseInt(str);
}


function getWindowSize() {
 var x,y;
 if(document.all){//IE
  x=document.body.clientWidth;
  y=document.body.clientHeight;
 }
 else{
  x=window.innerWidth;
  y=window.innerHeight;
 }
 return new Array(x,y);
}



// Thanks! http://www.simplexsimple.com/archives/2006/09/post.html
function backToTop() {
  var x1 = x2 = x3 = 0;
  var y1 = y2 = y3 = 0;
  if (document.documentElement) {
      x1 = document.documentElement.scrollLeft || 0;
      y1 = document.documentElement.scrollTop || 0;
  }
  if (document.body) {
      x2 = document.body.scrollLeft || 0;
      y2 = document.body.scrollTop || 0;
  }
  x3 = window.scrollX || 0;
  y3 = window.scrollY || 0;
  var x = Math.max(x1, Math.max(x2, x3));
  var y = Math.max(y1, Math.max(y2, y3));
  window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));
  if (x > 0 || y > 0) {
      window.setTimeout("backToTop()", 25);
  }
}


function jsonValue(j,k,v) {
 // handles JSON object values;
 // j = JSON object
 // k = JSON object key
 // v = JSON object value
 // if v is passed value of k in j is updated and returns the value
 // unless returns value of k

 var evalue;

 if (typeof(v) != 'undefined') {
  if (isNaN(v)) {
   evalue = "'" + v + "'";
  }
  else {
   evalue = v;
  }
  eval('j' + '.' + k + ' = ' + evalue);
 }
 return eval('j' + '.' + k);
}

/*
function windowOpen(p) {
 var param = {};
 
 window.open(
  p.url,
  p.windowName
 )
}
*/

function removeAllChildren(e) {
 var e = $(e); if (!e) { return e };
 while (e.firstChild) {
  e.removeChild(e.firstChild);
 }
 return e;
}


function getRadioValue(radioName) {
 var radioGroup = document.getElementsByName(radioName);
 for (var i = 0; i < radioGroup.length; i++) {
  if (radioGroup[i].checked == true) {
   return radioGroup[i].value
  }
 }
}

function getQuerystring(key, default_) {
/*
  var value = getQuerystring('key_name');
*/
 if (default_==null) default_="";  
 key = key.replace(/[¥[]/,"¥¥¥[").replace(/[¥]]/,"¥¥¥]");  
 var regex = new RegExp("[¥¥?&]"+key+"=([^&#]*)");  
 var qs = regex.exec(window.location.href);  
 if(qs == null)  
  return default_;  
 else  
  return qs[1];  
}  

function getJsParam( fn ) {
 /*
  // usage
  in HTML file: <script src="/path/to/filename.js?key=value" ></script>
  // in script source:
  var params = getJsParam('filename.js'); // returns Object;
*/
 //読み込まれたスクリプトファイルの一覧を取得  
 var scripts = document.getElementsByTagName( 'script' );  
 var script;  
 var params = {};  
   
 //該当スクリプトファイルの抜き出し extracting filename
 for ( var i=0; i<scripts.length; i++ ) {  
  var s = scripts.item( i );  
  if( s.src.indexOf( fn ) != -1 ) {  
   script = s;  
   break;  
  }  
 }  
 if( script ) {  
  script.src.match( /(.*)(\?)(.*)/ );  
  if( RegExp.$3 ) {  
   var a = RegExp.$3.split( '&' );  
   if( a ) {  
    for( var k=0; k<a.length; k++ ) {  
     var p = a[ k ].split( '=' );  
     if( p[0] ) {  
      params[ p[0] ] = p[1];  
     }  
    }  
   }
   else { return false; }  
  }
  else { return false; }  
 }
 else { return false; }  
 return params;  
}  




function pathToUri(href,loc) { /* リンク(a[href])と現在位置(window.location.href)からURIを得る */
 var path = href;
 if (typeof(loc) == 'undefined') { loc = window.location.href }
 
 var loc_cd = loc.replace(/(\x2f)?[^\x2f]*?$/,'$1');
 var url = '';
 
 if (path.match(/^https?\x3a\x2f\x2f/)) { return(path); }
 if (path.match(/^\x2e\x2f/)) { return(path.replace(/^\x2e\x2f(.*?)$/, loc_cd + '$1')); }
 if (path.match(/^\x2f/)) {
  var root = loc.replace(/^(https?:\x2f\x2f.*?\x2f).*?$/, '$1');
  return root + path.replace(/^\x2f/, '');
 }

 while (path.match(/^\x2e\x2e\x2f/)) {
  path = path.replace(/^\x2e\x2e\x2f/, '');
  loc_cd = loc_cd.replace(/[^\x2f]*?\x2f$/, '');
 }
 return(loc_cd + path);
}



function setAnchorImages(e,p) { 
/*
 メニューなどのリンク画像をロールオーバー＆現在位置なら現在位置用画像に置換。
 jqueryが必要。
 Event.domReady.add(function(){ setAnchorImages('#navi a',{suffix_here:'_here'}); })
 ↑の書き方ならprototypeとdomreadyが必要。
*/

 if (typeof(e) == 'undefined') { e = document };
 if (typeof(p) == 'undefined' || typeof(p) === null) { p = {} };
 if (typeof(p.suffix_o) == 'undefined' ) { p.suffix_o = '_o' };
 
 jQuery(e).each(function(){
  var img = jQuery(this).children('img').get(0);
  if (typeof(img) == 'undefined') { return true; }
  var href = jQuery(this).attr('href');
  var imgsrc = img.src;
  var suffixSrc = function(src,suffix){return src.replace(/^(.*?)(\x2e)([^\x2e]+?$)/,'$1'+suffix+'$2$3');};
  var imgsrc_o = suffixSrc(imgsrc,p.suffix_o);
  if (typeof(p.suffix_here) != 'undefined' ) {
   var here = window.location.href; 
   if (pathToUri(href,here) == here) {
    imgsrc_here = suffixSrc(img.src,p.suffix_here);
    jQuery(img).attr('src', imgsrc_here);
    imgsrc = imgsrc_here;
   }
  };
  
  jQuery(img).mouseover(function(){ this.src = imgsrc_o; });
  jQuery(img).mouseout(function(){ this.src = imgsrc });
 });
}


function dec2hex (dec) {
 var hex = "";
 while (dec) {
  var last = dec & 15;
  hex = String.fromCharCode(((last>9)?55:48)+last) + hex;
  dec >>= 4;
 }
 return hex;
}

function qw($str) {
 if (typeof($str) == 'string' && $str) {
  return $str.replace(/(^[\s]+)|([\s]+$)/g, "").replace('/[\s]+/', "\x20").split("\x20");
 }
 return;
}
////// FORM FOCUSING AND FALSE SUBMIT
/*
USAGE: 
<form id="example" onsubmit="return falseSubmit(this)">
	<input type="text" name="el01">
	<input type="text" name="el02">
	<input type="text" name="el03">
	<input type="text" name="el04">
	<input type="text" name="el05">
	<input type="button" value="submit">
	<div style="width: 1px;height: 1px;overflow: hidden;">　<input type="submit"></div>
</form>
function setFocusElements(eid,opts) {
 var a = $(eid).getElementsByTagName('input');;
 setEventHandler(eid, 'onsubmit', 'return falseSubmit(this)');
 
 var btn;
 var submit;
 
 for (var i = 0; i < a.length; i++){
  if (a[i].type == 'text') { setEventHandler(a[i],'onfocus', 'setFocusElement(this)'); }
  if (a[i].type == 'button') { btn = a[i]; }
  if (a[i].type == 'submit') { submit = a[i]; }
 }
 if (isObject(submit)) {
  btn = $(eid).appendChild(createElementWithAttrs(
    'input',
    { type:'button', value:submit.value, onclick:'this.form.submit()' }
   )
  );
 }
 else {
  submit = createElementWithAttrs('input', { type:'submit', value:btn.value });
 }

 var e = $(eid).appendChild(createElementWithAttrs('div', { style:'width:1px; height:1px; overflow:hidden;' }));
 e.appendChild(submit);
 return eid;
}


function setFocusElement(obj,opts){
 if (!isObject(obj)) { return(false) };
 if (!isObject(opts)) { opts = {} }

 opts.bgFocused = opts.bgFocused? opts.bgFocused : "#ffeeee";
 opts.bgUnFocused = obj.style.backgroundColor? obj.style.backgroundColor : "#fffff";

 if(focuselements){
  focuselements.style.backgroundColor = opts.bgUnFocused;
 }

 obj.style.backgroundColor = opts.bgFocused;
 focuselements = obj;
}

function getInputElements(obj) {
 var a = obj.getElementsByTagName('input');
 var aa = new Array;
 
 for (var i = 0; i < a.length; i++) {
  if (a[i].type == 'text') {
   aa.push(a);
  }
 }
 return aa;
}

var focuselements;
function falseSubmit(obj) {
 var flag;
 var movefocus;
 for (var i=0; i < obj.length; i++) {
  if (flag) {
   movefocus = obj.elements[i];
   flag = 0;
  }
  if (obj.elements[i] == focuselements) {
   flag = 1;
  }
 }
 movefocus.focus();
 return false;
}

*/