// JavaScript Document
/**
* This function attaches pan functionality to the supplied image argument
* @param HTMLElement elImg The image to be panned
* @param int pW The parent element's width
* @param int pH The parent element's height
* @param int to The timeout length in milliseconds

* http://www.phpbuilder.com/board/showthread.php?t=10361220

*/
function jtaCreateImagePan(elImg, intvl) {
    if (typeof(elImg)=='string'){
		elImg=document.getElementById(elImg);
	}
    if (elImg&&!elImg.jtaPan) {
        var pObj=elImg.parentNode;
        var imgW=getSt(elImg,'width');
        var imgH=getSt(elImg,'height');
        var pW=getSt(pObj, 'width');
        var pH=getSt(pObj, 'height');
        var mxX=(imgW<=pW) ? 0 : imgW-pW;
        var mxY=(imgH<=pH) ? 0 : imgH-pH;
        elImg.jtaPan=new jtaImagePan(elImg,mxX,mxY,intvl,pObj);
    }
}

function jtaImagePan(elImg,mxX,mxY,intvl,pObj) {
    this.img=elImg;
    this.pObj=pObj;
    this.mxX=mxX;
    this.mxY=mxY;
    this.hDir=this.mxX?'left':null;
    this.vDir=this.mxY?'up':null;
    this.intvl=intvl;
    this.to=null;
    this.imgW=getSt(elImg,'width');
    this.imgH=getSt(elImg,'height');
    this.pW=getSt(this.pObj, 'width');
    this.pH=getSt(this.pObj, 'height');
//    if (bCent){
//        elImg.style.left=(mxX-this.pW)/2+'px';
//        elImg.style.top=(mxY-this.pH)/2+'px';
//    }
    this.pan=this.imgW>getSt(pObj,'width')||this.imgH>getSt(pObj,'height')?this.cycle:this.nocycle;
}

jtaImagePan.prototype.cycle=function(){
    var lft=getSt(this.img,'left');
    var top=getSt(this.img,'top');

    // move horizontally
    if (this.hDir=='left') {
        lft--;
        if (lft<-this.mxX) {
            this.hDir='right'; // reverse it
        } else {
            this.img.style.left=lft+'px';
        }
    }
    if (this.hDir=='right') {
        lft++;
        if (lft>0) {
            this.hDir='left'; // reverse it
        } else {
            this.img.style.left=lft+'px';
        }
    }
    // move vertically as needed
    if (this.vDir=='up') {
        top--;
        if (top<-this.mxY) {
            this.vDir='down'; // reverse it
        } else {
            this.img.style.top=top+'px';
        }
    }
    if (this.vDir=='down') {
        top++;
        if (top>0) {
            this.vDir='up'; // reverse it
        } else {
            this.img.style.top=top+'px';
        }
    }
    
    this.to=setTimeout(function(panObj){return function(){panObj.cycle();}}(this),this.intvl);
}

jtaImagePan.prototype.nocycle=function(){}

jtaImagePan.prototype.clear = function() {
    if (this.to) {
        clearTimeout(this.to);
    }
}

function getSt(el,styl) {
	if (el.currentStyle) return parseInt(el.currentStyle[styl.replace(/-/g,'')]);
	return parseInt(document.defaultView.getComputedStyle(el,null).getPropertyValue(styl.toLowerCase()));
} 
