/*====================================
  ベースライブラリ
  - hmdx.Util
  - hmdx.Event
  - hmdx.Comm
  - hmdx.ImageLoader
  Ver.20090407
=====================================*/

if(!hmdx) var hmdx = {};

hmdx.require = function(filePath, absoluteURLFlag)
{
    if(absoluteURLFlag) filePath = "http:\/\/www.hmdx.com\/js\/" + filePath;
    document.write('<script type="text\/javascript" src="'+filePath+'" charset="UTF-8"><\/script>');
}

hmdx.env = {

UA : {
nameArray : ["msie","webkit","gecko","opera"], // Safariは"webkit"&&"gecko"なので先に判定
check : function()
{
    var UAStr = navigator.userAgent.toLowerCase();
    var UAName;
    for(var i=0, n_len = this.nameArray.length; i<n_len; i++){
        UAName = this.nameArray[i];
        if(UAStr.indexOf(UAName) > -1){
            this[UAName] = true;
            return;
        }
    }
},
getIEVersion : function()
{
    var v = navigator.appVersion;
    this.version = v.charAt(v.indexOf("MSIE")+5);
}
} // UA

}; // hmdx.env

hmdx.env.UA.check();
if(hmdx.env.UA.msie) hmdx.env.UA.getIEVersion();

/* ユーティリティ関数 ----------------------------------------------------------------------*/
hmdx.Util = function(){};

hmdx.Util.prototype = {

getElementsByTagAndClassName : function(tagName, className, targetElem) // :Array
{
    if(!targetElem) targetElem = document;
    var children = targetElem.getElementsByTagName(tagName);
    var child, classNames;
    var elements = [];

    for (var i=0, c_len=children.length; i<c_len; i++) {
        child = children[i];
        classNames = child.className.split(' ');
        for (var j=0, cn_len=classNames.length; j<cn_len; j++) {
            if (classNames[j] == className) {
                elements[ elements.length ] = child;  // IE5.5以上は elements.push(child)でもよい
                break;
            }
        }
    }
    return elements;
},

getElementByAttribute : function(targetElems, attr, value) // :DOM Object
{
    var elem;
    for (var i=0, e_len=targetElems.length; i<e_len; i++) {
        elem = targetElems[i];
        if (elem[attr] == value) return elem;
    }
},

cacheElements : function(obj) // :Object
{
    var o = {};
    for(var prop in obj){
        if(typeof obj[prop] == "string") o[prop] = document.getElementById( obj[prop] );
        else if(typeof obj[prop] == "object") o[prop] = this.cacheElements(obj[prop]);
    }
    return o;
},

appendCSS : function(filePath) // :DOM Object
{
    // var index = document.styleSheets.length;
    var link = document.createElement("link");
    link.setAttribute("rel","stylesheet");
    link.setAttribute("type","text/css");
    link.setAttribute("href",filePath);
    link.setAttribute("media","screen,tv");
    var head = document.getElementsByTagName("head").item(0);
    head.appendChild(link);
    return link;
},

getComputedStyle : function(elem, propStr) // :Object
{
    var cs = elem.currentStyle || document.defaultView.getComputedStyle(elem, null);
    return cs[propStr];
},

getClientSize : function() // :Object
{
    var d = document;
    if(window.opera) return { width: d.body.clientWidth, height: d.body.clientHeight };

    var w,h;
    if(d.compatMode){
        if(d.compatMode == "CSS1Compat"){ // FF,IE6+標準モード
            w = d.documentElement.clientWidth;
            h = d.documentElement.clientHeight;
        }else{ // FF,IE6+互換モード
            w = d.body.clientWidth;
            h = d.body.clientHeight;
        }
    }else{
        if(window.innerWidth){ // Safari
            w = window.innerWidth;
            h = window.innerHeight;
        // メモ：SafariのinnerWidthはFF,Operaと違いスクロールバーの内側の幅・高さを返す
        }else{ // IE5
            w = d.body.clientWidth;
            h = d.body.clientHeight;
        }
    }
    return { width: w, height: h };
},

getPageSize : function() // :Object
{
    var d = document;
    var w,h;
    if(document.compatMode == "CSS1Compat"){
        w = d.documentElement.scrollWidth;
        h = d.documentElement.scrollHeight;
    }else{
        w = d.body.scrollWidth;
        h = d.body.scrollHeight;
    }// メモ：Safariはページサイズがブラウザ有効表示サイズ以下にならない
    return { width: w, height: h };
},

getPageScroll : function() // :Object
{
    var d = document;
    return {
        left: d.body.scrollLeft || d.documentElement.scrollLeft,
        top: d.body.scrollTop  || d.documentElement.scrollTop
    }
}

} //hmdx.Util.prototype

/*  イベント ------------------------------------------------------- */
hmdx.Event = function(){};

hmdx.Event.prototype = {

addEvent : function(element, eventType, func, useCapture) // : Boolean
{
    if(element.addEventListener){
        element.addEventListener(eventType, func, useCapture);
        return true;
    }
    else if(element.attachEvent){
        var r = element.attachEvent("on"+eventType, func);
        return r;
    }
    else {
        return false;
    }
},
getKeyString : function(e) // :String
{
    var keycode;
    if(e == null) keycode = event.keyCode;
    else keycode = e.which;

    var keyStr;
    if(keycode == 27) keyStr = "esc";
    else keyStr = String.fromCharCode(keycode).toLowerCase();
    return keyStr;
},
stopPropagation : function(e) // :Void
{
    if(e == null) event.cancelBubble = true;
    else e.stopPropagation();
},
preventDefault : function(e) // :Void
{
    if(e == null) event.returnValue = false;
    else e.preventDefault();
}

} //hmdx.Event.prototype

/*  HTTP通信 ----------------------------------------------------------------------- */
hmdx.Comm = function()
{
    this.parent = null;
    this.bindObj = null;
    this.onComplete = null;
    this.method = "GET";
    this.data = null;
    this.asyncFlag = true;
}
hmdx.Comm.prototype = {
/*===================================================================================
  @param data   : String : POST送信の時のみ使用 URI文字列  ex."prop1=hoge&prop2=foo"
  @param method : String : GET｜POST｜PUT｜PROPFIND のいずれか
  @param filePath : String : 自ドメイン内のみ 相対パスで記述 ex."js/hoge.js"
    サーバーとの通信の場合は"/hoge.php?prop1=hoge&prop2=foo"（GET送信）
  @param asyncFlag : Boolean : 非同期で通信するか否か
=====================================================================================*/
requestFile : function(filePath, method, data, asyncFlag)
{
    if(!method) method = this.method;
    if(!data) data = this.data;
    if(!asyncFlag) asyncFlag = this.asyncFlag;
    var self = this;
    var httpObj = this.createHttpRequest();
    httpObj.open( method , filePath , asyncFlag );
    httpObj.onreadystatechange = function()
    {
      if (httpObj.readyState == 4){
          self.callBack(httpObj);
          // file:///やftp://の場合statusが0になるのでローカルでは下は使えない
          // if(httpObj.status == 200) self.callBack(httpObj);
      }
    }
    if(method=="POST") httpObj.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
    httpObj.send( data );
},
createHttpRequest: function()
{
    if(window.ActiveXObject){
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                return new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e2) {
                return null;
            }
         }
    } else if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    } else {
        return null;
    }
},
callBack : function(httpObj)
{
    if(this.onComplete){
        if(typeof this.onComplete == "string" && this.bindObj) this.bindObj[this.onComplete](httpObj);
        else this.onComplete(httpObj);
    }
}
}// hmdx.Comm.prototype

/*  画像ロード ----------------------------------------------------------------------- */
hmdx.ImageLoader = function(targetImgElem)
{
    if(targetImgElem) this.init(targetImgElem);
    this.parent = null;
    this.bindObj = null;
    this.onComplete = null;
}

hmdx.ImageLoader.prototype = {

init : function(targetImgElem)
{
    this.element = targetImgElem;
},
requestImage : function(filePathStr, altTextStr)
{
    if(!altTextStr) altTextStr = "画像（タイトル不明）";
    var img = new Image();
    img.parent = this;
    img.alt = altTextStr;
    img.onload = function(){ this.parent.setSrc(this) };
    img.src = filePathStr;
},
setSrc : function(imgObj)
{
    this.element.alt = imgObj.alt;
    this.element.src = imgObj.src;
    if(this.onComplete){
        if(typeof this.onComplete == "string" && this.bindObj) this.bindObj[this.onComplete](imgObj);
        else this.onComplete(imgObj);
    }
}

} // hmdx.ImageLoader.prototype

