/*******************************************************************************
* Copyright (C) Inpros Marketing Systems Co.,Ltd. All Rights Reserved
* All rights reserved.
* Project Downjones:
* $Author: czarft $
* $Date:  $
* $Source:  $
* $Revision: $
*******************************************************************************/
/** @file
 *  @brief
 *
 */
var aMenuList = new Array();
var sUserAgent = navigator.userAgent;
var isIE = Prototype.Browser.IE;
var OP = Prototype.Browser.Opera;
var Safari = Prototype.Browser.WebKit;
var nowClick = false;
jQuery.noConflict();
Event.observe(window, 'load', function() {
    navigationDropDown.init();
 	if ($('news_button')) {
		var newsoption = {
		  firstname: "mynews",
		  secondname: "showhere",
		  thirdname:"news_display",
		  fourthname:"news_button",
		  newsspeed:'8000'
		}
		jQuery.init_plus(newsoption);

		/*var myoffset=jQuery('#news_button').offset();
		var mytop=myoffset.top-190;//161
		var myleft=myoffset.left-470;
		jQuery('#news_button').css({top:mytop,left:myleft});*/
	}

});
//Event.observe(window, 'resize', function() {
//    setupMenu ("resize");
//});
var navigationDropDown = function(){
    var aMenuitems = new Array ();
    var aLastestNews = new Array ();
    var objSubnavNews;
    var objSubnavTopics;
    var objSubnav;
    var objNaviLI;
    return {
            init : function(){
               objSubnav = $("boxSubnav").cloneNode(true);
               $("boxSubnav").remove();
               var listNavi = $$("#navigation li");

               if (typeof listNavi =="object") {
                   objNaviLI = listNavi[0].cloneNode(true);
               }
               $('navigation').update();
               new Ajax.Request('../../../imagesNew/xml/data.xml?cache='+new Date().getTime(), {
                  method: 'get',
                  onSuccess: function(res) {
                     navigationDropDown.onSuccessData(res);
                  },
                  onFailure : function (transport){
                     alert('please check connection');
                  }
                });
            },
            onSuccessData : function (res) {
                if (res.responseXML) {
                    var xml = new JKL.ParseXML(res);
                    var aData = xml.parse();
                    if (typeof aData['mainmenubar']=="undefined") return ;
                    aData = aData['mainmenubar']['menuitems'];
                    var Count = (typeof aData.length == "undefined")?1:aData.length;
                    var index=0;
                    var newDivObj;
                    while (index<Count) {
                        var aTmp = (typeof aData.length == "undefined")?aData:aData[index];
                        newDivObj = this.createObjectSubnav ();
                        this.createObjectSubnavNews (newDivObj,aTmp);
                        this.setUpNavigation(newDivObj,aTmp['menuname'],aTmp['menulink']);

                        newDivObj.id = "boxSubnav"+index;
                        aMenuList.push(newDivObj.id);
                        if (typeof aTmp['lastestnews'] != "undefined" || typeof aTmp['topics'] != "undefined"){
                            if (isIE) {//Only IE
                                newDivObj.style.filter = "progid:DXImageTransform.Microsoft.Alpha(Opacity=90, Style=0)"
                                newDivObj.style.filter = "progid:DXImageTransform.Microsoft.Shadow(direction=135,color=#dddddd,strength=7)";
                            } else {
                               jQuery(newDivObj).dropShadow({left:4,top:5,blur:4,opacity:'0.3'});
                               $("boxSubnav"+index+"_dropShadow").style.visibility = "hidden";
                            }
                            newDivObj.setStyle({
                              visibility:'hidden',
                              opacity:0.9
                            });
                        } else {
                            newDivObj.remove();
                        }
                        index++;
                    }
                    $('navigation').style.visibility = "visible";
                }
            },
            createObjectSubnav : function () {
               var objTmp = objSubnav.cloneNode(true);
               $('wrapper').appendChild(objTmp);
               return objTmp;
            },
            createObjectSubnavNews : function (obj,Data) {
               if (typeof Data['lastestnews'] != "undefined") {
                   var aData  = Data['lastestnews']['item'];
                   var objTmp = obj.down().cloneNode(true);
                   var tagP =  objTmp.down(0);
                   var tagLI = obj.down('li').cloneNode(true);
                   var tagUL = objTmp.down().next();
                   tagUL.update();
                   obj.down().remove();
                   var Count = (typeof aData.length == "undefined")?1:aData.length;
                   var index=0;
                   while (index<Count) {
                        var aTmp = (typeof aData.length == "undefined")?aData:aData[index];
                        if (typeof aTmp['headtext']!= "undefined") {
                            tagP.update(aTmp['headtext']);
                        } else {
                            var tmpO = tagLI.cloneNode(true);
                            tmpO.down(0).update(aTmp['head']);
                            tmpO.down(0).href = aTmp['link_url'];
                            tagUL.appendChild(tmpO);
                        }
                        index++;
                   }
                   obj.appendChild(objTmp);
               } else {
                   obj.down().remove();
               }

               if (typeof Data['topics'] != "undefined") {
                  var aData = Data['topics']['item'];
                  this.createObjectSubnavTopics (obj,aData);
               } else {
                 obj.down().remove();
               }

            },
            createObjectSubnavTopics : function (obj,aData) {
               var objTmp = obj.down().cloneNode(true);
               var tagP   = objTmp.down(0);
               var tagLI  = obj.down().down('li').cloneNode(true);
               var tagUL  = objTmp.down().next();
               tagUL.update();
               obj.down().remove();
               var Count = (typeof aData.length == "undefined")?1:aData.length;
               var index=0;
               while (index<Count) {
                    var aTmp = (typeof aData.length == "undefined")?aData:aData[index];
                    if (typeof aTmp['headtext']!= "undefined") {
                        tagP.update(aTmp['headtext']);
                    } else {
                        var tmpO = tagLI.cloneNode(true);
                        tmpO.down(0).update(aTmp['head']);
                        tmpO.down(0).href = aTmp['link_url'];
                        tagUL.appendChild(tmpO);
                    }
                    index++;
               }
               obj.appendChild(objTmp);
            },
            setUpNavigation : function (objChild,name,linkS) {
                var objNavi = objNaviLI.cloneNode(true);
                objNavi.down(0).href = linkS;
                objNavi.down(0).innerHTML = name;
                $('navigation').appendChild(objNavi);
                if (typeof objChild !="undefined") {
                    var aWin = getWindowWidthHigh();
                    var aOffsetT = Position.cumulativeOffset($('wrapper'));
                    var aOffset = Position.cumulativeOffset(objNavi);
                    var x = (isIE)?(aOffset[0]-4) :(aOffset[0]-6);
                    x-=aOffsetT[0] - 6;
                    if (aWin[0] > objChild.getWidth()+aOffset[0] + aOffsetT[0]) {

                    } else {
                        x-=objChild.getWidth()- 70;
                    }
                    var y = aOffset[1]+28+"px";

                    objChild.setStyle({
                      top: y,
                      left: x+"px"
                    });
                    //--[event]-------
                    objNavi.observe('mouseover', function(event){
                        nowClick = true;
                        checkBeforeShow(objChild);
                    });
                    objNavi.observe('mouseout', function(event){
                        nowClick = false;
                        setTimeout ("hideAll();",100);
                    });
                    objChild.observe('mouseover', function(event){
                        nowClick = true;
                        checkBeforeShow(objChild);
                    });
                    objChild.observe('mouseout', function(event){
                        nowClick = false;
                        setTimeout ("hideAll();",100);
                    });

                    $('bodyId').observe('onclick', function(event){
                        nowClick = false;
                        setTimeout ("hideAll();",100);
                    });
                }
            }

    };
}();
function  checkBeforeShow (obj) {
    nowClick = false;
    if (obj.style.visibility!= "visible") {
        if($(obj.id+"_dropShadow")) {
           $(obj.id+'_dropShadow').style.visibility = 'visible';
        }
        obj.style.visibility = 'visible';
    }
    hideAll (obj.id);
}

function hideAll (exceptId) {
    if (nowClick == false) {
        nowClick = true;
        aMenuList.each(function(index) {
            var tmpObj = document.getElementById (index);
            if (typeof tmpObj !="undefined" && tmpObj && exceptId!=index) {
                if (tmpObj.style.visibility== "visible") {
                    tmpObj.style.visibility = "hidden";
                    if($(index+"_dropShadow")) {
                       $(index+"_dropShadow").style.visibility = "hidden";
                    }
                }
            }
        });
    }
}

function getWindowWidthHigh() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth,myHeight];
}


/*------------------------------------------------------------------------------*/
//  Class Parse XML
//
//  jkl-parsexml.js ---- JavaScript Kantan Library for Parse XML
//  From http://www.kawa.net/works/js/jkl/parsexml.html
//  modofied By czarft 2006-07-11 for parseOnly not load URL
//  note: now not add CSV,JSON,TextFile
if ( typeof(JKL) == 'undefined' ) {
    JKL = function() {};
}

// ================================================================
//  class: JKL.ParseXML

JKL.ParseXML = function (resXML) {
    if (!resXML)return false;
    this.req = resXML;
    return this;
};
// ================================================================
//  class variables

JKL.ParseXML.VERSION = "0.19";
JKL.ParseXML.MIME_TYPE_XML  = "text/xml";
JKL.ParseXML.MAP_NODETYPE = [
    "",
    "ELEMENT_NODE",                 // 1
    "ATTRIBUTE_NODE",               // 2
    "TEXT_NODE",                    // 3
    "CDATA_SECTION_NODE",           // 4
    "ENTITY_REFERENCE_NODE",        // 5
    "ENTITY_NODE",                  // 6
    "PROCESSING_INSTRUCTION_NODE",  // 7
    "COMMENT_NODE",                 // 8
    "DOCUMENT_NODE",                // 9
    "DOCUMENT_TYPE_NODE",           // 10
    "DOCUMENT_FRAGMENT_NODE",       // 11
    "NOTATION_NODE"                 // 12
];

// ================================================================
//  method: parse()
//  return: parsed object
//  Download a file from remote server and parse it.

JKL.ParseXML.prototype.parse = function () {
    //alert('parse');
    var data = this.parseResponse();
    return data;
};
// ================================================================
//  method: parseResponse()
JKL.ParseXML.prototype.parseResponse = function () {
    //alert('parseResponse');
    var root = this.documentElement();
    var data = this.parseDocument( root );
    return data;
};
// ================================================================
//  method: documentElement()
//  return: XML DOM in response body

JKL.ParseXML.prototype.documentElement = function() {
    // debug.print( "documentElement: "+this.req );
    //alert('documentElement');
    if ( ! this.req ) return;
    if ( this.req.responseXML ) {
        return this.req.responseXML.documentElement;    // XMLHTTPRequest
    } else {
        return this.req.documentElement;                // IXMLDOMDocument
    }
};

// ================================================================
//  convert from DOM root node to JavaScript Object
//  method: parseElement( rootElement )

JKL.ParseXML.prototype.parseDocument = function ( root ) {
    // debug.print( "parseDocument: "+root );
    //alert('parseDocument');
    if ( ! root ) return;

    var ret = this.parseElement( root );            // parse root node
    // debug.print( "parsed: "+ret );

    if ( this.usearray == true ) {                  // always into array
        ret = [ ret ];
    } else if ( this.usearray == false ) {          // always into scalar
        //
    } else if ( this.usearray == null ) {           // automatic
        //
    } else if ( this.usearray[root.nodeName] ) {    // specified tag
        ret = [ ret ];
    }

    var json = {};
    json[root.nodeName] = ret;                      // root nodeName
    return json;
};

// ================================================================
//  every child/children into array
JKL.ParseXML.prototype.setOutputArrayAll = function () {
    this.setOutputArray( true );
};
//  a child into scalar, children into array
JKL.ParseXML.prototype.setOutputArrayAuto = function () {
    this.setOutputArray( null );
};
//  every child/children into scalar (first sibiling only)
JKL.ParseXML.prototype.setOutputArrayNever = function () {
    this.setOutputArray( false );
};
//  specified child/children into array, other child/children into scalar
JKL.ParseXML.prototype.setOutputArrayElements = function ( list ) {
    this.setOutputArray( list );
};
//  specify how to treate child/children into scalar/array
JKL.ParseXML.prototype.setOutputArray = function ( mode ) {
    if ( typeof(mode) == "string" ) {
        mode = [ mode ];                // string into array
    }
    if ( mode && typeof(mode) == "object" ) {
        if ( mode.length < 0 ) {
            mode = false;               // false when array == []
        } else {
            var hash = {};
            for( var i=0; i<mode.length; i++ ) {
                hash[mode[i]] = true;
            }
            mode = hash;                // array into hashed array
            if ( mode["*"] ) {
                mode = true;            // true when includes "*"
            }
        }
    }
    this.usearray = mode;
};
// ================================================================
//  method: addNode( hash, key, count, value )

JKL.ParseXML.prototype.addNode = function ( hash, key, cnts, val ) {
    if ( this.usearray == true ) {              // into array
        if ( cnts == 1 ) hash[key] = [];
        hash[key][hash[key].length] = val;      // push
    } else if ( this.usearray == false ) {      // into scalar
        if ( cnts == 1 ) hash[key] = val;       // only 1st sibling
    } else if ( this.usearray == null ) {
        if ( cnts == 1 ) {                      // 1st sibling
            hash[key] = val;
        } else if ( cnts == 2 ) {               // 2nd sibling
            hash[key] = [ hash[key], val ];
        } else {                                // 3rd sibling and more
            hash[key][hash[key].length] = val;
        }
    } else if ( this.usearray[key] ) {
        if ( cnts == 1 ) hash[key] = [];
        hash[key][hash[key].length] = val;      // push
    } else {
        if ( cnts == 1 ) hash[key] = val;       // only 1st sibling
    }
};
// ================================================================
//  convert from DOM Element to JavaScript Object
//  method: parseElement( element )

JKL.ParseXML.prototype.parseElement = function ( elem ,keyxx) {
    //alert("come from key = "+keyxx);
    // debug.print( "nodeType: "+JKL.ParseXML.MAP_NODETYPE[elem.nodeType]+" <"+elem.nodeName+">" );
    //  COMMENT_NODE
    if ( elem.nodeType == 7 ) {
        return;
    }

    if ( elem.nodeType == 3 || elem.nodeType == 4 ) {
        var bool = elem.nodeValue.match( /[^\x00-\x20]/ ); // for Safari
        if ( bool == null ) return;     // ignore white spaces
        return elem.nodeValue;
    }

    var retval;
    var cnt = {};

    //  parse attributes
    if ( elem.attributes && elem.attributes.length ) {
        retval = {};
        for ( var i=0; i<elem.attributes.length; i++ ) {
            var key = elem.attributes[i].nodeName;
            if ( typeof(key) != "string" ) continue;
            var val = elem.attributes[i].nodeValue;
            if ( ! val ) continue;
            if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
            cnt[key] ++;
            this.addNode( retval, key, cnt[key], val );
        }
    }

    //  parse child nodes (recursive)
    if ( elem.childNodes && elem.childNodes.length ) {
        var textonly = true;
        if ( retval ) textonly = false;        // some attributes exists
        var lenN = elem.childNodes.length;
        for ( var i=0; i<lenN && textonly; i++ ) {
            var ntype = elem.childNodes[i].nodeType;
            if ( ntype == 3 || ntype == 4 ) continue;
            textonly = false;
        }
        if ( textonly ) {
            if ( ! retval ) retval = "";
            var lenN2 = elem.childNodes.length;
            for ( var i=0; i<lenN2; i++ ) {
                retval += elem.childNodes[i].nodeValue;
            }
        } else {
            if ( ! retval ) retval = {};
            var lenN3 = elem.childNodes.length;
            for ( var i=0; i<lenN3; i++ ) {
                var key = elem.childNodes[i].nodeName;

                if ( typeof(key) != "string" ) continue;
                //alert("--->"+elem.childNodes[i].childNodes.length+" "+key);
                var val = this.parseElement( elem.childNodes[i],key );
                if ( ! val ) {//Edit By czarft
                    val = "";
                }
                if ( typeof(cnt[key]) == "undefined" ) cnt[key] = 0;
                cnt[key] ++;
                //alert("-->ADD KEY ="+key);
                this.addNode( retval, key, cnt[key], val );
            }
        }
    }
    return retval;
};

// ================================================================
//  method: responseText()
//  return: text string in response body

JKL.ParseXML.prototype.responseText = function() {
    return this.req.responseText;
}


function print_r(aData, keyName, deep) {
    var sRet = '';

    if (typeof keyName == 'undefined') {
        keyName = '';
    }

    if (typeof deep == 'undefined') {
        deep = 1;
    } else {
        deep = deep + 1;
        if (deep > 20)
            return 'max deep reach';
    }
    //&& aData instanceof Array
    if (typeof aData == 'object') {
        for (var a in aData) {
            if (aData.propertyIsEnumerable(a)) {
                sRet = sRet + print_r(aData[a], keyName + "[" + a + "]", deep);
            }
        }
        return sRet;
    } else {
         return keyName + " = " + aData + "\n";
    }
}

/**
 * Debug  array
 */
function p(data) {
    var tex = document.createElement("TEXTAREA");
    if(typeof data=='string'){
        tex.value = data;
    }else{
        tex.value = print_r(data);
    }
    tex.style.position = "absolute";
    tex.style.left = "150px";
    tex.style.top = "50px";
    tex.style.width = "700px";
    tex.style.height = "500px";
    tex.style.zIndex = 3;
    tex.focus();
    tex.onblur = Function("myRemoveNode(this);");
    document.getElementsByTagName('BODY')[0].appendChild(tex);

}