Flash = function(swf, width, height, version, id)
{
    this.swf = swf || "";
    this.width = width || "100%";
    this.height = height || "100%";
    this.requiredVersion = version || 6;
    this.id = id || "mainSWF";
    this.params = new Object();
    this.variables = new Object();
};

Flash.hasVersion = function(requiredVersion)
{
    var hasVersion = false;
    if (navigator.plugins.length > 0 && navigator.plugins["Shockwave Flash"]) { // NS/Mozilla
        var description = navigator.plugins["Shockwave Flash"].description;
        var version = description.match(/\d{1,2}/);
        hasVersion = (version >= requiredVersion);
    }
    else if (window.ActiveXObject && window.execScript && navigator.userAgent.indexOf('Mac') == -1) { // Win IE
        Flash.hasActiveX = false;
        window.execScript("On error resume next: Flash.hasActiveX = IsObject(CreateObject('ShockwaveFlash.ShockwaveFlash." + requiredVersion + "'))", "VBScript");
        hasVersion = Flash.hasActiveX;
        delete Flash.hasActiveX;
    }
	 //alert(hasVersion);
    return hasVersion;
};

Flash.resizeTo = function(id, w, h)
{
    var movie = document.getElementById(id);
    movie.width = w;
    movie.height = h;
};

Flash.prototype.getSWF = function()
{
    return this.swf;
};

Flash.prototype.setSWF = function(swf)
{
    this.swf = swf;
};

Flash.prototype.getWidth = function()
{
    return this.width;
};

Flash.prototype.setWidth = function(w)
{
    this.width = w;
};

Flash.prototype.getHeight = function()
{
    return this.height;
};

Flash.prototype.setHeight = function(h)
{
    this.height = h;
};

Flash.prototype.getRequiredVersion = function()
{
    return this.requiredVersion;
};

Flash.prototype.setRequiredVersion = function(v)
{
    this.requiredVersion = v;
};

Flash.prototype.getId = function()
{
    return this.id;
};

Flash.prototype.setId = function(id)
{
    this.id = id;
};

Flash.prototype.getParam = function(name)
{
    return this.params[name];
};

Flash.prototype.getParams = function()
{
    return this.params;
};

Flash.prototype.setParam = function(name, value)
{
    this.params[name] = value;
};

Flash.prototype.getVariable = function(name)
{
    return this.variables[name];
};

Flash.prototype.getVariables = function()
{
    return this.variables;
};

Flash.prototype.setVariable = function(name, value)
{
    this.variables[name] = value;
};

Flash.prototype.getVariablePairs = function()
{
    var variablePairs = new Array();
    for (var name in this.getVariables()) {
        variablePairs.push(name + "=" + escape(this.getVariable(name)));
    }
    if (variablePairs.length > 0) {
        return variablePairs.join("&");
    }
    else {
        return null;
    }
};

Flash.prototype.getParamTags = function()
{
    var paramTags = "";
    for (var param in this.getParams()) {
        paramTags += '<param name="' + param + '" value="' + this.getParam(param) + '" />';
    }
    if (paramTags == "") {
        paramTags = null;
    }
    return paramTags;
};

Flash.prototype.getHTML = function()
{
    var flashHTML = "";
    if (window.ActiveXObject && navigator.userAgent.indexOf('Mac') == -1) { // PC IE
        flashHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + this.getWidth() + '" height="' + this.getHeight() + '" id="' + this.getId() + '">';
        flashHTML += '<param name="movie" value="' + this.getSWF() + '" />';
        if (this.getParamTags() != null) {
            flashHTML += this.getParamTags();
        }
        if (this.getVariablePairs() != null) {
            flashHTML += '<param name="flashVars" value="' + this.getVariablePairs() + '" />';
        }
        flashHTML += '</object>';
    }
    else { // Everyone else
        flashHTML += '<embed type="application/x-shockwave-flash" src="' + this.getSWF() + '" width="' + this.getWidth() + '" height="' + this.getHeight() + '" id="' + this.getId() + '"';
        for (var param in this.getParams()) {
            flashHTML += ' ' + param + '="' + this.getParam(param) + '"';
        }
        if (this.getVariablePairs() != null) {
            flashHTML += ' flashVars="' + this.getVariablePairs() + '"';
        }
        flashHTML += '></embed>';
    }
    
    return flashHTML;
};

Flash.prototype.render = function(elementId)
{
    //if(Flash.hasVersion(this.getRequiredVersion())) {
        if (elementId) {
            document.getElementById(elementId).innerHTML = this.getHTML();
        }
        else {
            document.write(this.getHTML());
        }
   // }
};
///////////////////////////////////////////////////////////////////////////
// make me an array of error messages
// heading
// message
// width of box
///////////////////////////////////////////////////////////////////////////
var errorMessage = new Array(11) // 2 total counting 0
						// error heading, error message, width of errorbox
errorMessage[0]= ['An Error Has Occured','Please correct the problem in the area below.','200'];
errorMessage[1]= ['Invalid Email Address','Please enter a valid email address.','200'];
errorMessage[2]= ['Invalid Password','Please enter a valid password.',''];
errorMessage[3]= ['Name Required','Please enter your name.','200'];
errorMessage[4]= ['Address Required','Please enter street address.',''];
errorMessage[5]= ['City Required','Please enter your city.',''];
errorMessage[6]= ['Zip Code Required','Please enter your zip code.',''];
errorMessage[7]= ['Account Name Required','Please enter your full name as you wouldl like it to appear on your account.',''];
errorMessage[8]= ['Social Security Number Invalid','Please enter a valid Social Security Number.',''];
errorMessage[9]= ['Invalid Date','Please enter the date as mm/dd/yyyy.',''];
errorMessage[10]= ['Invalid Number','Please enter digits only.',''];
errorMessage[11]= ['First Name Required','Please enter your first name.',''];
errorMessage[12]= ['Last Name Required','Please enter your last name.',''];
errorMessage[13]= ['Invalid Phone Number','Please enter a valid phone number.',''];



///////////////////////////////////////////////////////////////////////////
// autoValidateMe function - the lazyman's validator
///////////////////////////////////////////////////////////////////////////
function autoValidateMe(form) {
turnOffErrorFloat();
var formName = form.getAttribute('name');
var formObj = document.getElementById(formName);
var Error;
if (formObj) { inputs = formObj.getElementsByTagName("input"); }

for (var i = 0; i < inputs.length; i++) {
// reset all red inputboxes
if (inputs[i].getAttribute('type') == 'text') {
	var origClass = inputs[i].getAttribute('origClass');
		if (origClass) { inputs[i].className = origClass; }
		else { 
			if (inputs[i].getAttribute('class')) { 
			inputs[i].className = inputs[i].getAttribute('class');
			inputs[i].setAttribute("origClass",inputs[i].getAttribute('class'));
			}
	
		}
	}
}

for (var i = 0; i < inputs.length; i++) {
	if ((inputs[i].type == 'text') || (inputs[i].type == 'password')) {
	//alert(inputs[i].getAttribute('name'));
	var valAttribute = inputs[i].getAttribute('validate');
		if (valAttribute) {
			var b = inputs[i].getAttribute('m');
			if (!b) { b = 0; } //
			Error = validateMe(inputs[i].getAttribute('name'),formName,inputs[i].getAttribute('id'));
			if (Error) { break; }
		}
	}
	}
if (Error) { return false; }
else { return true; }
}


function makeObj(v) {
return eval('(' + v + ')'); 
}

///////////////////////////////////////////////////////////////////////////
// validateMe function - the master validator
///////////////////////////////////////////////////////////////////////////
function validateMe(name, formName, theId) {
//alert(name + ' - ' + theId);
// get the attribute that says what to validate
var outcome = false;
var vtype = document.getElementById(theId).getAttribute('validate');
var options = makeObj(vtype);

if (typeof(options.m) == 'object') {
//, head, message, width - errorMessage[b][0],errorMessage[b][1],errorMessage[b][2]
var head = options.m.heading;
var message = options.m.body;
var width = options.m.width;
options.m
} 
else {
//, head, message, width - errorMessage[b][0],errorMessage[b][1],errorMessage[b][2]
var head = errorMessage[options.m][0];
var message = errorMessage[options.m][1];
var width = errorMessage[options.m][2];
}
//digit length stuff
if (options.len) {
	var can_be_blank = options.len.blank;
	var min = options.len.min;
	var max = options.len.max;
	if (!max) { max = min; }
}

	// is it an email address
		if (options.type == 'email') {
			outcome = isEmailAddr(document[formName][name].value);
			}
	// is it empty
		else if (options.type == 'blank') {
			if (document[formName][name].value == '') { outcome = true; }
		}
	// is a zip code
		else if (options.type == 'zipCode') {
			outcome = checkzip(document[formName][name]);
		}
	// is a digitLength
		else if (options.type == 'digitLength') {
			outcome = checklength(document[formName][name],min,max,can_be_blank);
		}
	// is a phone number
		else if (options.type == 'phoneNumber') {
			outcome = checkphone(document[formName][name]);
		}
	// is a social security number
		else if (options.type == 'social') {
			outcome = checkSocial(document[formName][name]);
		}
	// is a date
		else if (options.type == 'date') {
			outcome = checkDate(document[formName][name]);
		}
	// is all digits
		else if (options.type == 'digit') {
			outcome = digitsonly(document[formName][name].value);
		}
	
	// if there was an error, show the box	
	if (outcome) {
		displayErrorFloat(theId,formName,head,message,width,options.align);
	}
return outcome;
}



//////////////////////////////////////////////////////////////////////
// make the current error message disappear
//////////////////////////////////////////////////////////////////////

function turnOffErrorFloat() {
	document.getElementById('errorContainer').style.display = 'none';
	document.getElementById('errorBottomFloat').style.display = 'none';
}


//////////////////////////////////////////////////////////////////////
// display floating error message
//////////////////////////////////////////////////////////////////////
function displayErrorFloat(obj,formName,heading,body,w,alignment) {
// turn off any existing error boxes
turnOffErrorFloat();

// assign header and body
document.getElementById('errorHeadingFloat').innerHTML = heading;
document.getElementById('errorBodyFloat').innerHTML = body;

// find positions of form element
var inputX = findPosX(document.getElementById(obj));
var inputY = findPosY(document.getElementById(obj));
var inputW = document.getElementById(obj).offsetWidth;

// display the errorContainer
document.getElementById('errorContainer').style.display = "block";

// if width param was passed, the assign it to box
if (w) { document.getElementById('errorContainer').style.width = w + 'px'; }

// find the width and height of the errorContainer
var errorContainerW = document.getElementById('errorContainer').offsetWidth;
var errorContainerH = document.getElementById('errorContainer').offsetHeight;

//alert(alignment);
//var alignObj = makeObj(alignment);

if (typeof(alignment) == 'object') { 
 document.getElementById('errorContainer').style.left = (inputX + parseInt(alignment.left));
 document.getElementById('errorContainer').style.top = (inputY + parseInt(alignment.top));
}

else {
// left alignment
if (alignment == 'right') { document.getElementById('errorContainer').style.left = ((inputX + inputW) - 40); }
else if (alignment == 'center') { document.getElementById('errorContainer').style.left = ((inputX + (inputW/2)) - (errorContainerW/2)); }
else { document.getElementById('errorContainer').style.left = (inputX - 10); }

// top alignment
inputY = inputY - (errorContainerH + 20);
document.getElementById('errorContainer').style.top = inputY + "px";
}



errorContainerX = findPosX(document.getElementById('errorContainer'));
errorContainerY = findPosY(document.getElementById('errorContainer'));

if (alignment == 'right') { document.getElementById('errorBottomFloat').style.left = (errorContainerX + 20); }
else if (alignment == 'center') { document.getElementById('errorBottomFloat').style.left = ((errorContainerX + (errorContainerW/2) - 12)); }
else { document.getElementById('errorBottomFloat').style.left = (errorContainerX + 20); }
document.getElementById('errorBottomFloat').style.top = (errorContainerY + (errorContainerH - 3));
document.getElementById('errorBottomFloat').style.display = "block";


// make the input box turn red and add focus to it
document[formName][obj].className = "inputError";
//document[formName][obj].style.backgroundColor = "#F8E0DE";
document[formName][obj].focus();

new Effect.ScrollTo('errorContainer', {offset: -30, duration: .2, queue: 'end'});
}














function isEmailAddr(email) {  
var result = true; 
var theStr = new String(email); 
var index = theStr.indexOf("@"); 
if (email == '') { return true; } 
else if (index > 0) { var pindex = theStr.indexOf(".",index);
if ((pindex > index+1) && (theStr.length > pindex+1)) result = false; }
return result; 
}

function checkzip(obj) {
var zip = getNumber(obj.value);
obj.value = zip;
if (zip.length < 5) { return true; }
else { return false; }
}

function checkphone(obj) {
var phone = getNumber(obj.value);
obj.value = phone;
if (phone.length < 10) { return true; }
else { return false; }
}

function checklength(obj,min,max,can_be_blank) {
var oblen = getNumber(obj.value);
var origvalue = obj.value;
obj.value = oblen;
//alert(oblen + '<' + min + ' - ' + oblen + '>' + max);

//alert('min:' + (oblen >= parseInt(min)));
//alert('max:' + (oblen <= parseInt(max)));

// can be blank
if ((oblen.length >= parseInt(min)) && (oblen.length <= parseInt(max))) { return false; }
else { 
		if (can_be_blank == 'yes') { 
			if (origvalue == '') { return false; }
			else { return true; }
		}
		else {
			return true;
		}
 }

}

function checkSocial(obj) {
var soc = getNumber(obj.value);
soc = formatSocial(soc);
if (soc != "--") { obj.value = soc; }
if (soc.length != 11) { return true; }
else { return false; }
}

function checkDate(obj) {
var d = getNumber(obj.value);
d = formatDate(d);
if (d != "//") { obj.value = d; }
if (d.length != 10) { return true; }
else { return false; }
}

function digitsonly(wee) {
zee = getNumber(wee);
if ((wee.length != zee.length) || (wee.length == 0) || (wee == '')) {
return true;
}
}

////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////

function checkblank(n,c,t) {
	if (document.tf[n].value == ""){
	  alert(c);
	  if (t != '1') { document.tf[n].focus(); }
	return false;
	}
	else { return true; }
}

function checkemail(n,c) {
if ((document.tf[n].value == "") || (!isEmailAddr(document.tf[n].value))) {
        alert(c);
	document.tf[n].focus();
	return false;
	}
else { return true; }
  }


function checkpayment() {
	if (document.tf.paymenttype.value == ""){
	  alert('Please select a payment type.');
	  document.tf.paymenttype.focus();
	return false;
	}
	else if (document.tf.paymenttype.value != "Check") { 
		if (document.tf.nameoncard.value == "") { alert('Please enter the name as it appears on the credit card.'); document.tf.nameoncard.focus(); return false; }
		var cc = getNumber(document.tf.ccnumber.value);
		document.tf.ccnumber.value = cc;
		if (!cc > 0) { alert('Please enter a valid Credit Card Number.'); document.tf.ccnumber.focus(); return false; }
		else { return true; }
	}
	else { return true; }
}





function formatNumber(tobject)
	{
		var unformatted = stringReplace(tobject.value, "-", "")
		var formatted = unformatted.substring(0,3) + "-" + unformatted.substring(3,6) + "-" + unformatted.substring(6,10)
		if (unformatted.length > 10)
		{
			tobject.value = formatted + "-" + unformatted.substring(10,15)
		} else {
			tobject.value = formatted
		}
	}
	
function formatSocial(tobject)
	{
		var unformatted = stringReplace(tobject, "-", "");
		var formatted = unformatted.substring(0,3) + "-" + unformatted.substring(3,5) + "-" + unformatted.substring(5,9);
		return formatted;
	}	
	
function formatDate(tobject)
	{
		var unformatted = stringReplace(tobject, "/", "");
		var formatted = unformatted.substring(0,2) + "/" + unformatted.substring(2,4) + "/" + unformatted.substring(4,8);
		return formatted;
	}	
	
function stringReplace(originalString, find, replace)
	{
		var pos=0, preString, postString
		pos = originalString.indexOf(find)
		while (pos != -1)
		{
			preString = originalString.substring(0,pos)
			postString = originalString.substring(pos+1, originalString.length)
			originalString = preString + replace + postString
			pos = originalString.indexOf(find)
		}
		return originalString;
	}




function getNumber(sNumber)
{
	var valid = "0123456789";
	var temp;
	var sNewNumber = '';
	for (var i=0; i < sNumber.length; i++) 
	{
		temp = '' + sNumber.substring(i, i+1);
		if (valid.indexOf(temp) != "-1") 
		{
			sNewNumber = sNewNumber + temp;
		}
	}
	return sNewNumber;
}



//////////////////////////////////////////////////////////////////////
// add a page load event
//////////////////////////////////////////////////////////////////////
// Add it to window.onload event
//addOnLoad(function() {clearfix("clearthis");});

/*
 * Adds a function into the onload event
 * Usage: addOnLoad(functionName)
 * Or, if you need to pass arguments in the
 * function:
 * addOnLoad(function() {functionName("argument")})
*/
function addOnLoad(newFunction) {
    var currentOnLoad = window.onload;
    if (typeof window.onload != "function") {
        window.onload = newFunction;
    }
    else {
        window.onload = function() {
            currentOnLoad();
            newFunction();
        }
    }
}



//////////////////////////////////////////////////////////////////////
// assign click events to the promoClass on the HP
//////////////////////////////////////////////////////////////////////

function setupPromoEvents() { 
var sp = $$('.promo').each( function(e) {
var inc = e.getElementsByTagName("a");
e.setAttribute('link',inc[0].getAttribute('href'));
e.onclick = function() { location.href = this.getAttribute('link'); }
e.onmouseover = function() { this.className = "promoActive"; }
e.onmouseout = function() { this.className = "promo"; }
});
}

//////////////////////////////////////////////////////////////////////
// show regions on homepageizzle
//////////////////////////////////////////////////////////////////////
var rrTimerID;

function hpRegion(startRegionH,processing) {

var regionCookie = readCookie('region');
if (regionCookie) {
	var rob = document.regionForm.region;
	for (var i = 0; i < rob.length; i++) {
		if (rob[i].value == regionCookie) {
			rob.selectedIndex = i; 
		}
	}
}
	
	
if (document.getElementById('hpRegionContainer').style.display == "block") { 
document.getElementById('rbottom').style.display = "none";
if (processing) { document.getElementById('hpSelectARegion').style.backgroundPosition = "0 -50px"; }
else { document.getElementById('hpSelectARegion').style.backgroundPosition = "0 0"; }
RegionUp(startRegionH,startRegionH); }
else {
document.getElementById('rbottom').style.display = "block";
document.getElementById('hpSelectARegion').style.backgroundPosition = "0 -25px"; 
RegionDown('1',startRegionH); }
}


function RegionUp(h,startRegionH) {
clearTimeout(rrTimerID);
if (h > 1) {
h = h - 20;
if (h < 1) { h = 1; }
document.getElementById('hpRegionContainer').style.height = h;
rrTimerID = setTimeout("RegionUp('" + h + "')", 10); // do it again and again
}
else if (h == 1) { document.getElementById('hpRegionContainer').style.display = "none"; }
}



function RegionDown(h,startRegionH) {
clearTimeout(rrTimerID);
if (h == 0) { h = 1; }
document.getElementById('hpRegionContainer').style.display = "block";
h = parseFloat(h);
if (h < startRegionH) {
h = h + 20;
document.getElementById('hpRegionContainer').style.height = h;
rrTimerID = setTimeout("RegionDown('" + h + "','" + startRegionH + "')", 30); // do it again and again
}
else { document.getElementById('hpRegionContainer').style.height = startRegionH; }
}



//////////////////////////////////////////////////////////////////////
// scroll
//////////////////////////////////////////////////////////////////////
var pl3TimerID;
var times = 0;
var scrollToPos = "-190";
var sp;
var sc;
var curX;
var scc;
var max;

function pl3scroll(d) {
////////////////////////////////////////////////////////////////////////////////////
// the first time you clicky, get the total number of promo divs to know when to stop
if (!sc) {
sp = document.getElementById('promoLevel3Inside').getElementsByTagName("div");
sc = 0;
scc = 0;
for (var i = 0; i < sp.length; i++) { if (sp[i].className == "promo") { sc++; } }
}
////////////////////////////////////////////////////////////////////////////////////
if (d == "prev") { scc = scc - 1; }
else { scc++; }
if (scc < 0) { scc = 0; } 
curX = parseFloat(document.getElementById('promoLevel3Inside').style.left);
if (!curX) { curX = 0; }
max = sc / 4;
if (scc > max) { scc = max; }
//alert('scc:' + scc + ' max:' + max);

if (scc == max) { document.getElementById('FeaturesNext').className = ""; }
else {  document.getElementById('FeaturesNext').className = "active"; }
if (scc > 0) { document.getElementById('FeaturesPrev').className = "active"; }
else {  document.getElementById('FeaturesPrev').className = ""; }

pl3Loop(d);
}


function pl3Loop(d) {
clearTimeout(pl3TimerID);
stopPos = (scrollToPos * scc); // with of promo div X current next/prev number
if (curX != stopPos) {
if (d == "next") { curX = curX - 10; } // subtract 4 to go forward
else { curX = curX + 10; if (curX > 0) { curX = 0; } } // add 4 to go backwards
document.getElementById('promoLevel3Inside').style.left = curX; // set current left pos
pl3TimerID = setTimeout("pl3Loop('" + d + "')", 0); // do it again and again
}
//else { 
//	alert(stopPos); alert(curX); // says im done!
//	 }
}

//////////////////////////////////////////////////////////////////////
// cookie functions
//////////////////////////////////////////////////////////////////////
function createCookie(name,value,days,domain)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	wholecookie = name+"="+value+expires+"; path=/;";
	if (domain) { wholecookie = wholecookie + "domain=" + domain + ";"; }
	document.cookie = wholecookie;
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name,domain)
{
	createCookie(name,"",-1,domain);
}

//////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////
// find x and y positions of an element
//////////////////////////////////////////////////////////////////////
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}
//////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////
// scrollPageTo(endPosition)
//////////////////////////////////////////////////////////////////////
var scrolldelay;
function scrollPageTo(end) {
		clearTimeout(scrolldelay); // clear the repeater
		var currentPos = (document.all)?document.body.scrollTop:window.pageYOffset; 
		if (currentPos > end) {
    	window.scrollBy(0,-10); // horizontal and vertical scroll increments
    	scrolldelay = setTimeout('scrollPageTo(\'' + end + '\')',10); 
		}
		//alert(end);
}



//////////////////////////////////////////////////////////////////////
// upperFirst(whattomakeuppercasefirst)
// makes things all lowercase then uppercases the first letter of
// each word
//////////////////////////////////////////////////////////////////////
function upperFirst(u){
 u = u.toLowerCase();
 u = u.split(' ');
 for (i=0;i<u.length;i++)
   u[i] = u[i].replace(/^(.)/,u[i].charAt(0).toUpperCase());
 return u.join(' ');
}
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// make me a window
//////////////////////////////////////////////////////////////////////

function makewindow(url,name,wi,hi,scroll) {  
if (!scroll) { scroll = 0; }
mywin = window.open(url,name,'width=' + wi + ',height=' + hi + ',toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll); }

//////////////////////////////////////////////////////////////////////
// autotab
//////////////////////////////////////////////////////////////////////
var phone_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
				}
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	//////////////////////////////////////////////////////////////////////
// define regions
//////////////////////////////////////////////////////////////////////

var timerID; // for shutoff function
var regions = new Array(16) // 16 total counting 0
regions[0]="Cincinnati";
regions[1]="Dayton";
regions[2]="Mason";
regions[3]="Beavercreek";
regions[4]="Franklin";
regions[5]="Huber Heights";
regions[6]="Kettering";
regions[7]="Miamisburg";
regions[8]="Middletown";
regions[9]="Monroe";
regions[10]="Oakwood";
regions[11]="Springboro";
regions[12]="Spring Valley";
regions[13]="Trenton";
regions[14]="Vandalia";
regions[15]="West Carrollton";





//////////////////////////////////////////////////////////////////////
// prev next buttons for intro page
//////////////////////////////////////////////////////////////////////
var regionState = 0; // starting region 
var totalRegions = 2; // total region uls divided by 2
var increment = "214"; // total pixels to move to the left per 2 uls

function region(direction) {
	if (direction == "prev") {
		if (regionState > 0) { regionState = (regionState - 1); }
	}
	else if (direction == "next") {
		if (regionState < (totalRegions - 1)) { regionState = (regionState + 1); }
	}
	
	var location = (increment * regionState);
	document.getElementById('regionContainerInner').style.left = "-" + location + "px";
	
	if (regionState == 0) { document.getElementById('regionPrev').className = "prevRegionDisabled"; }
	else { document.getElementById('regionPrev').className = "prevRegion"; }
	
	if (regionState < (totalRegions - 1)) { document.getElementById('regionNext').className = "nextRegion"; }
	else { document.getElementById('regionNext').className = "nextRegionDisabled"; }
}


//////////////////////////////////////////////////////////////////////
// select region button
//////////////////////////////////////////////////////////////////////
var regionVisible = "no";

function initRegion() {

/*document.getElementById('selectARegionButton').onclick = function() {
	turnOffErrorFloat();
	if (regionVisible == "no") {
	document.getElementById('mainContainerInner').style.top = '-699px';
	document.getElementById('selectARegionButton').style.backgroundPosition = "0 -21px";
	regionVisible = "yes";
	elbo();
	}	
	else {
	document.getElementById('mainContainerInner').style.top = '-233px';
	document.getElementById('selectARegionButton').style.backgroundPosition = "0 0";
	regionVisible = "no";
	elbo();	
	}
}

document.getElementById('regionClose').onclick = function() {
	document.getElementById('mainContainerInner').style.top = '-233px';
	document.getElementById('selectARegionButton').style.backgroundPosition = "0 0";
	regionVisible = "no";
	elbo();	
}

*/


// setup click events for regions
var x=0;
var regionCookie = readCookie('region');

if (regionCookie) {
regionCookie = regionCookie.replace('%20',' ');
if (regionCookie == '') { regionCookie = "Cincinnati"; }
if (regionCookie != "Cincinnati") { document.getElementById('introSiteId').innerHTML = ": " + regionCookie; }
} 
//for (x=0; x<16; x++) { 
//var obj = regions[x];
//if (regionCookie == '') { regionCookie = "Cincinnati"; }
//if (regionCookie != "Cincinnati") { document.getElementById('introSiteId').innerHTML = ": " + regionCookie; }
//document.getElementById(obj).onclick = changeRegion;
//if (regionCookie == obj) { document.getElementById(obj).className = 'active'; }
//}

}

//////////////////////////////////////////////////////////////////////
// show region elbo
//////////////////////////////////////////////////////////////////////
function elbo() {
//////////////////////////////////////////////////////////////////////
// on resize, move elbo
//////////////////////////////////////////////////////////////////////
window.onresize = elbo;
//////////////////////////////////////////////////////////////////////

if (regionVisible == "yes") {
var sabX = findPosX(document.getElementById('selectARegionButton'));
var sabY = findPosY(document.getElementById('selectARegionButton'));
document.getElementById('introElbo').style.top = (sabY - 12) + "px";
document.getElementById('introElbo').style.left = (sabX - 90) + "px";
document.getElementById('introElbo').style.display = "block";
}
else {
document.getElementById('introElbo').style.display = "none";
}
}




//////////////////////////////////////////////////////////////////////
// change the region based on click
//////////////////////////////////////////////////////////////////////
function changeRegion(r) {
// turn off all 
var x=0;

for (x=0; x<16; x++) { 
var obj = regions[x];
document.getElementById(obj).className = ''; }
eraseCookie('region');
createCookie('region', this.innerHTML,90,'cincinnatibell.com');
document.getElementById('introSiteId').innerHTML = ": " + this.innerHTML;
this.className = "active";
clearTimeout(timerID);
timerID = setTimeout("shutoff()", 1500);
new Effect.Highlight(this);
}
//////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////
// if you clicky the region, wait 2 seconds to run this to close region
//////////////////////////////////////////////////////////////////////
function shutoff() {
document.getElementById('mainContainerInner').style.top = '-233px';
document.getElementById('selectARegionButton').style.backgroundPosition = "0 0";
regionVisible = "no";
elbo();
clearTimeout(timerID);
}
//////////////////////////////////////////////////////////////////////

function setupRegionDropDown() {
var regionCookie = readCookie('region');
if (regionCookie) {
	var rob = document.regionForm.region;
	for (var i = 0; i < rob.length; i++) {
		if (rob[i].value == regionCookie) {
			rob.selectedIndex = i; 
		}
	}
}
}


//////////////////////////////////////////////////////////////////////
// change the region based dropdown
//////////////////////////////////////////////////////////////////////
function changeRegionDD(r) {
// turn off all 
eraseCookie('region');
var cookieDomain = '';
if (location.hostname.indexOf("cincinnatibell.com") > -1) { cookieDomain = "cincinnatibell.com"; }
createCookie('region', r.value,90,cookieDomain);
clearTimeout(timerID);
// squish the button, then make it rotatey
//hpRegion('80','yes');
new Effect.BlindUp('regionNav', { duration: .2});
// wait then reload
if ((r.value == "Mason") || (r.value == "Morrow") || (r.value == "SouthLebanon")) { timerID = setTimeout("location.href = '/consumer/bundles/';", 1200); }
else { timerID = setTimeout("location.href = location.href;", 1200); }
}


var regionVisible = "no";


//////////////////////////////////////////////////////////////////////
// onload, setup the events
//////////////////////////////////////////////////////////////////////

addOnLoad(function() { initNav(); });

function initNav() {
var x=0;
var lvl3active = 0;
var loggedinCookie = readCookie('loggedin');
var nl3;
var nl2SignOut;
var lvl3buttons;
var lvl3active;

//////////////////////////////////////////////////////////////////////
// setup click events for level3Nav and link for clicky
// get the div named navLevel3
nl3 = document.getElementById('navLevel3');

if (nl3) {
// get all the li tags inside of nl3
lvl3buttons = nl3.getElementsByTagName("li");

// loop through all li tags in nl3
// assign click, over and out events unless they
// have an class of active
for (var i = 0; i < lvl3buttons.length; i++) {
	//lvl3buttons[i].onclick = function () { location.href = this.getElementsByTagName("a")[0].href;	 }
	
	if (lvl3buttons[i].id == nl3_id) { lvl3buttons[i].className = "active"; }
	
   if (lvl3buttons[i].className != "active") {
		lvl3buttons[i].onmouseover = function () {this.style.background='transparent url(/images/nav/level3bg_over.gif) repeat-x'; }
		lvl3buttons[i].onmouseout = function () {this.style.background='transparent'; }
	}
	else { lvl3active = lvl3buttons[i].getElementsByTagName("a")[0].href; }
}
}
	
	
//////////////////////////////////////////////////////////////////////
// set the sign in sign out button status
if (loggedinCookie) {
	if (loggedinCookie == "1") { document.getElementById('inout').innerHTML = "<a href=\"/my/out/\">Sign Out</a>"; }
}


}
// end init


//////////////////////////////////////////////////////////////////////
// put the region in the site id 
//////////////////////////////////////////////////////////////////////
function siteIdRegion() {
var regionCookie = readCookie('region');
if (regionCookie == '') { regionCookie = "Cincinnati"; }
if (regionCookie != "Cincinnati") { document.getElementById('hpsiteId').innerHTML = ": " + regionCookie; document.getElementById('navLevel2').className = "withRegion"; }

}

//////////////////////////////////////////////////////////////////////
// abbreviate really long stuff
// thing to shorten, length to shorten too
//////////////////////////////////////////////////////////////////////
function abrev(obj,len) {
	var abv = obj.innerHTML;
		if (abv.length > len) {
			var abv_a = abv.split("");
			var abvTemp = '';
				for (i =0; i < len; i++) { abvTemp += abv_a[i]; }
						obj.innerHTML = abvTemp + '...';
		}
	}

	
	
	
//////////////////////////////////////////////////////////////////////
// customer support product help ajax wizzywig
//////////////////////////////////////////////////////////////////////	

function updateContent_1(target, select, an) {
if (select != '#') {
new Ajax.Updater(target, select, {asynchronous:true, evalScripts:true, onComplete:function(request){ new Effect.Appear(target); if (an && $(an)) { new Effect.ScrollTo(an, {offset: -20, duration:.5}); } }});
}
else { $(target).innerHTML = ''; new Effect.Highlight('topTopics'); }
}

function updateCategory_1(target, select) {
if(select != '#') {
new Ajax.Updater(target, select, {asynchronous:true, evalScripts:true, onComplete: function(request) { new Effect.Highlight('topTopics'); } });
}
else { $(target).innerHTML = ''; new Effect.Highlight('topTopics'); }
}
  
function  preSelect(subcat, subtarget, form, target, an) {
	var len = form[subtarget].length;
	for (i=0; i < len; i++) {
			if (form[subtarget][i].innerHTML.toLowerCase() == subcat) {  
			form[subtarget].selectedIndex = i;
			updateContent(target, form[subtarget][i].value, an);
			 }
		}
		
}
	
	
	
	

//////////////////////////////////////////////////////////////////////
// assign behaviors for tabs
//////////////////////////////////////////////////////////////////////
var tabRules = {
		'.tabList li' : function(element){
			element.onmouseover = function(){
				this.style.cursor = 'pointer';
			}
			element.onclick = function() {
				location.href = element.getElementsByTagName("a")[0].getAttribute("href");
			}
		}
};

//////////////////////////////////////////////////////////////////////
// assign behaviors for manage icons
//////////////////////////////////////////////////////////////////////
var manageMyIconRules = {
		'ul.manageMyIcons li' : function(element){
			element.onclick = function(){
				location.href = element.getElementsByTagName("a")[0].getAttribute("href");
			}
		}
};


//////////////////////////////////////////////////////////////////////
// abbreviate name and street address
//////////////////////////////////////////////////////////////////////
var addressRules = {
		'div#accountInfoContainer label.name' : function(element){
			abrev(element, '20');
		},
		'div#accountInfoContainer label.address' : function(element){
			abrev(element, '40');
		}
};


//////////////////////////////////////////////////////////////////////
// addressSelectSpinner
//////////////////////////////////////////////////////////////////////
var spinnerRules = {
		'div#addressSelectSpinner' : function(element){
			var spinner = new Flash("/swf/loaders/spinner.swf", 16, 16, 7);
				 spinner.setParam("menu", "false");
				 spinner.setParam("quality", "best");
				 spinner.setParam("salign", "tl");
				 spinner.setParam("scale", "noscale");
				 spinner.setParam("wmode", "transparent");
				 spinner.render(element.id);
		}
};

//////////////////////////////////////////////////////////////////////
// assign behaviors for expand link my account
//////////////////////////////////////////////////////////////////////
var manageMyViewDetailsRules = {
		'.viewTextDetails' : function(element) {
			element.onclick = function(){
				var obj = element.getAttribute('title');
				new Effect.Appear(obj, {duration: '.5'});
				delay = setTimeout('new Effect.ScrollTo(\'' + obj + '\', {offset: -20, duration:1.0})', 1000);
				return false;
			}
		},
		'.viewDetails' : function(element) {
			element.onclick = function(){
				var obj = element.getAttribute('title');
				//new Effect.BlindDown(obj, {duration: '.5'});
				//new Effect.toggle(obj,'blind', {duration: '.5'});
				if ($(obj).style.display == 'block') { $(obj).style.display = 'none'; }
					else { $(obj).style.display = 'block'; 
					//delay = setTimeout('new Effect.ScrollTo(\'' + obj + '\', {offset: -20, duration:1.0})', 1000);
				 }
				return false;
			}
		}
};
//////////////////////////////////////////////////////////////////////
// assign behaviors for collapse link my account
//////////////////////////////////////////////////////////////////////
var manageMyCloseDetailsRules = {
		'.closeTextDetails' : function(element){
			element.onclick = function(){
				var obj = element.getAttribute('title');
				new Effect.Fade(obj, {duration: '.5'});
				return false;
			}
		}
};

//////////////////////////////////////////////////////////////////////
// assign behaviors to ldPlan highlight
//////////////////////////////////////////////////////////////////////
var planHighlightRules = {
		'.ldPlan' : function(element){
			element.onmouseover = function(){
				element.className = 'ldPlanActive';
			}
			element.onmouseout = function(){
				element.className = 'ldPlan';
			}
			element.onclick = function() {
				location.href = element.getElementsByTagName("h5")[0].getElementsByTagName("a")[0].getAttribute("href");
			}
		}
};


		var supportCategory = '';
        var CategoryID = '';
        var SubCategoryID = '';
        var expectedHash = '';
        var hashhistory = '';
        
       function makeHistory(newHash)
		{		
		window.location.hash = newHash;
		//alert("newHash: " + newHash);
		expectedHash = window.location.hash;
		//alert("expectedHash: " + expectedHash);
		return true;
		}



//////////////////////////////////////////////////////////////////////
// assign behaviors to cust_serv subnav
//////////////////////////////////////////////////////////////////////
var custServRules = {
		'div.navLevel7 ul li.ajax' : function(element){
			// take the text inside the link, replace the spaces with underscores
			// use that to create the bodyUrl for the ajax call for onclick
			// reset className
			var url = element.getElementsByTagName("a")[0].getAttribute('doc').toLowerCase();
			var anchor = element.getElementsByTagName("a")[0].getAttribute('anchor').toLowerCase();
			var bodyUrl = '/customer_support/product_support/documents/getdocument.aspx';				
			
					
			// add event
			// when click get the page via ajax call using prototype
			element.onclick = function(){
				var d = new Date();
				var m = 'idocumentid=' + url + '&m=' + d.getTime();	
				var ajax = new Ajax.Updater(
					{success: 'contentTarget'},
					bodyUrl,
					{method: 'get',
					parameters: m,
					onComplete: function() { new Effect.ScrollTo('contentTarget',{offset: -20, duration:.5});},
					onFailure: function() { document.getElementById('contentTarget').innerHTML = "Error"; },
					evalScripts: true});
					
					//CategoryID = document.helpForm.category[document.helpForm.category.selectedIndex].value;
					//SubCategoryID = document.helpForm.subcategory[document.helpForm.subcategory.selectedIndex].value;
					
					//makeHistory('category=' + CategoryID + '&subcategory=' + SubCategoryID + '&content=' + url );			
				return false;
			}
		}
};

//////////////////////////////////////////////////////////////////////
// zebra stripe your tables
//////////////////////////////////////////////////////////////////////
var tableStripes = {
		'table.zebra' : function(element){
			stripeTable(element);
		}
};




addOnLoad(function() { 
if ($('hpsiteId')) { $('hpsiteId').onclick = function() { location.href = '/'; }}
});


function stripeTable(o) {
	var c = 0;
	the_trs = o.getElementsByTagName('tr');
		for (i=1; i < the_trs.length; i++) {
			if (c == 0) { the_trs[i].className = 'even'; }
		else { the_trs[i].className = 'odd'; }
		c++;
		if (c > 1) { c = 0; }
	}
}

/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   Description:
   	
   	Uses css selectors to apply javascript behaviours to enable
   	unobtrusive javascript in html documents.
   	
   Usage:   
   
	var myrules = {
		'b.someclass' : function(element){
			element.onclick = function(){
				alert(this.innerHTML);
			}
		},
		'#someid u' : function(element){
			element.onmouseover = function(){
				this.innerHTML = "BLAH!";
			}
		}
	};
	
	Behaviour.register(myrules);
	
	// Call Behaviour.apply() to re-apply the rules (if you
	// update the dom, etc).

   License:
   
   	This file is entirely BSD licensed.
   	
   More information:
   	
   	http://ripcord.co.nz/behaviour/
   
*/   

var Behaviour = {
	list : new Array,
	
	register : function(sheet){
		Behaviour.list.push(sheet);
	},
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},
	
	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);
				
				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},
	
	addLoadEvent : function(func){
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

/*
   The following code is Copyright (C) Simon Willison 2004.

   document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names, 
     class names and ids and can be nested. For example:
     
       elements = document.getElementsBySelect('div#main p a.external')
     
     Will return an array of all 'a' elements with 'external' in their 
     class attribute that are contained inside 'p' elements that are 
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/
