﻿//flashID：需要插入flashID
//elm：需要插入flash的外层HTMLElement
//url: flash的地址
//w: flash宽
//h: flash高
//wmode: 背景是否透明 transparent

function insertFlash(flashID,elm, url, wmode, w, h) {
if (!document.getElementById(elm)) return;
var str = '';
str += '<object id="'+flashID+'" width="'+ w +'" height="'+ h +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
str += '<param name="movie" value="'+ url +'">';
str += '<param name="wmode" value="'+ wmode +'">';
str += '<embed width="'+ w +'" height="'+ h +'" src="'+ url +'" quality="autohigh" wmode="opaque" type="application/x-shockwave-flash" plugspace="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed>';
str += '</object>';
document.getElementById(elm).innerHTML = str;
}

function includeJs(option)
 {
        var _doc = document.getElementsByTagName('head')[0];
        var js = document.createElement('script');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', option.file);
        _doc.appendChild(js);

        if (!/*@cc_on!@*/0) { //if not IE
            //Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload
            js.onload = function () 
            {
          option.Success();//alert('Firefox2、Firefox3、Safari3.1+、Opera9.6+ support js.onload');

            }
        } else {
        //IE6、IE7 support js.onreadystatechange
        js.onreadystatechange = function () {
        if (js.readyState == 'loaded' || js.readyState == 'complete') {
        option.Success();    //alert('/IE6、IE7 support js.onreadystatechange');
           }
        }
    }

return false;
}

function loadFlash(flashID,elm,url,wmode,w,h,onupdata,onload)
{ 
 insertFlash(flashID,elm,url,wmode,w,h);
  var CheckFlashStatus=function()
    {
        var total= ani_GetFlashState(flashID,"loaded");    
        if(total<100)
        {
          onupdata(total);
        }
        else
        {
      
        onload();        
        clearInterval(flashtimer);
        }
    }
  var flashtimer=setInterval(CheckFlashStatus,10);
      
 
 
}

function ani_GetFlashState(FlashObjectID,v)
{
var ie = /*@cc_on!@*/false;
var FlashObject=$ID(FlashObjectID);
/* 获得当前FLASH的状态值[v=loaded(当前下载状态),v=current(当前播放针数),v=total(总播放针数)] */
    if(ie)
    {
    if(v=='loaded')
    return FlashObject.PercentLoaded();
    else if(v=='current')
    return FlashObject.CurrentFrame();
    else if(v=='total')
    return FlashObject.TotalFrames;
    }
    else
    {
      return 100;

    }
}
function loadImage(url, callback) {
    var img = new Image(); //创建一个Image对象，实现图片的预下载
    img.src = url;
   
    if (img.complete) { // 如果图片已经存在于浏览器缓存，直接调用回调函数
        callback.call(img);
        return; // 直接返回，不用再处理onload事件
    }

    img.onload = function () { //图片下载完毕时异步调用callback函数。
        callback.call(img);//将回调函数的this替换为Image对象
    };
};


/*
批量图片预加载
loadImages({
       url: expr, // 必须参数,  可为 url字符串, url数组, 或返回值符合前两者的函数
       ready: function( images, status){},         // 初始化就绪时调用
       complete: function(images, status){},     //全部加载完成时调用
       onload: function(status){},   //单个img加载成功时调用
       onerror: function(status){},  //单个img加载错误时调用
       oncomplete: function(status),  //单个img处理完成时调用
       timeout: 15                              //超时后, 无条件触发 '处理完成'
});
*/
function loadImages( s ){
    var urlset = [], undefined, toString = Object.prototype.toString;
    switch( toString.apply(s.url) ){
        case '[object String]': urlset[urlset.length] = s.url; break;
        case '[object Array]': if(!s.url.length){ return false; } urlset = s.url; break;
        case '[object Function]': s.url = s.url(); return imageLoad( s );
        default: return false;
    }
    var imgset =[], r ={ total:urlset.length, load:0, error:0, abort:0, complete:0, currentIndex:0 }, timer,
        _defaults = {
            url:'',
            onload: 'function',
            onerror: 'function',
            oncomplete: 'function',
            ready: 'function',
            complete: 'function',
            timeout: 15
        };
    for( var v in _defaults){
        s[v] = s[v]===undefined? _defaults[v]: s[v];
    }
    s.timeout = parseInt( s.timeout ) || _defaults.timeout;
    timer = setTimeout( _callback, s.timeout*1000);
    // 生成 image 对象数组
    for( var i=0,l=urlset.length,img; i<l; i++){
        img         = new Image();
        img.loaded    = false;
        imgset[imgset.length] = img;
    }
    // onload & onerror 绑定
    for( i=0,l=imgset.length; i<l; i++){
        imgset[i].onload      = function(){ _imageHandle.call(this, 'load', i ); };
        imgset[i].onerror     = function(){ _imageHandle.call(this, 'error', i ); };
        imgset[i].onabort     = function(){ _imageHandle.call(this, 'abort', i ); };
        imgset[i].src         = ''+urlset[i];
    }
    // ready 事件回调
    if( _isFn(s.ready) ){ s.ready.call({}, imgset, r); }    
    // onload & onerror 句柄
    function _imageHandle( handle, index ){
        r.currentIndex = index;
        switch( handle ){
            case 'load':
                this.onload  = null; this.loaded = true; r.load++;
                // onload 事件回调
                if( _isFn(s.onload) ){ s.onload.call(this, r); }    
                break;
            case 'error': r.error++;
                // onerror 事件回调
                if( _isFn(s.onerror) ){ s.onerror.call(this, r); }
                break;
            case 'abort': r.abort++; break;
        }
        r.complete++;
        // oncomplete 事件回调
        if( _isFn(s.oncomplete) ){ s.oncomplete.call(this, r); }
        // 判断全局加载
        if( r.complete===imgset.length ){  _callback(); }
    }
    function _callback(){
        clearTimeout( timer );
        if( _isFn(s.complete) ){ s.complete.call({}, imgset, r); }
    }
    function _isFn(fn){ return toString.apply(fn)==='[object Function]'; }
    return true;
}
//图片等比缩放 防止缩略图变形
function proDownImage(ImgD,proMaxWidth,proMaxHeight){
　　　var image=new Image();
　　　image.src=ImgD.src;
　　　if(image.width>0 && image.height>0){
　　　var rate = (proMaxWidth/image.width < proMaxHeight/image.height)?proMaxWidth/image.width:proMaxHeight/image.height;
　　if(rate <= 1){　
　　 ImgD.width = image.width*rate;
　　 ImgD.height =image.height*rate;
　　}
　　else {
　　　　　　　　　　　　　ImgD.width = image.width;
　　　　　　　　　　　　　ImgD.height =image.height;
　　　　　　　　　}
　　　}
}

//获取页面元素的绝对定位
var getAbsPos = function(pTarget)
{
                     var _left = _top = _right = _bottom = 0;
                     
                     _right+=pTarget.clientWidth;
                     _bottom+=pTarget.clientHeight; 
                     
                     
                     
                     if(pTarget.style.position != "absolute")
                     {
                            while(pTarget.offsetParent)
                            {
                                          
                                          _left += pTarget.offsetLeft;
                                          _top += pTarget.offsetTop;

                                          pTarget = pTarget.offsetParent;
                            }
                     }
                     

                     
                     _left += pTarget.offsetLeft;
                     _top += pTarget.offsetTop;
                     
                     _right+=_left;
                     _bottom+=_top; 
                     
             
                     
                     
                     return {left:_left,top:_top,right:_right,bottom:_bottom};
                     
}

function getElementPos(elementId) {
 var ua = navigator.userAgent.toLowerCase();
 var isOpera = (ua.indexOf('opera') != -1);
 var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
 var el = document.getElementById(elementId);
 if(el.parentNode === null || el.style.display == 'none') {
  return false;
 }      
 var parent = null;
 var pos = [];     
 var box;     
 if(el.getBoundingClientRect)    //IE
 {         
  box = el.getBoundingClientRect();
  var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
  return {x:box.left + scrollLeft, y:box.top + scrollTop};
 }else if(document.getBoxObjectFor)    // gecko    
 {
  box = document.getBoxObjectFor(el); 
  var borderLeft = (el.style.borderLeftWidth)?parseInt(el.style.borderLeftWidth):0; 
  var borderTop = (el.style.borderTopWidth)?parseInt(el.style.borderTopWidth):0; 
  pos = [box.x - borderLeft, box.y - borderTop];
 } else    // safari & opera    
 {
  pos = [el.offsetLeft, el.offsetTop];  
  parent = el.offsetParent;     
  if (parent != el) { 
   while (parent) {  
    pos[0] += parent.offsetLeft; 
    pos[1] += parent.offsetTop; 
    parent = parent.offsetParent;
   }  
  }   
  if (ua.indexOf('opera') != -1 || ( ua.indexOf('safari') != -1 && el.style.position == 'absolute' )) { 
   pos[0] -= document.body.offsetLeft;
   pos[1] -= document.body.offsetTop;         
  }    
 }              
 if (el.parentNode) { 
    parent = el.parentNode;
   } else {
    parent = null;
   }
 while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { // account for any scrolled ancestors
  pos[0] -= parent.scrollLeft;
  pos[1] -= parent.scrollTop;
  if (parent.parentNode) {
   parent = parent.parentNode;
  } else {
   parent = null;
  }
 }
 return {x:pos[0], y:pos[1]};
}

//获取鼠标坐标
function mouseCoords(ev) 
{ 
if(ev.pageX || ev.pageY)
{ 
return {x:ev.pageX, y:ev.pageY}; 
} 
return {      x:ev.clientX + document.body.scrollLeft - document.body.clientLeft, 
y:ev.clientY + document.body.scrollTop     - document.body.clientTop 

} 
}

//附加事件
    function addEventListener(obj,eventType,fn)
    {
    if(obj.addEventListener)
     {
        obj.addEventListener(eventType,fn,false);
     }
     else if(obj.attachEvent)
     {      
        obj.attachEvent("on"+eventType,fn)
     }
     else
     obj["on"+eventType]=fn;
    }


        //移出事件
    function removeEventListener(obj,eventType,fn)
    {
     if(obj.detachEvent)
     {
        obj.detachEvent("on"+eventType,fn)
     }
     else if(obj.removeEventListener)
     {
        obj.removeEventListener(eventType,fn,false);
     
     }
      else
         obj["on"+eventType]=null;
    }


//当文件准备时执行
function Ready(fn)
{
  Ready.isReady=function()
   {
     if(document && document.body && document.getElementById && document.getElementsByName && document.readyState=="complete")
      return true;
      else
     return false;
   }
    
    function updateReadyState()
    {  
      try
      {
       document.readyState="complete";
       }
       catch(e)
       {}
    }
    
   function run()
  {
       if(Ready.isReady())
       {
         for(var i=0;i<Ready.readyList.length;i++)
          {
           var fn=Ready.readyList[i];
           fn();
          }
          
           Ready.readyList=[];
           clearInterval(Ready.readyTimer);

       }
       
  }

      
      if(!Ready.readyTimer)
      {
        Ready.readyList=[];
        window.onload=updateReadyState
        addEventListener(window,"load",updateReadyState);
        addEventListener(window,"load",run);
        Ready.readyTimer=setInterval(run,100);
        
      }
      
   if(fn)
   {
      if(Ready.isReady())
      { 

        fn();
        return;
      }
      Ready.readyList.push(fn);
  }

    

}


//处理查询字符串
function getQuery(name,string)   
{   
    string=string || top.window.location.search
    
    var reg = new RegExp("\S*[&?]{1}"+ name +"=([^?&]*)");
    var r=string.match(reg);
    
    if (r!=null)
    return decodeURIComponent(r[1]);
     
    return null;   
}

//写cookies

document.setCookie=function(name,value)

{

var Days = 30;

var exp = new Date(); 

exp.setTime(exp.getTime() + Days*24*60*60*1000);

document.cookie = name + "="+ escape (encodeURIComponent(value)) + ";expires=" + exp.toGMTString();

}

//读取cookies

document.getCookie=function(name)

{

var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

if(arr=document.cookie.match(reg)) 
return decodeURIComponent(arr[2]);

else return null;

//alert(getCookie("UserInfo"));

//这是读取cookies的函数 
     //readcook(要读取的cookies的名字)

}

//删除cookies

document.delCookie=function(name)

{

var exp = new Date();

exp.setTime(exp.getTime() - 1);

var cval=getCookie(name);

if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();

}
  function AddFavorite(sURL, sTitle)
    {
        try
        {
            window.external.addFavorite(sURL, sTitle);
        }
        catch (e)
        {
            try
            {
                window.sidebar.addPanel(sTitle, sURL, "");
            }
            catch (e)
            {
                alert("加入收藏失败，请使用Ctrl+D进行添加");
            }
        }
    }
    
    function SetHome(obj,vrl)
    {
        try
        {
                obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl);
        }
        catch(e){
                if(window.netscape) {
                        try {
                                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
                        } 
                        catch (e) { 
                                alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将[signed.applets.codebase_principal_support]设置为'true'"); 
                        }
                        var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
                        prefs.setCharPref('browser.startup.homepage',vrl);
                 }
        }
    }
    

function showMenu(id)
{
 $ID(id).style.display=$ID(id).style.display=="none"?"":"none";
}


// JavaScript Document for public functions
function $ID(id){	//return HTML object by object id
	var obj = false;
	obj = document.getElementById(id);			

	if(obj == null){
		obj = parent.document.getElementById(id);
	}

	return obj ? obj : undefined;
}

function $V(id){	//return HTML object's value
	if( $ID(id) != undefined){
		return  $ID(id).value;
	}else{
		return null;
	}
}

function $Len(id){
	if( $ID(id) != undefined){
		return  $ID(id).options.length;
	}else{
		return null;
	}
}

function $Rows(id){
	if( $ID(id) != undefined){
		return  $ID(id).rows.length;
	}else{
		return null;
	}
}

//------ajax---------
function Ajax(option)
{
var request;
    (function createRequest()
    {
    try
    {
    request=new XMLHttpRequest();
    }
    catch(e)
    {
    try
    {
    request=new ActiveXObject("microsoft.XMLHTTP");

    }
    catch(e2)
    {
    try
    {
    request=new ActiveXObject("msxml2.XMLHTTP");
    }
    catch(e3)
    {
    alert("不支持Ajax");
    }
    }
    }
    })();

    (function sendRequest()
    {
    request.open(option.Method,option.URL,true);
    if(option.Method=="POST")
    {
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    }
    request.onreadystatechange =requestCallBack;
    request.send(option.Params);
    })();

    function requestCallBack()
    {
        if(request.readyState==4)
        {
            if(request.status==200)
            {
            option.Success(request);
            }
            else
            option.Failure(request);
        }

    }

}

function ScriptProxyTag(option)
{
 
 var tag= $ID("ScriptProxyTag");
 if(tag)
 {
  document.body.removeChild(tag);
 }
 
 var tag=document.createElement("script");
 
 tag.type="text/javascript";
 tag.id="ScriptProxyTag"
 var exp=new RegExp(/\S+([?&]){1}\S+/);
 if(option.src.match(exp))
 {
     tag.src=option.src+"&ResultValueName=Result&CallBackFunction="+option.CallBackFunction; 
 }
 else
 {
     tag.src=option.src+"?ResultValueName=Result&CallBackFunction="+option.CallBackFunction; 
 }
 document.body.appendChild(tag);

}
var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

//------select options control-----
function addOptions(selectId, arrValue, arrText){
	try{
		for(i = 0, arrLen = arrValue.length; i < arrLen; i++){
			if(arrText[i] != "" && arrValue[i] != ""){
				$ID(selectId).options.add( new Option(arrText[i], arrValue[i]) );
			}
		}
	}catch(e){}
}

function clearOptions(selectId){
	try{
		$ID(selectId).options.length=0;
	}catch(e){}
}

function setSelected(selectId, index){
	try{
		$ID(selectId).options[index].selected = true;
	}catch(e){}
}

//-----------set values-------
function setSrc(objId, url){
	try{
		$ID(objId).src = url;
	}catch(e){}
}

function setInnerHTML(objId, str){
	try{
		$ID(objId).innerHTML = str;
	}catch(e){}
}

function addInnerHTML(objId, str, tag){
	try{
		var tempStr = $ID(objId).innerHTML;
		if(tempStr.indexOf(str) == -1){
			$ID(objId).innerHTML += tag + str;
		}
	}catch(e){}
}

function setValue(objId, value){
	try{
		$ID(objId).value = value;
	}catch(e){}
}

function subFrameDoc(iframeId){
	try{
		var frameDoc;

		if(document.all){
		    try{
			frameDoc = window.frames[iframeId].document;
   		    }catch(e){
		        try{
				frameDoc = parent.window.frames[iframeId].document;
		        }catch(e){alert("Your IE's version is to old!\nPlease try some new one!");}
		    }
		}else{
		    try{
			frameDoc = document.getElementById(iframeId).contentWindow.document;
		    }catch(e){
			try{
				frameDoc = parent.document.getElementById(iframeId).contentWindow.document;
			}catch(e){alert("Your Firefox's version is to old!\nPlease try some new one!");}
		    }
		}

		return frameDoc ? frameDoc : null;
	}catch(e){return false;}
}

function setSubFrameValue(iframeId, objId, str){
	var frameDoc = subFrameDoc(iframeId);
	frameDoc.getElementById(objId).value = str;
}

function resetValue(objId){
	try{
		$ID(objId).value = "";
	}catch(e){}
}

function setBgColor(obj, color){
	try{
		if(obj.style.backgroundColor == ""){
			obj.style.backgroundColor = color;
		}else{
			obj.style.backgroundColor = "";
		}
	}catch(e){}
}

function setWidth(objId, value){
	try{
		$ID(objId).style.width = value;
	}catch(e){}	
}//set style width

function setHeight(objId, value){
	try{
		$ID(objId).style.height = value;
	}catch(e){}	
}//set style height

function setTop(objId, value){
	try{
		$ID(objId).style.top = value;
	}catch(e){}	
}//set style top

function setLeft(objId, value){
	try{
		$ID(objId).style.left = value;
	}catch(e){}	
}//set style left

function setRight(objId, value){
	try{
		$ID(objId).style.right = value;
	}catch(e){}	
}//set style right

function setBottom(objId, value){
	try{
		$ID(objId).style.bottom = value;
	}catch(e){}	
}//set style bottom

//--------check value-----
function isNull(objId){
	if($ID(objId) != undefined && $ID(objId).value != ""){
		return false;
	}else{
		return true;
	}
}

//--------disable object------
function disable(objId){
	try{
		$ID(objId).disabled = true;
	}catch(e){}	
}

function release(objId){
	try{
		$ID(objId).disabled = false;
	}catch(e){}
}

//--------show or hide div window----
function show(objId){
	try{
		if($ID(objId).style.display != "block"){
			$ID(objId).style.display = "block";
		}else{
			$ID(objId).style.display = "none";
		}
	}catch(e){}		
}

//---------calculate--------
function addExpression(objId){
	var value = 0.0;
	try{
		var arr = new Array();
		arr = ($ID(objId).value).split("+");

		var i = 0;
		for(i=0; i<arr.length; i++){
			value += parseFloat(arr[i]);
		}
	}catch(e){alert("add error");}
	return parseFloat(value);
}

//----------string decode-----
function trim(str){
	var re = / /g;
	str = str.replace(re, "");
	return str;
}

function trin(str){
	var re = /\n/g;
	str = str.replace(re, "");
	re = /\r/g;
	str = str.replace(re, "");
	return str;
}

//----location redirect----
function ifDel(url){
	if(confirm("确定删除？")){
		window.location.href=url;
	}
}

//----div drag----
function drag(div){
	div.onmousedown=function(a){
		//change div background color
		div.style.backgroundColor = "#0080C0";
	
		var d=document;
		if(!a)a=window.event;
		var x=a.layerX?a.layerX:a.offsetX,y=a.layerY?a.layerY:a.offsetY;
		if(div.setCapture){
			div.setCapture();
		}
		else if(window.captureEvents){
			window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
		}

		d.onmousemove=function(a){
			if(!a)a=window.event;
			if(!a.pageX)a.pageX=a.clientX;
			if(!a.pageY)a.pageY=a.clientY;
			var tx=a.pageX-x,ty=a.pageY-y;
			div.style.left=tx;
			div.style.top=ty;
		};

		d.onmouseup=function(){
			//change back div background color
			div.style.backgroundColor = "#00A3F0";

			if(div.releaseCapture)
				div.releaseCapture();
			else if(window.captureEvents)
				window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
			d.onmousemove=null;
			d.onmouseup=null;
		};
	};
}

//----disable some key or button---
function disCtrlAnd(evt, keycode){
	if(evt.ctrlKey && evt.keyCode == keycode){
		evt.keyCode=0;
		return false;
	}else{
		return true;
	}
}

function disAltAnd(evt, keycode){
	if(evt.altKey && evt.keyCode == keycode){
		evt.keyCode=0;
		return false;
	}else{
		return true;
	}
}
function Apply(from,to)
{
     for(var p in from)
     {
       to[p]=from[p];
     }
}
//------MD5 call nums-------
/*function MD5_S(num, str){
	var i=0;
	for(i=0; i<num; i++){
		str = MD5(str);
	}
	
	return str;
}*/

function getSelectValue(Control)
{
     var selectedIndex=Control.selectedIndex;
     if(selectedIndex<=0)
       {
         selectedIndex=0;
         Control.selectedIndex=selectedIndex;
       }
       
       
      if(Control.options.length>0)
      {
          return Control.options[selectedIndex].value
      }
     
}

function getSelectText(Control)
{
     var selectedIndex=Control.selectedIndex;
     if(selectedIndex<=0)
       {
         selectedIndex=0;
         Control.selectedIndex=selectedIndex;
       }
       
       
      if(Control.options.length>0)
      {
          return Control.options[selectedIndex].text
      }
     
}

function tabSelect(tabName,maxIndex,Index,ClassName,overClassName)
{
 for(var i=0;i<=maxIndex;i++)
 {
  $ID(tabName+"menu"+i).className=ClassName;
  $ID(tabName+"content"+i).style.display="none";
 }
 
 $ID(tabName+"menu"+Index).className=overClassName;
 $ID(tabName+"content"+Index).style.display="block";
 
}

function TabHover(tabName,Index,overClassName)
{
 $ID(tabName+"menu"+Index).className=overClassName;
 $ID(tabName+"content"+Index).style.display="block";
}

function TabBlur(tabName,Index,className)
{
 $ID(tabName+"menu"+Index).className=className;
 $ID(tabName+"content"+Index).style.display="none";
}

function CheckLoginSubmit(userID,pwdID)
{
 if($ID(userID).value=='')
 {
  alert('请输入用户名');
  return false;
 }else if($ID(pwdID).value=='')
 {
  alert('请输入密码');
  return false;
 }
 else 
 return true;
 
}
//<div id="tabs3" class="tabs">
//<li class="tab1"><a rel="3-a">生理热门排行</a></li>
//<li><a rel="3-b">心理热门排行</a></li>
//</div>
//ddtabmenu.definemenu("tabs5", 0);
//Only 1 configuration variable below
//DD Tab Menu- Last updated April 27th, 07: http://www.dynamicdrive.com
//Only 1 configuration variable below
var ddtabmenu={
disabletablinks: false, ////Disable hyperlinks in 1st level tabs with sub contents (true or false)?
currentpageurl: window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, ""), //get current page url (minus hostname, ie: http://www.dynamicdrive.com/)
definemenu:function(tabid, dselected){
this[tabid+"-menuitems"]=null
this.addEvent(window, function(){ddtabmenu.init(tabid, dselected)}, "load")
},
showsubmenu:function(tabid, targetitem){
var menuitems=this[tabid+"-menuitems"]
for (i=0; i<menuitems.length; i++){
menuitems[i].className=""
if (typeof menuitems[i].hasSubContent!="undefined")
document.getElementById(menuitems[i].getAttribute("rel")).style.display="none"
}
targetitem.className="current"
if (typeof targetitem.hasSubContent!="undefined")
document.getElementById(targetitem.getAttribute("rel")).style.display="block"
},
isSelected:function(menuurl){
var menuurl=menuurl.replace("http://"+menuurl.hostname, "").replace(/^\//, "")
return (ddtabmenu.currentpageurl==menuurl)
},
addEvent:function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
},
init:function(tabid, dselected){
var menuitems=document.getElementById(tabid).getElementsByTagName("a")
this[tabid+"-menuitems"]=menuitems
for (var x=0; x<menuitems.length; x++){
if (menuitems[x].getAttribute("rel")){
this[tabid+"-menuitems"][x].hasSubContent=true
if (ddtabmenu.disabletablinks)
menuitems[x].onclick=function(){return false}
}
else //for items without a submenu, add onMouseout effect
menuitems[x].onmouseout=function(){this.className=""}
menuitems[x].onmouseover=function(){ddtabmenu.showsubmenu(tabid, this)}
if (dselected=="auto" && typeof setalready=="undefined" && this.isSelected(menuitems[x].href)){
ddtabmenu.showsubmenu(tabid, menuitems[x])
var setalready=true
}
else if (parseInt(dselected)==x)
ddtabmenu.showsubmenu(tabid, menuitems[x])
}
}
}
