/*
 * site.js -- functions in use throughout the website
 *
 */

var previousOverflow='';
var previousOverflowX='';
var previousOverflowY='';
var onCloseCodeRef= function() {};
function overlayPopup(d,html,url,x,y,coderef,hideclosebar,noscrollto,hideoverlay,popupclass,posX,posY) {
	onCloseCodeRef = coderef ? coderef : function() { }
	var div = top.document.getElementById(d);
	if ( ! div ) div = top.document.body;
	var overlay;
	if ( ! hideoverlay ) {
		overlay = top.document.createElement('div');
		overlay.id = d+'Overlay';
		overlay.className='divOverlay';
		div.appendChild(overlay);
	}

	var popup = top.document.getElementById(d+'OverlayPopup');
	var newPopup = false;
	if ( ! popup ) {
		newPopup = true;
		popup = top.document.createElement('div');
		popup.id=d+'OverlayPopup';
		popup.className='OverlayPopup';
		if ( posX || posY ) {
			top.document.body.appendChild(popup);
		} else {
			div.appendChild(popup);
		}
	}
	if ( ! popup ) { return; }

	if ( newPopup ) {
		previousOverflow = div.style.overflow;
		previousOverflowX = div.style.overflowX;
		previousOverflowY = div.style.overflowY;
		div.style.overflow = 'hidden';
		div.style.overflowX = 'hidden';
		div.style.overflowY = 'hidden';
		if ( overlay ) {
			overlay.style.height=div.scrollHeight;
			overlay.style.display='block';
		}
	}

	popup.style.top  = posY ? posY+'px' : '0px';
	popup.style.left = posX ? posX+'px' : '0px';

	if ( noscrollto == true ) {
	} else {
		window.scrollTo( div.offsetLeft || 0 , div.offsetTop || 0 );
	}

	if ( x ) popup.style.width=x+'px';
	if ( y ) popup.style.height=y+'px';

	if ( posX || posY ) {
			popup.style.margin = '0';
	}

	if ( ! hideclosebar ) popup.innerHTML = "<div class='topBar'><img onClick=\"onCloseCodeRef(); enableDiv('"+d+"');\" src=/fishicons/del_selected.png border=0 /></div>";
	popup.innerHTML += "<div id='"+d+"popupContainer' "+ ( popupclass ? 'class="' + popupclass + '"' : '' )  +"></div>";
	
	// if ( style )  ...

	if ( html ) {
		top.document.getElementById(d+'popupContainer').innerHTML = html;
		popup.style.display='block';
	}
	if ( url ) {
		insertGetRequestInto(d+'popupContainer',url);
	}
}
function enableDiv(d) {
	var popup = top.document.getElementById(d+'OverlayPopup');
	popup.parentNode.removeChild(popup);
	//top.document.body.removeChild(popup);
	var overlay = top.document.getElementById(d+"Overlay");
	if ( overlay ) overlay.parentNode.removeChild(overlay);

	var div = top.document.getElementById(d);
	if ( ! div ) div = top.document.body;
	div.style.overflow  = previousOverflow;
	div.style.overflowX  = previousOverflowX;
	div.style.overflowY  = previousOverflowY;
}

function popupDialog(url,x,y) {
	var target 	= 'overallWidth';
	var html 	= 'Loading...';
	overlayCenteredPopup(target,html,url,x,y,null,null,true);
}

function overlayCenteredPopup(d,html,url,x,y,coderef,hideclosebar,noscrollto,hideoverlay,popupclass) {
	var obj = document.getElementById(d);
	if ( !obj ) return;

	// center on object
	//var oPos = getPos(obj);
	//var posX = oPos[0] + ( parseInt(obj.offsetWidth)  / 2 + .5 ) - ( x / 2 );
	//var posY = oPos[1] + ( parseInt(obj.offsetHeight) / 2 + .5 ) - ( y / 2 );

	var wPos = getFrameCenter(top);
	var posX = x ? Math.round( wPos[0] - ( x / 2 ) ) : wPos[0];
	var posY = y ? Math.round( wPos[1] - ( y / 2 ) ) : wPos[1];
	overlayPopup(d,html,url,x,y,coderef,hideclosebar,noscrollto,hideoverlay,popupclass,posX,posY);
}


var xmlReq;
function insertGetRequestInto(target,url) {
	var tgt=null;

	// create a buffer div if need be.
	if ( target == '__BUFFER' ) {
		if ( top.document.getElementById(target) ) return;
		tgt = top.document.createElement('div');
		tgt.id = target;
		tgt.style.display="none";
		top.document.body.appendChild(tgt);
	} else if ( target.id ) {
		tgt = target;
	} else {
		tgt = top.document.getElementById(target);
	}
	if ( ! tgt || ! url ) return;

	top.document.body.style.cursor="wait";

	loadXMLDoc( url,function() {
	
		if ( xmlReq.readyState == 4 ) {
			var status = 0;
			try {
			if ( xmlReq.status != undefined && xmlReq.status != 0 ) {
					status == xmlReq.status;
				} else {
					status = -1;
				}
			}
			catch(e) {
				status = -1;
			}
			if ( !status ) {
				tgt.innerHTML = xmlReq.responseText;

				var scriptregex = new RegExp(/<script>([\s\S]+?)<\/script>/gim);		
				var m = scriptregex.exec(xmlReq.responseText);
				while ( m != null ) {
					for (var i=1; i < m.length; i++ ) {
						eval(m[i]);
/*
						try {
							eval(m[i]);
						} catch(e) {
							alert("Error running embedded script:\n"+e);
						}
*/
					}
					try {
						var m = scriptregex.exec(xmlReq.responseText);
					} catch(e) {
						m = null;
					}
				}

			} else {
				var err = "status: "+status;
				//alert(err);
			}

			// remove the buffer object
			if ( tgt.id == '__BUFFER' ) top.document.body.removeChild(tgt);
		
			top.document.body.style.cursor="auto";
		}
	} );
}
function loadXMLDoc(url, callback) {
	if ( ! callback ) return;

	xmlReq = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			xmlReq = new XMLHttpRequest();
        } catch(e) {
			xmlReq = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		xmlReq = false;
        	}
		}
    }
	if(xmlReq) {
		xmlReq.open("GET", url, true);
		xmlReq.onreadystatechange = callback;
		xmlReq.send("");
	}
}

/*
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
        } else {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
    }
}
*/

function toggleBox(id,val) {
	var a = document.getElementById(id);
	if ( !a ) { return }
	if ( ! val ) val = 'block';
	a.style.display= (a.style.display == '' || a.style.display == 'none') ? val : 'none';
}

function updateUpgrader() {
	var spanWS = document.getElementById('b1mx_ws_price');
	var spanRN = document.getElementById('b1mx_rn_price');
	var spanSubTotal = document.getElementById('subtotal');
	var qws = document.getElementById('b1mx_ws_q');
	var qrn = document.getElementById('b1mx_rn_q');

	var ws_price = document.getElementById('_U_ws_price').value;
	var rn_price = document.getElementById('_U_rn_price').value;
	var max_ws   = parseInt(document.getElementById('_U_max_ws').value);
	var max_rn   = parseInt(document.getElementById('_U_max_rn').value);


	var ws_total = 0;
	var rn_total = 0;
	if ( qws != null && qws.value > 0 ) {
		if ( parseInt(qws.value) > max_ws ) qws.value = max_ws;
		spanWS.innerHTML = formatNumber( parseInt(qws.value) * ws_price, '$,##0.00' );
		ws_total = parseInt(qws.value) * ws_price;
	}
	if ( qrn != null && qrn.value > 0  ) {
		if ( parseInt(qrn.value) > max_rn ) qrn.value = max_rn;
		spanRN.innerHTML = formatNumber( parseInt(qrn.value) * rn_price, '$,##0.00' );
		rn_total = parseInt(qrn.value) * rn_price;
	}

	var t  = ws_total + rn_total;
	spanSubTotal.innerHTML = formatNumber(t, '$,##0.00' );
}

function showInlineTab(i) {
	var flag=false;
	var j = 1;
	while ( 1 ) {
		var div = document.getElementById('inlineTab'+j);
		if ( !div ) break;
		div.style.display = i == j ? 'block' : 'none';
		j++;
	}
}


function loginLink(url) {
		var u =  document.getElementById('loginFormUsername');
		if ( u ) {
			u.focus();
			return;
		} else {
//			overlayPopup("overallWidth","Loading...","/login_popup.mhtml?url="+u, 300);
			if ( url == undefined ) url='';
			overlayPopup("overallWidth","Loading...","/widgets/account/index.mhtml?url="+url, 300);
		}
}
function passwordReset() {
		overlayPopup("overallWidth","Loading...","/widgets/passwordReset/", 400 );
}

function getRefresh(url) {
	window.open(url,'sfmgr');
	setTimeout("window.location.reload(true);", 3000 );
}

function doLogin() {
	var f = top.document.getElementById('loginForm');
	if ( ! f ) {
		alert("An error occured.  Please contact webmaster@splutterfish.com for assistance.");
		return;
	}
	if ( ! f['username'].value || ! f['password'].value ) {
		alert("You must enter both a username and password.");
		return;
	}

	var buf = buffer('_bufLOGIN');

	// execute the login request
	var qs = 'username=' + escape(f['username'].value) + '&password=' + escape(f['password'].value) + '&url='+escape(f['url'].value);
	if ( f['__REMEMBER'].checked == true ) qs = qs + '&__REMEMBER=1';
	overlayPopup("overallWidth","<div style='padding:3px;'>Logging in...</div>",'',300);
	insertGetRequestInto(buf.id, '/widgets/account/login.mhtml?' + qs);
	
}
function buffer(id) {
	var buf = top.document.createElement('div');
	buf.id = id;
	buf.style.display="none";
	top.document.body.appendChild(buf);
	return buf;
}
function doLoginCallback() {
	var login = top.document.getElementById('login_username');
	var error  = top.document.getElementById('login_error');
	var url  = top.document.getElementById('login_url');
	if ( error && error.innerHTML != '' ) {
		overlayPopup("overallWidth",error.innerHTML,'',300);
	} else {
		var u = login.innerHTML;
		overlayPopup("overallWidth","<div style='padding:3px;'><b>Welcome, " + u + "!</b><br />Please wait while this page refreshes...</div>",'',300);
		if ( window.location.href.match('/logout\.mhtml') ) {
			window.location.href="/sf/WebContent/MyAccount";
		} else if ( url && url.innerHTML )  {
			enableDiv('overallWidth');
			window.location.href=url.innerHTML;
		} else {
			enableDiv('overallWidth');
			window.location.reload(true);
		}
	}
}


/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function fmSetCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ( (expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function fmGetCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function fmDeleteCookie(name, path, domain)
{
    if (fmGetCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// recurse through an elements child nodes, looking for form elements.
function findFormElements(o) {
    if ( ! o.childNodes ) return;
	var inputs = new Array;
    for (var i=0; i<o.childNodes.length; i++) {
		var el = o.childNodes[i];
		if ( el.tagName == 'INPUT' || el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' ) {
			inputs[ inputs.length ] = el;
		} else if ( el.childNodes ) {
			var els = findFormElements(el);
			if ( els ) {
				for ( var j=0; j<els.length; j++ ) {
					inputs[inputs.length] = els[j];
				}
			}
		}
	}
	return inputs;
}

// turn form inputs into a string suitable for a GET.
function serializeForm(f) {
	var inputs = findFormElements(f); 
	var qs='';
	for ( var i=0 ; i < inputs.length; i++ ) {
        if (inputs[i].tagName == "INPUT") {
            if (inputs[i].type == "checkbox") {
                if (inputs[i].checked) {
                    qs += inputs[i].name + "=" + inputs[i].value + "&";
                } else {
                    qs += inputs[i].name + "=&";
                }   
            } else if (inputs[i].type == "radio") {
                if (inputs[i].checked) {
                    qs += inputs[i].name + "=" + inputs[i].value + "&";
                }   
            } else if ( inputs[i].name ) { 
                qs += inputs[i].name + "=" + inputs[i].value + "&";
            }   
        }   
        if (inputs[i].tagName == "SELECT") {
            var sel = inputs[i];
            qs += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
        }   
    }   
    return qs; 
}	

var registeredFunctions = new Array();
function regFunction(id,code) {
	registeredFunctions[id] = new Function(code);
}
function execFunction() {
	var f = registeredFunctions[ arguments[0] ];
	if ( ! f ) return;
	return f(arguments);
}
function delFunction(id) {
	if ( ! registeredFunctions[id] ) return;
	registeredFunctions[id] = null;
}

function irc(chan) {
	var qs = chan ? '?channel='+escape(chan) : '';
	window.open('/widgets/irc'+qs,"_blank","left=22,top=22,scrolling=no,toolbar=no,directories=no,width=600,height=550");
}

function loginOnEnter(e) {
	var val = typeof(e.which ) != 'undefined' ? e.which : e.keyCode;
	if ( val != 13 ) return;
	var f = document.getElementById('loginForm');
	if ( ! f ) return;
	doLogin();
}

function noEnter(e) {
	var val = typeof(e.which ) != 'undefined' ? e.which : e.keyCode;
	if ( val == 13 ) return false;
}


function getPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	    curleft = obj.offsetLeft
	    curtop = obj.offsetTop
	    while (obj = obj.offsetParent) {
	        curleft += obj.offsetLeft
	        curtop += obj.offsetTop
	    }   
	}   
	return [curleft,curtop];
}

function getFrameCenter(frame) {
	if ( !frame ) frame = self;
	var x,y,ox,oy;
	if (frame.innerHeight) // all except Explorer
	{
		x = frame.innerWidth;
		y = frame.innerHeight;
		ox = frame.pageXOffset;
		oy = frame.pageYOffset;
	}
	else if (frame.document.documentElement && frame.document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = frame.document.documentElement.clientWidth;
		y = frame.document.documentElement.clientHeight;
		ox = frame.document.documentElement.scrollLeft;
		oy = frame.document.documentElement.scrollTop;
	}
	else if (frame.document.body) // other Explorers
	{
		x = frame.document.body.clientWidth;
		y = frame.document.body.clientHeight;
		ox = document.body.scrollLeft;
		oy = document.body.scrollTop;
	}

	return [ ox + Math.round( x / 2 + .5 ), oy + Math.round( y / 2 + .5 ) ];
}

var suggestTimer = null;
var suggestTable = null;
var suggestColumn = null;
var suggestId = null;
var suggestDelim = '';
var suggestTerm = '';
	
function updateTagsOnEnter(e,id,url) {
	hideSuggestions();
	var val = typeof(e.which) != 'undefined' ? e.which : e.keyCode;
	if ( val != 13 ) return;
	var u = top.document.getElementById(id);
	if ( ! u ) return;
	insertGetRequestInto('__BUFFER', url + ( url.indexOf('?') != -1 ? '&' : '?' ) + '__VALUE='+u.value);
	return;
}
function suggestSearch(table,column,id,url,delim,e) {
	suggestTable = table;
	suggestColumn = column;
	suggestId = id;
	suggestDelim = delim;
	
	var val = typeof(e.which) != 'undefined' ? e.which : e.keyCode;
	switch (val) {

		case 0:
			return false;

		case 9:
			hideSuggestions(true);
			return false;

		case 37:
			return false;

		case 39:
			return false;

		case 38: // up arrow
			nextSuggestion(-1);
			return false;

		case 40: // down arow
			nextSuggestion(1);	
			return false;
		
		case 13: // enter
			hideSuggestions(true);
			var u = top.document.getElementById(suggestId);
			if ( u.value && url != null ) {
				var limg = top.document.getElementById(suggestId+'_loading');
				if ( limg ) {
					limg.style.display='block';
				}
				insertGetRequestInto('__BUFFER', url + ( url.indexOf('?') != -1 ? '&' : '?' ) + '__VALUE='+u.value);
			}
			return false;	
		default: // reset the timer between keypresses
			hideSuggestions();
			if ( suggestTimer ) {
				clearTimeout(suggestTimer);
			}
			suggestTimer = setTimeout('get_suggestion()',200);
			return true;
	}
}

function nextSuggestion( dir ) {
	var l = top.document.getElementById(suggestId+'_suggestionList');
	if ( ! l ) return;
	var li = new Array();
	for ( var i=0; i < l.childNodes.length; i++ ) {
		if ( l.childNodes[i].tagName == 'LI' ) li.push( l.childNodes[i] );
	}
	var selected=-1;
	for ( var i=0; i < li.length; i++ ) {
		if ( li[i].className == 'selected' ) selected=i;
		li[i].className='';
	}
	var i = selected + dir < 0 ? 0 : 
			selected + dir >= li.length ? li.length - 1 : 
			selected + dir;
	li[i].className='selected';

	var d = top.document.getElementById(suggestId+'_suggestions');
	if ( li[i].offsetTop > d.scrollTop + d.offsetHeight ) {
		d.scrollTop += ( 2 * li[i].offsetHeight );
	} else if ( li[i].offsetTop + li[i].offsetHeight < d.scrollTop ) {
		d.scrollTop -= li[i].offsetHeight;
	}
	
}

function takeSuggestion(li) {
	var el = top.document.getElementById(suggestId);
	el.focus();
	if ( suggestDelim ) {
		var re = new RegExp( '(.*)((?:'+suggestDelim+'\s*)?'+suggestTerm+')' );
		var m = re.exec(el.value);
		el.value = m == null ? li.innerHTML : m[1] + li.innerHTML;
		el.value += suggestDelim + ' ';
	} else {
		el.value = li.innerHTML;
	}
	hideSuggestions();
}

function get_suggestion() {
	clearTimeout(suggestTimer);
	var str = top.document.getElementById(suggestId).value;
	if ( str && suggestDelim ) {
		while ( str && str.indexOf(suggestDelim ) != -1 ) {
			str = str.substr(1);
		}
	}
	while ( str && str.indexOf(' ') == 0 ) {
		str = str.substr(1);
	}
	while ( str && str.indexOf(' ') == str.length ) {
		str = str.substr( 0, str.length-1 );
	}
	suggestTerm = str;

	if ( str ) {
		suggest(str, suggestTable, suggestColumn, 20);
	} else {
		var d = top.document.getElementById(suggestId+'_suggestions');
		if ( d ) {
			d.style.display='none';
		}
	}
}

function suggest(str,table,fields,limit) {
	var obj = top.document.getElementById(suggestId+'Form');
	var qs;
	if ( obj ) {
		obj.fields.value = fields;
		obj.__TABLE.value = table;
		obj.term.value = str;
		obj.callback.value = 'suggestCallBack';
		qs = '?' + serializeForm(obj);
	} else {
		qs = '?__TABLE='+suggestTable+'&fields='+suggestColumn+'&callback=suggestCallBack&term=' + escape(str);
	}
	var limg = top.document.getElementById(suggestId+'_loading');
	if ( limg ) {
		limg.style.display='inline';
	}
	insertGetRequestInto('__BUFFER','/widgets/suggest/'+qs);
}
function hideSuggestions(doTake) {
	if ( suggestTimer ) {
		clearTimeout(suggestTimer);
	}
	var d = top.document.getElementById(suggestId+'_loading');
	if ( d ) d.style.display='none';
	d = top.document.getElementById(suggestId+'_suggestions');
	if ( d ) d.style.display='none';
	if ( doTake == true ) {
		var l = top.document.getElementById(suggestId+'_suggestionList');
		if ( !l || l.style.display == 'none' ) return;
		for ( var i=0; i < l.childNodes.length; i++ ) {
			var li = l.childNodes[i];
			if ( li.tagName == 'LI' && li.className == 'selected' ) {
				takeSuggestion(li);
				break;
			}
		}
	}
	//top.document.getElementById(suggestId).focus();
}
function suggestCallBack(data) {
	if ( ! data.length ) {
		hideSuggestions();	
		return;
	}
	var d = top.document.getElementById(suggestId+'_suggestions');
	var u = top.document.getElementById(suggestId);
	if ( ! d ) {
		d = top.document.createElement('div');
		d.id = suggestId+'_suggestions';
		top.document.body.appendChild(d);
		d.className='inputSuggestions';
	}
	d.style.width= ( parseInt(u.offsetWidth) - 3 ) +'px';
	var pos = getPos( u );
	d.style.left = ( pos[0] + 1 ) +'px';
	d.style.top  = (pos[1]+parseInt(u.offsetHeight) )+'px';
	d.style.display='none';
	var html = "<ul id='"+suggestId+"_suggestionList'>";
	for ( var i=0; i < data.length; i++ ) {
		var val = eval( "data["+i+"]."+suggestColumn );
		html += "<li onClick='takeSuggestion(this);' onMouseOver='this.className=\"selected\";' onMouseOut='this.className=\"\";' >"+val+"</li>";
	}
	html += "</ul>";
	d.innerHTML = html;
	d.style.display='block';
	var limg = top.document.getElementById(suggestId+'_loading');
	if ( limg ) {
		limg.style.display='none';
	}
}


