/*                         */
/* FLASH control functions */
/*                         */ 

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) 
  {
    return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

function StopFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	callbackOnComplete = '';
	flashMovie.StopPlay();
	flashplaying = false;
}

function PlayFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	if (IsPlaying(id)) {
		callbackOnComplete = '';
		flashMovie.StopPlay();
	} else
		flashMovie.Play();
	flashplaying = !flashplaying;
}

function MuteFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	saveVolume = flashMovie.GetVolume();
	flashMovie.SetVolume(0);
	//flashMovie.SetMute(true);
}

function UnMuteFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	flashMovie.GetVolume(saveVolume);
	saveVolume = 0;
//	flashMovie.SetMute(false);
}

function RewindFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	callbackOnComplete = '';
	flashMovie.Rewind();
}

function NextFrameFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	// 4 is the index of the property for _currentFrame
	var currentFrame=flashMovie.TGetProperty("/", 4);
	var nextFrame=parseInt(currentFrame);
	if (nextFrame>=10)
		nextFrame=0;
	callbackOnComplete = '';
	flashMovie.GotoFrame(nextFrame);		
}

function GotoFrameFlashMovie(id,frame) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	callbackOnComplete = '';
	flashMovie.GotoFrame(frame);
	flashMovie.Play();
}

function GetCurrentFrame(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return -2;
	
	
	if (browser.isNS) {
		// have to wait until the Flash has loaded, otherwise SetVariable will fail.
		// test if the current frame is >= 0...
		// before it's loaded, it's -1.
		// Before Flash itself initialises, CurrentFrame doesn't exist, so check for that too.
		var currFrame = flashMovie.CurrentFrame;
		if (typeof(currFrame) == "function")
			currFrame = flashMovie.CurrentFrame();
		if (typeof(currFrame) == "number" && currFrame >= 0)
			return currFrame;
		else
			return -1;
	} else {
		var currFrame = 0;
		try {
			currFrame = flashMovie.TGetProperty("/", 4)
		} catch (e) {
			return -1;
		}
		return currFrame==undefined?-1:currFrame;
	}
	
	
	
	
	
	
	
	if(!flashMovie)return -2;
	// 4 is the index of the property for _currentFrame
	var currFrame = 0;
	try {
		currFrame = flashMovie.TGetProperty("/", 4)
	} catch (e) {return -1;}
	return currFrame==undefined?-1:currFrame;
}

function IsLoaded(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	return (flashMovie.PercentLoaded() == 100);
}

function IsPlaying(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	
	if (navigator.appName.indexOf("Microsoft Internet")!=-1)
		return flashMovie.IsPlaying();
	else {
 		if (GetCurrentFrame(id)==GetTotalFrames(id)) 
 			flashplaying = false;
		return flashplaying;
	}
}

function PercentLoaded(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	return flashMovie.PercentLoaded();
}

function GetTotalFrames(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return -2;
	// 5 is the index of the property for _totalFrames
	var totalFrames = 0;
	try {
		totalFrames = flashMovie.TGetProperty("/", 5)
	}
	catch (e) {	return -1;}
	return totalFrames==undefined?-1:totalFrames;
}

function ZoominFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	flashMovie.Zoom(90);
}

function ZoomoutFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	flashMovie.Zoom(110);
}

function SendDataToFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	flashMovie.SetVariable("/:message", document.controller.Data.value);
}

function ReceiveDataFromFlashMovie(id) {
	var flashMovie=getFlashMovieObject(id);
	if(!flashMovie)return;
	var message=flashMovie.GetVariable("/:message");
	document.controller.Data.value=message;
}

/*                           */
/* FLASH playback controller */
/*                           */

var pausebutton_image = 'pics/pause-btn.gif';
var playbutton_image = 'pics/play-btn.gif';
var pausebutton_image_obj = false;
var flashplaying = false;
var saveVolume = 0;
var sliderbar_handle = 'pics/slider_handle.gif';
var slider_handle_image_obj = false;
var sliderObjectArray = new Array();
var sliderIdArray = new Array();
var slider_counter = 0;
var slideInProgress = false;
var handle_start_x;
var event_start_x;
var handle_start_y;
var event_start_y;
var currentSliderIndex;
var sliderHandleWidth = 9;
var sliderTimerArray= new Array();
var callbackOnComplete; /* function to call when movie playback completes without pause being pressed */

function getImageSliderHeight(){
	if(!slider_handle_image_obj){
		slider_handle_image_obj = new Image();
		slider_handle_image_obj.src = sliderbar_handle;
	}
	if(slider_handle_image_obj.width>0){
		return;
	}else{
		setTimeout('getImageSliderHeight()',50);
	}
}

function getImagePausebuttonHeight(){
	if(!pausebutton_image_obj){
		pausebutton_image_obj = new Image();
		pausebutton_image_obj.src = pausebutton_image;
	}
	if(pausebutton_image_obj.width>0){
		return;
	}else{
		setTimeout('getImagePausebuttonHeight()',50);
	}
}

function positionSliderImage(e,theIndex)
{
	var theValue = sliderObjectArray[theIndex]['formTarget'];
	if(theValue/1>sliderObjectArray[theIndex]['max'])theValue = sliderObjectArray[theIndex]['max'];
	if(theValue/1<sliderObjectArray[theIndex]['min'])theValue = sliderObjectArray[theIndex]['min'];
	if (!sliderObjectArray[theIndex]['formTarget']) return;
		sliderObjectArray[theIndex]['formTarget'].value = theValue;
	var handleImg = document.getElementById('slider_handle' + theIndex);
	if (sliderObjectArray[theIndex]['max']-sliderObjectArray[theIndex]['min']!=0) {
		var ratio = sliderObjectArray[theIndex]['width'] / (sliderObjectArray[theIndex]['max']-sliderObjectArray[theIndex]['min']);
		var currentValue = sliderObjectArray[theIndex]['formTarget']-sliderObjectArray[theIndex]['min'];	
		handleImg.style.left = Math.round(currentValue * ratio) + 'px';	
	}
}

function getSliderValue(id) {
	var theIndex = sliderIdArray[id];
	return sliderObjectArray[theIndex]['formTarget'];
}

function setSliderValue(id,position,max) {
	var theIndex = sliderIdArray[id];
	sliderObjectArray[theIndex]['formTarget']=position;
	if (max) sliderObjectArray[theIndex]['max']=max;
	positionSliderImage(false,theIndex);
}

function initMoveSlider(e)
{

	if(document.all)e = event;	
	slideInProgress = true;
	event_start_x = e.clientX;
	event_start_y = e.clientY;
	handle_start_x = this.style.left.replace('px','');
	handle_start_y = this.style.top.replace('px','');
	currentSliderIndex = this.id.replace(/[^\d]/g,'');
	return false;
}

function startMoveSlider(e)
{
	if(document.all)e = event;	
	if(!slideInProgress)return;	
	var leftPos = handle_start_x/1 + e.clientX/1 - event_start_x;
	var topPos  = handle_start_y/1 + e.clientY/1 - event_start_y;
	
	if(leftPos<0)leftPos = 0;
	if(topPos<0) topPos = 0;

	if(leftPos/1>sliderObjectArray[currentSliderIndex]['width'])leftPos = sliderObjectArray[currentSliderIndex]['width'];
	document.getElementById('slider_handle' + currentSliderIndex).style.left = leftPos + 'px';
	
	var ratio = sliderObjectArray[currentSliderIndex]['width'] / (sliderObjectArray[currentSliderIndex]['max']-sliderObjectArray[currentSliderIndex]['min']);
	//alert('lp='+leftPos+'  '+'ratio='+ratio+'  '+'    min='+sliderObjectArray[currentSliderIndex]['min']);
	var convertedValue =  Math.round(leftPos / ratio) + sliderObjectArray[currentSliderIndex]['min'];	
	
	if(sliderObjectArray[currentSliderIndex]['onchangeAction']){
		eval(sliderObjectArray[currentSliderIndex]['onchangeAction']+'("'+sliderObjectArray[currentSliderIndex]['id']+'",'+convertedValue+')');
	}
}

function stopMoveSlider()
{
	slideInProgress = false;
}

function sliderbar(targetElId,width,min,max,onchangeAction,pausebutton_enabled)
{
	//alert('sliderbar: '+targetElId+','+width+','+min+','+max+','+onchangeAction+',')
	if(!slider_handle_image_obj){
		getImageSliderHeight();		
	}
	if (pausebutton_enabled)
		if(!pausebutton_image_obj){
			getImagePausebuttonHeight();		
		}
	var sliderbarId = 'sliderbar_' + targetElId;
	slider_counter = slider_counter +1;
	sliderObjectArray[slider_counter] = new Array();
	sliderIdArray['sliderbar_'+targetElId]=slider_counter;  /* save targetID xref to slider counter */
	//alert('setting index '+slider_counter);
	sliderObjectArray[slider_counter] = {"id":targetElId,"width":width - sliderHandleWidth,"min":min,"max":max,"formTarget":min,"onchangeAction":onchangeAction};
	
	var theValueX = sliderObjectArray[slider_counter]['formTarget'];
	
	var parentObj = document.createElement('DIV');

	parentObj.style.height = '12px';	// The height of the image
	parentObj.style.position = 'relative';
	parentObj.id = 'slider_container' + slider_counter;
	document.getElementById(sliderbarId).appendChild(parentObj);
	
	var obj = document.createElement('DIV');
	obj.className = 'sliderbar';
	obj.innerHTML = '<span></span>';
	obj.style.width = (width - 3) + 'px';
	obj.id = 'slider_slider' + slider_counter;
	obj.style.position = 'absolute';
	obj.style.bottom = '0px';
	parentObj.appendChild(obj);
	
	var handleImg = document.createElement('IMG');
	handleImg.style.position = 'absolute';
	handleImg.style.left = '0px';
	handleImg.style.border = '0';
	handleImg.style.zIndex = 5;
	handleImg.src = slider_handle_image_obj.src;
	handleImg.id = 'slider_handle' + slider_counter;
	handleImg.onmousedown = initMoveSlider;
	
	parentObj.style.width = obj.offsetWidth + 'px';
	
	if(document.body.onmouseup){
		if(document.body.onmouseup.toString().indexOf('stopMoveSlider')==-1){
			alert('You allready have an onmouseup event assigned to the body tag');
		}
	}else{
		document.body.onmouseup = stopMoveSlider;
		document.body.onmousemove = startMoveSlider;	
	}
	handleImg.ondragstart = function () { return false; };
	parentObj.appendChild(handleImg);
	positionSliderImage(false,slider_counter);
	rescheduleSlider(targetElId,slider_counter);
}

/*                           */
/* FLASH helper functions */
/*                           */

function addDiv(obj,id,width,height,top,left,bgcolor,zindex,content,insertbefore) {
	var newDiv = document.createElement('DIV');	
	newDiv.style.height = height+'px';	
	newDiv.style.top = top+'px';
	newDiv.style.left = left+'px';
	newDiv.style.width = width+'px';
	newDiv.style.height = height+'px';
	if (bgcolor)
		newDiv.style.backgroundColor = bgcolor;
	if (zindex)
		newDiv.style.zindex = zindex;
	
	newDiv.style.position = 'absolute';
	newDiv.id = id;
	if (content) {
		newDiv.innerHTML=content;
	}
	if (insertbefore) {
		var parentObj = obj.parentNode;
		parentObj.insertBefore(newDiv,obj.nextSibling);
	} else if (obj) {
		obj.appendChild(newDiv);
	} else 
		alert('cannot add div to null parent');
}

function setAllOnClicks() {
	/* add onclick event to all A with class=flashpop */
	var links = document.getElementsByTagName('a');	
	for(var no=0;no<links.length;no++)
		if (links[no].className=='flashpop')
			if (!links[no].onclick) 
				links[no].onclick = function() { return genFlashMovieEZ(this); }
}

function addAnEvent(obj, evType, fn){ 
	if (obj.addEventListener){ 
		obj.addEventListener(evType, fn, false); 
		return true; 
	} else if (obj.attachEvent){ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} else { 
		return false; 
	} 
}

function removeDiv(dId) {
    var obj = document.getElementById(dId);
	if (obj)
    	obj.parentNode.removeChild(obj);
}

function getElementPositionId(elemID) {
    return getElementPosition(document.getElementById(elemID));
}

function getElementPosition(obj) {
    var offsetTrail = obj;
    var offsetWidth = 0;
    var offsetHeight = 0;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
    	if (!offsetWidth) offsetWidth = offsetTrail.offsetWidth;
    	if (!offsetHeight) offsetHeight = offsetTrail.offsetHeight;
        offsetLeft += offsetTrail.offsetLeft;
        offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 && 
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop, width:offsetWidth, height:offsetHeight};
}


/* run setallonclicks init upon page load */
addAnEvent(window,'load',setAllOnClicks);

function genFlashMovieEZ(obj) {
/* build a media player on the fly and pops it up next to the A tag that triggered it */
	var id = 'FlashMovieEZ';
	var container = 'EZcontainer';
	var container_title_height = 10;
	var container_border_width=3;
	var theater = 'EZtheater';
	var theater_width = obj.getAttribute('width');
	var theater_height = obj.getAttribute('height');
	var controller = 'EZcontroller';
	var controller_height = 20;
	var container_top = obj.getAttribute('top');
	var container_left = obj.getAttribute('left');
	
	if(obj.firstChild.nodeType == 3) {	//if linking text, return position of the anchor link
		var obj_location = getElementPosition(obj);
	} else { //otherwise, return position of the linked content
		var obj_location = getElementPosition(obj.firstChild);
	}

	var callback = '';

	if (container_top) {
		container_top=obj_location.top + (parseInt(container_top));
	} 
	else 
		container_top=obj_location.top;
	
	if (container_left)
		container_left=obj_location.left+obj_location.width + 20 + (parseInt(container_left));
	else
		container_left=obj_location.left+obj_location.width + 20;

	removeDiv(theater);	
	removeDiv(container);
	
	if (!theater_width || !theater_height) { alert('Height and width must be specified within the <A> tag'); return false; }
	theater_width = parseInt(theater_width);
	theater_height = parseInt(theater_height);
	
	var content = '<strong>FLASH is required to view this video</strong><br><br>click <a href="http://www.macromedia.com/go/getflashplayer" target="_blank">here</a> to be directed to the Flash software installation site. After installing FLASH, return here and refresh the screen.</strong>';
	
	/* create a container DIV */
//	addDiv(obj,container,

	addDiv(obj,container,
			theater_width + (2*container_border_width),
			theater_height + container_title_height + controller_height + (2 * container_border_width),
			container_top - container_title_height,
			container_left,
			'gray',0,'<span id="'+id+'_framecounter" style="font-size: 8pt; color: #fff;">&nbsp;</span>',true);
		
	var cont = document.getElementById(container);
	
	/* add a drag bar across to top */	
	var dragImg = document.createElement('IMG');
	dragImg.style.position = 'absolute';
	dragImg.style.top = '0px';
	dragImg.style.left = '0px';
	dragImg.src = '/pics/spacer.gif';
	dragImg.style.width = theater_width+'px';
	dragImg.style.height = container_title_height+'px';
	dragImg.style.border = '0';
	dragImg.id = 'dragImg';
	dragImg.onmousedown = function (e) { dragStart(e,container); };
	cont.appendChild(dragImg);
	
	

	/* add a close box to the top right of the container DIV */
	var closebox_url = '/pics/home/player/icons/player_close.gif';
	var closebox_url_width = 15;
	var closeImg = document.createElement('IMG');
	closeImg.style.position = 'absolute';
	closeImg.style.top = '0px';
	closeImg.style.left = theater_width + (container_border_width) - closebox_url_width +'px';
	closeImg.style.border = '0';
	closeImg.src = closebox_url;
	closeImg.onclick = function() {	removeDiv(theater);	removeDiv(container); }
	
	
	
	cont.appendChild(closeImg);
	
	/* create a theater DIV */
	addDiv(cont,theater,
			theater_width,
			theater_height,
			container_title_height + container_border_width,
			container_border_width,
			'',99,content);
			
	/* create a controller DIV */
	addDiv(cont,controller,
			theater_width,
			controller_height,
			container_title_height + theater_height + container_border_width,
			container_border_width,
			'white',99);

	genFlashMovie(id,theater,controller,obj.href,theater_width,theater_height,true,'','',callback);
	return false;
}

function genFlashMovie(id,tgt,ctlr,filename,width,height,pausebutton_enabled,bgcolor,version,callback) {
	/* if pausebutton_enabled = 'false', no pause button displayed */
		
	if(!width)width='320';
	if(!height)height='240';
	if(!version)version='7';
	if(!bgcolor)bgcolor='#000';
	
	if (callback)
		callbackOnComplete = callback;
		
	if (!document.getElementById(tgt).innerHTML) {
   		alert('No theater div found - define a DIV with id='+tgt+' in your document');
   		return false;
	}
	if (!document.getElementById(ctlr)) {
   		alert('No controller div found - define a DIV with id='+ctlr+' in your document');
		return false;
	}   
	var so = new SWFObject(filename,id,width,height,version,bgcolor);
	so.addParam('wmode','transparent');
	var embTag = so.getSWFHTML();
	flashplaying = true;
	
	if (!embTag) {
		callbackOnComplete = '';
		embTag = '<a href="http://www.macromedia.com/go/getflashplayer" target="_blank"><img src="pics/home/player/player_open_screen_noflash.jpg" border=0></a>';
	}
	
	assignDivInnerHtml (tgt,embTag);
	
	if(ctlr) {
		if (document.getElementById(ctlr))
			if (document.getElementById(ctlr).getAttribute('width'))
				genFlashController(id,ctlr,document.getElementById(ctlr).getAttribute('width'),pausebutton_enabled);
			else 
				genFlashController(id,ctlr,width,pausebutton_enabled);
	}
}

function updateSlider(id,theIndex) {
	if(!IsPlaying(id) && !browser.isNS)
		if(callbackOnComplete) {
			eval(callbackOnComplete);
			return;
		}
	
	if (document.getElementById(id)) {
		currFrame = GetCurrentFrame(id);
		setSliderValue('sliderbar_'+id,currFrame,GetTotalFrames(id));
		var fctDiv = document.getElementById(id+'_framecounter');
		if (fctDiv) {
			var pctMsg = document.createTextNode((!IsLoaded(id))?'Loading ('+PercentLoaded(id)+'%)..':'');
			fctDiv.replaceChild(pctMsg,fctDiv.firstChild);
		}
	}
	if (document.getElementById(id+'_pause_play_button'))
		document.getElementById(id+'_pause_play_button').src = IsPlaying(id)?pausebutton_image:playbutton_image;
	rescheduleSlider(id,theIndex);
}

function rescheduleSlider(id,theIndex) {
	//var theIndex = document.getElementById(id).getAttribute('sliderIndex');	
	if (sliderTimerArray[theIndex]) clearTimeout(sliderTimerArray[theIndex]);
	sliderTimerArray[theIndex] = setTimeout('updateSlider("'+id+'",'+theIndex+')',1000);
}

function genFlashController(id,tgt,width,pausebutton_enabled) {
   if(!tgt)tgt='controller';
   if (!document.getElementById(tgt)) {
   		alert('No controller div found - define a DIV with id='+tgt+' in your document');
   		return;
   }
   var pause = (!pausebutton_enabled)?'':'<td><a onclick="this.blur();" href="javascript: PlayFlashMovie(\''+id+'\');"><img id="'+id+'_pause_play_button" src="'+pausebutton_image+'" border=0></a></td>';
   var playhead = '<table border=0 cellspacing=0 cellpadding=2><tr>'+pause+'<td id="sliderbar_'+id+'"></td><td></td></table>';
   if (pausebutton_enabled)
	   playhead ='<style>.sliderbar {'+
		'border-top:1px solid #9d9c99;'+
		'border-left:1px solid #9d9c99;'+
		'border-bottom:1px solid #eee;'+
		'border-right:1px solid #eee;'+
		'background-color:#f0ede0;'+
		'height:3px;'+
		'position:absolute;'+
		'bottom:0px;}</style>'+playhead;

	assignDivInnerHtml (tgt,playhead);
	sliderbar(id,width - (!pausebutton_enabled?20:26), 0, 0,'GotoFrameFlashMovie',pausebutton_enabled);
}

function assignDivInnerHtml (srcDivId,theHTML) {
	/* Replace the innerHTML of the passed div id. 
	   Required for IE because once you create a DIV, you cannot change it's innerHTML. But, you can replace 
	   the DIV - so we clone the old div, assign HTML to the cloned innerHTML, then replace the old DIV. */
	var tgtDiv=document.createElement('DIV');
	var srcDiv = document.getElementById(srcDivId);
	
	tgtDiv = srcDiv.cloneNode(true);
	tgtDiv.innerHTML = theHTML;
	srcDiv.parentNode.replaceChild(tgtDiv,srcDiv);
	return;
}

/*  container drag code */

// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(event, id) {

  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Clear the drag element global.

  dragObj.elNode = null;

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}
