var TCApplication = {wsrurl:"/WebObjects/textunes.woa/1/wsr",wosid:"wosid=Hpj271WPdvfeVJgbUPqYMM",l:function(k){if (TCApplication.loc && TCApplication.loc[k]) return TCApplication.loc[k]; else return '/'+k+'/';}};
function $tc_wosid() { if (TCApplication.wosid) {return "?"+TCApplication.wosid;} else {return "";} }
/** Start:app **/
(function(){
	// TT namespace in window
	this.tt = (this.tt || {});
	tt.website = (tt.website || {});
	
	function TTInputFieldClass(pConfig) {
		var TTInput = this;

		function initialize() {
			TTInput.formId = pConfig.formId;
			TTInput.queryFieldName = pConfig.queryFieldName;
			TTInput.initValue = pConfig.initValue;
		
			Event.observe(document, "dom:loaded", TTInput.init.bindAsEventListener(TTInput));
			
			return TTInput;
		}
		
		return initialize();	
	}	
	
	TTInputFieldClass.prototype = {
		formId: null,
		form: null,
		
		queryFieldName: null,
		query: null,
		
		initValue: null,
		
		init: function() {
			this.form = $(this.formId);
			this.query = $(this.form[this.queryFieldName]);
			
			if (this.query.value.strip()==="") {
				this.query.value = this.initValue;
			}

			Event.observe(this.form, "submit", this.submit.bindAsEventListener(this));
			Event.observe(this.query, "focus", this.focus.bindAsEventListener(this));
			Event.observe(this.query, "blur", this.blur.bindAsEventListener(this));
		},
		
		focus: function() {
			if (this.query.value === this.initValue) {
			 	this.query.value = "";
			 }
		},
		
		blur: function() {
			if (this.query.value.strip() === "") {
				this.query.value = this.initValue;
			}
		},
		
		submit: function(e) {
			if (this.query.value === this.initValue || this.query.value.strip() === "") {
				this.query.value = "";
			}
		}
	};
	
	tt.website.TTInputField = function(pConfig){
		return new TTInputFieldClass(pConfig);
	};
	
	/**
	 * Methods for showing, hiding and interaction with a
	 * contextual bubble style overlay.
	 */

	tt.utils = tt.utils || {};
	
	tt.bubbleOverlay = function( options ) {
		var 
		
		o = {
			bubbleId: '',
			content: '',
			position: 'bottom'
		},
		
		bubbleWidth = 320,
		
		_wrapper,
		_close,
		_content,
		
		init = function() {
			if ( options ) Object.extend(o, options);
			
			// Common Elements
			_wrapper = $( o.bubbleId );
			_close = _wrapper.down('.boClose');
			_content = _wrapper.down('.boContent');
			
			// We open the overlay above the triggering Element
			if ( o.position === 'top' ) {
				_wrapper.addClassName('boWrapperTop');
			}
			
			// Remove the links to the app if this is not the right plattform
			if ( !(tt.os.ios || tt.os.android) ) {
				_content.down('.appOnly').remove();
			}
			
			// Close button handling
			//tt.utils.fastClick( _close, close );
			_close.observe( 'click', function( event ) {
				event.stop();
				close();
			});
			
			// close overlay when buttons are clicked
			addOverlayHandler( 'click', '.button', close);
		},
		
		addOverlayHandler = function( eventType, elements, callback ) {
			_content.observe( eventType, function( event ) {
				var el = event.findElement( elements );
				if ( el && Object.isFunction( callback ) ) {
					callback.call( el, event );
				}
			});
		},
		
		positionOverlay = function( openingElement ) {
			var contextOffset = openingElement.cumulativeOffset().toArray(),
				left = (tt.os.ios || tt.os.android) ? 0 : contextOffset[0] + openingElement.getWidth()/2 - bubbleWidth/2,
				top = contextOffset[1];
				
			if ( o.position === 'bottom' ) {
				top += openingElement.getHeight();
			} else if ( o.position === 'top' ) {
				top -= _wrapper.getHeight();
			}
			
			_wrapper.setStyle({ left: left+'px', top: top+'px' });
		},
		
		open = function( contextElement ) {
			if ( contextElement ) positionOverlay( contextElement );
			_wrapper.addClassName('open');
			
			if ( tt.os.ios || tt.os.android ) {
				Effect.ScrollTo(o.bubbleId, { duration:'0.8', offset:-20 });
			}
		},
		
		close = function() {
			_wrapper.removeClassName('open');
			_wrapper.setStyle({ left: '-999em' });
		},
		
		destroy = function() {
			_wrapper.remove();
		},
		
		/**
		 * Public API
		 */
		methods = {
			open: open,
			close: close,
			destroy: destroy
		}
		;
		
		// Let's get crackin
		init();
		
		return methods;	
	};
	
	/**
	 * Append touch or click handler to element depending on the device.
	 * @param {Prototype Element} element: The element to attach the click handler to
	 * @param {Function} callback: The click handler function
	 */
	tt.utils.fastClick = function( element, callback  ) {
		if ( tt.os.touch ) {
			element
			.observe('touchend', function( event ) {
				if ( Object.isFunction( callback ) ) {
					callback.call( element, event );
				}
			})
			.observe('click', function( event ) { event.stop(); });
		} else {
			element.observe('click', function( event ) {
				event.stop();
				if ( Object.isFunction( callback ) ) {
					callback.call( element, event );
				}
			});
		}
	};
	
	/**
	 * Detecting the User Agent
	 */
	
	(function($){
		function detect( ua ) {
	        var os = {},
	            android = ua.match(/(Android)\s+([\d.]+)/),
	            iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/),
	            ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
				isTouchDevice = ('ontouchstart' in window);
	
	        if ( android ) {
	            os.android = true;
	            os.version = android[2];
	        }
	
	        if ( iphone ) {
	            os.ios = true;
	            os.version = iphone[2].replace(/_/g, '.');
	            os.iphone = true;
	        }
	
	        if ( ipad ) {
	            os.ios = true;
	            os.version = ipad[2].replace(/_/g, '.');
	            os.ipad = true;
	        }
	
			if ( isTouchDevice ) {
				os.touch = true;
			}
	
	        return os;
	    }
	
		$.os = detect(navigator.userAgent);
	})( tt );
	
	// The DOM is ready so here we go
	document.observe("dom:loaded", function() {
		
		var sampleButton = $('getsample'),
			buyButton = $('buybook'),
			sampleBubble, buyBubble;
			
		if ( sampleButton ) {
			sampleBubble = tt.bubbleOverlay({ bubbleId: 'sampleBubble' });
			tt.utils.fastClick( sampleButton, function( event ) {
				sampleBubble.open( this );
			});
		}
		
		if ( buyButton && buyButton.hasClassName('openBubble') ) {
			buyBubble = tt.bubbleOverlay({ bubbleId: 'buyBubble', position: 'top' });
			tt.utils.fastClick( buyButton, function( event ) {
				buyBubble.open( this );
			});
		}
	});
})();
/** End:app **/
/** Start:TTBookBrowser **/
function TTBookBrowser(elementId, batchcount, genres, publisher) {
	this.elementId = elementId;
	this.boxwidth = $(elementId).getWidth();
	this.batchcount = batchcount;
	this.allGenres = genres;
	this.genres = genres;
	this.publisher = publisher;
	this.batch = 0;
	this.backlink = $$("#"+elementId+"B a.backlink")[0];
	this.forelink = $$("#"+elementId+"B a.forelink")[0];
	this.batcher = $(elementId+"B");
	$(elementId+'_1').hide();
	this.allowToggle = true;
	this.currentBox = 0;
	this.backlink.observe("click", this.clickBack.bindAsEventListener(this));
	this.forelink.observe("click", this.clickNext.bindAsEventListener(this));
	var catselectlinks = $$("#"+elementId+"G a");
	catselectlinks.each(function(l) {
		l.observe("click", this.selectGenre.bindAsEventListener(this));
	}.bind(this));
}

TTBookBrowser.prototype = {

	clickBack: function(event) {
		if (this.allowToggle) {
			this.allowToggle = false;
			if (this.batch>0) { 
				this.batch = this.batch-1;
			}
			else {
				this.batch = this.batchcount-1;
			}
			this.direction = 1;
			this.reloadContent(); 
		}
		Event.stop(event);
	},

	clickNext: function(event) {
		if (this.allowToggle) {
			this.allowToggle = false;
			if (this.batch<this.batchcount-1) { 
				this.batch = this.batch+1;
			}
			else {
				this.batch = 0;
			}
			this.direction = -1;
			this.reloadContent();
		}
		Event.stop(event);
	},
	
	selectGenre: function(event) {
		$$("#"+this.elementId+"G a").each(function(l){l.removeClassName("selected");});
		var l = event.element();
		l.addClassName("selected");
		var genre = l.readAttribute("rel");
		if (genre=="ALL") {
			this.genres = this.allGenres;
		}
		else {
			this.genres = "(\""+genre+"\")";
		}
		this.batch = 0;
		this.direction = 1;
		this.reloadContent();
		Event.stop(event);
	},
	
	reloadContent: function() {
		this.batcher.setStyle({ backgroundImage: "url("+TCApplication.wsrurl+"/app/loadbooks.gif)"});
		new Ajax.Updater(this.elementId+'_'+((this.currentBox+1)%2), TTBookBrowser.contentURL,{
			parameters: { batch: this.batch, genres: this.genres, count: 9, publisher: this.publisher},
			onComplete: function(transport) {
				this.moveBoxes();
				if ("true"==transport.getHeader("x-tc-showbatcher")) {
					this.batcher.style.visibility = "visible";
				}
				else {
					this.batcher.style.visibility = "hidden";
				}
			}.bindAsEventListener(this)
		});
	},
	
	moveBoxes: function() {
		var box_out = $(this.elementId+'_'+this.currentBox);
		new Effect.Move(box_out, { x: this.direction*this.boxwidth, y: 0, mode: 'relative', duration:0.5, afterFinish: function() { box_out.hide(); } });
		this.currentBox = (this.currentBox+1)%2;
		var box_in = $(this.elementId+'_'+this.currentBox);
		box_in.style.left = (-this.direction*this.boxwidth)+"px";
		box_in.show();
		new Effect.Move(box_in, { x: 0, y: 0, mode: 'absolute', duration:0.5, afterFinish: function() { this.allowToggle = true; this.batcher.setStyle({ backgroundImage: "none"}); }.bind(this) });
	}

};
/** End:TTBookBrowser **/
if (!TTBookBrowser) TTBookBrowser={};
TTBookBrowser.contentURL="/WebObjects/textunes.woa/1/ajax/TTBookBrowser"+$tc_wosid();
TTBookBrowser.dataURL="/WebObjects/textunes.woa/1/ajax/TTBookBrowser/data"+$tc_wosid();


