String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
};

sharedScripts = new Object();
sharedScripts.contentSearch = function(searchString) {
	if (searchString.length) {
		window.location = '?page=search&searchString=' + searchString;
	};
};

// Write a script tag to the page while the page is loading 
// - Caution - potential for timing issues
// - Caution - if called after the page is loaded will overwrite the existing document content
sharedScripts.writeScript = function(src) {

	document.write('<script src="' + src + '" type="text/JavaScript"><\/script>');

};

// Add a script tag to the page after it has loaded
// - Caution - potential for timing issues
sharedScripts.addScript = function(src) {
   var head = document.getElementsByTagName("head")[0];
   script = document.createElement('script');
   script.type = 'text/javascript';
   script.src = src;
   head.appendChild(script);
};

// Syncronous XMLHttpRequest to load script content
// Caution - cross site limitations - an XMLHttpRequest is being made to request the .js file content
sharedScripts.loadScript = function(src) {
	
	var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
	request.open("GET", src, false);
	request.send(null);
	
	var head = document.getElementsByTagName("head")[0];
	script = document.createElement('script');
	script.type = 'text/javascript';
	script.text = request.responseText;
	head.appendChild(script);	
	
};

//TODOD - create ajax class and move this into it
function hostpath() {
	var href = window.location.href;
	var d = href.match('^(ftp|http|https|file)://([^/]+)(/.*)?(/.*)')[4];
	//alert(d);
	if (d!='/') {
		var href = href.replace(d, '') + '/';	
	};
	//alert(href);
		
	//href = window.location.href.replace(window.location.hash, '').replace(window.location.search, '').replace('default.aspx', '');
	//alert(href);
	
	return href;
};

var popupTitle
var popupHeadline
var popupContent
var popupWindow
	
function trackOutboundLink(a, _event) {
	pageTracker._trackPageview(_event); window.setTimeout(function(){ window.open(a.href); },200);
}		

/* begin - restore scroll position on postback */
window.onscroll = function () { 
	if (document.getElementsByName('scrolly')[0]) {
		var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0)
		{
			document.getElementsByName('scrollx')[0].value = (document.all) ? document.body.parentElement.scrollLeft : window.pageXOffset; 
			document.getElementsByName('scrolly')[0].value = (document.all) ? document.body.parentElement.scrollTop : window.pageYOffset; 
		}
		window.status = document.getElementsByName('scrollx')[0].value + ',' + document.getElementsByName('scrolly')[0].value;
	};
} 
window.onload = function() { 
	if (document.getElementsByName('scrolly')[0]) {
		window.scrollTo(document.getElementsByName('scrollx')[0].value, document.getElementsByName('scrolly')[0].value);

		window.status = document.getElementsByName('scrollx')[0].value + ',' + document.getElementsByName('scrolly')[0].value;

	};
}
/* end - restore scroll position on postback */

function popup(title,headline,page,querystring,content,height,width,action,bScrollbars) {
  // If the "page" is popupText.aspx, you may include several sentences as "content".
  // If the "page" is default.aspx, the page should use template pageBodyPopup.ascx 
  // to hide side menus.
	
	querystringParams = 'title=' + title + '&headline=' + headline
	if (querystring == '') {
		querystring = '?' + querystringParams
		} else {
		if (querystring.substring(0, 1) != '?') {
		  querystring = '?' + querystring;
		  };
		querystring = querystring + '&' + querystringParams
		}
	var URL = page + querystring
	var scrollbars = 'no';
	var action = '';
	if (bScrollbars) {scrollbars='yes'}
	if (action != '') {
		if (querystring == '') {
			URL += '?action=' + action
		}
		else {
			URL += '&action=' + action
		}
	}
	if ((window.navigator.userAgent.indexOf('Opera') < 0) && (popupWindow != null)) { popupWindow.close() }
	popupTitle = title;
	popupHeadline = headline;
	popupContent = content;
	popupWindow = window.open(URL,'popup','top=45,left=80,width=' + width + ',height=' + (height+30) + ',menubar=no,toolbar=no,scrollbars='+scrollbars,true);
	//popupWindow = null;
	
}

function emailContent(URL,Title,siteName) {
	if (!siteName) {
		siteName = 'Marvin.com';
	};
	if (!URL) {
		URL = escape(window.location);
	}
	if (!Title) {
		Title = escape(document.title);
	}
	var mailto = 'mailto:?subject=' + Title + '&body=Look%20what%20I%20found%20on%20' + siteName + ':%0A%0A' + Title + '%0A' + URL;
	window.location = mailto;
}

function printPage() {
	if (window.navigator.userAgent.indexOf('Netscape') > 0) {
			window.setTimeout(window.print,1);
	} 
	else {
		window.print();
	}
}


/* Querystring functionality used on search page (search.ascx) */

function Querystring()
{
// get the query string, ignore the ? at the front.
	var querystring=location.search.substring(1,location.search.length);

// parse out name/value pairs separated via &
	var args = querystring.split('&');

// split out each name = value pair
	for (var i=0;i<args.length;i++)
	{
		var pair = args[i].split('=');

		// Fix broken unescaping
		temp = unescape(pair[0]).split('+');
		name = temp.join(' ');

		temp = unescape(pair[1]).split('+');
		value = temp.join(' ');

		this[name]=value;
	}

	this.get=Querystring_get;
}

function Querystring_get(strKey,strDefault)
{
	var value=this[strKey];
	if (value==null)
	{
		value=strDefault;
	}

	return value;
}

function getQuerystringVar(varName) {
	var value = ""
	if (window.location.search.indexOf(varName + '=') != -1) {value = window.location.search.substring(window.location.search.indexOf(varName + '=') + varName.length + 1,(window.location.search+'&').indexOf('&',window.location.search.indexOf(varName + '=') + varName.length))}
	return value;
	}

/* Cookies */

function Cookies()
{

	// get the cookie string
	var cookies=document.cookie;
	
	// parse out name/value pairs
	var args = cookies.split(';');
	
	// split out each name = value pair
	for (var i=0;i<args.length;i++)
	{
		var pair = args[i].split('=');
		name = pair[0].trim();
		if (pair[1]==undefined) { //can happen if the key has no value
			value = '';
		} else {
			value = pair[1].trim();
		};
		this[name]=value;

	}
	this.get=Cookies_get;
	this.set=Cookies_set;	
}

function Cookies_get(name,strDefault)
{
	var value=this[name];
	if (value==null)
	{
		value=strDefault;
	}
	return value;
}
function Cookies_set(name, value)
{
	//alert(document.cookie);
}

function getCookiesVar(varName) {
	var value = ""
	if (window.location.search.indexOf(varName + '=') != -1) {value = window.location.search.substring(window.location.search.indexOf(varName + '=') + varName.length + 1,(window.location.search+'&').indexOf('&',window.location.search.indexOf(varName + '=') + varName.length))}
	return value;
	}

/* Html partial removal from form fields */

function replaceAll(textValue, searchfor, newvalue) {
		return textValue.replace(new RegExp(searchfor, 'g'), newvalue);
}

function removeHtmlFromString(originalString) {
		var s = originalString;
		s = replaceAll(s, "&", "&amp;");
		s = replaceAll(s, "<", "&lt;");
		s = replaceAll(s, ">", "&gt;");
		// s = replaceAll(s, "=", "equals");
		return s;
}

function removeHtmlFromField(textField) {
	// Parameter will usually be the object "this"
	var s = "";
	s = textField.value;
	s = replaceAll(s, "&", "&amp;");
	s = replaceAll(s, "<", "&lt;");
	s = replaceAll(s, ">", "&gt;");
	// s = replaceAll(s, "=", "equals");
	textField.value = s;
	return s;
}

function removeAmpersandFromString(originalString) {
	// Used for parameter values in the querystring that contain an ampersand.
	var s = originalString;
	s = replaceAll(s, "&", "%26");
	return s;
}

function cleanSearchTerm(originalString) {
	var s = originalString;
	// Add spaces to separate HTML code from regular words for searching.
	s = replaceAll(s, " & ", " and ");
	s = replaceAll(s, "&", " and ");
	// s = replaceAll(s, "<", " < ");
	// s = replaceAll(s, ">", " > ");
	s = replaceAll(s, "<", " less than ");
	s = replaceAll(s, ">", " greater than ");
	s = replaceAll(s, "/", " - ");
	s = replaceAll(s, "\\\\", " - ");
	s = removeHtmlFromString(s);
	s = removeAmpersandFromString(s);
	return s;
}



function ajax(url, vars, callbackFunction, callbackParams, returnXML) {
					
	var request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");

	//request.open("POST", url, true);
	//request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.open("GET", url, true);

	request.onreadystatechange = function(){
			if (request.readyState == 4 && request.status == 200) {
				if (request.responseText){
					if (callbackParams) {
						if (returnXML) {
							callbackFunction(request.responseXML.documentElement, callbackParams);
						} else {
							callbackFunction(request.responseText, callbackParams);
						};						
					} else {
						if (returnXML) {
							callbackFunction(request.responseXML.documentElement);
						} else {
							callbackFunction(request.responseText);;
						};		
					};          
				} 
				else {
					callbackFunction('', callbackParams);
			}
		} 
		else if (request.readyState == 4) {
			callbackFunction('', callbackParams);
		}
	}

	request.send(vars);

}

var contentRotator = function () {

	var el;
	var i = 0;

	return {

		init: function (target, interval) {

			var self = this;
			el = $(target);
			$(el[i]).siblings(target).each(function () {
				$(this).toggle(false);
			});

			if (el.length > 1) {
				setInterval(function () {
					$(el[i++]).toggle(false);
					if (i == el.length) {
						i = 0;
					};
					$(el[i]).toggle(true);
				}, interval);
			};

		}

	};

} ();

var definitions = function () {

	var c = $('<div class="definition-frame"></div>');   //container for iframe
	var fMargin = 5;

	return {

		init: function () {
			var self = this;
			$('a.definition').each(function () {
				var link = $(this);
				if (!link.hasClass('clickable')) {
					link.addClass('definition-enabled')
					link.click(function () {
						definitions.show(link);
						return false;
					});
				};
				link.hover(function () {
					definitions.show(link);
				}, function () {
					definitions.hide();
				});
			});
			c.appendTo('body');
			definitions.hide();

			//definitions.show($($('a.definition')[0]));

		},
		show: function (link) {
			var frame = $('<iframe src="/default_fullscreen.aspx?page=definitions&value=' + link.html().replace(' ', '-').toLowerCase() + '" frameborder="none" scrolling="no"></iframe>');
			c.empty();
			frame.css('border', '0px');
			frame.appendTo(c);
			frame.load(function () {
				var self = $(this);
				try {
					self.height(this.contentWindow.document.body.offsetHeight + 50);
				} catch (e) { };
				self.width(c.width() - fMargin * 2);
				definitions.setPosition(link, self.parent());
			});
			c.toggle(true);
		},
		hide: function () {
			c.css('left', '-10000px');
			c.toggle(false);
			c.empty();
		},
		setPosition: function (link) {
			var left = (link.offset().left);
			var top = (link.offset().top + link.height() + 5);
			if (left + c.width() > document.body.offsetWidth) {
				left = link.position().left + link.width() - c.width() - 20;
			};
			c.css('z-index', '10000000');
			c.css('left', left + 'px');
			c.css('top', top + 'px');
		}
	};

} ();
$(function () {
	definitions.init();
});

var topicSelector = function () {
	var selectedIndex = 0;
	return {
		init: function () {
			var top = $('.topic-selector');
			var li = $('.topic-selector li');
			var img = $('.topic-selector li img');
			var p = $('.topic-selector p');
			li.each(function () {
				var el = $(this);
				el.hover(function () {
					if (selectedIndex != el.index()) {
						el.css('text-decoration', 'underline')
						el.css('cursor', 'pointer')
					};
				}, function () {
					el.css('text-decoration', 'none');
				});
				el.click(function () {
					selectedIndex = el.index();
					var sibs = el.siblings('li');
					var vis = $(p[selectedIndex]);
					top.css('background-image', 'url(\'' + $(img[selectedIndex]).attr('src') + '\')');
					vis.toggle(true);
					vis.siblings('p').toggle(false);
					el.attr('class', 'topic-selected');
					el.css('text-decoration', 'none');
					sibs.attr('class', '');                    
				});
			});
			$(li[selectedIndex]).click();
		}
	};
} ();

var linkButtons = function () {
	return {
		init: function (buttonSelector) {
			$(buttonSelector).each(function () {
				var e = $(this);
				var a = e.find('a');
				if (a.length != 0) {
					e.css('cursor', 'pointer');
					e.click(function () {
						window.location = $(a[0]).attr('href');
					});
				};
			});
		}
	};
} ();

var rankRadio = function () {
	var l;
	function rank(index) {
		for (i = 0; i < l.length; i++) {
			i <= index ? $(l[i]).addClass('on') : $(l[i]).removeClass('on');
		};
	};
	return {
		init: function (container) {
			var s = $(container);
			l = s.find('label');
			s.find('input').each(function (index) {
				var r = $(this);
				r.is(':checked') ? rank(index) : 1 == 1;
				r.click(function () {
					rank(index);
				});
			});
			s.addClass('rankRadio');
		}
	};
} ();
var reviews = function () {
	var self;
	return {
		init: function () {
			if (self) { return }; //prevent re-init
			self = this;
			var isProduct = !$.reviews.product & $.reviews.product.length == 0;
			if (isProduct) {
				$.post($.reviews.productsUrl, { src: $.reviews.source }, function (data) {
					if (data != "error" && data != "exception") {
						var source = $('#product-list-template').html();
						var template = Handlebars.compile(source);
						var data = { name: '', products: data };
						$($.reviews.productsSelect).html(template(data));
						$($.reviews.productsSelect + '>select').change(function () {
							if (this.selectedIndex == 0) {
								self.buildPager();
							} else {
								self.buildPager($(this).val());
							};
						});
					}
					else {
						$($.reviews.productsSelect).html('');
					};
				});
			};
			self.buildPager($.reviews.product);
		},
		buildPager: function (product) {
			product = !product ? unescape($.reviews.product) : unescape(product);
			$.post($.reviews.reviewsUrl, { src: $.reviews.source, product: product, page: 1, pagesize: $.reviews.pagesize, pagecount: 1 }, function (data) {
				if (data != "error" && data != "exception") {
					var source = $('#product-review-pager-template').html();
					var template = Handlebars.compile(source);
					var pages = new Array();
					for (i = 1; i <= parseInt(data); i++) {
						pages.push({ 'page': i })
					};
					$($.reviews.reviewsContainer + '-pager').html(template({ name: '', pages: pages }));
					$($.reviews.reviewsContainer + '-pager>a').click(function () {
						var a = $(this);
						self.search(product, parseInt(a.text()));
						$($.reviews.reviewsContainer + '-pager>a').removeClass('selected');
						a.addClass('selected');
						return false;
					});
					$($($.reviews.reviewsContainer + '-pager>a')[0]).click();                    
				}
				else {
					$($.reviews.reviewsContainer + '-content').html('');
					$($.reviews.reviewsContainer).toggle(false);
				};
			});
		},
		search: function (product, page) {
			product = !product ? unescape($.reviews.product) : unescape(product);
			page = !page ? 1 : page;
			$.post($.reviews.reviewsUrl, { src: $.reviews.source, product: product, page: page, pagesize: $.reviews.pagesize }, function (data) {
				if (data != "error" && data != "exception") {
					var source = $('#product-review-template').html();
					var template = Handlebars.compile(source);
					var d;
					$.each(data, function (key, value) {
						d = new Date(+value.created.replace(/\/Date\((-?\d+)\)\//gi, "$1"));
						value.created = $.datepicker.formatDate('MM dd, yy', d);  //d.getDate() + '-' + (parseInt(d.getMonth()) + 1) + '-' + d.getFullYear();
					});
					var data = { name: '', reviews: data };
					$($.reviews.reviewsContainer + '-content').html(template(data));
					$($.reviews.reviewsContainer).toggle(true);
				}
				else {
					$($.reviews.reviewsContainer + '-content').html('');
					$($.reviews.reviewsContainer).toggle(false);
				}
			});
		}
	};
} (); 

var framer = function (container, src, height, width, scrolling) {
	var o = this;
	width = !width ? '100%' : width;
	height = !height ? 200 : height;
	scrolling = !scrolling ? 'no' : scrolling;
	o.c = $('<div></div>');
	o.c.addClass('framer');
	o.c.appendTo($(container));
	src.indexOf('?') != -1 ? src += '&frame=1' : src += '?frame=1';
	o.f = $('<iframe id="product-reviews" src="' + src + '" frameborder="0" scrolling="' + scrolling + '"></iframe>');
	o.f.load(function () {
		var wh = this.contentWindow.document.body.offsetHeight;
		var fh = !wh ? height : wh+50;
		o.f.height(fh);
		o.f.width(width);
		o.c.height(fh);
		o.c.width(width);
	});
	o.c.show = function () {
		!o.shown ? o.f.appendTo(o.c) : o.shown;
		o.shown = true;
	};
	o.show = function () {
		o.c.show();
	}
}


