JournalSearch = function(element){
	this.element = element;
	this.initialValue = element.value;
	
	this.init();
}

JournalSearch.prototype = {
	init : function(){
		var ref = this;
		var el = ref.element;
		Event.observe(el, "focus", function(e){
			if(el.value == ref.initialValue){
				el.value = '';
			}
			el.removeClassName("initial");
		});
		Event.observe(el, "blur", function(e){
			if( !el.value || el.value.strip() == '' ){
				el.addClassName("initial").value = ref.initialValue;
			}
		});
		Event.observe($("jSearchForm"), "submit", function(evt){
			if(el.value == '' || el.value == ref.initialValue){
				Event.stop(evt);
				alert("Please enter a search term in the search box.");
				el.focus();
			}
		});
	}
}

/*
 * encapsulates the product page ajax functionality including
 *  the tab navigation, async content loading and google preview
 */
ProductPage = function(element, productType, prdId, isbn, initialState){
	this.element = element;
	this.productId = prdId;
	this.isbn = isbn;
	this.productType = productType;

	this.cache = new Hash();

	this.initialState = initialState;
	this.productNav = new ProductNav($("productNav"), this);
	this.gView = new GoogleBooksView(isbn);

	this.init();
};

ProductPage.prototype = {
	init: function(){

		var page = this;
		
		var bookmarked = YAHOO.util.History.getBookmarkedState("tabview") || this.initialState;

		YAHOO.util.History.register("tabview", bookmarked, function(state) {
			page.productNav.onSelect(state);
		});

		try {
			YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
		} catch (e) { console.log(e); }

		YAHOO.util.History.onReady(function () {
			var currentState = YAHOO.util.History.getCurrentState("tabview");
			if(currentState != page.initialState){
				page.productNav.onSelect(currentState);
			}
		});
	},

    /*
     * @param prdType: [book,journal]
     * @param contentType: the tabId from the server side (toc, title, etc...)
     */
	displayContent: function(contentType){
		this.initialState = contentType;
		YAHOO.util.History.navigate("tabview", contentType);

		if(this.cache.get(contentType)){
			$("productContent").update(this.cache.get(contentType));
			if(YAHOO.sgpb) YAHOO.sgpb.ui.render(jQuery("#productContent"));
		}
		else if(contentType == 'google'){
			this.productNav.resetState();
			var content = this.gView.render($("productContent"));
		}
		else{
			var cacheRef = this.cache;
			var url = "/product/" + this.productType + "/details.nav?productId=" + this.productId + "&ct_p=" + contentType;
			new Ajax.Request(url, {
				method :'get',
				onSuccess: function(transport) {
					var response = transport.responseText;
					cacheRef.set(contentType, response);
					$("productContent").update(response);
					if(YAHOO.sgpb) YAHOO.sgpb.ui.render(jQuery("#productContent"));
					if(contentType == 'reviews'){
						initCustomerReviews();
					}
				}
			});
		}

		if($("staticSubscription")){
			$("staticSubscription").show();
		} 
		if(this.productNav.afterDisplayHandlers[contentType]){
			this.productNav.afterDisplayHandlers[contentType]();
		}
	},

	webTrendsTags: function(contentType){
		
			var url = "/webTrendsTags.data?ct_p=" + contentType+"&productType="+ this.productType;
			new Ajax.Request(url, {
				method :'get',
				onSuccess: function(transport) {
					try{
						var response = transport.responseText.evalJSON();
						dcsMultiTrack("WT.cg_s",response.webTrendsTags['WT.cg_s'], "WT.cg_n",response.webTrendsTags['WT.cg_n']);
					}catch(e){
						if(console) console.log(e);
					}
				}
			});
		}		
}

/*
 * encapsulates the tab-based navigation on the product page
 */
ProductNav = function(element, productPage){
	this.productId = productPage.productId;
	this.productPage = productPage;
	this.element = element;
	this.primaryNavItems;
	this.secondaryNavItems;
	this.element.select("#secondary")[0]

	this.initialState = productPage.initialState;
	this.secondaryNav = (this.element.select("#secondary")[0]) ?
		new SecondaryNav(this.element.select("#secondary")[0], this) :
		null;

	this.init();
}

ProductNav.prototype = {
	init : function(){

		var prNav = this;

		var pNavItems = Array();
		this.element.select("li.navItem").each(function(nav){
			pNavItems[pNavItems.length] = new NavItem(nav, false, prNav);
		});
		this.primaryNavItems = pNavItems;

		var sNavItems = Array();
		this.element.select("li.secNavItem").each(function(nav){
			sNavItems[sNavItems.length] = new NavItem(nav, true, prNav);
		});
		this.secondaryNavItems = sNavItems;
	},

	isSecondaryMenuVisible : function(){
		return this.getSelectedItem().revealsSecondary();
	},

	showHideSecondary : function(show){
		var ref = this;
		if(this.secondaryNav){
			this.primaryNavItems.each(function(item){
				var el = item.element;
				if( show ){
					if( !( el.hasClassName("revealsSecondary") ) ){
						el.removeClassName("revealed");
					}
					else{
						el.addClassName("revealed");
					}
				}
			});
			( show ? this.element.addClassName("showSecondary") : this.element.removeClassName("showSecondary")  );
			( show ? $("secondary").show() : $("secondary").hide() );
		}
	},

	onSelect : function(contentType){
		this.productPage.displayContent(contentType);
		this.productPage.webTrendsTags(contentType);
		this.resetState();
	},

	selectedItem : function(){

		for(var i = 0; i < this.primaryNavItems.length; i++){
			var p = this.primaryNavItems[i].getContentType();
			if(this.productPage.initialState == p){
				return this.primaryNavItems[i];
			}
		}

		for(var i = 0; i < this.secondaryNavItems.length; i++){
			var s =  this.secondaryNavItems[i].getContentType();
			if(this.productPage.initialState == s){
				return this.secondaryNavItems[i];
			}
		}

	},

	resetState : function(){

		var s = this.selectedItem();
		this.primaryNavItems.each(function(item){
			var el = item.element;
			el.removeClassName("revealed");
			if(s.isSecondary && el.hasClassName("revealsSecondary")){
				el.addClassName("selected");
			} else {
				el.removeClassName("selected");
			}
			item.element.setStyle({"border-bottom-color": ""});
		});

		this.secondaryNavItems.each(function(item){
			item.element.removeClassName("selected");
		});
		s.element.addClassName("selected");
		if(s.revealsSecondary() && !s.isSecondary){
			this.element.select("li.secNavItem.default").each(function(secondary){
				secondary.addClassName("selected");
			});
		}

		this.showHideSecondary(s.isSecondary || s.revealsSecondary());
	}
}

ProductNav.prototype.afterDisplayHandlers = {
	subscribe : function(){
		if($("staticSubscription")) $("staticSubscription").hide();
	}
}

/*
 * encapsulates a single tab and link
 */
NavItem = function(element, isSecondary, productNav){
	this.element = element;
	this.anchor = this.element.select("a")[0];
	this.productNav = productNav;

	this.isSecondary = isSecondary;

	this.init();
}

NavItem.prototype = {
	init: function(){
		var me = this;
		if(!this.isSecondary && this.element.hasClassName("revealsSecondary")){
			this.element.addClassName("reveal");
		}
		/* 
		 * if the link has class:ext, do not add an onclick.
		 * It is set to open in a new tab...
		 */
		if(!this.anchor.hasClassName("ext")){
			Event.observe(
				this.anchor, "click",
				function(event){ me.clik( event, me ); }
			);
		}
		if(this.anchor.hasClassName("popup")){
			Event.observe(this.anchor, 'click', function( event ){ 
				openPopup(me.anchor.href);
				Event.stop( event );
			});
		};
		Event.observe(
			this.element, "mouseout",
			function(event){ me.mouseout( event, me ); }
		);
		Event.observe(
			this.element, "mouseover",
			function(event){ me.mouseover( event, me ); }
		);
	},

	clik : function(event, me){
		Event.stop(event);
		YAHOO.util.History.navigate("tabview", me.getContentType());
	},

	mouseout : function(event, me){
		Event.stop(event);
		me.productNav.resetState();
	},

	mouseover : function(event, me){
		if(!me.isSecondary){
			if(me.revealsSecondary()){
				me.productNav.showHideSecondary(true);
			}
		}
	},

	getContentType : function(){
		var result = "";
		this.element.className.split(" ").each(function(entry){
			if(entry.indexOf("ct_p:") >= 0){
				result = entry.split(":")[1];
			}
		});
		return result;
	},

	revealsSecondary : function(){
		return this.isSecondary
			|| this.element.hasClassName("revealsSecondary");
	}
}

/*
 * the secondary nav container
 */
SecondaryNav = function(element, productNav){
	this.element = element;
	this.productNav = productNav;
	this.init();
}

SecondaryNav.prototype = {
	init : function(){
		var me = this;
		Event.observe(
			this.element, "mouseover",
			function(event){ me.mouseover(event, me) }
		);
		Event.observe(
			this.element, "mouseout",
			function(event){ me.mouseout(event, me) }
		);
	},

	mouseover : function(event, me){
		this.productNav.showHideSecondary(true);
	},

	mouseout : function(event, me){
		this.productNav.resetState();
	}
}

/*
 * encapsulates google books functionality 
 *
 */
GoogleBooksView = function(isbn){
	this.isbn = isbn;
	this.init();
}

GoogleBooksView.prototype = {
	init : function(){		
		var s = document.createElement("script");
		s.setAttribute("id", "jsonScript");
		s.setAttribute("src",
			"http://books.google.com/books?bibkeys=" 
			+ escape(this.isbn) + 
			"&jscmd=viewapi&callback=googlePreviewCallback");
		s.setAttribute("type", "text/javascript");
		document.body.appendChild(s);
	},

	render : function(container){
		container.update(new Element('div',
		{	'id' : "_googleContent",
			'class' : "googlePreview",
			'style' : "width: 609px; height: 700px;"
		}).insert(' '));		
		google.setOnLoadCallback(this.previewCallback(this.isbn));		
	},

	previewCallback : function(isbn){
		var viewer = new google.books.DefaultViewer(document.getElementById("_googleContent"));
		viewer.load("ISBN:" + isbn);
		$('_googleContent').show();
	}
}

function googlePreviewCallback(booksInfo){
	for (i in booksInfo){
		if(booksInfo[i].preview != "noview"){
			$('_google').show();
			return;
		}
	}
	$('_google').hide();
}

/*
 * scripts
 *
 */

function copyWebtrendsImage(replaceStr){
	if(gImages){
		var lastImage = gImages[gImages.length - 1];
		var src = lastImage.src;
		var startIndex = src.indexOf("&WT.cg_s");
		var endIndex = src.indexOf("&WT.cg_n");
		var stringToReplace = src.substring(startIndex,endIndex);
		replaceStr = "&WT.cg_s="+replaceStr;
		var newSrc = src.replace(stringToReplace, replaceStr);
		var newImg = new Image;
		newImg.src = newSrc;
		gImages[gImages.length] = newImg;
	}
}

function initCustomerReviews(){
	$$(".reportReview").each(function(item){
		Event.observe(item, "click", function(event){
			displayReportReview(item);
		});
	});
	Event.observe("reportReviewClose", "click", function(event){
		$('reportReview').addClassName("hidden");
	});
	Event.observe("reportReviewCancel", "click", function(event){
		$('reportReview').addClassName("hidden");
	});
	Event.observe("bttnReportReview", "click", function(event){
		setReportReview($('bttnReportReview').value);
	});
}

function setReportReview(reviewId){
	var url = "/setReportReview.data?reviewId=" + reviewId ;
	new Ajax.Request(url, {
		method :'post',
		onSuccess: function(transport) {
			$('reportReview').addClassName("hidden");
		}
	});
}

function displayReportReview(obj){
	$(obj).absolutize();
	x= $(obj).getStyle("top").substring(0, $(obj).getStyle("top").indexOf('px'));
	$('reportReview').setStyle({top: (x -102) + 'px',left:'339px'})
	$('bttnReportReview').value=$(obj).id;
	$('reportReview').removeClassName("hidden");
}


function setVisible(obj)
{
	obj = document.getElementById(obj);
	obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible';	
}
function openPopup(url){
	window.open(url,'Child','scrollbars=yes,height=500,width=1020,top='+document.body.clientHeight/2+',left='+document.body.clientHeight/2);
}

document.observe("dom:loaded", function(){
	if($("jsearchbox")){
		new JournalSearch($("jsearchbox"));
	}

});

Event.observe(window, 'load', function() {
	var pn = $("prdnav");
	if(pn){
		new ProductPage( 
			$("product"),
			pn.readAttribute( "data-prd-type" ),
			pn.readAttribute( "data-prd-id" ),
			pn.readAttribute( "data-isbn" ),
			pn.readAttribute( "data-initial-state" ));
	}
});
