/** 
* @projectDescription	Globally-used javascript
*
* @id	base.js
*/

// IE6 Browser Detection
Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE") + 5), 10) === 6;

Effect.Transitions.EaseFromTo = function(pos) {
    if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
    return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);   
}; 
Effect.Transitions.easeOutSine = function (pos) {
     return Math.sin(pos * (Math.PI / 2));
};


/*--------------------------------------------------------------------------*/

var PopUp = Class.create({
	initialize : function (trigger, pop, options) {
	    if ((! trigger) || (! pop)) { return; }
		this.trigger = trigger;
		this.pop = $(pop);
		
		this.options = Object.extend({
			modal:  false,
			centered: false,
			fade: false,
			closeSelector:  '.close',
			handleSelector: '.overlay_head',
			enableHover: false,
			delay: 0,
			onOpen:    Prototype.emptyFunction,
			onClose:   Prototype.emptyFunction
		}, options || {});
		
		PopUp.i = 0;
		PopUp.open = false;
		this.setup();
	},
	setup : function () {
		this.pop.hide();
		if (this.options.enableHover) {
			this.trigger.observe('mouseenter', this.show.bindAsEventListener(this));
			
		}
		else {
			this.trigger.observe('click', this.open.bindAsEventListener(this));
		}
	},
	show: function (ev) {
		this.trigger.observe('mouseleave', function () {
			if (this.timeout) {
				clearTimeout(this.timeout);
				return;
			}
		}.bind(this));	
		
		this.timeout = setTimeout(this.open.bind(this), this.options.delay);
	},
	open : function (ev) {
		document.observe('pop:keepOpen',  function () { 
			Event.stopObserving(document, 'click', this.close_listener);
			
		}.bind(this));			
		
		// allow only one popup opened at a time
		if (PopUp.open) { 
			PopUp.open.close(false); 
		}
		PopUp.open = this;	
	
		document.fire("pop:active");
		this.toTop();
		this.trigger.addClassName("active");
		
		// close button(s)
		this.pop.select(this.options.closeSelector).each(function (el) {
			el.observe('click', this.close.bind(this));
		}.bind(this));
		
		// draggable handle
		this.pop.select(this.options.handleSelector).each(function (el) {
			this.draggable = new Draggable(this.pop, { handle: this.handle, starteffect: false, endeffect: false });
		}.bind(this));
				
		// close pop if user clicks anywhere in document
		this.close_listener = this.close.bindAsEventListener(this);
		Event.observe(document, 'click', this.close_listener);
		document.observe('pop:close',  this.close_listener);
		
		if (this.options.enableHover) {
			this.pop.observe('mouseleave', this.close_listener);
		}
		
		this.pop.observe('mouseenter', function () {
			Event.stopObserving(document, 'click', this.close_listener); 
		}.bind(this));

		this.pop.observe('mouseleave', function () {
			Event.observe(document, 'click', this.close_listener); 
		}.bind(this));
		
		// modal version
		if (this.options.modal) {
			this.initModalWindow('modal_overlay');
		}
		
		// centered version
		if (this.options.centered) {
			this.center();
		}

		// fade effect when appearing
		if (this.options.fade) {
			this.pop.appear({duration: 0.2});
		}
		// else just show
		else {
			this.pop.show();
		}
		
		
		(this.options.onOpen || Prototype.emptyFunction)();

		if (typeof(ev) === 'object') {
			ev.stop();
		}
	},
	close : function (ev) {

		document.fire("pop:inactive");
		PopUp.open = false;

		this.trigger.removeClassName("active");
		if (this.options.modal) {
			$('modal_overlay').hide();
		}
		if (this.options.fade) {
			this.pop.fade({duration: 0.2});
		}
		else {
			this.pop.hide();
		}
			
		Event.stopObserving(document, 'click', this.close_listener);
		document.stopObserving('pop:close',  this.close_listener);
		this.pop.stopObserving('mouseenter');
		this.pop.stopObserving('mouseleave');
		
		(this.options.onClose || Prototype.emptyFunction)();
		
		if (ev) {
			ev.stop();
		}
	},
	initModalWindow: function (el) {
		$(el).setStyle({
			height: $$('body').first().getHeight() + "px",
			zIndex: 100
		});

		$(el).show();
	},
	toTop: function () {
		PopUp.i += 1;
		this.pop.style.zIndex = PopUp.i + 1000;
		this.pop.show();
	},
	center: function () {
		if (this.hasBeenCentered) { 
			return;
		}
		var w, h, pw, ph, ws;
		w = this.pop.offsetWidth;
		h = this.pop.offsetHeight;
		Position.prepare();
		ws = this.getWindowSize();
		pw = ws[0];
		ph = ws[1];
		this.pop.setStyle({
			top: (ph / 2) - (h / 2) +  Position.deltaY + "px",
			left: (pw / 2) - (w / 2) +  Position.deltaX + "px"
		});
		//this.hasBeenCentered = true;
	},
	getWindowSize: function (w) {
		w = w ? w : window;
		var width, height;
		width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
		height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
		return [width, height];
	},
	toggleSelects: function () {
		if (Prototype.Browser.IE6) {
			$$('select').each(function (e) {
				$(e).toggle();
			});
		}
	}
});

/*--------------------------------------------------------------------------*/

var Navigation = Class.create({
	initialize: function (container) {
		this.container = $(container);
		this.menus = this.container.select('.megadrop');
		this.togglers = this.container.select('#main_nav li.menu');

		if ((this.togglers.length > 0) && (this.menus.length > 0)) {
			this.setup();
		}
	},
	setup: function () {
		this.togglers.each(function (el, i) {
			pop = new PopUp(el, this.menus[i], {enableHover: true, delay: 150});
		}.bind(this));
	}
});

/*--------------------------------------------------------------------------*/

var stateLookup = {"ALABAMA":"AL","ALASKA":"AK","ARIZONA":"AZ","ARKANSAS":"AR","CALIFORNIA":"CA","COLORADO":"CO","CONNECTICUT":"CT","DELAWARE":"DE","DISTRICT OF COLUMBIA":"DC","FLORIDA":"FL","GEORGIA":"GA","HAWAII":"HI","IDAHO":"ID","ILLINOIS":"IL","INDIANA":"IN","IOWA":"IA","KANSAS":"KS","KENTUCKY":"KY","LOUISIANA":"LA","MAINE":"ME","MARYLAND":"MD","MASSACHUSETTS":"MA","MICHIGAN":"MI","MINNESOTA":"MN","MISSISSIPPI":"MS","MISSOURI":"MO","MONTANA":"MT","NEBRASKA":"NE","NEVADA":"NV","NEW HAMPSHIRE":"NH","NEW JERSEY":"NJ","NEW MEXICO":"NM","NEW YORK":"NY","NORTH CAROLINA":"NC","NORTH DAKOTA":"ND","OHIO":"OH","OKLAHOMA":"OK","OREGON":"OR","PENNSYLVANIA":"PA","RHODE ISLAND":"RI","SOUTH CAROLINA":"SC","SOUTH DAKOTA":"SD","TENNESSEE":"TN","TEXAS":"TX","UTAH":"UT","VERMONT":"VT","VIRGINIA":"VA","WASHINGTON":"WA","WEST VIRGINIA":"WV","WISCONSIN":"WI","WYOMING":"WY"};

/* Omniture event tracking */
var Omniture = {
	// when tracking the "state facts" tab, include the selected state. look
	// at both instances of the state drop-down depending on the page status. 
	_getSelectedProductState: function() {
		var selState = $F($("product_header").down("select")) || $F($("select_state").down("select"));
		return (selState != "ZZ") ? stateLookup[selState].toLowerCase() : "ZZ";
	},
	_getIncTypeName: function(val) {
		switch(val) {
			case "INC_SCORP": return "S Corporation"; break;
			case "INC_CCORP": return "C Corporation"; break;
			case "LLC": return "Limited Liability Company"; break;
			case "LP":  return "Limited Partnership";
			case "LLP": return "Limited Liability Partnership"; break;
			case "NP":  return "Nonprofit"; break;
			default: return "";
		}
	},
	_getCurrentIncType: function() {
		// save inc. type
		var incType = undefined;
		return Omniture._getIncTypeName($F("current_product"));
	},
	// track tab usage on product pages
	trackProductTab: function(tabName, href) {
		if ((typeof(s) != "object") || tabName.match(/overview/i)) { return; }
		
		tabName = tabName.toLowerCase();
		
		if (tabName == "state facts") {
			var selState = Omniture._getSelectedProductState();
			if (selState != "ZZ") {
				tabName = tabName + " - " + selState;
			}
		}
		
       // starting and managinge pages have slightly different Omniture
        // implementations. determine the type, and track as needed.
        if (s.pageName.match(/:::/)) {
            //managing your business
            s.pageName = s.pageName.replace(":::", tabName);
            s.prop2 = s.prop1 + ":" + tabName;
        } else {
            // starting your business
            var path = s.pageName.split(":");
            path[2] = tabName;
            s.pageName = path.join(":");
            s.prop2 = s.prop1 + ":" + tabName;
        }

		s.pageURL = href;
		void(s.t());
	},
	// track product page pushdown
	// only track when querty string doesnt have a state or intl
	trackProductPushdown: function()  {
		//if (typeof(s) != "object") { return; }
	
		var incType  = Omniture._getCurrentIncType();
		var selState = Omniture._getSelectedProductState();
		
		// track ajax event
		var s = s_gi(s_account);
		s.linkTrackVars = "events,prop28";
		s.linkTrackEvents = "event19";
		s.events = "event19";
		s.prop28 = selState.toLowerCase();
		void(s.tl(this, 'o', incType + ' - Pushdown'));
	},
	// track order now button on incorporation pages
	trackProductOrderButton: function(el) {
		//if (typeof(s) != "object") { return; }
		
		var incType  = Omniture._getCurrentIncType();
		var selState = Omniture._getSelectedProductState();
		
		var selPkg = undefined;
		switch(el.id) {
			case "btnKit1": selPkg = "Basic"; break;
			case "btnKit2": selPkg = "Enhanced"; break;
			case "btnKit3": selPkg = "Deluxe"; break;
		}
		
		var s = s_gi(s_account);
		s.linkTrackVars = "eVar21";
		s.eVar21 = selState.toLowerCase();
		void(s.tl(this, 'o', incType + ' - Order Now - ' + selPkg));
	},
	// track clicks on the incorporate now button
	trackIncorporateNow: function() {
		var s = s_gi(s_account);
		s.linkTrackVars = "events";
		s.linkTrackEvents = "event20";
		s.events = "event20";
		void(s.tl(this, 'o', 'Incorporate Now'));
	},
	// track order nowbutton clicks
	trackIncorporateNowOrderButton: function(selState, incType) {
		var s = s_gi(s_account);
		s.linkTrackVars = "eVar18,eVar19";
		s.eVar18 = selState.toLowerCase();
		s.eVar19 = Omniture._getIncTypeName(incType);
		void(s.tl(this, 'o', 'Incorporate Now - Order Now'));
	},
	// track each step of the incorporation wizard (s.prop 21-26)
	trackIncWizard: function(stepNum) {
		var s = s_gi(s_account);		
		var prop = "prop2" + stepNum;
		s.linkTrackVars = prop;
		s[prop] = "Step " + stepNum;
		void(s.tl(this, 'o', 'Incorporation Wizard - Step ' + stepNum));
	},
	// track clicks on the incorporation wizard's start over button,
	trackIncWizardRestart: function() {
		var s = s_gi(s_account);
		s.linkTrackVars = "prop27";
		s.prop27 = "Start Over"
		void(s.tl(this, 'o', 'Incorporation Wizard - Start Over'));
	},
	// tracks results of the incorporation wizard
	trackIncWizardResult: function(incType) {
		var s = s_gi(s_account);
		s.linkTrackVars = "eVar9";
		s.eVar9 = incType;
		void(s.tl(this, 'o', 'Incorporation Wizard - Result'));
	},
	// track click to chat
	trackLiveChat: function() {
		var s = s_gi(s_account);
		s.linkTrackVars = "events";
		s.linkTrackEvents = "event8";
		s.events = "event8";
		void(s.tl(this, 'o', 'Click to Chat'));
	}
}

/*--------------------------------------------------------------------------*/

// T&T - creates a dynamic mbox for tracking purposes
// Usage: TestNTarget.trackAjaxEvent("xxx", "yyyy");
var TestNTarget =  {
	trackAjaxEvent: function(divName, mboxName, params) {
		var el = document.createElement("div");
		el.setAttribute("id", divName);
		document.getElementsByTagName("body")[0].appendChild(el);
		
		if (typeof(params) == "undefined") {
			params = "";
		}
		
		mboxDefine(divName, mboxName, params);
		mboxUpdate(mboxName, params);
	}
}

/*--------------------------------------------------------------------------*/

var PostForm = Class.create({
    initialize: function(container, url, options){
        this.url = url;
        this.container = container;
        this.options = options
        this.trigger = options.trigger;
        this.inputs = this.container.select('input, textarea');
        if (this.trigger)
            this.setup();
    },
    setup: function(){
        this.trigger.observe('click', this.post.bind(this));
        this.inputs.each(function(inp){
            new OnEnter(inp, this.post.bind(this));
        }.bind(this));
    },
    post: function(ev){
        if (ev && ev.stop)
            ev.stop();
        var data = Form.serializeElements(this.inputs, true);
        if (this.options.extra_params)
            data = Object.extend(data, this.options.extra_params);
        var form = new Element('form', {id:'topost',action:this.url, method:this.options.method || 'post'});
        for (k in data){
            form.insert(new Element('input',{type:'hidden',name:k,value:data[k]}));   
        }
        $$('body')[0].insert(form);
        form.submit();
    }
});

/*--------------------------------------------------------------------------*/

var OnEnter = Class.create({
    initialize: function(field, callback){
        this.field = field;
        this.callback = callback;
        this.field.observe('keypress', function(ev){if (ev.keyCode==Event.KEY_RETURN) this.callback(ev)}.bind(this));
    }
});

/*--------------------------------------------------------------------------*/

var SearchField = Class.create({
    ENDPOINT : 'search-results.php?q=#{term}&offset=0&submit.x=43&submit.y=10',
    initialize: function(container){
        this.field = container.down('input.prompt');
        this.button = container.down('div.submit')
        this.button.observe('click', this.do_search.bind(this));
        new OnEnter(this.field, this.do_search.bind(this));
    },
    do_search: function(ev){
        ev.stop();
        if (this.field.present())
            document.location = this.ENDPOINT.interpolate({term:this.field.value});
    }
});

/*--------------------------------------------------------------------------*/

var LoggerInner = Class.create({
    initialize: function(container){
        this.container = container;
        this.user = container.down('.signin_email');
        this.pass = container.down('.signin_password');
        this.submit = container.down('button');
        this.setup();
    },
    setup: function(){
        this.submit.observe('click', this.check.bind(this));
        [this.user,this.pass].each(function(f){ new OnEnter(f, this.check.bind(this))}.bind(this));
    },
    check: function(ev){
        ev.stop();
        var params = Form.serializeElements([this.user, this.pass], true);
        new Ajax.Request('/stat/user.asp?action(1)=AC&un=#{un}&pw=#{pw}'.interpolate(params), {
            method:'get',
            onSuccess: function(r){
                if (r.responseText.match(/\D/)){ //Is this an error?
                    this.container.down('.error').hide().replace('<p class="error">The e-mail address / username and password you entered did not match any accounts in our file. Please try again.</p>').show();
                }else{
                    var form = new PostForm(this.container, '/stat/user.asp?page=status', {
                        extra_params:{'AccountID':r.responseText, 'Action(1)':'AL'}
                    });
                    form.post();
                }
            }.bind(this)
        });
    }
});

/*--------------------------------------------------------------------------*/

var Tabs = Class.create({
	initialize: function (container, togglers, tabs, active, options) {
		this.container = $(container);
		this.togglers = $(togglers);
		this.tabs = $(tabs);
		this.active = active || 0;
		this.options = options || null;
		this.setup();
	},
	setup: function () {
		this.tabs[this.active].addClassName('active');
		this.togglers[this.active].addClassName('active');
		
		this.togglers.each(function (el, i) {
			el.onclick = function () {
				if (i !== this.active) {
					el.addClassName('active');
					this.togglers[this.active].removeClassName('active');
					
					if (this.tabs.length === this.togglers.length) {
						this.tabs[this.active].removeClassName('active');
						this.tabs[i].addClassName('active');
					}
				}
				this.active = i;
				return false;
			}.bind(this);
		}.bind(this));
	}
});

/*--------------------------------------------------------------------------*/

var AjaxTabs = Class.create(Tabs, {
	setup: function($super){
		this.cache = {};
		this.togglers.each(function(toggler, i){
			toggler.observe('click', function(ev) { this.click(ev, i); }.bind(this));
			if (toggler.hasClassName('active')) { this.active = i; }
		}.bind(this));
		this.tab = this.tabs[0].addClassName('active');
		this.togglers[this.active].addClassName('active');
		this.extra_params = this.options ? this.options.extra_params : null;
		this.onUpdate = this.options ? this.options.onUpdate ? this.options.onUpdate : null : null;
		this.notfirst = false;
		//this.reload();
		document.observe('state:selected', this.update_link.bind(this));
	},
	click: function(ev, idx){
		var el = ev.element ? ev.element() : ev;
		var url = el.readAttribute('href');
		var tab_name = el.innerHTML;
		
		this.togglers[this.active].removeClassName('active');
		
		var cache_key = el.readAttribute('href');
		var cache = this.cache[cache_key];
		if (cache) {
			this.tab.select('div.container').invoke('hide');
			cache.show();
		} else {
			if (this.extra_params) { 
				url += (url.include('?') ? '&' : '?')+Object.toQueryString(this.extra_params);
			}
			this.loading();
			new Ajax.Request(url, {
				method:'get',
				onSuccess: function (r) {
					var div = new Element('div').addClassName('container').insert('<div>'+r.responseText.stripScripts()+'</div>');
					
					this.cache[cache_key] = div;
					this.tab.select('div.container').invoke('hide');
					if (this.notfirst) {
						this.tab.insert(div);
					} else {
						this.tab.update(div);
						this.notfirst = true;
					}
										
					this.loading(true);
					if (this.onUpdate) this.onUpdate();
					
					// temporary workaround for state facts drop-down during a/b test
					if (url.include("state-facts") && $("main").hasClassName('displayAltPage')) {
						this.createStateFactsDropDown(div, url.toQueryParams().state);
					}
				}.bind(this)});
			}
		this.active = idx;
		this.togglers[this.active].addClassName('active');
		
		// Track tab click via Omniture
		if (tab_name != "Overview") {
			Omniture.trackProductTab(tab_name, url); 
		}
		
		if (ev.stop) { ev.stop(); }
	},
	loading: function(done){
        this.container.down('#product_tab_loader')[done?'hide':'show']();
        var o = this.container.down('.overlay');
        if (! done)
            o.style.height = this.container.getHeight()-70+'px';
        o[done?'hide':'show']();
	    
	},
	reload: function(){
	    this.click(this.togglers[this.active].down('a'), this.active);
	},
	update_link: function(event){
	    var initmode = event.memo.init || false;
	    if (initmode)
	       delete event.memo['init'];
	       
        this.togglers.each(function(el){
        	var el = el.down('a');
    		var href = el.readAttribute('href').split('?');
    		var params = href.length>1 ? href[1].toQueryParams() : {};
    		Object.extend(params, event.memo);
    		el.writeAttribute('href', href[0]+'?'+Object.toQueryString(params));
        }.bind(this));	
        // bust cache
        this.tabs.invoke('update');
        this.cache = {};
        if (! initmode)
            this.reload(); 
	},
	createStateFactsDropDown: function(div, state) {
		// creates a state drop-down for product page a/b test
		var globalStateDropDown = $("select_state").down("select");
		
		// create the new state drop-down
		var sel = document.createElement("select");
		sel[0] = new Option("Select State", "");
		$H(stateLookup).each(function(state, i){
			sel[i+1] = new Option(state.key.capitalize(true), state.key);
		});
		sel.value = state;
		//sel.selectedIndex = globalStateDropDown.selectedIndex;
		
		// create remaining html
		var markup = new Element('div', { 'id': 'tab-drop-down', 'class': 'state-select' }).update('<strong>Select a State:</strong>');
		markup.insert(sel);
		$(div).insert({ top: markup });
		
		$(sel).observe('change', function() {
			document.fire('state:selected', { onload:true, state: $F(sel) });
		});
	}
});
String.prototype.capitalize = String.prototype.capitalize.wrap( 
  function(proceed, eachWord) { 
    if (eachWord && this.include(" ")) {
      // capitalize each word in the string
      return this.split(" ").invoke("capitalize").join(" ");
    } else {
      // proceed using the original function
      return proceed(); 
    }
  }); 
  
/*--------------------------------------------------------------------------*/

var PromptLabel = Class.create({
	initialize: function (field) {
		this.field = $(field);
		this.label = this.field.down('label'); // the <label>
		this.input = this.field.down('input.prompt'); // the <input>
		this.setup();
	},
	setup: function () {
		if (this.input.value !== '') {
			this.focus();
		}
		this.label.observe('click', this.focus.bind(this));
		this.input.observe('focus', this.focus.bind(this));
		this.input.observe('blur', this.blur.bind(this));
	},
	focus: function () {
		this.label.hide();
		this.field.addClassName('active');
		this.input.addClassName('active');
	},
	blur: function () {
		if (this.input.value === '') {
			this.label.show();
		}
		this.field.removeClassName('active');
	}
});

/*--------------------------------------------------------------------------*/

var HoverDelay = Class.create({
	initialize : function (trigger, options) {
		this.options = Object.extend({
			closeSelector : '.close', 
			enterCb : function () {},	
			leaveCb : function () {},	
			delay : 0.5
		}, options || {});
		
		this.trigger = $(trigger);
		this.timeout = null; 
		this.active = false;
		this.setup();
	},
	setup : function () {
		var eEvt, lEvt;
		eEvt = this.open.bindAsEventListener(this);
		lEvt = this.close.bindAsEventListener(this);
		this.trigger.observe('mouseenter', eEvt);
		this.trigger.observe('mouseleave', lEvt);
		this.trigger.observe('hoverdelay:stop', function () {
			this.trigger.stopObserving('mouseenter', eEvt);
			this.trigger.stopObserving('mouseleave', lEvt);
		}.bind(this));
		document.observe('pop:active', function () { 
			this.inactive = true; 
		}.bind(this));
		document.observe('pop:inactive', function () { 
			this.inactive = false;
		}.bind(this));
	}, 
	open : function (event) {
		if (this.inactive) { 
			return;
		}
		this.timeout = function () {
			this.trigger.addClassName("active");
			this.options.enterCb.bind(this)();
			this.active = true;
		}.bind(this).delay(this.options.delay);
	},
	close : function (ev) {
		if (this.inactive) { 
			return;
		}
		if (this.timeout) {
			window.clearTimeout(this.timeout);
			this.timeout = null;
		}
		if (this.active) {
			this.options.leaveCb.bind(this)(ev);
			this.active = false;
			this.trigger.removeClassName("active");
		}
	}
});

/*--------------------------------------------------------------------------*/

var AjaxStateFees = Class.create({
	initialize: function (container) {
		this.container = $(container);
		this.togglers = this.container.select('ul.tabs li');
		this.msg = this.container.down('.msg');
		this.tabs = [];
		this.container.select('div.tab').each(function (el) {
			this.tabs.push({
				content: el,
				loaded: false
			});
		}.bind(this));
		
		this.url = '/partials/state_fees_partial.asp?f=';
		this.loader = this.container.down('.overlay').hide();
		this.load(0);
		this.setup();
	},
	setup: function () {
		this.togglers.each(function (el, i) {
			el.observe('click', this.load.bind(this, i));
		}.bind(this));
	},
	load: function (idx) {
		var target = this.url + idx;
		if (!this.tabs[idx].loaded) {
			new Ajax.Updater(this.tabs[idx].content, target, {
				method: 'get',
				onLoading: function (t) {
					this.loader.show();
					target = this.url;
				}.bind(this),
				onSuccess: function (t) {
					this.loader.hide();
					this.tabs[idx].loaded = true;
					target = this.url;
				}.bind(this),
				onFailure: function (t) {
					this.loader.hide();
					this.msg.show();
					target = this.url;
				}
			});
		}
	}
});

/*--------------------------------------------------------------------------*/

var SimpleToggler = Class.create({
	initialize: function (trigger, content, options) {
		this.trigger = trigger;
		this.content = content;
		
		this.options = Object.extend({
			duration: 0.2
		}, options || {});		
		
		this.setup();
	},
	setup: function () {
		this.trigger.observe('click', this.toggler.bind(this));
	},
	toggler: function (ev) {
		this.trigger.toggleClassName("active");
		Effect.toggle(this.content, 'slide', { duration: this.options.duration }); 
		ev.stop();
	}
});

/*--------------------------------------------------------------------------*/

var MyAccountPopUp = Class.create(PopUp, {
	initialize: function ($super, trigger, pop) {
		this.trigger = trigger;
		this.pop = pop;
		this.cancelBtn = this.pop.down('.forgot_pw');
	
		this.options = {
			onOpen: this._open.bind(this)
		}; 
		
		if (this.cancelBtn) {
			this.cancelBtn.observe('click', function () {
				this.pop.hide();
			}.bind(this));
		}
		
		$super(this.trigger, this.pop, this.options);
	},
	_open: function () {	
		if (!this.fields) {
			this.pop.select('.field').each(function (el) {
				var prompt;
				prompt = new PromptLabel(el);
			});
			
			this.fields = true;
		}
	}
});

/*--------------------------------------------------------------------------*/

var HowItWorksPop = Class.create(PopUp, {
	initialize: function ($super, trigger, pop) {
		this.trigger = trigger;
		this.pop = pop;
		
		this.options = {
			modal: true,
			centered: true,
			onOpen: this._open.bind(this),
			onClose: this._close.bind(this)
		};
		
		$super(this.trigger, this.pop, this.options);
	},
	_open: function () {
		this.slide = new PageSlide($('hw_slide'), $('hw_slide').down('.tabs'), $('hw_slide').select('.steps li'));
	},
	_close: function () {
		this.slide.reset();
	}
});

/*--------------------------------------------------------------------------*/

var AdvancedTabs = Class.create({
	initialize: function (container, options) {
		this.container  = $(container);
		this.togglers = this.container.select('.tabs li');
		this.tabs = this.container.select('.tab');
		
		this.options = Object.extend({
			closeSelector: '.close'
		}, options || {});
		
		this.setup();
	},
	setup: function () {
		this.togglers.each(function (el, i) {
			el.observe('click', this.show.bindAsEventListener(this, i));
		}.bind(this));
		this.container.select(this.options.closeSelector).each(function (el, i) {
			el.observe('click', this.close.bindAsEventListener(this, i));
		}.bind(this));
	},
	show: function (ev, i) {
		this.togglers.invoke('removeClassName', 'active');
		this.togglers[i].addClassName('active');
		this.tabs.invoke('removeClassName', 'active');
		this.tabs[i].addClassName('active');
		if (ev) {
			ev.stop();
		}
	},
	close: function (ev, i) {
		this.togglers.invoke('removeClassName', 'active');
		this.tabs.invoke('removeClassName', 'active');
		if (ev) {
			ev.stop();
		}
	}
});

/*--------------------------------------------------------------------------*/

var PageSlide = Class.create({
	initialize : function(container, contents, buttons, options){
		this.container = $(container);
		this.contents = contents;
		this.offset = contents.positionedOffset()[0];
		this.prevBtn = this.container.down('.prev');
		this.nextBtn = this.container.down('.next');
		this.width = this.container.select('.tab')[0].getWidth();
		this.buttons = buttons;
		
		this.buttons.each(function (el,idx) {
			el.observe('click', function(ev){
				ev.stop();
				this.go(idx);
			}.bind(this));
		}.bind(this));
		
		this.slideCount = this.buttons.length;
		this.nextBtn.observe('click', this.next.bind(this));
		this.prevBtn.observe('click', this.prev.bind(this));
		this.go(0);
	},
	go : function(idx){
		this.container.select('.tab')[this.current || 0].fire('nav:go');
		if (idx < 0 || idx >= this.slideCount) return;

		this.current = idx;
		
		this.buttons.invoke('removeClassName', 'active');
		this.buttons[idx].addClassName('active');
		
		if (this.moving) this.moving.cancel();
		this.moving = new Effect.Move(this.contents, {
			mode: 'absolute', 
			x:(-(idx*this.width)+this.offset), 
			duration: 0.3, 
			afterFinish: function(){
				this.prevBtn.style.display = this.current==0?'none':'block'
				this.nextBtn.style.display = this.current==this.slideCount-1 ? 'none':'block';
			}.bind(this)
		});
	},
	next : function(ev){
		ev.stop();
		this.go(this.current+1);
	},
	prev : function(ev){
		ev.stop();
		this.go(this.current-1);
	},
	reset: function () {
		this.buttons.invoke('removeClassName', 'active');
		this.buttons[0].addClassName('active');
		this.go(0);
	}
});

/*--------------------------------------------------------------------------*/

var ToolTip = Class.create({
	initialize: function (trigger, popup, options) {
		this.trigger = $(trigger);
		this.popup = $(popup);
		this.popup.hide();
		
		this.options = Object.extend({
			parent: this.trigger.up(),
			delay: 500
		}, options || {});
		
		this.setup();
	},
	setup: function () {
		this.options.parent.makePositioned();
		var triggerPos = this.trigger.positionedOffset();
		this.popup.setStyle({
			position: 'absolute',
			top: triggerPos['top'] + 'px',
			left: triggerPos['left'] + this.trigger.getWidth() + 'px'
		});
		
		this.trigger.observe('mouseenter', this.openme.bind(this));
		this.trigger.observe('mouseleave', this.closeme.bind(this));
	},
	openme: function (ev) {
		setTimeout(function () {
			if (this.options.content){
				this.popup.down('.inner p').update(this.options.content);
			}
			if (this.options.positioned){
				var pos = this.trigger.cumulativeOffset();
				this.popup.setStyle({
					top:(pos['top']-20)+'px',
					left:(pos['left']+this.trigger.getWidth())+'px'
				});
			}
			this.popup.show();
		}.bind(this), this.options.delay);
		
		if (ev) {
			ev.stop();
		}
	},
	closeme: function (ev) {
		setTimeout(function () {
			this.popup.hide();
		}.bind(this), this.options.delay);
		
		if (ev) {
			ev.stop();
		}
	}
});

/*--------------------------------------------------------------------------*/

var IncorpPopUp = Class.create(PopUp, {
	initialize: function ($super, trigger, pop) {
		this.trigger = trigger;
		this.pop = pop;
		this.selects = this.pop.select('select');
		
		this.options = {
			centered: true,
			modal: true,
			onOpen: this._open.bind(this)
		};
		this.setup_form();
		$super(this.trigger, this.pop, this.options);
	},
	setup_form: function(){
	    this.pop.down('button').observe('click', function(ev){
    	    ev.stop();
	        var key = Form.serializeElements(this.pop.select('input'), true).incorporate_type;
            document.location = INCORP_URLS[key]+'?state='+$F(this.pop.down('select'));

			//Omniture
			Omniture.trackIncorporateNowOrderButton($F(this.pop.down('select')), key);
	    }.bind(this));
	},
	_open: function () {
		
		new ToolTip('select_state_tooltip_trigger', 'select_state_tooltip');
		new ToolTip('select_business_tooltip_trigger', 'select_business_tooltip');
		
		this.selects.each(function (el) {
			el.observe('focus', function () {
				document.fire('pop:keepOpen');
			}.bind(this));
			el.observe('change', function () {
				document.fire('pop:keepOpen');
			}.bind(this));
		}.bind(this));
		
		//Omniture
		Omniture.trackIncorporateNow();
	}
});

/*--------------------------------------------------------------------------*/

var IncorpPriceSwitch = Class.create({
    initialize: function(container, prods, amounts){
        this.container = container;
        this.display= this.container.down('#incorp_startfrom');
        this.inps = this.container.select('input[name=incorporate_type]');
        this.inps.invoke('observe','click',this.handler.bind(this));
        this.stateSelect = this.container.select('select')[0];
        this.stateSelect.observe('change', this.handler.bind(this));
        var prods = $F(prods).split(',');
        var amounts = $F(amounts).split(',');
        this.amounts = {};
        prods.each(function(p, idx){
            this.amounts[p] = amounts[idx];
        }.bind(this));
        //this.do_change(Form.serializeElements(this.inps, true).incorporate_type);
    },
    handler: function(ev){
        var key = $F(ev.element());
        this.findPrice(this.stateSelect.getValue(), Form.serializeElements(this.inps, true).incorporate_type);
        //this.do_change(key);
    },
    do_change: function(key){
        this.display.update(this.amounts[key]);
    },
    findPrice: function(state, product){
        new Ajax.Request('/GetKitPricesByState.aspx', {
            method: 'get',
            parameters: {state:state, product:product},
            evalJSON: true,
            onSuccess: function(r){
                r = r.responseText.evalJSON();
                this.display.update(r[0])
            }.bind(this)
        });
    }
});

/*--------------------------------------------------------------------------*/

var BasicSlider = Class.create({
	initialize: function (container, increment) {
		this.container = $(container);
		this.increment = increment;
		this.contents = this.container.down('.slides');
		this.slides = this.contents.select('li.slide');
		this.prevBtns = this.container.select('.prev');
		this.nextBtns = this.container.select('.next');
		this.slideCount = this.slides.length / this.increment;
		this.offset = this.contents.positionedOffset()[0];
		this.width = this.slides[0].getWidth(); /* calculate width instead of declaring it explicitly */
		this.setup();
	},
	setup: function () {
		//handle ie6's lack of hover support on non-anchor elements
		if (Prototype.Browser.IE6) {
			this.prevBtns.each(function (el) {
				el.observe('mouseenter', function () {
					this.addClassName('hover_prev');
				});
				el.observe('mouseleave', function () {
					this.removeClassName('hover_prev');
				});
			}.bind(this));
			this.nextBtns.each(function (el) {
				el.observe('mouseenter', function () { 
					this.addClassName('hover_next');
				});
				el.observe('mouseleave', function () {
					this.removeClassName('hover_next');
				});
			}.bind(this));
		}

		this.prevBtns.each(function (el) {
			el.addClassName('active');
			el.observe('click', this.next.bind(this));
		}.bind(this));
		
		this.nextBtns.each(function (el) {
			el.addClassName('active');
			el.observe('click', this.prev.bind(this));
		}.bind(this));
		
		this.goTo(0);
	},
	goTo: function (idx) {
		if (this.current === idx) {
			return;
		}
		if (idx < 0 || idx >= this.slideCount) {
			return;
		}
		this.current = idx;
		if (this.moving) {
			this.moving.cancel();
		}
		
		this.moving = new Effect.Move(this.contents, { 
			mode: 'absolute', 
			x: (-(idx * this.width) + this.offset), 
			duration: 0.6, 
			transition: Effect.Transitions.easeOutSine, 
			afterFinish: function () {
				if (this.current === 0) {
					this.prevBtns.invoke('addClassName', 'disabled_prev');
				}
				else {
					this.prevBtns.invoke('removeClassName', 'disabled_prev');
				}
				if (this.current === (this.slideCount - 1)) {
					this.nextBtns.invoke('addClassName', 'disabled_next');
				}
				else {
					this.nextBtns.invoke('removeClassName', 'disabled_next');
				}
			}.bind(this)
		});
	},
	prev: function (ev) {
		this.goTo(this.current + 1);
		ev.stop();
	},
	next: function (ev) {
		this.goTo(this.current - 1);
		ev.stop();
	}
});

/*--------------------------------------------------------------------------*/

var VideoPlayer = Class.create(PopUp, {
	initialize: function ($super, trigger, pop, aplay) {
		this.trigger = trigger;
		this.pop = pop;
		
		this.options = {
			onOpen:  this._open.bind(this),
			onClose: this._close.bind(this),
			modal: true,
			centered: true,
			headerSelector: "div.video_header",
			videoSelector:  "video_player"
		};
		this.aplay = aplay; // autoplay = true or false
		
		$super(this.trigger, this.pop, this.options);
	},
	_open: function () {
		if (this.trigger.title && this.options.headerSelector) {
			this.header = this.pop.down(this.options.headerSelector);

			if (this.header) {
				this.header.innerHTML = this.trigger.title;
			}
		}
		if (this.options.modal) {
			$('modal_overlay').show();
		}
		this.trigger.removeClassName('active');
		var url;
		
		if (this.trigger.href) {
			url = this.trigger.href;
		}
		else {
			url = this.trigger.className.split('video video_popup_trigger')[1];
		}
	
		this.swf = new SWFObject("/images/flash/video_player.swf", "VIDEO_PLAYER", "640", "360", "8.0.0", "#000");
		this.swf.addVariable("video_url", url);
		this.swf.addVariable("graphic_url", "/images/video_thumbnail.png");
		this.swf.addVariable("aplay", "true");
		this.swf.addParam("wmode", "transparent");
		this.swf.addParam("allowScriptAccess", "always");
		this.swf.write(this.options.videoSelector);

	},
	_close: function () {
		if (this.options.modal) {
			$('modal_overlay').hide();
		}
		this.pop.down('#video_player').update('');
	}
});

/*--------------------------------------------------------------------------*/

var ScrollDropdown = Class.create({
	initialize: function (dropdown) {
		this.dropdown = $(dropdown);

		this.dropdown.observe('change', function (ev) {
			var val = this.dropdown.value;
			new Effect.ScrollTo(val);
			Event.stop(ev);
		}.bindAsEventListener(this));
		
	}
});

/*--------------------------------------------------------------------------*/

var GlobalToolTip = Class.create({
	initialize: function(container){
		this.container = container;
		this.tool = $('global_tooltip');
		this.setup();
	},
	setup: function(){
		this.container.select('a[title]').each(function(el) {
			if (el.hasClassName('video')) return;
			var content = el.readAttribute('title');
			el.writeAttribute('title', null);
			new ToolTip(el, this.tool, {'content':content,'positioned':true});
		}.bind(this));
	}
});

/*--------------------------------------------------------------------------*/

var DECODER = {
    codes:$H({
        '/':/%2F/g,
        '?':/%3F/g,
        '&':/%26/g,
        '=':/%3D/g,
        '.':/%2E/g
    })
    ,
    decode: function(s){
        DECODER.codes.each(function(k){
            s = s.replace(k.value,k.key);
        });
        return s;
    }    
};

/*--------------------------------------------------------------------------*/

var CookieLogin = Class.create({
    initialize: function(container, cookies_urls){
        this.container = container;
        var no_cookies = true;
        cookies_urls.each(function(c_u){
            var c = Cookie.get(c_u[0]);
            if (c){
                no_cookies = false;
                var acct_link = (c_u[1].indexOf('COOKIE:')==-1) ? c_u[1] : DECODER.decode(Cookie.get(c_u[1].split(':')[1]));
                container.update('<a href="'+ acct_link +'">Hi, '+c+'</a>. <a href="'+c_u[2]+'">(Sign Out)</a>');
                throw $break;
            }
            
        });
        if (no_cookies){
            if ($('myaccount_drop')) {
				new MyAccountPopUp($('trigger_myaccount_drop'), $('myaccount_drop'));
                new LoggerInner($('myaccount_drop'));
            }
        }
        
        
    }
});

/*--------------------------------------------------------------------------*/
 
var Cookie = {
  build: function() {
    return $A(arguments).compact().join("; ");
  },
  secondsFromNow: function(seconds) {
    var d = new Date();
    d.setTime(d.getTime() + (seconds * 1000));
    return d.toGMTString();
  },
  set: function(name,value,seconds){
    var expiry = seconds ? 'expires=' + Cookie.secondsFromNow(seconds) : null;
    document.cookie = Cookie.build(name + "=" + value, expiry, "path=/");
  },
  get: function(name){
    var valueMatch = new RegExp(name + "=([^;]+)").exec(document.cookie);
    return valueMatch ? valueMatch[1] : null;
  },
  unset: function(name){
    Cookie.set(name,'',-1);
  }
};

/*--------------------------------------------------------------------------*/

function IncorpNowPopup() {
	var incorp = $('incorporate');
	if ($('trigger_incorporate') && incorp) {
		new IncorpPopUp($('trigger_incorporate'), incorp);
		new IncorpPriceSwitch(incorp, incorp.down('#uiTxtOptionsList'), incorp.down('#uiTxtPriceList'));
	}
}

/*--------------------------------------------------------------------------*/

function MyAccountPop() {
	var tmd = $('trigger_myaccount_drop');
	if (tmd){
	    new CookieLogin($$('#secondary_nav .account')[0], [
	       ['affiliate_status', '/ac/afc/home.aspx', '/ac/logout.aspx'],
	       ['user%5Fstatus', 'COOKIE:scbc%5Flink', '/logout']
	       ]);
	}
}

/*--------------------------------------------------------------------------*/

function AffiliateLogin (container) {
	var ERR_MSG_TEXT = "Our Affiliate Center does not recognize the username and/or password you entered. If you are a BizFilings customer and wish to access our Online Status Center or BizComply, <a href='/login.php'>click here</a>. If you are an affiliate and need username or password assistance, please contact our Business Development department at 800-981-7183 or affiliates@BizFilings.com";
	new PostForm(container, '/ac/login.aspx', {trigger:container.down('button')});
	var qParams = document.location.search.toQueryParams();
	if (qParams.e) {
		var err_msg = new Element('p').addClassName('error').insert(ERR_MSG_TEXT);
		$$('#tout_affiliate .field')[1].insert(err_msg);
	}
}

/*--------------------------------------------------------------------------*/

function BizAffiliates(container) {
	container.select('.field').each(function(el) {
		new PromptLabel(el);
	});
	AffiliateLogin(container);
}

/*--------------------------------------------------------------------------*/

function globalDomReady() {
	// cache background images in ie6 to prevent multiple http requests
	if (Prototype.Browser.IE6) {
		try {
			document.execCommand('BackgroundImageCache', false, true);
		} catch (e) {}
	}
	
	/* main navigation */
	if ($('main_nav')) {
		new Navigation('container');
	}

	/* global search */
	var globalSearch = $('search');
	if (globalSearch) {
		new PromptLabel(globalSearch);
		new SearchField(globalSearch);
	}
	
	/* myaccount popup */
	if ($('trigger_myaccount_drop')) {
		MyAccountPop();
	}	
	
	/* help popup */
	var triggerHelpDrop = $('trigger_help_drop');
	var helpDrop = $('help_drop');
	if (triggerHelpDrop && helpDrop) {
		new PopUp(triggerHelpDrop, helpDrop);
	}	
	
	/* incorporate now popup */
	if ($('trigger_incorporate') && $('incorporate')) {
		IncorpNowPopup();
	}
	
	/* how it works popups */
	var triggerHowItWorks = $('trigger_how_it_works');
	var howItWorks = $('how_it_works');
	var triggerHowItWorksAlt = $('trigger_how_it_works_alt');
	if (triggerHowItWorks && howItWorks) {
		new HowItWorksPop(triggerHowItWorks, howItWorks);
	}
	if (triggerHowItWorksAlt && howItWorks) {
		new HowItWorksPop(triggerHowItWorksAlt, howItWorks);
	}	

	/* affiliate log in tout */
	var toutAffiliate = $('tout_affiliate');
	if (toutAffiliate) {
		BizAffiliates(toutAffiliate);
	}
	
	/* feedback popup */
	var triggerFeedbackPop = $('trigger_feedback_popup');
	var feedbackPop = $('feedback_popup');
	if (triggerFeedbackPop && feedbackPop) {
		new PopUp(triggerFeedbackPop, feedbackPop); 
	}
	
	/* pricing policy */
	var triggerPricingPolicy = $('pricing_policy_popup_trigger');
	var pricingPolicyPop = $('pricing_policy_popup');
	if (triggerPricingPolicy && pricingPolicyPop) {
		new PopUp(triggerPricingPolicy, pricingPolicyPop, {centered: true, modal: false}); 
	}
	
	/* partners tout slider */
	var partnerSlides = $('partner_slides');
	if (partnerSlides) {
		new BasicSlider(partnerSlides, 1); 
	}
	
	/* compare incorporation options popup */
	var triggerIncorporationOptions = $('trigger_incorporation_options');
	var incorporationOptions = $('incorporation_options');
	var triggerIncorporationOptionsAlt = $('trigger_incorporation_options_alt');
	if (triggerIncorporationOptions && incorporationOptions) {
		new PopUp(triggerIncorporationOptions, incorporationOptions, {centered: true, modal: true}); 
	}
	if (triggerIncorporationOptions && incorporationOptions) {
		new PopUp(triggerIncorporationOptionsAlt, incorporationOptions, {centered: true, modal: true}); 
	}
	
	/* video popups */
	$$('.video_popup_trigger').each(function (el) {
		new VideoPlayer(el, $('video_popup'));
	});
		
	/* track live chat links for Omniture */
	var liveChatLinks = $$('a[href*=liveperson.net]');
	liveChatLinks.each(function (el) {
		el.observe('click', function (ev) {	
			Omniture.trackLiveChat();
			ev.stop();
		}.bindAsEventListener());
	});
	
	
	
}

