var clickToInitiate = '<%=clickToInitiate%>';

//	if theme = "" then theme = request.cookies("LS")("thm")
//	if theme = "" then theme = session("nav")
//	if theme = "" then theme = "0"
//	strTheme = "/CADElmw/Themes/" & theme & "/"
	
function OSGradient() {
	this.initialize.apply(this, arguments);
}

OSGradient.applyGradient = function(style, element) {
	var gradient = new OSGradient(style);
	gradient.applyGradient(element);
};

// Create a gradient for each element that has a divStyle.
// +divstyle.js+ sets the divStyles automatically.  This function does
// nothing if +divstyle.js+ has not been loaded, unless JavaScript
// code has explicitly set the +divStyle+ properties of any HTML
// Elements.
OSGradient.applyGradients = function() {
	try {DivStyle.initialize()} catch(e) {}
    var elements = document.getElementsByTagName('*');
    for (var i = 0, e; e = elements[i++]; ) {
        var style = e.divStyle;
        if (style && style.gradientStartColor)
            OSGradient.applyGradient(style, e);
    }
};

// Number of bands necessary for a smooth gradient, by component.
// The max of the color range and height are pinned to this.
OSGradient.maxBands = [192, 192, 96];

// The following properties need to be set in order for style.zIndex
// to work in IE.  This function is called the first time that a
// gradient is attached to an element.
OSGradient.setBodyStyle = function() {
	OSGradient.setBodyStyle = function() {}
    var style = document.body.style;
    style.position = 'relative';
    style.left = 0;
    style.top = 0;
    style.zIndex = 0;
};

//
// Instance methods
//

OSGradient.prototype.initialize = function(style) {
	this.style = style;
};

OSGradient.prototype.applyGradient = function(e) {
    var width = e.offsetWidth, height = e.offsetHeight;
	var gradientElement = (this.createCanvasGradient(e, width, height) ||
						   this.createGradientElement(width, height));
    OSGradient.setBodyStyle();
	this.attachGradient(e, gradientElement);
};

OSGradient.prototype.createCanvasGradient = function(e, width, height) {
	var canvas = document.createElement('canvas');
	var ctx;
	// Return null if canvas isn't supported.  The caller will
	// fall back on divs.
	try {ctx = canvas.getContext('2d')} catch (e) {return null}
	
	// Safari requires the following prior to rendering
	e.appendChild(canvas);
	if (navigator.appVersion.match(/Konqueror|Safari|KHTML/))
		canvas.style.position = 'fixed';
    canvas.setAttribute('width', width);
    canvas.setAttribute('height', height);
	
	var style = this.style;
    var c0 = style['gradient-start-color'];
    var c1 = style['gradient-end-color'];
    var r = style['border-radius'];
	
	ctx.beginPath();
	ctx.moveTo(0,r);
	//arcTo() produces NS_ERROR_NOT_IMPLEMENT in Firefox 1.5; use arc() instead:
	//ctx.arcTo(0,0,r,0,r);
	ctx.arc(r,r,r,Math.PI,-Math.PI/2,false);
	ctx.lineTo(width-r,0);
	//ctx.arcTo(width,0,width,r,r);
	ctx.arc(width-r,r,r,-Math.PI/2,0,false);
	ctx.lineTo(width,height-r);
	//ctx.arcTo(width,height,width-r,height,r);
	ctx.arc(width-r,height-r,r,0,Math.PI/2,false);
	ctx.lineTo(r,height);
	//ctx.arcTo(0,height,0,height-r,r);
	ctx.arc(r,height-r,r,Math.PI/2,Math.PI,false);
	ctx.clip();
	var g = ctx.fillStyle = ctx.createLinearGradient(0,0,0,height);
	g.addColorStop(0, OSUtils.color.long2css(c0));
	g.addColorStop(1, OSUtils.color.long2css(c1));
	ctx.rect(0,0,width,height);
	ctx.fill();
	return canvas;
};

OSGradient.prototype.makeSpan = function(x, y, width, height, color, opacity) {
	var properties = {position: 'absolute',
					  left: x+'px',
					  top: y+'px',
					  width: width+'px',
					  height: height+'px',
					  // for IE:
					  'font-size': 1,
					  'line-height': 0,
					  background: color};
	if (opacity != undefined) properties.opacity = opacity;
	var style = [];
	for (var p in properties)
		style.push(p + ':' + String(properties[p]));
	// IE requires the &nbsp;
	return '<div style="'+style.join(';')+'">&nbsp;</div>';
};

OSGradient.prototype.createGradientElement = function(width, height) {
	var style = this.style;
    var c0 = style['gradient-start-color'];
    var c1 = style['gradient-end-color'];
    var r = style['border-radius'];
	
	function xAt(y) {
		var dy = Math.max(r-y, y-(height-r));
		if (dy >= 0)
			return r - Math.sqrt(r*r-dy*dy);
		return 0;
	};
	
	var bands = 0;
	for (var shift = 24; (shift -= 8) >= 0; )
		bands = Math.max(bands,
						 1+Math.min(Math.abs(c0 - c1) >> shift & 255,
									OSGradient.maxBands[2-shift/8]));
	bands = Math.max(bands, height);
	
	var transitions = [];
	for (var i = 0; i <= bands; i++)
		transitions.push(Math.floor(i * height / bands));
	
	if (r) {
		var tops = [];
		var bottoms = [];
		var lastx = null;
		for (var y = 0; y <= r; y++) {
			var x = Math.ceil(xAt(y));
			if (x == lastx) continue;
			lastx = x;
			transitions.push(y);
			transitions.push(height-y);
		}
		transitions.sort(function(a,b){return a-b});
	}
	OSUtils.Array.removeDuplicates(transitions);
	
    var spans = [];
    for (var i = 0; i < transitions.length-1; i++) {
        var y = transitions[i];
        var h = transitions[i+1] - y;
        var x = Math.ceil(xAt(y));
        var color = OSUtils.color.interpolate(c0, c1, y/height);
		spans.push(this.makeSpan(x, y, width-2*x, h,
								 OSUtils.color.long2css(color)));
    }
	
    var g = document.createElement('div');
    g.innerHTML = spans.join('');
	if (true) {
	g.style.position = 'absolute';
    g.style.left = '0px';
    g.style.top = '0px';
    g.style.width = "100%";
    g.style.height = '100%';
    g.style.zIndex = -1;
	}
	
	return g;
};

OSGradient.prototype.attachGradient = function(parent, gradient) {
	gradient.style.position = 'absolute';
    gradient.style.left = '0px';
    gradient.style.top = '0px';
	// Setting the canvas's dimensions erases its contents in Firefox,
	// even though it's the SAME DIMENSIONS.
	if (gradient.width != parent.offsetWidth)
		gradient.width = parent.offsetWidth;
	if (gradient.height != parent.offsetHeight)
		gradient.height = parent.offsetHeight;
	gradient.style.zIndex = -1;
	
    if (!parent.style.position.match(/absolute|relative/i))
		parent.style.position = 'relative';	
	// The canvas parent has already been set, for Safari.
	if (gradient.parentNode != parent)
		parent.appendChild(gradient);
};

/*
 * Utilities
 */
OSUtils = window.OSUtils || {};
if (!OSUtils.color) {OSUtils.color = {}}
if (!OSUtils.Array) {OSUtils.Array = {}}

// 0x123456 -> "#123456"
OSUtils.color.long2css = function(n) {
  var a = "0123456789ABCDEF";
  var s = '#';
  for (var i = 24; (i -= 4) >= 0; )
    s += a.charAt((n>>i) & 0xf);
  return s;
};

// (a,b,0)->a; (a,b,1)->b; a and b are rrggbb color numbers.
OSUtils.color.interpolate = function(a, b, s) {
  var n = 0;
  for (var i = 24; (i -= 8) >= 0; ) {
    var ca = (a >> i) & 0xff;
    var cb = (b >> i) & 0xff;
    var cc = Math.floor(ca*(1-s) + cb*s);
    n |= cc << i;
  }
  return n;
};

// Modify +ar+ in-place to remove consecutive duplicates.
OSUtils.Array.removeDuplicates = function(ar) {
	var i = 0, j = 0;
	while (j < ar.length) {
		var v = ar[i] = ar[j++];
		if (!i || ar[i-1] != v) i++;
	}
	ar.length = i;
	return ar;
};

function setGradientStyles() {

	adjustBanner()

	if (top.normalStyle == 'undefined' || top.normalStyle == undefined) return;
	var i = 0;
	
	var d = document.getElementsByTagName('div')
	for (i=0; i < d.length-1; i++) {
		if (d[i].title.indexOf('Tip:') != -1) {
			if (d[i].innerHTML.indexOf('1px') == -1) {
				d[i].style.textAlign = 'center';
				OSGradient.applyGradient(top.normalStyle,d[i])
				XBrowserAddHandler(d[i],'mouseover',function(e) { applyHoverRef(e) } )
				XBrowserAddHandler(d[i],'mouseout',function(e) { applyNormalRef(e) } )
				if (1==2) {
					if (d[i].addEventListener) {
						d[i].addEventListener ("mouseover",function() {applyHover(function() {event} )},false);
						d[i].addEventListener ("mouseout",function() {applyNormal(function() {event} )}, false);
					} else if (d[i].attachEvent) {
						d[i].attachEvent ("onmouseover",function() {applyHover(event)} );
						d[i].attachEvent ("onmouseout",function() {applyNormal(event)} );
					} else {
						d[i].onmouseover = function(){OSGradient.applyGradient(top.hoverStyle,d[i])};
						d[i].onmouseout = function(){OSGradient.applyGradient(top.normalStyle,d[i])};
					} 
				}
			}
		}
	}
	d = document.getElementsByTagName('input')
	// Look to see if there are any text elements in this page
	for (i=0; i < d.length-1; i++) {
		if (d[i].type == 'text') {
			if ( isVisible(d[i]) ) {
				if (d[i].value == '') {
					// Only focus if nothing is there
					d[i].focus();
					if (typeof formIsDirty != 'undefined') {
						// If there is a dirty checker, reset it after a bit
						setTimeout('FPEreset()',500);
					}
				}
				return;
			}
		}
	}
}

function FPEreset() {
	formIsDirty = false;
}

function isVisible(obj)
{
    if (obj == document) return true
    
    if (!obj) return false
    if (!obj.parentNode) return false
    if (obj.style) {
        if (obj.style.display == 'none') return false
        if (obj.style.visibility == 'hidden') return false
    }
    
    //Try the computed style in a standard way
    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "")
        if (style.display == 'none') return false
        if (style.visibility == 'hidden') return false
    }
    
    var style = obj.currentStyle
    if (style) {
        if (style['display'] == 'none') return false
        if (style['visibility'] == 'hidden') return false
    }
    
    return isVisible(obj.parentNode)
}

function XBrowserAddHandler(target,eventName,handlerName) {
	if ( target.addEventListener )
		target.addEventListener(eventName, handlerName, false);
	else if ( target.attachEvent )
		target.attachEvent("on" + eventName, handlerName);
	else
	target["on" + eventName] = handlerName;
}

var applyHoverRef = function applyHover(e) {
	var evt = e || window.event;
	//if (window.event) e = window.event; e
	var theDiv = evt.srcElement ? evt.srcElement : e.target;
	if (theDiv != null && theDiv != '') {
		cleanDiv(theDiv);
		OSGradient.applyGradient(top.hoverStyle,theDiv);
		theDiv.cursor = 'pointer';
	}
}
var applyNormalRef = function applyNormal(e) {
	var evt = e || window.event;
	//if (window.event) e = window.event; e
	var theDiv = evt.srcElement ? evt.srcElement : e.target;
	if (theDiv != null && theDiv != '') {
		theDiv.cursor = 'default';
		cleanDiv(theDiv);
		OSGradient.applyGradient(top.normalStyle,theDiv);
	}
}

function cleanDiv(theDiv) {
	var i = theDiv.innerHTML.toLowerCase().indexOf('<div');
	if (i > -1) {
		var x = theDiv.innerHTML.toLowerCase().indexOf(' 1px');
		if (x > -1) {
			theDiv.innerHTML = theDiv.innerHTML.substring(0,i-1);
		}
	}
}

function CADEbutton(btnType,btnText,btnAction,btnID,btnWidth,btnMouseover) {
	var s = ''
	var i = 0;
	if (btnID == '') {
		// No ID, just create a random one
		btnID = Math.floor(Math.random()*10001);
	}

	var isImage = false

	if (btnMouseover == '') {
		// No mouseover text, use a standard one with the button text
		btnMouseover = clickToInitiate + ' ' + btnText;
	}
	s = s + '<input value="' + btnText + '" type="button" title="' + btnMouseover + ' "';
	s = s + ' id="' + btnID + '"';
	s = s + ' name="' + btnID + '"';
	switch (btnType.toLowerCase()) {
		case 'submit':
			if (btnAction == '') {
				// No onclick action, default to submitting this form
				s = s + ' onclick="findForm(this).submit()"';
			}
			else {
				// got an onclick action, replace this.form with a function to find the parent form
				i = btnAction.toLowerCase().indexOf('this.form');
				if (i > -1) {
					btnAction = btnAction.substring(0,i) + 'findForm(this)' + btnAction.substring(i+9);
				}
				s = s + ' onclick="' + btnAction + '"'
			}
			break;
		case 'button':
			// got an onclick action, replace this.form with a function to find the parent form
			i = btnAction.toLowerCase().indexOf("this.form");
			if (i > -1) {
				btnAction = btnAction.substring(0,i) + "findForm(this)" + btnAction.substring(i+9);
			}
			s = s + ' onclick="' + btnAction + '"'
			break;
	}
	s = s + ' style="position:relative;display:inline-block;font-size:12px;font-family:Arial;text-align:center;';	// open style
	if (btnWidth != '') {
		s += 'width:' + btnWidth + 'px;';
	}
	s = s + 'color:' + top.btnFont + ';'
	s = s + "background: transparent url(" +top.header.strTheme+ "normal.gif) repeat center top;"
	s = s + '"';	// close style
	
	s = s + " onmouseover=" + '"' + "this.style.backgroundImage='url(" +top.header.strTheme+ "hover.gif)'; btnMouseover('btn" + btnID + "')" + '"'
	s = s + " onmouseout=" + '"' + "this.style.backgroundImage='url(" +top.header.strTheme+ "normal.gif)'; btnMouseout('btn" + btnID + "')" + '"'
	s = s + '>';
	s = s + '</input>';
	return s;
}

function confirmDelete() {
	var ans = confirm(top.youSure);
	return ans;
}

function confirmForm(child) {
	var theForm = findForm(child);
	if (confirmDelete()) {
		theForm.submit();
	}
}

function submitForm(formName) {
	if (document.forms[formName] != null) {
		document.forms[formName].submit()
	}
}

function findForm(child) {
	var p = child.parentNode;
	while (p.tagName.toLowerCase() != 'form') {
		// climb the parent tree looking for the containing form
		if (p.parentNode == null ) {
			return document.forms[0];
		}
		p = p.parentNode;
	}
	return p;
}

/*
 * Initialization
 */

// If divstyle.js has been included, define these:
try {
	DivStyle.defineProperty('gradient-start-color', 'color');
	DivStyle.defineProperty('gradient-end-color', 'color', 0xffffff);
	DivStyle.defineProperty('border-radius', 'number', 0);
} catch(e) {}

if (window.addEventListener) {
    window.addEventListener('load', OSGradient.applyGradients, false);
    window.addEventListener('load', setGradientStyles, false);
} else if (window.attachEvent) {
    window.attachEvent('onload', OSGradient.applyGradients);
    window.attachEvent('onload', setGradientStyles);
} else {
    window.onload = (function() {
        var nextfn = window.onload || function(){};
        return function() {
            OSGradient.applyGradients();
            nextfn();
        }
    })();
}

function adjustBanner() {
	var ele = document.getElementById('divBanner')
	if (ele != null) {
		var pageTop = (parseInt(top.mainHeight) - parseInt(ele.offsetHeight)) 
		//top.idxDisplayMessage(pageTop + ' ' + document.body.scrollHeight + ' ' + ele.offsetTop + ' ' + ele.style.left + ' ' + ele.offsetWidth + ' ' + ele.offsetHeight + ' ' + top.mainWidth + ' ' + top.mainHeight + ' ' + ele.style.position)
		if (ele.offsetTop < pageTop) {
			ele.style.position = 'absolute'
			ele.style.width = '100%'
			ele.style.top = parseInt(pageTop) + 'px'
		}
	}
}

function resetBanner() {
	var ele = document.getElementById('divBanner')
	if (ele != null) {
		var pageTop = (parseInt(top.mainHeight) - parseInt(ele.offsetHeight)) 
		//top.idxDisplayMessage(pageTop + ' ' + document.body.scrollHeight + ' ' + ele.offsetTop + ' ' + ele.style.left + ' ' + ele.offsetWidth + ' ' + ele.offsetHeight + ' ' + top.mainWidth + ' ' + top.mainHeight + ' ' + ele.style.position)
		if (ele.offsetTop < pageTop) {
			ele.style.position = 'absolute'
			ele.style.width = '100%'
			ele.style.top = parseInt(pageTop) + 'px'
		}
		else {
			ele.style.position = 'relative'
			ele.style.top = 0
		}
	}
}

