
var pg = null;
var radio_class = null;



var RadioClass = new Class({
	 Implements: [Options],
		
		options: {
	
			useElements: 'div[class="score-drink"] input[type="radio"], div[class="score-pub"] input[type="radio"]'
			// , div[id="recommend-pub"] input[type="radio"]
		},
		
		radioElements: null,
		
		initialize: function (options) {
			this.setOptions(options);
			this.loadElements();		
		},
		
		loadElements: function () {
			
			this.radioElements = $$(this.options.useElements);
		},
		
		freeElements: function () {
			
			this.radioElements.each(function (t) {
				
				t.setStyles({
					'position': 'static',
					'left': '0px'
				});
				
				var p = t.getParent();
				if (p !== null) { // i.e. element has been removed via removeDrink();
					p.removeClass('unselected').removeClass('selected').removeEvents('click');
				}

			});
			
		},
		
		processElements: function () {
			
			
			this.radioElements.each(function (t) {
				
				t.setStyles({
							'position': 'absolute',
							'left': '-9999px'
				});
				
				var p = t.getParent();
				
				if (t.get('checked') === false) {
					p.addClass('unselected');
				} else {
					p.addClass('selected');
				}
				
				p.addEvent('click', function () {
					
					
					if (t.id.indexOf('drink_id') === -1) {
						
						
						/* unset any radio buttons in the same group (i.e. name) */
						$$('input[name="' + t.name + '"]').getParent().removeClass('selected').addClass('unselected');
						
					
						if (t.get('checked') === false) {
							t.set('checked', true);
							p.removeClass('unselected').addClass('selected');
						} else {
							t.set('checked', false);
							p.removeClass('selected').addClass('unselected');
						}
					} else {
						if ($('pubs-other') && $('pubs-other').get('value') !== 'Other - please enter here') {
							
							alert("Just enter your drink name then click the 'Score this drink' button to choose your drink, or choose a drink from the menu.");
							
						} else {
							
							alert('Sorry, you need to choose a drink before you can score it.');
							
						}
					}
				
				});
			
				
			
			});
			
		}	
			
});

var ScoreYourDrinkClass = new Class({
	 Implements: [Options],
		
		options: {
			
		},
		
		sTable: null,
		opt: null,
		drink_id: 0,
		drink_name: '',
		drink_form_holder: 'score-your-drink-form-holder',
		selectedDrinks: [],
	  
		
		
		initialize: function (options) {
			
			this.sTable = $('drink_holder_drink_id').get('html');
			
			this.addAnotherDrink();
			
			this.setupTable();
			
		},
		
		setupTable: function () {
			
			var t = this;
			
			var opt = $('pubs-drink_id'); // the select menus
			
			if ($(opt)) {
				opt.addEvent('change', function (e) {
					
					if (opt.get('value') != '99999') {
					
							t.loadDrink(opt);
						
					}
				
				});
			}
			
			if ($('add-drink')) {
				
				
				
				$('add-drink').addEvent('click', function (e) {
					
					if ($('pubs-other') && $('pubs-other').get('value').clean() === '') {
						
						alert('Sorry, you need to enter a drink name or choose a drink from the menu');
						
					} else {
						if ($('add-drink')) {
							$('add-drink').setStyle('display', 'none');
							t.loadDrink(opt);
						}
						
					}
					
				});
			}
			
			if ($('pubs-other')) {
				
				
				
				
				$('pubs-other').addEvent('focus', function (elem) {
					
					
					if (this.get('value') === 'Other - please enter here') {
						this.set('value', '');
					}
					
					$('add-drink').setStyle('display', 'inline');
					
					var j = opt.options.length;
					
					if (opt.options[opt.selectedIndex].value != '99999') {
					
						for (i = 0; i < j; i++) {
							
							if (opt.options[i].value == '99999') {
								opt.options[i].selected = true;
							}
						
						}
					}
					
					
			
				});
			}
			
		},
		
		loadDrink: function (opt) {
			
			
			
			var drink_id = opt.get('value');
			
			
			if (drink_id == 99999) {
				
				var drink_name = $('pubs-other').get('value');
				
				
				
			} else {
			
				var drink_name = opt.getSelected().get('text');
				
			}
			
			/*
			 * Note XOR operator ^
			 */
			if ((drink_id != 0 && drink_id != 99999) ^ (drink_id == 99999 && $('pubs-other').value != '')) {
				
				
			
				
				
				
				this.buildDrink(drink_id);
				
			
				
				if (opt.getSelected().get('value') == '99999') {
					
					$('other-holder').setStyle('display', 'none');
					
				}
				
				this.selectedDrinks.push(drink_id); // add the selected drink to the array of selected drinks
				
				$('pubs-DrinkName_' + drink_id).set('value', drink_name);

				$('name_placeholder_' + drink_id).set('text', drink_name); // set the name
				
				if ($('pubs-other')) {
					$('pubs-other').value = 'Other - please enter here';
				}
				
				opt = null;
				if ($('score-drink-select-row')) {
					$('score-drink-select-row').dispose();
				}
				
				$('score-drink-table-change-' + drink_id).setStyle('display', 'block');
				$('drink_score_another_drink').setStyle('display', 'block');
				
				
				resetFancyForm();
				
				// now restset the choose text
				
			
				
				
				
				
			}
			
		},
		
		buildDrink: function (drink_id) {
			
			var str = $('drink_holder_drink_id');
			
			if (str !== null) { // total hack because of some wierd loop error that occurs on the first loop through i.e. first drink
			
				
				var new_str = str.get('html').replace(/drink_id/g, drink_id);
					
				
				str.set('html', new_str);
				str.setProperty('id', 'drink_holder_' + drink_id); // reset the id of the entire table
			}
			
		},
		
		addAnotherDrink: function () {
			if ($('drink_score_another_drink')) {
			
				$('drink_score_another_drink').addEvent('click', function () {
					
					elem = $(this.id);
					
					elem.setStyle('display', 'none');
					
					var holder = new Element('div', { 'class': 'score-drink', 'id': 'drink_holder_drink_id' });
					holder.set('html', pg.sd.sTable);
					holder.inject(elem, 'before');


					var opt = $('pubs-drink_id').options;
					
					var l = opt.length;
					
					
					
					
					for(i = 0; i < pg.sd.selectedDrinks.length; i++) {
						
						
						
					
						
						for(j = 0; j < l; j++) {
							
														
							if (pg.sd.selectedDrinks[i] == opt[j].value) {
								
								if (opt[j].value == 99999) {
									$('other-holder').setStyle('display', 'none');
								}
								
								$('pubs-drink_id').remove(j);
								l--; // the length needs to get shorter as we remove drinks
								
							}
							
						};
						
						
						
					}
				
					pg.sd.setupTable();

					resetFancyForm();
					
					

				});
			}
		}
		
		
	
});

var TabManagerClass = new Class({
	Implements: [Options],

	options: {
		tabElementHolder: 'pub-tab-list',
		tabElement: 'div#pub-tab-list ul li a',
		tabSectionClass: 'div.pub-tab',
		tabSectionHeaders: 'h2.pub-tab-header',
		firstTab: null,
		loadForms: true,
		isAjax: true
	},

	list: null,
	//sections is new
	currentSection: null,
	selectedTab: null,
	selectedTabId: null,
	tabList: null,
	sd: null,
	

	initialize: function (options) {
		
	/* 
	* variable tab int id of pub-tab set inline in html on initial page load
	*/

		this.setOptions(options);
	
		/* generate the tabs and add the event handlers */
		this.buildTabList();

		/*new grab the sections, they will be needed to match up with the tabList */
		this.sections = $$(this.options.tabSectionClass);
		
		/* call this on initial page load i.e. not via ajax 
		* 
		* populate the selectedTab & selectedTabId variables
		*/

		if (typeof (tab) !== 'undefined' && tab !== null) {

			if ($(tab) !== null)	{

				this.setSelectedTab($(tab));

			}
		}
		
		//set the firstTab
		if(this.options.firstTab){
			this.setSelectedTab($(this.options.firstTab))
		}

		if(this.options.loadForms == true){
			this.loadForms();
		} else {
			// do nothing but we coud put in the Medaibox scan page in the future
		}

	},

	/*
	* based on the id of the selected tab, load the correct chunks of sub code neceassry for the other various forms
	*/
	loadForms: function () {
		
		

		switch (this.selectedTabId) {

		case 'pub-tab-scorethislocal':

			radio_class = new RadioClass();

			syl_form();
			
			//if (this.sd === null) {

				this.sd = new ScoreYourDrinkClass();
				this.sd.setupTable();

			//}

			break;
		case 'pub-tab-reviews':

			reviews();

			break;
			
		default:
			// do nothing
			break;

		}

		Mediabox.scanPage();

	},

	setOptions: function (options) {
		for(i in options) {
			this.options[i] = options[i];
		}
	},
	
	
	setSelectedTab : function (el) {
		
		if(this.currentSection){
			this.currentSection.removeClass('current')
		}
		
		this.selectedTab.removeClass('current');
		
		this.selectedTab = el;
		
		this.selectedTabId = $(this.selectedTab).id;
		
		//grab the relevant section and add a current to it
		var idSplit = this.selectedTabId.split('-');
		
		var sectionClass = idSplit[idSplit.length - 1];
		
		//set the current section if the first tab was set, should prevent clash with old functionality
		if(this.options.firstTab){
			this.currentSection = $$(this.options.tabSectionClass+'.'+sectionClass)[0]
			this.currentSection.addClass('current');
			
			//make all other tabs display none
			$$('.pub-tab').each(function(el){
				if(el.hasClass('current')){
					el.setStyle('display', 'block');
				}else{
					el.setStyle('display', 'none');
				}
			})
		}
		
		el.addClass('current');
		if (el.getParent().hasClass('right-tab')) {
			el.getParent().getParent().getParent().removeClass('blue-border').addClass('red-border');
		}
		
	},
	
	showTab : function(tab){
		
		var tab = $(tab);
		
		if(tab != null){
			
			this.setSelectedTab(tab);
			
			this.toggleSections();
			
		}
		
		
		
		
	},
	
	buildTabList : function () {
		
		var t = this;
		
		
		
		this.tabList = $$(this.options.tabElement);
		
		this.tabList.each(function (el) {
			
			el.addEvent('click', function (e) {
				e.preventDefault();
				t.setSelectedTab(this);
				t.toggleSections();
			});	
			
			if (el.hasClass('current')) {
				t.selectedTab = el;
			}
						
		});
		
	},
	
	/*
	 * Update the contents of a new tab into the page via an ajax request for pagination
	 * @todo possible to refactor with toggleSections()?
	 */
	loadTabPage : function () {
		
		
		var t = this;
		$$('#pub-tab-holder p.paginate-tabs a').each(function (el) {
			el.addEvent('click',function () {
				//get content via ajax
				var req = new Request({
					method: 'get',
					url: el.getProperty('href')+'/type-js/',
					onRequest: function () {
						showLoading();
					},
					onComplete: function (response) {
						hideLoading();
						$('pub-tab-holder').innerHTML = response+'<div class="spacer"></div>';  
						reviews();
						t.loadTabPage();
						Mediabox.scanPage();
					}
				}).send();
				return false;
			});
		});
	},
	
	/*
	 * Load the contents of a new tab into the page via an ajax request
	 */
	toggleSections : function () {
		
		if(this.options.isAjax == true){
			var t = this;
			
		
			//get content via ajax
			var req = new Request({
				
				method: 'get',
				url: t.selectedTab.getProperty('href')+'/type-js/',
				evalScripts: true,
				onRequest: function () {
					showLoading();
				},
				onComplete: function (response) {
					
					hideLoading();
					
					$('pub-tab-holder').innerHTML = response+'<div class="spacer"></div>';
					//only show "add picture" tools on click, tidy things up a bit
					if($('showPic') && $('scoreMinusTenReplace')){
						var slider = new Fx.Slide($('scoreMinusTenReplace')).hide()
						$('showPic').addEvent('click', function(e){
							new Event(e).stop()
							slider.toggle();
						})
					}
					
					
					t.loadForms();
					//t.loadTabPage();
				
					//t.loadTabPage(); // ? do we need this ? is this just making another unecessary ajax call ? possibly just reviews ?
					
					}
			}).send();
		} else {
			//grab the sections and only make current visible
			if(this.options.firsTab){
				$$('.pub-tab').each(function(el){
					if(el.hasClass('current')){
						el.setStyle('display', 'block');
					}else{
						el.setStyle('display', 'none');
					}
				})
			}
		}
		

	}

});

function resetFancyForm() {
	
	radio_class.freeElements();
	radio_class.loadElements();
	radio_class.processElements();
	
}



function syl_form() 
{
	
		if ($('scoreyourlocal-header'))
		{
			
		
			//preload text
			var summary = $('pubs-summary');
			var comment = $('pubs-comments');
			summary.default_value = 'Please write a short, snappy headline about this pub or your drink';
			comment.default_value = 'Please add comments here';
			if (summary.value.length == 0) {
				summary.value = summary.default_value;
			}
			if (comment.value.length == 0) {
				comment.value = comment.default_value;
			}
			summary.addEvent('focus',function () {
												if (summary.value === summary.default_value) {
													summary.value = '';
												}
			});
			comment.addEvent('focus',function () {
												if (comment.value === comment.default_value) {
													comment.value = '';
												}
			});
			
					
			
			resetFancyForm();
			
			function tgtp(e) {
					if (getTarget(e).checked)
					{
						$('score-your-pub-form-holder').setStyle('display', 'block');
						$('pubs-score_pub').checked = true;
						//$('pubs-score_pub2').checked = true;
					}
					else
					{
						$('score-your-pub-form-holder').setStyle('display', 'none');
						$('pubs-score_pub').checked = false;
						//$('pubs-score_pub2').checked = false;							
					}
	 			
			}
			function tgtd(e) {
				if (getTarget(e).checked)
				{
					$('score-your-drink-form-holder').setStyle('display', 'block');
					$('score-drink-fm').setStyle('display','block');
					$('pubs-score_drink').checked = true;
					//$('pubs-score_drink2').checked = true;
				}
				else
				{
					$('score-your-drink-form-holder').setStyle('display', 'none');
					$('score-drink-fm').setStyle('display','none');
					$('pubs-score_drink').checked = false;
					//$('pubs-score_drink2').checked = false;
				}
	
			}
	
			$$('#pubs-score_pub, #pubs-score_pub2').addEvent('click', function (e) {
				tgtp(e);
			});
			$$('#pubs-score_drink, #pubs-score_drink2').addEvent('click', function (e) {
				tgtd(e);
			});
		}
}

function reviews()
{
	
	
	
	
	if ($('reviews-header'))
	{
		
		//add expander links for pub summary
		var links = $$('table td.rateheadtop span');
		
		var link = $$('#individual-reviews span');
		
		if(links[0] === undefined && link === undefined){
			
		} else {
		
		//check if the review is open or closed	
		if(links[0] !== undefined){
			if(links[0].innerHTML == 'See more +' || $$('span.review-full').innerHTML == 'See this review in full +'){
				var open = 0; 
			}else{
				var open = 1;
			}
		}
		
		//we have 2 sections that will be either open or closed - span.split-copy and any sub-rows
		
		//check if the sections exist and if they are meant to be open or closed
		if(!open){
			//add expander links for pub summary
			if($$('table tr.hide')){
				$$('table tr.hide').setStyle('display','none');
			}
			
			//add expander link for individual reviews
			$$('table.score-this-pub tr.sub-row, table.score-this-drink tr.sub-row, div.review-body span.split-copy').setStyle('display','none');
			$$('div.review-body span.split-copy-dots').set('text','[...]').setStyle('display','inline');
		}
		
		//split out the links and expander_link code
		if(links[0]){
			links.addEvent('click',function () {
				if (links[0].innerHTML == 'See less -')
				{
					//hide
					links.each(function (el) {el.innerHTML = 'See more +';});
	
					$$('table tr.hide').setStyle('display','none');				
				}
				else
				{
					//show
					links.each(function (el) {el.innerHTML = 'See less -';});
					$$('table tr.hide').setStyle('display','table-row');
				}
			});	
		}
			//add expander link for individual reviews
			var link = $$('#individual-reviews span');
			
			
			
			//add expander link for individual reviews
			link.addEvent('click',function () {
				if (link[0].innerHTML == 'Hide full reviews -')
				{
					//hide
					link[0].innerHTML = 'See all reviews in full +';
					$$('table.score-this-pub tr.sub-row, table.score-this-drink tr.sub-row, div.review-body span.split-copy').setStyle('display','none');
					$$('div.review-body span.split-copy-dots').set('text','[...]').setStyle('display','inline');
					$$('span.review-full').setStyle('display','inline');
					$$('span.review-full').set('text','See this review in full +');
				}
				else
				{
					//show
					link[0].innerHTML = 'Hide full reviews -';
					$$('div.review-body span.split-copy-dots').set('text','').setStyle('display','none');
					$$('table.score-this-pub tr.sub-row, table.score-this-drink tr.sub-row').setStyle('display','table-row');
					$$('div.review-body span.split-copy').setStyle('display','inline');
					//$$('span.review-full').setStyle('display','none');
					$$('span.review-full').set('text','Hide full review -');
				}
			});
			
		//	}
			
			//add expander link for each review
			var linksi = $$('span.review-full');
			linksi.each(function (el) {
				el.addEvent('click',function (e) {
					var l = getTarget(e);
					var container = l.getParent().getParent();
					if (l.innerHTML == 'See this review in full +' || l.innerHTML == 'See this review in full')
					{
						//show
						l.innerHTML = 'Hide full review -';
						$(container).getElements('span.split-copy-dots').set('text','').setStyle('display','none');
						$(container).getElements('table.score-this-pub tr.sub-row, table.score-this-drink tr.sub-row').setStyle('display','table-row');
						$(container).getElements('span.split-copy').setStyle('display','inline');
					}
					else
					{
						//hide
						l.innerHTML = 'See this review in full +';
						$(container).getElements('table.score-this-pub tr.sub-row, table.score-this-drink tr.sub-row, div.review-body span.split-copy').setStyle('display','none');
						$(container).getElements('span.split-copy-dots').set('text','[...]').setStyle('display','inline');
						$(container).getElements('span.split-copy').setStyle('display','none');
					}
				});
			});
		}
		
	}
	
	//add sort drop down handler
	if ($('sort'))
	{
		var sort = $('sort');
		sort.addEvent('change',function (el) {		
			//get content via ajax
			var req = new Request({
				method: 'get',
				url: $('sort-form').getProperty('action')+'/type-js/sort-'+sort.value+'/',
				onRequest: function () {
					showLoading();
				},
				onComplete: function (response) {
					hideLoading();
					$('pub-tab-holder').innerHTML = response+'<div class="spacer"></div>';
					reviews();
					pg.loadTabPage();
					}
			}).send();
			
		});
	}
}





function removeDrink(obj) {
	
	$(obj).getParent().getParent().getParent().getParent().getParent().getParent().destroy();
	
	$('drink_score_another_drink').setStyle('display', 'block');
	
	//resetFancyForm();
	
	return false;
	
	
	
}

window.addEvent('domready', function () {
	if ($('pub-tab-aboutus')) {
		pg = new TabManagerClass({
			targetElement: ''
		});
		
		
	}
});



		

