//Hook up the ui
$(function () {
	
	P.module('reserveButton', function () {
		$reserve = $('#reserve');
		return {
			init: function () {
				/*
				$reserve.click(function () {
					console.log('submit');
					$('#ripple_form').unbind('submit').submit();
				});
				*/
			}()
		};
	});
	
	/*P.module('segments', function () {
		var $cloud = $('#create_section #tag_cloud').attr('id', '#tag_cloud_start');
		
		function toggleCollapse () {
			var $this = $(this),
				isCollapsed = $cloud.hasClass('collapsed'),
				tagClicked = false;
			
			function getFullHeight() {
				var $clone = $cloud.clone(true).css({
						height: null,
						width: $cloud.width() + 'px',
						position: 'absolute',
						left: '-9999px'
					}).removeClass('collapsed');
				height = $clone.appendTo($cloud.parent()).height();
				$clone.remove();
				return height;
			}
			
			$cloud.stop().animate({
				height: isCollapsed? getFullHeight() + 'px': '0px'
			}, 400, function () {
				var $slide = $('#start_details .slide').eq(0).css('height', '');
				$('#start_details').css('height', $slide.height() + 10 + 'px');
				fitSlidebox();
				$cloud[isCollapsed? 'removeClass': 'addClass']('collapsed');
			});
			return false;
		}
		
		function collapse () {
			tagClicked = false;
			$cloud.animate({
				height: '0px'
			}, 400, function () {
				$(this).addClass('collapsed');
			});	
			P.hovers.hideTooltip();
			return false;
		}
		
		function expand () {
			if ($cloud.hasClass('collapsed')) {
				toggleCollapse();
			}
			return false;
		}
						
		function clickTag () {
			var selected = [],
				ids = [];
			if ($(this).hasClass('selected')) {
				$(this).removeClass('selected');
			} else {
				if ($cloud.find('a.selected').length < 6) {
					$(this).addClass('selected');
				}
			}
			$cloud.find('a.selected').each(function () {
				selected.push($(this).html());
				ids.push($(this).attr('tagid'));
			})
			$('#ipt_targets').val(selected.sort().join(', '));
			$('#ipt_targets_hidden').val(ids.join('-'));
			
			
			//return false;
		}
		
		return {
			collapse: collapse,
			toggle: toggleCollapse,
			init: function () {
				$cloud.find('a').click(clickTag);
				$('#ipt_targets').focus(expand);
				$('input, textarea').not('#ipt_targets').focus(collapse);
				$.each($('#ipt_targets').val().split(', '), function () {
					if (this.length < 1) return;
					$cloud.find('a:contains("' + this + '")').addClass('selected');
				});
				return true;
			}()
		};
	});*/
	
	
	P.module('logicSelector', function () {
		
		var $el = $('#logic_selector') || $('<div class="hidden offscreen absolute" id="logic_selector"></div>'),
			$toggle = $('#ui_toggle_logic');
		
		function show (e) {
			$(this).addClass('selected').find('.toggle').text('-');
			$el.css({
				opacity: 0,
				left: $(this).offset().left + 'px',
				top: $(this).offset().top + $(this).height() + 'px'
			}).animate({
				opacity: 1
			}, 400);
			return this;
		}
		
		function hide () {
			$toggle.removeClass('selected').find('.toggle').text('+')
			$el.animate({
				opacity: 0
			}, 400, function () {
				$(this).css('left', '-9999px');
			});
			return this;
		}
		
		function toggle (e) {
			return ($toggle.hasClass('selected')? hide: show).call(this, e);
		}
		
		return {
			show: show,
			hide: hide,
			toggle: toggle,
			init: function () {
				$el.css('opacity', 0).appendTo('body').click(function () {
					
				});
				$('#ui_toggle_logic').click(function (e) {
					toggle.call(this, e);
					return false;
				});
				$el.find('.close').click(hide);
				//$('input[name="logic"]').get(0).checked = true;
				//$('body').click(hide);
				return true;
			}()
		};
	});
	
	P.module('companyBlurbs', function () {
		return {
			init: function () {
				$('ol#ripples li').each(function () {
					var desc = $(this).find('.title').attr('title') || '',
						url = $(this).find('.logo a').attr('href') || '';
					$(this).find('.title').removeAttr('title').tooltip(desc.length > 0? desc: 'Test hover (this Ripple doesn\'t have a description).', {
						top: -20
					});
					if (url.length > 0) $(this).find('.logo a').tooltip(url);
				});
				return true;
			}()
		};
	});
	
	/*P.module('softwarePreview', function () {
		
		var views = [];
		
		function addView (specs) {
			views.push(View(specs));
			return this;
		}
		
		function addViews (arr) {
			var a;
			for (a in arr) {
				addView(arr[a]);
			}
		}
		
		function View (specs) {
			
			var $thumb = $(specs.thumb),
				$bio = $(specs.bio),
				timeout = null,
				selected = false;
				
			function show () {
				$bio.stop().css('left', '0px').css('height', $('#team_bio').height() + 'px').animate({
					opacity: 1
				}, 200);
			}
			
			function getName () {
				return $thumb.text();
			}
			
			function delay () {
				timeout = window.setTimeout(unselect, 1000);
			}
			
			function hide () {
				window.clearTimeout(timeout);
				$bio.animate({
					opacity: 0
				}, 200, function () {
					$(this).css('left', '-9999px');
				});
			}
			
			function select () {
				selected = true;
				window.clearTimeout(timeout);
				$.each(views, function (i) {
					if (this.getName() !== getName() && this.isSelected()) {
						this.unselect();
					}
				});
				$thumb.addClass('selected');
				show();
				return this;
			}
			
			function unselect () {
				selected = false;
				hide();
				$thumb.removeClass('selected');
				return this;
			}
			
			return {
				getName: getName,
				select: select,
				unselect: unselect,
				isSelected: function () {
					return selected;
				},
				init: function () {
					$bio.css({
						opacity: 0
					});
					$thumb.hover(select);
					if ($bio.height() > $('#product_details .details').height()) $('#product_details .details').height($bio.height() + 'px');
					return true;
				}()
			};
		}
		
		return {
			init: function () {
				var i,
					$thumbs = $('#product_details  #product_details_nav li'),
					$details = $('#product_details .details li');
				for (i = 0; i < $thumbs.length; i++) {
					addView({
						thumb: $thumbs.eq(i),
						bio: $details.eq(i)
					})
				}
				views[0].select();
				return true;
			}()
		};
		
	});*/
	
		
	/*P.module('summary', function () {
		
		var $about = $('#ipt_about'),
			$diff = $('#ipt_diff'),
			$matters = $('#ipt_matters'),
			$counter = $('#summary_counter'),
			$preview = $('#live_preview');
		
		function joined () {
			return([$about.val(), $diff.val(), $matters.val()]).join('');
		}
		
		function prePlusJoined () {
			return ([
				'This Ripple is about ' + $about.val(),
				$diff.val().length > 0? "It's different because " + $diff.val(): '',
				$matters.val().length > 0? "It matters because " + $matters.val(): ''
			]).join(' ');
		}
		
		function error (msg) {
			location.href = '#';
		}
		
		function change () {
			var left = 300 - joined().length;
			if (left < 0) {
				$counter.css('color','red');
			} else {
				$counter.css('color', '');
			}
			$counter.text(left);
			$preview.find('.desc').text(prePlusJoined());
		}
		
		
		return {
			get: function () {
				
			},
			init: function () {
				$preview.appendTo('body');
				$about.add($diff).add($matters).keyup(change);
				$('#ipt_org').keyup(function () {
					$preview.find('.title').html('<strong>' + $(this).val() + '</strong>');
				});
				$('#tag_cloud_start a').live('click', function () {
					var tags = $('#ipt_targets').val().split(', ');
					$preview.find('.tags').html('<strong>Tags:</strong> <a href="javascript:;">' + tags.join('</a>, <a href="javascript:;">') + '</a>');
				});
				$('#preview').click(function (e) {
					$preview.css({
						opacity: 0,
						left: '50%',
						top: $(this).offset().top + 5 + 'px'
					}).animate({
						opacity: 1
					}, 400);
					var tags = $('#ipt_targets').val().split(', ');
					$preview.find('.tags').html('<strong>Tags:</strong> <a href="javascript:;">' + tags.join('</a>, <a href="javascript:;">') + '</a>');
				});
				$preview.find('.close').click(function (e) {
					$preview.animate({
						opacity: 0
					}, 400, function () {
						$(this).css({
							left: '-9999px'
						});
					});
				});
				$preview.find('.title').html('<strong>' + $('#ipt_org').val() + '</strong>');
				$preview.find('.tags').html('<strong>Tags:</strong> <a href="javascript:;">' +  $('#ipt_targets').val().split(', ').join('</a>, <a href="javascript:;">') + '</a>');
				$preview.find('.logo img').attr('src', $('#myimg img').attr('src'));
				change();
				return true;
			}()
		};
	});
	
	
	P.module('labelHovers', function () {		
		var hoverText = {
			ipt_org: "Name of organization as you want us to view it (limit 30 characters)",
			ipt_desc: "Describe your organization (optional) if it helps (limit 60 characters).",
			ipt_targetaud: "Complete the statement by describing your target audience (who you want us to share this ripple with) so we'll recognize them in our own networks (limit 180 characters).",
			ipt_targets: "Tags tell us how to spread your ripple - who you want to reach and in what areas of interest and/or advocacy. Click tags to add/delete segments. Minimum 3, maximum 6.",
			ipt_about: "Complete phrase 1 (required), plus your choice of either phrase 2 or 3. You may complete all 3 if you like. (combined 300 character limit)",
			ipt_logo: "Click on Browse to upload a JPEG or GIF file of your logo or any other image you want displayed next to your ripple.",
			ipt_url: "Enter URL you want us to visit, to get to know you more (e.g., your website, twitter or facebook page).",					
			cvv2Number: '<img src="/images/cvv.jpg"/>'
		};
		return {
			getText: function (name) {
				return hoverText[name];
			},
			init: function () {
				var h;
				for (h in hoverText) {
					$('label[for=' + h + ']').hover(function () {
						var text = hoverText[h];
						return function (e) {
							P.hovers.showTooltip(e, text);
						};
					}(), P.hovers.hideTooltip);
					$('#' + h).focus(function () {
						var text = hoverText[h],
							name = h;

						return function (e) {
							e.pageX = $('label[for="' + name + '"]').offset().left;
							e.pageY = $('label[for="' + name + '"]').offset().top;
							//P.hovers.showTooltip(e, text, name === 'cvv2Number');
							$('label[for=' + name + ']').mouseover();
						};
					}()).blur(P.hovers.hideTooltip);
				}
				return true;
			}()		
		};
	});
	
	
	P.module('disclosure', function () {
		var text = {
			marketing_bundle: "As First 100, you get unlimited ripples, or marketing microsites for 1 year. And because ripples are easy to start, you can have a new microsite every day, week, or month for 12 months - all yours for $365. That's 365 days of viral campaigns for only $1 a day.",
			launch_ahead: "The First 100 will launch simultaneously in 100 metros, ahead of everyone else. They will carry a perpetual tag as the First 100, in recognition of their leadership in opening new marketing capabilities to consumers and brands big and small in their respective markets.",
			opening_ripple: "Full software and media offerings will be released November 2009, at which point The First 100 Ripples launch simultaneously in 100 metros. And Ripple100 opens to the general public. As the First 100, you get advance access to Ripple100 technology, allowing you to launch first."
			};		
		function hover (e) {
			P.hovers.showBigTooltip(e, text[$(this).attr('class')]);
		}
								
		return {
			init: function () {
				$('.marketing_bundle, .launch_ahead, .opening_ripple').hover(hover, P.hovers.hideBigTooltip);
				return true;
			}()
		};
	});
	
	P.module('characterLimits', function () {
		var fields = {};
	
		function addField (name, specs) {
			fields[name] = new Field(specs);
		}
		
		function Field (specs) {
			var $input = $(specs.input),
				$label = $(specs.label);
			$input.keyup(function () {
				$label.text((specs.before || '') + (specs.max - $input.val().length) + (specs.after || ''));
			});
			$label.attr('maxlength', specs.max).text((specs.before || '') + (specs.max - $input.val().length) + (specs.after || ''));
			return $input;
		}
		
		return {
			addField: addField,
			init: function () {
					addField('name', {
						input: '#ipt_org',
						label: '#name_counter',
						max: 30
					});
					addField('name', {
						input: '#ipt_desc',
						label: '#desc_counter',
						max: 60
					});
					addField('name', {
					    input: '#ipt_targetaud',
						label: '#ta_counter',
						max:180
					});
                    				}()
		};
		
	});
	
	P.module('bios', function () {
		
		var people = [];
		
		function addPerson (specs) {
			people.push(Person(specs));
			return this;
		}
		
		function addPeople (arr) {
			var a;
			for (a in arr) {
				addPerson(arr[a]);
			}
		}
		
		function Person (specs) {
			
			var $thumb = $(specs.thumb),
				$bio = $(specs.bio),
				$name = $bio.find('h4'),
				$position = $bio.find('h5'),
				timeout = null,
				selected = false;
			
			function getName () {
				return $thumb.attr('alt');
			}
			
			function getPosition () {
				return $position.text();
			}
			
			function show () {
				$bio.stop().css('left', '0px').css('height', $('#team_bio').height() + 'px').animate({
					opacity: 1
				}, 200);
			}
			
			function delay () {
				timeout = window.setTimeout(unselect, 1000);
			}
			
			function hide () {
				window.clearTimeout(timeout);
				$bio.animate({
					opacity: 0
				}, 200, function () {
					$(this).css('left', '-9999px');
				});
			}
			
			function select () {
				selected = true;
				window.clearTimeout(timeout);
				$.each(people, function (i) {
					if (this.getName() !== getName() && this.isSelected()) {
						this.unselect();
					}
				});
				$thumb.parent().addClass('selected');
				show();
				return this;
			}
			
			function unselect () {
				selected = false;
				hide();
				$thumb.parent().removeClass('selected');
				return this;
			}
			
			return {
				getName: getName,
				select: select,
				unselect: unselect,
				isSelected: function () {
					return selected;
				},
				init: function () {
					$bio.css({
						opacity: 0,
						left: '-9999px',
						top: $thumb.parent().parent().height() + 'px',
						position: 'absolute',
						background: '#fff'
					}).hover(select, delay);
					$thumb.hover(select, delay);
					if ($bio.height() > $('#team_bio').height()) $('#team_bio').height($bio.height() + 'px');
					return true;
				}()
			};
		}
		
		return {
			init: function () {
				$.each('abe,amy,andre,bob,david,eric'.split(','), function () {
					addPerson({
						thumb: '#thumb_' + this,
						bio: '#' + this + '_bio'
					});
				});
			}()
		};
		
	});*/
	
		
	
	/*P.module('boxes', function () {
		var	views = {};
			
		function View (specs) {
			var $details = $(specs.details),
				$header = $(specs.header),
				$menu = $(specs.menu),
				isOpen = false;
				
			function getName () {
				return specs.name;
			}
			
			function goTo (slide) {
				$menu.find('a').removeClass('selected').eq(slide).addClass('selected');
				if ($details.data('slidebox_slide') !== slide) {
					gotoSlide($details, slide);
				}
				//fixOuterSlidebox();
				return this;
			}
			
			function fixOuterSlidebox () {
				var $openSlidebox = $details.siblings('.ui_slidebox').not('.collapsed'),
					$curSlide = $openSlidebox.find('.slide').eq($details.data('slidebox_slide'));
				$('#main').stop().animate({
					//height: getSlideHeight() - $curSlide.height() + $details.find('.slide').eq($details.data('slidebox_slide')).height() + 'px'
				}, 500, function () {
					fitSlidebox();
				});
			}
			
			function expand () {
				$.each(views, function () {
					if (this.getName() === specs.name) return;
					this.collapse();
				});
				isOpen = true;
				expandBox($details);
				showMenu($menu);
				$header.addClass('selected');
				fixOuterSlidebox();
				return this;
			}
			
			function collapse () {
				isOpen = false;
				collapseBox($details);
				hideMenu($menu);
				$header.removeClass('selected');
				return this;
			}
			
			function toggle () {
				return (isOpen?collapse:expand)();
			}
			
			function addInline (el, slide) {
				$(el).click(function () {
					expand();
					if (specs.slides !== false) goTo(slide);
					return false;
				});
			}
			
			if (specs.slides !== false) {
				$details.slidebox();	
			}
			
			return {
				expand: expand,
				collapse: collapse,
				toggle: toggle,
				addInline: addInline,
				getName: getName,
				goTo: goTo,
				isOpen: function () {
					return isOpen;
				},
				init: function () {
					$details.find('.slide').height($details.find('.slides').height() + 'px');
					$header.click(function () {
						toggle();
						return false;
					});
					$details.click(function () {
						//return false;
					});
					$menu.find('a').each(function (i) {
						$(this).click(function () {
							expand();
							goTo(i);
							$menu.find('a').removeClass('selected');
							$(this).addClass('selected');
							return false;
						});
					}).eq($details.data('slidebox_slide')).addClass('selected');
					return true;
				}()
			};
		}
		
		function addView (specs) {
			var i, inline = specs.inline,
				obj = views[specs.name] = View(specs);
			
			if (inline) {
				for (i = 0; i < inline.length; i++) {
					obj.addInline.apply(obj, inline[i]);
				}
			}
			
			return this;
		}
		
		function addViews (obj) {
			var o, cur;
			for (o in obj) {
				cur = obj[o];
				cur.name = o;
				addView(cur);
			}
		}
		
		function showMenu (el) {
			var $el = $(el);
			if ($el.hasClass('hidden')) $el.css('opacity', 0);
			$el.stop().removeClass('hidden').animate({
				opacity: 1
			}, 400);
		}
		
		function hideMenu (el) {
			$(el).stop().animate({
				opacity: 0
			}, 400, function () {
				$(this).addClass('hidden');
			});
		}
		
		function collapseBox (el) {
			var $el = $(el),
				height = $el.find('.slide').eq($el.data('slidebox_slide')).height();
			$el.animate({
				height: '0px'
			}, 400, function () {
				$(this).addClass('collapsed');
				fitSlidebox();
			});
		}
		
		function expandBox (el) {
			var $el = $(el),
				height;
			
		//	if ($el.data('slidebox_init') === true) {
		//		height = $el.find('.slide').eq($el.data('slidebox_slide')).height();
		//	} else {
				height = getFullHeight($el);
		//	}
			$el.css('opacity', 1).animate({
				height: height + 10 + 'px'
			}, 400, function () {
				$(this).removeClass('collapsed');
				//fitSlidebox();
			});
		}
		
		function gotoSlide (el, slide) {
			$(el).slidebox('go', slide);
		}
		
		return {
			addViews: addViews,
			addView: addView,
			expand: expandBox,
			collapse: collapseBox,
			show: showMenu,
			hide: hideMenu,
			init: function () {
				addViews({
					launch: {
						header: '#about h3 a.go_launch_details_1',
						menu: '#launch_menu',
						details: '#launch_details',
						inline: [
							['#about p a.go_launch_details_1', 0],
							['#about p a.go_launch_details_2', 1]
						]
					},
					product: {
						header: '#about h3 a.go_product_details_1',
						menu: '#product_menu',
						details: '#product_details',
						inline: [
							['#about p a.go_product_details_1', 0],
							['#about p a.go_product_details_2', 1]
						]
					},
					start: {
						header: '#about h3 a.go_start_details_1',
						menu: '#start_menu',
						details: '#start_details',
						inline: [
							['#about p a.go_start_details_1', 0],
							['#about p a.go_start_details_2', 1]
						]
					},
					people: {
						header: '#about h3 a.go_people_details_1',
						menu: '#people_menu',
						details: '#people_details',
						slides: false,
						inline: [
							['#about p a.go_people_details_1', 0],
							['#about p a.go_people_details_2', 1]
						]
					}
				});
			}()
		};		
	});*/
	
		
		
	function getFullHeight($cloud) {
		var $clone = $cloud.clone(true).removeClass('collapsed').css({
				height: '',
				width: $cloud.width(),
				position: 'absolute',
				left: '-9999px'
			});
		height = $clone.appendTo($cloud.parent()).height();
		$clone.remove();
		return height;
	}
		
	function toggleCollapse (el) {
		var $this = $(this),
			$cloud = $(el),
			isCollapsed = $cloud.hasClass('collapsed');
	

		$cloud.animate({
			height: isCollapsed? getFullHeight($cloud) + 'px': '0px'
		}, 400, function () {
			$cloud[isCollapsed? 'removeClass': 'addClass']('collapsed');
			fitSlidebox();
		});
		
					/*
		$cloud.slideToggle(400, function () {		
			$cloud[isCollapsed? 'removeClass': 'addClass']('collapsed');
			fitSlidebox();
		});
		
		*/
	}
	
	function showMenu (el) {
		$el = $(el);
		$el.removeClass('hidden').animate({
			opacity: 1
		}, 400);
	}
	
	function hideMenu (el) {
		$el = $(el);
		$el.animate({
			opacity: 0
		}, 400, function () {
			$el.addClass('hidden');
		});
	}
	
	function expand (el) {
		$(el).animate({
			height: getFullHeight($(el)) + 'px'
		}, 400, function () {
			$(el).removeClass('collapsed');
			fitSlidebox();
		});
	}
	
	function fitSlidebox () {
	//	$('#main').css({
	//		height: $('#main .slides > .section').eq($('#main').data('slidebox_slide')).height() + 25 + 'px'
	//	});
	}
	
	function getSlideHeight () {
		return $('#main .slides > .section').eq($('#main').data('slidebox_slide')).height();
	}
	
	function clickDetailItem (section, slide) {
		return function () {
			var $el = $('#' + section + '_details');
			$el.animate({
				height: $el.find('.slide').eq(slide).height() + 10 + 'px'
			}, 400, function () {
				fitSlidebox();
				$el.removeClass('collapsed');
			});
			$('#' + section + '_details').slidebox('go', slide);
			$('#' + section + '_menu').removeClass('hidden');
			$('.go_' + section + '_details_' + (slide + 1)).addClass('selected').siblings('a').removeClass('selected');
			return false;
		};
	}
	
	$('#go_ripples').click(function () {
		$('#main').slidebox('go', 0);
		$('#ui_toggle_metros').show()
	});
	$('#go_about').click(function () {
		$('#main').slidebox('go', 1);
		$('#ui_toggle_metros').hide()
	});
	$('#logo').click(function () {
		$('#go_ripples').click();
	});
	
	$('#primary_nav a').not('#ui_toggle_metros').not('#go_login').click(function () {
		$('#primary_nav a.selected').removeClass('selected');
		$(this).addClass('selected');
	});
	
	$('#ui_toggle_metros').click(function () {
		toggleCollapse.call(this, '#metro_cloud');
		$('.toggle', this).text($('.toggle', this).text() === 'Show'? 'Hide': 'Show');
	});
	
	
	$('#ui_toggle_tags').click(function () {
		toggleCollapse.call(this, '#tag_cloud');
		$('.toggle', this).text($('.toggle', this).text() === 'Choose'? 'Hide': 'Choose');
	});
	
	$('#metro_cloud a').hover(P.hovers.showMeter, P.hovers.hideMeter);
	P.filters.gatherData();
	/*$('#tag_cloud a').click(function () {
		var tags = $('#ipt_targets').val().split(', ');
		$(this).toggleClass('selected');
		P.filters.execute();
		$('#live_preview').find('.tags').html('<strong>Tags:</strong> <a href="javascript:;">' + tags.join('</a>, <a href="javascript:;">') + '</a>');
	});*/
	
	/*$('#launch_details')
		.slidebox().click(function () {
			return false;
		})
		.find('.slide')
		.eq(1)
		.find('div')
		.addClass('cloud')
		.html($('#metro_cloud').html())
		.find('a')
		.removeAttr('href')
		.hover(P.hovers.showMeter, P.hovers.hideMeter);
	
		
	$('#product_details')
		.find('.slide')
		.eq(1)
		.find('div')
		.addClass('cloud')
		.html($('#tag_cloud').html())
		.find('a')
		.removeAttr('href');*/
	
		
	
		
	P.fitSlidebox = fitSlidebox;
	
	
	if (location.href.indexOf('/metros/') > -1 || location.href.indexOf('metros=') > -1) {
	
		$('#main').slidebox({init: 0});
		//$('#main').data('slidebox_slide', 1);
		//$('#main').slidebox('go', 0);
		//$('#main').css('height', $('#main .slide').eq(1).height() + 10 + 'px');
	} else if(location.href.indexOf('learnmore=1') > -1) {
		
		$('#main').slidebox({init: 1});
		
	}else{
                $('#main').slidebox();
        }
	
});