var snsWidget = {
        missingChapter: false,
	config: {
		url: {
			jsonFeed: "http://sharecare.simonandschuster.com/jsfeed.aspx?chapterisbns=",//"http://shop.sands.com/bridgeline_json.php?chapterisbns=",
                        jQuery: "http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" //"http://cdn.sands.com/jquery.min.js"
		}		
	},
	load: function() {
		var oldonload = window.onload;
		if (typeof window.onload !== 'function') {
			window.onload = snsWidget.setup;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				snsWidget.setup();
			};
		}
	},
	getChapters: function() {
		var chapters = [], isbn;
		for(isbn in snsInlineChapterISBNs) {
			if(typeof isbn === "string" || typeof isbn === "number") {
				chapters.push(isbn);
				chapters[isbn] = snsInlineChapterISBNs[isbn];
			}
		}
                
		return chapters;
	},

	formatChapters: function() {
		var chap_list = '', chaps, i, j;
		chap_list += snsWidget.getChapters().join(',');
		
		snsWidget.formatChapters = function() { return chap_list; };
		return chap_list;
	},
	setup: function setup () {
		if(typeof snsInlineChapterISBNs === 'undefined' || snsWidget.getChapters().length < 1) {return; }
		
		snsWidget.data = {};
		snsWidget.books = [];
		snsWidget.chapters = [];
		snsWidget.content = [];
		snsWidget.lightBoxContent = [];
		
		if(typeof snsWidgetCSSRoot !== 'undefined') {
			snsWidget.loadCSS(encodeURI(snsWidgetCSSRoot));
		}
		
		if(typeof jQuery === 'undefined') {
			snsWidget.loadJS(snsWidget.config.url.jQuery, snsWidget.init);
		} else {
			snsWidget.init();
		}
	},
	init: function init() {
		if(typeof jQuery === 'undefined') { return; }
		snsWidget.fetch();
		snsWidget.lightBox.init();
	},
	loadJS: function(url, callback, type) {
		var done = false,
			scriptTag = document.createElement('script');

		scriptTag.type = 'text/javascript';
		scriptTag.setAttribute('src',url);
		
		if(type && type === 'jsonp') {
			scriptTag.setAttribute('id', 'snsWidgetJSONp');
		}

		if(typeof callback === 'function') {
			scriptTag.onload = scriptTag.onreadystatechange = function () {
				if (( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete"))) {
					done = true;
					callback(); 
					scriptTag.onload = scriptTag.onreadystatechange = null;
				}
			};
		}

		document.getElementsByTagName('head')[0].appendChild(scriptTag);
	},
	loadCSS: function loadCSS(url) {
		if(typeof url === "undefined") { return; }

		var linkTag = document.createElement('link');

		linkTag.type = 'text/css';
		linkTag.rel = 'stylesheet';
		linkTag.setAttribute('href',url);

		document.getElementsByTagName('head')[0].appendChild(linkTag);
	},
	fetch: function fetch(){
		var chaptersRequested = snsWidget.formatChapters(),
			jsonURL = snsWidget.config.url.jsonFeed + chaptersRequested + "&callback=snsWidget.handleJSON";
		snsWidget.loadJS(jsonURL, "", 'jsonp');
	},
	handleJSON: function(data){
		if (typeof(data) === 'undefined'){ 
			return ; 
		}
                var chapterISBN = snsWidget.getChapters()[0];
                var chapter = new Object();
                chapter[chapterISBN] = {};
                if (data.books[data.book_to_show]['chapters'] == null || data.books[data.book_to_show]['chapters'][chapterISBN] == null) {
                    data.books[data.book_to_show]['chapters'] = chapter;
                    snsWidget.missingChapter = true;
                }    

	  	snsWidget.data = data.books;
		var jsonpScriptTag = document.getElementById("snsWidgetJSONp");
		if(jsonpScriptTag) {
			document.getElementsByTagName('head')[0].removeChild(jsonpScriptTag);
		}
		snsWidget.parse();	
	},
	parse: function parse() {
		var parser = {
			init: function() {
				parser.parseChapters();
			},
			parseChapters: function() {
				var isbn, chapterIsbn, tempBook;
				for(isbn in snsWidget.data) {
					tempBook = snsWidget.data[isbn];
					for(chapterIsbn in tempBook.chapters) {
						tempBook.chapters[chapterIsbn].book = isbn;
						if(snsWidget.getChapters()[chapterIsbn]) {
							snsWidget.chapters.push(chapterIsbn);
							snsWidget.chapters[chapterIsbn] = tempBook.chapters[chapterIsbn];
						}
					}
					delete tempBook.chapters;
					snsWidget.books.push(isbn);
					snsWidget.books[isbn] = tempBook;
				}			
			}
		};

		parser.init();
		
		snsWidget.generate();
		snsWidget.lightBox.builder();
		snsWidget.render();
	},
	generate: function generate() {
		var generator = {
			generate: function(){
				var index, isbn,
					showRelated = (snsWidget.chapters.length > 1);
				for(index in snsWidget.chapters) {
					if(typeof snsWidget.chapters[index] === "string") {
						isbn = snsWidget.chapters[index];
						snsWidget.content.push(isbn);
						snsWidget.content[isbn] = generator.generateInlineWidget(isbn, showRelated);
					}
				}
			},
			generateInlineWidget: function(isbn, showRelatedLink) {
				if(typeof isbn === 'undefined') { return; }
				var tempChapterData = snsWidget.chapters[isbn],
					tempBookData = snsWidget.books[tempChapterData.book],
					htmlContent = "";
					
				htmlContent += "<img src='" + tempBookData.thumbnailUrl + "' title='" + tempBookData.title + "' />";
				htmlContent += "<div class='snsWidgetCopyText'>";
                                if (snsWidget.missingChapter === true) {
                                    htmlContent += "Find out more about this book <span>" + tempBookData.title + "</span> <br/>";
                                }
                                else {
                                    htmlContent += "Find out more about this topic in <span>Chapter " + tempChapterData.chapter_number + ": " + tempChapterData.title + "</span> <br/>";
                                    htmlContent += " from my book <span>" + tempBookData.title + "</span>";
                                }
				htmlContent += "</div>";
				htmlContent += "<div class='snsWidgetLinks'>";
				if(tempBookData.buylink) {
					htmlContent += "<span class='price'>" + tempBookData.listPrice + "</span> <a href='" + tempBookData.buylink + "' target='_blank' class='snsWidget_book_buy_link' onclick=\"pageTracker._trackEvent('Widget', 'S&S', 'S&S Buy Book');\">Buy the Book</a> ";
				}
				if(tempChapterData.buylink) {
					htmlContent += "<span class='price'>" + tempChapterData.listPrice + "</span> <a href='" + tempChapterData.buylink + "' target='_blank' class='snsWidget_chapter_buy_link' onclick=\"pageTracker._trackEvent('Widget', 'S&S', 'S&S Buy Chapter');\">Buy the Chapter</a> ";
				}
				if(showRelatedLink) {
					htmlContent += "<a href='#snsWidgetRelatedLink_" + isbn + "' id='snsWidgetRelatedLink_" + isbn + "' target='_blank' class='snsWidgetRelatedChaptersLink'>View Related Chapters</a> ";
				}
				htmlContent += "</div>";
				return htmlContent;
			}
		};
		generator.generate();
	},
	render: function render() {
		var isbn;
        pageTracker._trackEvent('Widget', 'S&S', 'S&S View');
		for(isbn in snsWidget.content) {
			jQuery(".snsWidget." + isbn).html(snsWidget.content[isbn]).slideDown();
		}
		jQuery(".snsWidgetRelatedChaptersLink").bind("click", snsWidget.lightBox.show);
		for(isbn in snsWidget.lightBoxContent) {
			snsWidget.lightBox.elem.holder.append(snsWidget.lightBoxContent[isbn]);
		}
                
	},
	lightBox: {
		init: function() {
			var htmlContent = "<div id='snsWidgetLightBox'><div id='snsWidgetLB_header'>";
			htmlContent += "<a href='#close' id='snsWidgetLightBoxClose'>close</a>";
			htmlContent += "<h2 id='snsWidgetLB_caption'>RELATED CHAPTERS AND BOOKS</h2>";
			htmlContent += "</div><div id='snsWidgetLBContent_holder'></div></div>";
			htmlContent += "<div id='snsWidgetLightBoxOverlay'></div>";
				
			jQuery("body").append(htmlContent);
			
			snsWidget.lightBox.elem = {
				docBody: jQuery("html, body"),
				overlay: jQuery("#snsWidgetLightBoxOverlay"),
				holder: jQuery("#snsWidgetLightBox"),
				content: jQuery("#snsWidgetLBContent_holder"),
				close: jQuery("#snsWidgetLightBoxClose")
			};
		},
		builder: function () {
			var	fragment = jQuery("<div id='snsWidgetLBContent'></div>"),
				check = function(value) {
					return (value)? "" : "snsWidget_hiddenItem";
				},
				build = {
					init: function() {
						build.books();
						build.chapters();
						snsWidget.lightBox.elem.content.append(fragment);
					},
					books: function() {
						var index;
						for(index in snsWidget.books) {
							if(typeof snsWidget.books[index] === "string") {
								build.book(snsWidget.books[index]);
							}
						}
					},
					chapters: function(bookIsbn) {
						var index;
						for(index in snsWidget.chapters) {
							if(typeof snsWidget.chapters[index] === "string") {
								build.chapter(snsWidget.chapters[index]);
							}
						}
					},
					book: function(bookIsbn) {
						if(typeof bookIsbn === 'undefined') { return; }
						
						var htmlContent = "<div class='snsWidgetLB_book' id='snsWidgetLB_book_" + bookIsbn + "'>";
						htmlContent += "<img src='" + snsWidget.books[bookIsbn].thumbnailUrl + "' class='snsWidgetLB_bookCover' />";
						htmlContent += "<div class='snsWidgetLB_book_info'>";
						htmlContent += "<h3 class='snsWidgetLB_title'>" + snsWidget.books[bookIsbn].title + "</h3>";
						htmlContent += ((snsWidget.books[bookIsbn].subtitle)? ("<div class='snsWidgetLB_subtitle'>" + snsWidget.books[bookIsbn].subtitle + "</div>"):"");
						htmlContent += "<div class='snsWidgetLB_book_links " + check(snsWidget.books[bookIsbn].buylink) + "'>";
						htmlContent += "<span class='snsWidgetLB_price'>" + snsWidget.books[bookIsbn].listPrice + "</span> ";
						htmlContent += "<a class='snsWidgetLB_buy_link' target='_blank' href='" + snsWidget.books[bookIsbn].buylink + "' onclick=\"pageTracker._trackEvent('Widget', 'S&S', 'S&S Buy Book');\">Buy the book</a>";
						htmlContent += "</div>";
						htmlContent += "</div>";
						htmlContent += "<ul class='snsWidgetLB_chapters'></ul>";
						htmlContent += "</div>";
						
						fragment.append(htmlContent);
					},
					chapter: function(chapterIsbn) {
						if(typeof chapterIsbn === 'undefined') { return; }
						
						var htmlContent = "<li class='snsWidgetLB_chapter' id='snsWidgetLB_chapter_" + chapterIsbn + "'>";
						htmlContent += "<h4 class='snsWidgetLB_chapterTitle'>Chapter " + snsWidget.chapters[chapterIsbn].chapter_number;
						htmlContent += " : " + snsWidget.chapters[chapterIsbn].title + "</h4>";
						htmlContent += ((snsWidget.chapters[chapterIsbn].subTitle)? ("<div class='snsWidgetLB_subtitle'>" + snsWidget.chapters[chapterIsbn].subTitle + "</div>"):"");
						htmlContent += "<div class='snsWidgetLB_book_links " + check(snsWidget.chapters[chapterIsbn].buylink) + "'>";
						htmlContent += "<span class='snsWidgetLB_price'>" + snsWidget.chapters[chapterIsbn].listPrice + "</span> ";
						htmlContent += "<a class='snsWidgetLB_buy_link' target='_blank' href='" + snsWidget.chapters[chapterIsbn].buylink + "' onclick=\"pageTracker._trackEvent('Widget', 'S&S', 'S&S Buy Chapter');\">Buy the chapter</a>";
						htmlContent += "</div>";
						htmlContent += "</li>";
						
						fragment.find("#snsWidgetLB_book_" + snsWidget.chapters[chapterIsbn].book + " .snsWidgetLB_chapters").append(htmlContent);
					}
				};
				
			build.init();
		},
		handleCurrentISBN: function(isbn) {
			var liBox = snsWidget.lightBox.elem,
				currentChapter = liBox.holder.find("#snsWidgetLB_chapter_" + isbn),
				currentBook = currentChapter.parents(".snsWidgetLB_book");
				
			snsWidget.bow = currentBook;
			liBox.holder.find(".snsWidgetLB_book, .snsWidgetLB_chapter").show();
				
			currentChapter.hide();
			if(currentBook.find(".snsWidgetLB_chapter:visible").length < 1) {
				currentBook.hide();
			}
			
		},
		show: function() {
			var liBox = snsWidget.lightBox.elem, 
				currentChapterISBN = /snsWidgetRelatedLink_(\d+)/.exec(jQuery(this).attr("id"))[1];
			liBox.overlay.show();
			liBox.docBody.addClass("snsWidgetBlockScroll");
			
			liBox.holder.show();
			
			snsWidget.lightBox.handleCurrentISBN(currentChapterISBN);
			
			liBox.close.click(snsWidget.lightBox.hide);
			jQuery(document).bind('keydown', snsWidget.lightBox.handleKey);
			
			return false;
		},
		hide: function() {
			var liBox = snsWidget.lightBox.elem;
			liBox.docBody.removeClass("snsWidgetBlockScroll");
			liBox.holder.hide();
			liBox.overlay.hide();
			jQuery(document).unbind('keydown', snsWidget.lightBox.handleKey);
			return false;
		},
		handleKey: function(e) {
			var keycode = (e === null)? event.keyCode : e.which;
			
			if(keycode === 27) {
				snsWidget.lightBox.hide();
			}
		}
	}
};

