/*
*	All  JavaScript should use jQuery or the $scout namespace
*	http://jquery.com/
*/

/****************************************************************************
*	LOAD
****************************************************************************/

// jQuery doesn't allow caching of getJSON and getScript by default.
// This will normalize behavior between all AJAX calls.
$.ajaxSetup({
	cache: true
});

$(document).ready(function() {
	$scout.init();
});

/****************************************************************************
*	$SCOUT NAMESPACE
****************************************************************************/

var $scout = { };
$scout.template = { };

/****************************************************************************
*	SCOUT FUNCTIONS
****************************************************************************/

	/* INIT */
	
$scout.init = function() {	
	// Table row highlight plug-n-play.
	$("table.row-highlight tbody tr").tableRowHighlight("#fdfedc", "#ffffff");

	// Slider plug-n-player
	$(".content-slider").slider();
	
	// Popup plug-n-play.
	$("a.popup").popups("active");
	
	// Tabs plug-n-play.
	$(".tabs").each(function() {
		var allowCollapse = false;
	
		if ($(this).hasClass("tabs-allow-collapse")) {
			allowCollapse = true;
		}
		
		$("a", this).tabs("active", allowCollapse);
	});
};

/****************************************************************************
*	SCOUT JQUERY PLUGINS
****************************************************************************/

	/* USER MENUS */
	
(function($) {

var secureURL = function(env, siteId, path) {
	return "https://secure." + env + "/a.z?s=" + siteId + "&amp;" + path;
};

$.fn.userHeaderMenu = function(env, siteId, secure, minimal) {
	var menu = "";
	var httpMedia = (secure == "True") ? "https://secure" : "http://media";
	var isMinimal = (minimal == "True") ? true : false;
	
	if ($.cookie("tisession")) {
		var email = $.cookie("email");
		
		if (email.length >= 20) {
			email = email.substr(0, 16) + "...";
		}
		
		menu += '<li>' + email + '</li>';
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=9&amp;redirecturl=" + escape(document.location.href)) + '">Sign Out</a></li>';
		menu += '<li>';
		menu += '	<a class="parent" href="' + secureURL(env, siteId, "p=5&amp;c=7") + '">My Profile</a>';
		menu += '	<ul>';
		menu += '		<li><a href="' + secureURL(env, siteId, "p=5&amp;c=7") + '">My Profile Home</a></li>';
		menu += '		<li><a href="' + secureURL(env, siteId, "p=5&amp;c=4") + '">Member Profile</a></li>';
		menu += '		<li><a href="' + secureURL(env, siteId, "p=5&amp;c=13") + '">Subscriptions</a></li>';
		menu += '		<li><a href="http://my.' + env + '/hotlist.aspx?s=' + siteId + '&amp;p=16">My HotList</a></li>';
		menu += '		<li><a href="' + secureURL(env, siteId, "p=5&amp;c=18") + '">Contact Us</a></li>';
		menu += '	</ul>';
		menu += '</li>';
	}
	else {
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=1&amp;redirecturl=" + escape(document.location.href)) + '">Sign In</a></li>';
		if (!isMinimal) {
			menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=3&amp;redirecturl=" + escape(document.location.href)) + '"><img src="' + httpMedia + '.scout.com/media/images/scout/sign-up.gif" alt="Sign Up" /></a></li>';
		}
	}
	
	this.append(menu);
};

$.fn.userFooterMenu = function(env, siteId) {
	var menu = "";
	
	if ($.cookie("tisession")) {
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=7") + '">My Profile Home</a></li>';
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=4") + '">Member Profile</a></li>';
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=13") + '">Subscriptions</a></li>';
		menu += '<li><a href="http://my.' + env + '/hotlist.aspx?s=' + siteId + '&amp;p=16">My HotList</a></li>';
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=18") + '">Contact Us</a></li>';
	}
	else {
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=1&amp;redirecturl=" + escape(document.location.href)) + '">Sign In</a></li>';
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=3&amp;redirecturl=" + escape(document.location.href)) + '">Sign Up</a></li>';
		menu += '<li><a href="' + secureURL(env, siteId, "p=5&amp;c=18") + '">Contact Us</a></li>';
	}
	
	this.append(menu);
};

})(jQuery);

	/* SHOWAD */
	
(function($) {

var adcodes = { };
var queue = { };
var sizecode = {
	"300x250": "1089",
	"728x90": "1390",
	"160x600": "1090",
	"180x150": "1087",
	"234x60": "1007",
	"120x30": "1025",
	"1x1": "1402"
};

// options = site, type, height, width, environment (optional)
$.fn.showAd = function(options) {
	var site = options.site = "" + options.site; // using for hash lookup not array lookup.
	
	this.each(function() {
		var target = this;
		
		var callback = function() {
			show(target, options);
		};
		
		if (!adcodes[site] || !adcodes[site].cached) {
			addQueue(site, callback);
			loadAdCodes(options);
		}
		else {
			callback();
		}
	});
};

$.showAd = { };

$.showAd.cacheAdCodes = function(data) {
	var site = data.siteId;
	
	$.each(data.ads, function() {
		//{"code":"T4LA79","height":90,"type":"DISPLAY","width":728}
		var type = this.type.toLowerCase();
		var sizekey = this.width + "x" + this.height;
		
		if (!adcodes[site][type]) {
			adcodes[site][type] = { };
		}
		
		adcodes[site][type][sizekey] = this.code;
	});
	
	adcodes[site].loading = false;
	adcodes[site].cached = true;
	
	runQueue(site);
}

var loadAdCodes = function(options) {
	var site = options.site;
	var environment = options.environment || "scout.com";

	if (!adcodes[site]) {
		adcodes[site] = {};
		adcodes[site].loading = false;
		adcodes[site].cached = false;
	}
	
	if (!adcodes[site].cached) {
		if (!adcodes[site].loading) {
			adcodes[site].loading = true;
			$.getScript("http://cdn-forums." + environment + "/adfeed.ashx?s=" + site + "&format=json&callback=$.showAd.cacheAdCodes");
		}
	}
	else {
		runQueue(site);
	}
};

var addQueue = function(site, callback) {
	if (!queue[site]) {
		queue[site] = [];
	}
	
	queue[site].push(callback);
};

var runQueue = function(site) {
	if (!queue[site]) {
		return;
	}

	$.each(queue[site], function() {
		this();
	});
	
	queue[site] = [];
};

var show = function(target, options) {
	var sizekey = options.width + "x" + options.height;

	if (adcodes[options.site] && adcodes[options.site][options.type] && adcodes[options.site][options.type][sizekey]) {
		var pg = adcodes[options.site][options.type][sizekey];
		var ap = sizecode[sizekey];
		
		dapMgr.enableACB(target.id, false);
		dapMgr.renderAd(target.id, "&PG=" + pg + "&AP=" + ap, options.width, options.height);
	}
};

})(jQuery);

	/* HOVERSTATES */

(function($) {

$.fn.hoverStates = function(hoverClass) {
	this.each(function() {
		$(this).hover(
			function() {
				$(this).addClass(hoverClass);
			},
			function() {
				$(this).removeClass(hoverClass);
			}
		);
	});
};

})(jQuery);

	/* TABLEROWHIGHLIGHT */

(function($) {

$.fn.tableRowHighlight = function(hColor, bgColor) {
	this.each(function() {
		$(this).hover(
			function() {
				$(this).animate({ backgroundColor: hColor }, "fast");
			},
			function() {
				$(this).animate({ backgroundColor: bgColor }, "fast");
			}
		);
	});
};

})(jQuery);

	/* SLIDER */
	
(function($) {
	$.fn.slider = function() {
		this.each(function() {
			var slides = $(".slide", this);
			var index = 0;
			var position = 0;
			var width = $(slides.get(0)).width();
			var pages = [];
			var prev = $("<a class='disabled' href='#'>prev</a>");
			var next = $("<a href='#'>next</a>");
			var that = this;
			
			if (slides.length <= 1) { return; }
			
			// Slide between pages, given an index (0 - length-1).
			var slideTo = function(i) {
				if (i < 0 || i >= slides.length) {
					return;
				}
			
				for (var k = 0; k < pages.length; k++) {
					var page = pages[k];
					
					if (i == k) {
						page.addClass("active");
						
						if (i < index) {
							position += width * (index - i);
						}
						else {
							position -= width * (i - index);
						}
						
						$(".slides", that).animate({ left: position + "px" }, "normal");
						
						index = i;
					}
					else {
						page.removeClass("active");
					}
				}
				
				prev.removeClass("disabled");
				if (index <= 0) {
					prev.addClass("disabled");
				}
				
				next.removeClass("disabled");
				if (index >= slides.length-1) {
					next.addClass("disabled");
				}
			};
			
			// Creating navigation for paging.
			
			$(".paging", this).append("<ul></ul>");
			
			// Prev page.
			prev.click(function() {
				slideTo(index-1);
				return false;
			});
			
			$(".paging ul", this).append($("<li class='prev'></li>").append(prev.get()).get());
			
			// Individual pages.
			slides.each(function(i) {
				pages[i] = $("<a href='#'>" + (i + 1) + "</a>");
				pages[i].click(function() {
					slideTo(i);
					return false;
				});
				
				if (i == 0) {
					pages[i].addClass("active");
				}
				
				$(".paging ul", that).append($("<li class='page'></li>").append(pages[i].get()).get());
			});
			
			// Next page.
			next.click(function() {
				slideTo(index+1);
				return false;
			});
			
			$(".paging ul", this).append($("<li class='next'></li>").append(next.get()).get());
		});
	};
})(jQuery);

	/* POPUPS */
	
(function($) {
	var getPopup = function(link) {
		var id = link.href.split("#");

		if (id.length <= 1) {
			return;
		}

		return $("#" + id[1]).get(0);
	};
	
	$.fn.popups = function(activeClass) {
		var links = [];
		this.each(function() {
			var linkPopup = getPopup(this);

			if (!linkPopup) {
				return;
			}
			
			links.push(this);
			$(linkPopup).css("display", "none")
			$(this).removeClass(activeClass);
			
			$(this).click(function() {
				// Show/hide current popup.
				if ($(linkPopup).css("display") == "none") {
					$(linkPopup).css("display", "block")
					$(this).addClass(activeClass);
				}
				else {
					$(linkPopup).css("display", "none")
					$(this).removeClass(activeClass);
				}
				
				// Close all other popups.
				for (var i = 0; i < links.length; i++) {
					var link = links[i];
					
					if (this.href != link.href) {
						$(getPopup(link)).css("display", "none");
						$(link).removeClass(activeClass);
					}
				}
				
				return false;
			});
		});
	};
	
})(jQuery);

	/* TABS */

(function($) {

// Returns tab target pane.
var getPane = function(tab) {
	if (tab.href) {
		var pane = tab.href.match(/^.*(#.*)$/);
		
		if (pane && pane[1]) {
			return $(pane[1]).get(0);
		}
	}
}

$.fn.tabs = function(activeClass, allowCollapse) {
	if (!this.length) return;

	var tabs = [];
	var active = null;
	
	// Gather tabs.
	this.each(function() {
		if (getPane(this)) {
			tabs.push(this);
			
			// Default active tab.
			if ($(this).hasClass(activeClass)) {
				active = this;
			}
		}
	});
	
	if (!tabs.length) return;
	
	// Hide all panes.
	$(tabs).each(function() {
		$(this).removeClass(activeClass);
		$(getPane(this)).hide();
	});
	
	// Set and show active tab.
	active = active || tabs[0];
	$(active).addClass(activeClass);
	$(active).show();
	$(getPane(active)).show();
	
	// Set events.
	$(tabs).each(function() {
		$(this).click(function(e) {
			if (!allowCollapse && $(this).hasClass(activeClass)) {
				return false;	// Don't fully collapse, must have at least one active tab.
			}
			
			var currentActive = active;
			
			// Show new active tab.
			if (this != active) {
				$(this).addClass(activeClass);
				$(getPane(this)).show();
				
				active = this;
			}
			else {
				// Full collapse, no active tabs.
				active = null;
			}
			
			// Remove active state and hide pane.
			if (currentActive) {
				$(currentActive).removeClass(activeClass);
				$(getPane(currentActive)).hide();
			}
			
			return false;
		});
	});
};
	
})(jQuery);

	/* XSLT */
	
(function($) {

$.fn.xslt = function(xmlUri, xslUri) {
	var result;
	var elements = this;

	if (window.ActiveXObject) {
		(function() {
		
		var getXML = function(uri) {
			var xml = new ActiveXObject("Microsoft.XMLDOM");
			
			xml.async = false;
			xml.load(uri);
			
			return xml;
		}
		
		var xml = getXML(xmlUri);
		var xsl = getXML(xslUri);
		
		if (xml && xsl) {
			result = xml.transformNode(xsl);
			
			if (result) {
				elements.each(function() {
					$(this).html(result);
				});
			}
		}
		
		})();
	}
	else {
		(function() {
		
		$.get(xmlUri, function(xmlData) {
			if (xmlData) {
				$.get(xslUri, function(xslData) {
					var processor = new XSLTProcessor();
					processor.importStylesheet(xslData);
					
					var result = processor.transformToFragment(xmlData, document);
					
					if (result) {
						elements.each(function() {
							$(this).html(result);
						});
					}
				}, "xml");
			}
		}, "xml");
		
		})();
	}
}

})(jQuery);

/****************************************************************************
*	JQUERY PLUGINS
****************************************************************************/

	/* COOKIE */

	/*
	 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
	 * Dual licensed under the MIT and GPL licenses:
	 * http://www.opensource.org/licenses/mit-license.php
	 * http://www.gnu.org/licenses/gpl.html
	 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

	/* COLOR ANIMATIONS */

	/*
	 * jQuery Color Animations
	 * Copyright 2007 John Resig
	 * Released under the MIT and GPL licenses.
	 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);
