/* the "getCookie," "setCookie" and "delCookie" functions were all lifted from marketing.js */
function getCookie(name) {
	var cname = name + "=";
	var dc = document.cookie;
	if (dc.length > 0) {
		begin = dc.indexOf(cname);
		if (begin != -1) {
			begin += cname.length;
			end = dc.indexOf(";", begin);
			if (end == -1) end = dc.length;
			return unescape(dc.substring(begin, end));
		}
	}
	return null;
}
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : "; expires=" + expires.toGMTString()) + ((path == null) ? "" : "; path=" + path) + ((domain == null) ? "" : "; domain=" + domain) + ((secure == null) ? "" : "; secure");
}
function delCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + ((path == null) ? "" : "; path=" + path) + ((domain == null) ? "" : "; domain=" + domain) + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

// set universal scroll speed (ms)
var scrollSpeed = 500;

/*
 * jQuery firmType plugin
 * Version 1.0 (July 28, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin replicates the functionality of the getFirmType function in
 * marketing.js. Returns the current user's firm type.
 *
 * (To be cleaned up later.)
 *
 */
(function ($) {
	$.fn.firmType = function () {
		var firmType,
			url = location.href.toLowerCase();

		if (url.indexOf('.sg') != -1 || url.indexOf('sg.eqdesign') != -1 || getCookie('Firm') == 'SN') {
			firmType = 'SN';
		}
		else if (url.indexOf('.ca') != -1 || url.indexOf('ca.eqdesign') != -1 || getCookie('Firm') == 'CA') {
			firmType = 'CA';
		}
		else if (url.indexOf('.au') != -1 || url.indexOf('au.eqdesign') != -1 || getCookie('Firm') == 'OB') {
			firmType = 'OB';
		}
		else if (url.indexOf('brokersxpress') != -1 || url.indexOf('bx.eqdesign') != -1 || getCookie('Firm') == 'BX') {
			firmType = 'BX';
		}
		else if (url.indexOf('advisorsxpress') != -1 || url.indexOf('ax.eqdesign') != -1 || getCookie('Firm') == 'AX') {
			firmType = 'AX';
		}
		else if (url.indexOf('optionsxpress.europe') != -1 || url.indexOf('optionsxpress.eu') != -1 || url.indexOf('eu.eqdesign') != -1 || getCookie('Firm') == 'EU') {
			firmType = 'EU';
		}
		else if (url.indexOf('oxint') != -1 || url.indexOf('oxint.eqdesign') != -1 || getCookie('Firm') == 'OXI') {
			firmType = 'OXI';
		}	
		else {
			firmType = 'OX';
		}

		return firmType;
	}
})(jQuery);

/*
 * jQuery popup plugin
 * Version 1.0 (August 5, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to take an arbitrary anchor element and
 * turn it into a popup window link. The "href" attribute is the URL to be
 * loaded, and the "rel" attribute indicates the target.
 *
 */
(function ($) {
	$.fn.popup = function (options) {
		var defaults = {
			width: screen.width / 2,
			height: screen.height / 2,
			titlebar: false,
			status: false,
			resizable: true,
			toolbar: false,
			scrollbars: true,
			menubar: false
		};
		var options = jQuery.extend(defaults, options);

		Boolean.prototype.setProperty = function () { // allow for sensible boolean option values
			if (this == true) {
				return 'yes';
			} else {
				return 'no';
			}
		};

		$(this).bind('click', function () {
			var href = this.href;
			var target = (this.rel) ? this.rel : 'popup';
			var posY = (parseInt(screen.height / 2)) - (parseInt(options.height / 2));
			var posX = (parseInt(screen.width / 2)) - (parseInt(options.width / 2));
			var win = window.open(href, target, 'titlebar=' + options.titlebar.setProperty() + ', screenX=' + posX + ', screenY=' + posY + ', left=' + posX + ', top=' + posY + ', status=' + options.status.setProperty() + ', resizable=' + options.resizable.setProperty() + ', toolbar=' + options.toolbar.setProperty() + ', scrollbars=' + options.scrollbars.setProperty() + ', menubar=' + options.menubar.setProperty() + ', width=' + options.width + ', height=' + options.height);
			win.focus();
			return false;
		});

		return this;
	}
})(jQuery);

/*
 * jQuery livePerson plugin
 * Version 1.1 (July 24, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to launch the OX LivePerson popup upon
 * clicking on an arbitrary link.
 *
 */
(function ($) {
	$.fn.livePerson = function () {
		window.name = 'lp_parent';
		var domain = location.href.toLowerCase(); 

		if (domain.indexOf('brokersxpress') != -1 || domain.indexOf('bx.eqdesign') != -1 || domain.indexOf('equawebbx1') != -1) {
			$(this).attr('href', 'https://server.iad.liveperson.net/hc/29625551/?cmd=file&file=visitorWantsToChat&site=29625551');
		} else {
			$(this).attr('href', 'http://server.iad.liveperson.net/hc/LPoptionsxpress/?cmd=file&file=visitorWantsToChat&site=LPoptionsxpress');
		}

		$(this).popup({
			width: 490,
			height: 330
		});
	}
})(jQuery);

/*
 * jQuery omniture plugin
 * Version 1.1 (July 15, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to set page-specific variables for
 * Omniture SiteCatalyst. Note that an arbitrary number of options may be
 * passed to the plugin, and it will still work.
 *
 * Options
 * - pageName: (default document.title)
 * - channel: (default 'PLR: Pre: N/A')
 * - prop18: (default 'PLR')
 *
 */
(function ($) {
	$.fn.omniture = function (options) {
		var defaults = {
			pageName: document.title,
			channel: 'PLR: Pre: N/A',
			prop18: 'PLR'
		};
		var options = $.extend(defaults, options);

		for (var option in options) {
			s[option] = options[option]; // the "s" object was previously defined in site_stats.js
		}

		var s_code = s.t();
		if (s_code) document.write(s_code);
	}
})(jQuery);

/*
 * jQuery showRandom plugin
 * Version 1.1 (July 24, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to show a specified number of random
 * items in a list and remove the rest from the DOM.
 *
 * Notes
 * - Any item with a class of "required" will be shown automatically.
 * - Any item with a class of "no-[<body> ID]" will be hidden automatically (and will override "required").
 * 
 * Options
 * - items: number of random items to display (default 1)
 *
 */
(function ($) {
	$.fn.showRandom = function (options) {
		var defaults = {
			items: 1
		};
		var options = $.extend(defaults, options);

		var $boxList = this;

		if ($boxList.length) { // test to see if selector exists (prevents script from hanging)
			var $boxes = $boxList.children();
			var numBoxes = $boxes.length;
			var boxesToDisplay = options.items;
			var boxesDisplayed = 0;
			var i = 1;
			var hideClass = 'no-' + $('body').attr('id');

			$boxes.each(function () {
				var required = $(this).hasClass('required');
				var hidden = $(this).hasClass(hideClass);

				if (required) { // show all required boxes
					$(this).removeClass('hidden');
					boxesToDisplay--;
					boxesDisplayed++;
				}
				if (hidden) { // hide all specified boxes
					$(this).remove();
					boxesDisplayed--;
				}
				if (required && hidden) { // ensure display count is correct
					boxesToDisplay++;
				}
			});

			while (i <= boxesToDisplay) {
				var randomBox = Math.floor(Math.random() * numBoxes);
				var $currentBox = $boxList.find('li').eq(randomBox);

				if ($currentBox.hasClass('hidden')) {
					$currentBox.removeClass('hidden');
					boxesDisplayed++;
					i++;
				}
			}

			$boxList.find('li.hidden').remove();
			$boxList.find('li').eq(boxesDisplayed).addClass('last');
		}
	}
})(jQuery);

/*
 * jQuery tableStripe plugin
 * Version 1.0 (July 17, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to apply alternating classes to table rows.
 * 
 * Options
 * - oddClass: class to be used for zero-indexed odd rows (default 'odd')
 * - evenClass: class to be used for zero-indexed even rows (default 'even')
 *
 */
(function ($) {
	$.fn.tableStripe = function (options) {
		var defaults = {
			oddClass : 'odd',
			evenClass : 'even'
		};
		var options = $.extend(defaults, options);

		return this.each(function () {
			$('> tbody:first > tr:even', this).addClass(options.evenClass);
			$('> tbody:first > tr:odd', this).addClass(options.oddClass);
		});
	}
})(jQuery);

/*
 * jQuery tabNavigation plugin
 * Version 1.0 (July 27, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to apply tab navigation to an arbitrary
 * link in a list.
 *
 */
(function ($) {
	$.fn.tabNavigation = function () {
		return this.bind('click', function () {
			var $parent = $(this).parent();
			var $list = $parent.parent().next();
			var activeClass = $parent.attr('id').substr(7); // truncate "tabs-n-" prefix

			$parent.siblings().removeClass('active');
			$parent.addClass('active');

			$list.find('li').removeClass('active');
			$list.find('li.' + activeClass).addClass('active').show();

			return false;
		});
	}
})(jQuery);

/*
 * jQuery clearField plugin
 * Version 1.0 (December 2, 2009)
 * Written by Nick Bourgeois <nbourgeois@optionsxpress.com>
 *
 * This plugin provides the ability to auto-clear text upon focus of a form
 * field.
 *
 */
(function ($) {
	$.fn.clearField = function () {
		return this.focus(function () {
			if (this.value == this.defaultValue) {
				this.value = '';
			}
		}).blur(function () {
			if(!this.value.length) {
				this.value = this.defaultValue;
			}
		});
	}
})(jQuery);

$(document).ready(function () {
	// allow for list bullets and numbers colored differently than adjacent text
	$('.bullets, .numbers').find('li').wrapInner('<span></span>');

	// launch LivePerson popup
	$('#header li.live-help a, #content a.live-help').livePerson();

	// launch Customer Service popup
	$('a.customer-service').popup({
		width: 700,
		height: 470
	});

	// launch glossary popup
	$('a.glossary').popup({
		width: 420,
		height: 350
	});

	// launch post-login FAQ popup
	$('a.faq').popup({
		width: 800,
		height: 600
	});

	// main navigation
	$('#header #main-navigation li').hover(function () {
		$(this).addClass('active');
	}, function () {
		$(this).removeClass('active');
	});

	// show three random marketing boxes
	$('#marketing ul').showRandom({
		items: 3
	});

	// simulate block-level linking
	$('#marketing ul li').hover(function () {
		var title = $(this).children().find('a').attr('title');
		$(this).attr('title', title);
	}).click(function () {
		var $anchor = $(this).children().find('a');
		var href = $anchor.attr('href');
		var said = $anchor.attr('rel');

		if (href.indexOf('?') == -1) {
			var delimeter = '?';
		} else {
			var delimeter = '&';
		}

		var url = href + delimeter + 'said=' + said;
		$anchor.attr('href', url);

		window.location.href = url;
	});

	// auto-clear text fields
	$('input.clear-field').clearField();

	// dynamically build site asset anchor URLs
	$('.site-asset').bind('click', function () {
		var href = $(this).attr('href');
		var said = ($(this).attr('rel')) ? $(this).attr('rel') : $(this).attr('id'); // use id if rel attribute is not populated

		if (said) {
			if (href.indexOf('?') == -1) {
				var delimeter = '?';
			} else {
				var delimeter = '&';
			}

			if (href.indexOf('#') == -1) {
				var url = href + delimeter + 'said=' + said;
			} else {
				var tempUrl = new Array();
				var tempUrl = href.split('#');
				var url = tempUrl[0] + delimeter + 'said=' + said + '#' + tempUrl[1];
			}

			$(this).attr('href', url);
			window.location.href = url;
		}
	});

	// hub navigation
	if ($('body').hasClass('hub')) {
		// "show more" functionality
		$('a.learn-more, ul li#see-more a').bind('click', function () {
			$('a.learn-more').hide();
			$('ul li#see-more').addClass('hidden');
			$('ul li#see-less').removeClass('hidden');
			if ($.browser.msie) {
				$('#content').fadeIn(scrollSpeed);
			} else {
				$('#content').slideDown(scrollSpeed);
			}
		});

		// "show less" functionality
		$('ul li#see-less a').bind('click', function () {
			$('a.learn-more').show();
			$('ul li#see-less').addClass('hidden');
			$('ul li#see-more').removeClass('hidden');
			if ($.browser.msie) {
				$('#content').fadeOut(scrollSpeed);
			} else {
				$('#content').slideUp(scrollSpeed);
			}
		});

		/* hub tab navigation
		$('li.nav-hub a').bind('click', function () {
			var $parent = $(this).parent();
			var activeClass = $parent.attr('id').substr(5); // assumes ID of <li> minus prefix == class of content to display

			$('li.nav-hub').removeClass('active');
			$('ul#list-more li#show-' + activeClass + ', ul#list-less li#hide-' + activeClass).addClass('active');

			$('#title ul li, #content ul li').removeClass('active');
			$('ul li.' + activeClass).addClass('active').show();

			return false;
		}); */

		// remove extraneous chars from location path (used for in-page link scrolling)
		function filterPath(string) {
			return string
				.replace(/^\//, '')
				.replace(/(index|default).[a-zA-Z]{3,4}$/, '')
				.replace(/\/$/, '');
		}
		var locationPath = filterPath(location.pathname);

		// auto-scroll in-page links
		$('a[href*=#]').each(function () {
			var thisPath = filterPath(this.pathname) || locationPath;
			if (locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/, '')) {
				var $target = $(this.hash),
					target = this.hash;
				if (target) {
					var targetOffset = $target.offset().top;
					$(this).bind('click', function (event) {
						event.preventDefault();
						$('html, body').animate({
							scrollTop: targetOffset
						}, scrollSpeed, function () {
							location.hash = target;
						});
					});
				}
			}
		});
	}

	if ($('body').is('#pricing-commissions')) {
		$('ul.tabs li a').tabNavigation();
		$('#interest-table table').tableStripe();
	}

	if ($('body').is('#faq')) {
		$('ul.tabs li a').tabNavigation();
		$('table.trading-level').tableStripe();
	}

	if ($('body').is('#glossary')) {
		$('table.trading-level').tableStripe();
	}

	// insert footer content for SEO purposes
	var footerContent = '<p>optionsXpress, Inc. makes no investment recommendations and does not provide financial, tax or legal advice. Content and tools are provided for educational and informational purposes only. Any stock, options, or futures symbols displayed are for illustrative purposes only and are not intended to portray a recommendation to buy or sell a particular security. Products and services intended for U.S. customers and may not be available or offered in other jurisdictions.</p><p>Online trading has inherent risk due to system response and access times that may vary due to market conditions, system performance, volume and other factors. An investor should understand these and additional risks before trading. Options involve risk and are not suitable for all investors. Please read <a href="http://www.optionsclearing.com/publications/risks/riskchap1.jsp">Characteristics and Risks of Standardized Options</a> or available by calling 888.280.8020 or 312.629.5455. Futures involve substantial risk and are not appropriate for all investors. Please read <a href="http://images.optionsxpress.com/static/pdf/risks_futures_options.pdf">Risk Disclosure Statement for Futures and Options</a> (PDF) prior to applying for an account.</p><p>&copy; <!-- <span value="WC@COPYRIGHT">2010</span> -->2010 optionsXpress, Inc. All rights reserved. Member <a href="http://www.finra.org/index.htm">FINRA</a>, <a href="http://www.sipc.org/">SIPC</a>, <a href="http://www.nyse.com/futuresoptions/nyseamex/1218155409117.html" target="_blank">AMEX</a>, <a href="http://www.nasdaqtrader.com/Micro.aspx?id=nasdaqoptions" target="_blank">NOM</a>, <a href="http://www.cboe.com/">CBOE</a>, <a href="http://www.iseoptions.com/">ISE</a>, <a href="http://www.arcaex.com">ArcaEX</a>, <a href="http://www.phlx.com/">PHLX</a> and <a href="http://www.nfa.futures.org/">NFA</a>.</p>';
	$('#footer').append(footerContent);

	// external links and PDFs (must be declared after footer content is added to DOM)
	$("a[href^='http']:not([href*='xpress'])").attr('target', '_blank');
	$("a[href$='pdf']").attr('target', '_blank').addClass('pdf').append('<em></em>');
});