var Void=function(){};if(!window.console){window.console={log:Void};};

function ReActivateSifr() {
    replaceSifrStatements();
}

var Site = {
	Init: function() { 
	    Site.HomePage.Init();
	},
	Border: {
	    Init: function() {
	        window.addEvent('domready', function() {
	           setTimeout( Site.Border.Fix, 1 );
	        });
	    },
	    Fix: function() {
	        var bubble = $$('.bottomBubble')[0];
	        var y = bubble.getPosition().y;
	        var mainContainer = $$('.mainNav .fakeMenuBackground')[0];
	        var number = (y % 6) - 1;
	        
	        if( number > 0 ) {
	        //    mainContainer.setStyle('padding-top', number);
	        }
	        $('debug').set('html', new Date() + "<br />Number: " + number + "<br />Y: " + y + "<br />New Y: " + bubble.getPosition().y );
	        
	        setTimeout( Site.Border.Fix, 200 );
	    }
	},
	Load: function() { },
	Intro: {
	    Interval: 500,
	    Init: function() {
            var mainContainer = document.getElement('.mainContainer');
            var introContainer = document.getElement('.introContainer');
          	var centerEle = document.getElement('.centerContainer');
          	var box = centerEle.getElement('.box');
          	var whiteBubble = centerEle.getElement('.whiteBubble .innerBubble');
          	var whiteBubble2 = centerEle.getElement('.whiteBubble .innerBubble2');
          	var greyBubble = centerEle.getElement('.greyBubble .innerBubble');
          	var greyBubble2 = centerEle.getElement('.greyBubble .innerBubble2');
            var skipIntro = document.getElement('.skipIntro');
            
          	/* setup intro, fix scroll bars, etc. */
      	    mainContainer.addClass('hidden');
            introContainer.__RESIZE = function() {    
                size = $(window).getScrollSize();
                introContainer.setStyles({
                    height: window.getHeight(),
                    width: window.getWidth()
                });
            };            
            
            introContainer.__RESIZE();
            
            window.addEvent('resize', introContainer.__RESIZE );
                            
            centerEle.removeClass('hidden');
       
            // step 1, transition from small to bubbles with background images.
            var step1 = function() {
                new Fx.Morph( box, { 'duration': 500 }).start({ 'height': 220, 'width': 380, 'margin-left': -190 });
                
                new Fx.Morph( whiteBubble2, { 'duration': 500 }).start({ 'height': 100, 'width': 300, 'opacity': 0 });
                new Fx.Morph( greyBubble2, { 'duration': 500 }).start({ 'height': 100, 'width': 300, 'opacity': 0 });
            }
            
            // expand the white bubble completely beyond the page
            var step2 = function() {
                new Fx.Morph( centerEle, { duration: 500 }).start({'top': [centerEle.getPosition().y, 0] });
                new Fx.Morph( box, { duration: 500 }).start({
                    'width': window.getWidth(),
                    'left': [ box.getPosition().x - box.getStyle('margin-left').toInt(), 0 ], 
                    'margin-left': 0
                });
                            
                new Fx.Morph( whiteBubble, { 'duration': 500 }).start({ 'height': window.getHeight() + 110, 'width': window.getWidth() });
				new Fx.Morph( whiteBubble2, { 'duration': 200 }).start({ 'opacity': 1 });
				
				new Fx.Morph( greyBubble2, { 'duration': 200 }).start({ 'opacity': 1 });
                new Fx.Morph( greyBubble.getParent(), { 'duration': 500 }).start({ 'opacity': [1, 0], 'top': window.getHeight() });
                new Fx.Morph( greyBubble, { 'duration': 500 }).start({ 'height': (window.getHeight() / 3), 'width': window.getWidth() });
            }
            
            // step 3 is destroy everything and fade out the white
            var step3 = function() {
                introContainer.destroy();
                greyBubble.destroy();
            
                new Fx.Morph( whiteBubble, { 
                    duration: 250,
                    onStart: function() {
                        mainContainer.removeClass('hidden');
                    },
                    onComplete: function() {
                        centerEle.destroy();
                        skipIntro.destroy();
                        $(document.body).removeClass('intro');
                        replaceSifrStatements();
                    }
                }).start({'opacity': 0});
            }
            
            var timer = setTimeout( step1, 1000 );
            var timer2 = setTimeout( step2, 6000 ); 
			var timer3 = setTimeout( step3, 6500 );
			
			skipIntro.setProperty('href','javascript:Void()');
			skipIntro.addEvent('click', function() {
			    clearTimeout( timer );
			    clearTimeout( timer2 );
			    clearTimeout( timer3 );
			    
			    step3();
			});
	    }
	},
	DefaultButton: {
		Add: function( options ) {
			window.addEvent('domready', function() {
				options.FieldEles.each( function( ele ) {
					$(ele).__DEFAULT_BUTTON = $(options.DefaultButton);
					$(ele).addEvent('keypress', Site.DefaultButton.Handler );
				});
			});
		},
		Handler: function(e) {
			var e = new Event(e);
			if( e.key == 'enter' ) {
				setTimeout( unescape( this.__DEFAULT_BUTTON.href ), 1 );
			}
		}
	},
	HomePage: {
	    Interval: 3000,
	    FadeInterval: 1000,
	    Init: function() {
	        if( $(document.body).hasClass('homepage') ) {
				Site.__CURRENT_PORTRAIT = 0;
				Site.__PORTRAIT_LOOP = 0;
		        Site.__ANIMATION_CONTAINER = $$('.animationContainer')[0];
				Site.__ANIMATION_CONTAINER.setStyles({
					opacity: 0,
					display: 'block'
				})
		        Site.__CONTENT_CONTAINER = $$('.contentContainer')[0];
	            setTimeout( Site.HomePage.ChangeImage, Site.HomePage.Interval );
	        }

	    },
	    ChangeImage: function() {
   	        var images = [ 
   	            'colloquy_homepage_portraits_01.jpg', 
   	            'txt_home_purple-sentence.gif',
   	            'colloquy_homepage_portraits_02.jpg',
   	            'txt_home_purple-sentence.gif',
	            'colloquy_homepage_portraits_03.jpg', 
	            'txt_home_purple-sentence.gif',
	            'colloquy_homepage_portraits_04.jpg',
	            'txt_home_purple-sentence.gif'
			];
			
			Site.__CURRENT_PORTRAIT++;
			
		    if( Site.__CURRENT_PORTRAIT > images.length - 1 ) {
			    Site.__CURRENT_PORTRAIT = 0;
			    Site.__PORTRAIT_LOOP++;
		    }		
		    
		    if( Site.__PORTRAIT_LOOP < 2 ) {
	            new Fx.Morph( Site.__ANIMATION_CONTAINER,{
	                'duration': Site.HomePage.FadeInterval,
	                'onComplete': function() {
				        Site.__CONTENT_CONTAINER.setStyle('background-image', 'url( /Assets/img/portraits/'  + images[Site.__CURRENT_PORTRAIT] + ')' );
    					
                        new Fx.Morph( Site.__ANIMATION_CONTAINER,{
                            'duration': 1000,
                            'onComplete': function() {
    	                        setTimeout( Site.HomePage.ChangeImage, Site.HomePage.Interval );
                            }

                        }).start({'opacity': [1, 0] });
	                }

	            }).start({'opacity': [0, 1] });
	        }
	    }
	},
	ExpandableBubble: {
		Add: function( options ) {
			window.addEvent('domready', function() {
				var ele = $(options.Id);
				if( ele ) {

				    var bubble = ele.getElement('.innerBubble');
				    
				    if( ! ele.__ANIMATE ) {
				        ele.__ANIMATE = new Fx.Morph(bubble,{ duration: 750,
			                'onComplete': function() {
			                    ele.removeClass('expanding');
			                    if( this.element.__IS_EXPANDED ) {
			                        ele.addClass('expandedBubble');
			                    }
			                }
				        });
				        
				        ele.__EXPAND_SIZE = { Width: options.Width, Height: options.Height};
				        ele.__NORMAL_SIZE = { 
				            Width: bubble.getSize().x - bubble.getStyle('padding-left').toInt(), 
				            Height: bubble.getSize().y - bubble.getStyle('padding-top').toInt() - bubble.getStyle('padding-bottom').toInt()
				        };
				    }
				    
					var button = ele.getElement('.expandBubble');
					
					ele.__IS_EXPANDED = false;
					
					button.addEvent('click', function() {
					    this.blur();
					    ele.addClass('expanding');
					    if( bubble.__IS_EXPANDED ) {
						    ele.removeClass('expandedBubble');
						    button.addClass('btnExpand');
						    button.removeClass('btnCollapse');
						    ele.__ANIMATE.options.transition = Site.ReadMore.Transitions.AnimateOut;
						    
						    ele.__ANIMATE.start({
							    'height': ele.__NORMAL_SIZE.Height,
							    'width': ele.__NORMAL_SIZE.Width
						    });
						    
						    bubble.__IS_EXPANDED = false;
						    
						} else {						    						    						    						    
						    button.removeClass('btnExpand');
						    button.addClass('btnCollapse');
						    ele.__ANIMATE.options.transition = Site.ReadMore.Transitions.AnimateIn;
						    
						    ele.__ANIMATE.start({
							    'height': ele.__EXPAND_SIZE.Height,
							    'width': ele.__EXPAND_SIZE.Width
						    });
						    
						    bubble.__IS_EXPANDED = true;
						}
					    return false;
					});		
					
					button.setProperty('href','javascript:Void()');			
				}
			});
		}
		
	},
	PollModule: {
	    MaxBarWidth: 220,
	    BarTransition: Fx.Transitions.Cubic.easeOut,
	    Add: function( options ) {
	        window.addEvent('domready', function() {
	            Site.PollModule.Init( $(options.Id) );
	        });
	    
	    },
	    Init: function( ele ) {
	        ele.getElement('.btnSubmitWide').addEvent('click', function() {
	            if( ! Site.__AJAX_RUNNING ) { 
	                var questionId = ele.getElement('input.questionId').value;
	                var answer = ele.getElement('.answer input[checked]');
                    if( ! answer ) {
                        alert( 'Please answer the poll question.' );
    	                
	                } else {	                
			            new Request({
				            'url': '/WebServices/PollQuestion.asmx/StorePollQuestion',
				            'method': 'POST',
				            'urlEncoded': false,
				            'headers': { 'Content-type': 'application/json' },
				            'onFailure': JSON.handleError,
				            'onComplete': function( responseText ) {
				                Site.__AJAX_RUNNING = false;
					            Site.PollModule.ShowResults( ele, JSON.decode( responseText ).d );
					            ReActivateSifr();
				            }
			            }).send( 
			                JSON.encode({
	                            QuestionId: questionId,
	                            AnswerId: answer.value
	                        }) 
	                    );
    	                
	                    Site.__AJAX_RUNNING = true;
			        }
			    }
			    return false;
			});
			
			var nextButton = ele.getElement('.btnNextQuestion');
			if (nextButton) {
			    nextButton.setProperty('href','javascript:Void()');
				nextButton.addEvent('click', function(){
				    if( ! Site.__AJAX_RUNNING ) {
					    new Request({
						    'url': '/WebServices/PollQuestion.asmx/GetNextPollQuestion',
						    'method': 'POST',
						    'urlEncoded': false,
						    'headers': { 'Content-type': 'application/json' },
						    'onComplete': function(responseText){
						        Site.__AJAX_RUNNING = false;
							    Site.PollModule.ShowQuestion(ele, JSON.decode(responseText).d);
							    ReActivateSifr();
						    }
					    }).send();
					    
					    Site.__AJAX_RUNNING = true;
					}
					
					return false;
				});
			}
	    },
	    ShowResults: function( ele, obj ) {
			console.log( obj );
	        var pollResult = ele.getElement('.pollAnswer');	        
			var questionContainer = ele.getElement('.pollQuestion');
	        var nextQuestionButton = ele.getElement('.btnNextQuestion');
	        var resultsUl = pollResult.getElement('ul');
			resultsUl.empty();
			
	        obj.PollChart.question.answers.each( function( answerEle ) {
	            var bar = null;
	            var barWidth = (( answerEle.Percentage / 100 )* Site.PollModule.MaxBarWidth);
                resultsUl.adopt( new Element('li').adopt( 
                    new Element('p').set('text', answerEle.AnswerText),
                    new Element('table', { 
                        'cellpadding': 0, 'cellspacing': 0, 'class': 'barGraph' 
                    }).adopt( new Element('tbody').adopt( new Element('tr').adopt( 
                       bar = new Element('td',{'class': 'bar'}).setStyles({'width': barWidth + 'px'}),  
                       new Element('td',{'class': 'percentage'}).set('text',answerEle.Percentage + '%')
                    )))
                ));
                
                new Fx.Morph( bar, { 'duration': 1000, 'transition': Site.PollModule.BarTransition }).start({ width: [0, barWidth + 'px' ] });        
	        });
	        
			pollResult.getElement('h3').set('text', obj.PollChart.QuestionText).removeClass('sIFR-replaced'); 
			
	        if( obj.HasNextQuestion && nextQuestionButton != null ) {
	            nextQuestionButton.getParent().removeClass('hidden');
	        } else {
	            nextQuestionButton.getParent().addClass('hidden');
	        }
	        
	        questionContainer.addClass('hidden');
	        pollResult.removeClass('hidden');
	    },
	    ShowQuestion: function( ele, obj ) {	    
	        var questionContainer = ele.getElement('.pollQuestion');
			var pollResult = ele.getElement('.pollAnswer');	    
	        var nextQuestionButton = ele.getElement('.btnNextQuestion');
			
	    	ele.getElement('.fullQuestionContainer .questionId').value = obj.question.QuestionID;
	    	ele.getElement('.fullQuestionContainer h3').set('text', obj.question.QuestionText).removeClass('sIFR-replaced');
			var answerUl = ele.getElement('.fullQuestionContainer .answer ul');
			answerUl.empty();
			obj.question.answers.each( function( answer, index ) {
			
				answerUl.adopt( new Element('li',{'class':'clearfix'}).adopt(
					new Element('input',{
						'type':'radio', 'value': answer.AnswerId, 'id': 'autoAnswer' + index, 'name': 'colloquyPoll'
					}),
					new Element('label', { 'for': 'autoAnswer' + index }).set('text',answer.AnswerText)
				));
			});
			
	        pollResult.addClass('hidden');
	        questionContainer.removeClass('hidden');
			
	        console.log( obj );
	    }
	},
	ReadMore: { 
		Transitions: {
			AnimateIn: Fx.Transitions.Cubic.easeIn,
			AnimateOut: Fx.Transitions.Cubic.easeOut
		},
		Set: function( eleId ) {
			window.addEvent('domready', function() {
				var ele = $(eleId);
				
				ele.__EXPANDABLE = ele.getElement('.expandable');
				ele.__BUTTON = ele.getElement('.buttonContainer a.readMoreButton');
			    ele.__BUTTON.VoidLink();
			    ele.__ANIMATE = new Fx.Morph(ele.__EXPANDABLE,{ duration: 750 });
			    ele.__ANIMATE.__BUTTON = ele.__BUTTON;
			    ele.__EXPANDABLE.setStyles({'display':'none'});
			    
				var setup = function() {
				    ele.__EXPANDABLE.setStyles({'display':'block'});
				    // set all properties				    
				    ele.__EXPANDABLE_HEIGHT = ele.__EXPANDABLE.getSize().y;
				    console.log( ele.__EXPANDABLE.getSize().y );
				    ele.__IS_EXPANDED = false;
    				
				    // hide the expandable element
				    ele.__EXPANDABLE.setStyles({ 'height': 0, 'overflow': 'hidden', 'opacity': 0 });
				    ele.__SETUP = true;
				}
				
				// set the animation element so that when it's done 
				ele.__ANIMATE.addEvents({
					'complete': function() {
						if( ele.__TYPE == 'fadeIn' ) {
							ele.__IS_EXPANDED = true;
							ele.__BUTTON.removeClass('readMoreButton').addClass('btnCollapseBlue');
						} else {
							ele.__IS_EXPANDED = false;
							ele.__BUTTON.addClass('readMoreButton').removeClass('btnCollapseBlue');
						}
					}
				});

				// set button so when clicked, it'll either expand or contract
				ele.__BUTTON.addEvent( 'click', function() {
				    if( ! ele.__SETUP ) { setup(); }
					if( ! ele.__IS_EXPANDED ) {
						ele.__TYPE = 'fadeIn';
						ele.__ANIMATE.options.transition = Site.ReadMore.Transitions.AnimateIn;
						
						// IE can't do text fading, so don't do it for those browsers
						ele.__ANIMATE.start({
							'height': [0, ele.__EXPANDABLE_HEIGHT],
							'opacity': [ Browser.Engine.trident ? 1 : 0, 1 ]
						});
					} else {
						ele.__TYPE = 'fadeOut';
						ele.__ANIMATE.options.transition = Site.ReadMore.Transitions.AnimateOut
						
						// IE can't do text fading, so don't do it for those browsers
						ele.__ANIMATE.start({
							'height': [ele.__EXPANDABLE_HEIGHT, 0],
							'opacity': [ 1, Browser.Engine.trident ? 1 : 0 ]
						});
					}
					return false;
				});
			});
		}
	},
	MainNav: {
		OffsetLeft: -25,
		Transitions: {
			AnimateIn: Fx.Transitions.Cubic.easeOut,
			AnimateOut: Fx.Transitions.Cubic.easeIn
		},
		// set each main nav element
		Set: function( eleId ) {
			window.addEvent('domready', function() {
				ele = $(eleId);
				
				// get all main nav eles that have subnavs in them.		
				var eles = ele.getElements('li.parent');
				
				eles.each( function( navItem ) {					
							
					// set default animation element to each nav item.
					Site.MainNav.Init( navItem );
					
					// if this page has a default nav, set it
					if( navItem.subMenu.hasClass('childSelected') ) {
						Site.__VISIBLE_MENU = navItem;
					}					
					
					// menu animation, animate subnav out
					navItem.AnimateOut = function() {
						// this is the default starting point of the fade out
						var offset = {
							'left': 0,
							'opacity': 1
						}
						
						// if it's in the middle of an animation, stop it and then recalculate the starting point
						if( navItem.__ANIMATE.timer ) {
							navItem.__ANIMATE.cancel();
							offset.left = navItem.__ANIMATE.element.getStyle('margin-left')
							offset.opacity = navItem.__ANIMATE.element.getStyle('opacity');
						}
						
						// set the animation type since animate ele is shared
						navItem.__ANIMATE.options.transition = Site.MainNav.Transitions.AnimateOut;						
						
						// start animation
						navItem.__ANIMATE.start({
							'margin-left': [offset.left, Site.MainNav.OffsetLeft], 
							'opacity': [offset.opacity, 0]
						});
					};
					
					// menu animation, animate subnav in
					navItem.AnimateIn = function() {
						// this is the default starting point of the fade in
						var offset = {
							'left': Site.MainNav.OffsetLeft,
							'opacity': 0
						}
						
						// if it's in the middle of an animation, stop it and then recalculate the starting point
						if( navItem.__ANIMATE.timer ) {
							navItem.__ANIMATE.cancel();
							offset.left = navItem.__ANIMATE.element.getStyle('margin-left')
							offset.opacity = navItem.__ANIMATE.element.getStyle('opacity');
						}
						
						// set the animation type since animate ele is shared
						navItem.__ANIMATE.options.transition = Site.MainNav.Transitions.AnimateIn;
						
						// start animation
						navItem.__ANIMATE.start({
							'margin-left': [offset.left, 0],
							'opacity': [offset.opacity, 1]
						});
					};

					// set the actual events on the nav items
					navItem.addEvents({
						'mouseenter': function() {
							// if the menu i'm hovered over is already showing, then don't do anything
							if( ! navItem.subMenu.hasClass('childSelected') ) {
								navItem.AnimateIn();
								
								// only 1 subnav can show at a time, so animate this out if there's a default nav for the page
								if( Site.__VISIBLE_MENU ) {
									Site.__VISIBLE_MENU.AnimateOut();
								}
							}
						},
						'mouseleave': function() {		
							// if the menu i'm hovered over is already showing, then don't do anything
							if( ! navItem.subMenu.hasClass('childSelected') ) {
								navItem.AnimateOut();
								
								// if this menu is shown by default on this page, then show it again
								if( Site.__VISIBLE_MENU ) {
									Site.__VISIBLE_MENU.AnimateIn();
								}
							}
						}
					});
				});
			});
		},
		Init: function( item ) {
			if( ! item.__INIT ) {
				// each nav item has a sub menu with it
				item.subMenu = item.getElement('ul.subMenu');
				
				// create the main animation element
				item.__ANIMATE = new Fx.Morph( item.subMenu, {
					'duration': 400
				});

				// if the item is not the menu that should show, then forcefully 'rehide' it correctly
				if( ! item.subMenu.hasClass('childSelected') ) {
					item.subMenu.setStyles({
						'margin-left': Site.MainNav.OffsetLeft,
						'opacity':'0',
						'display':'block'
					});
				}

				item.__INIT = true;
			}
		}
	}
}

Element.implement({
	// custom void link js reference
	VoidLink: function() {
		this.setProperty('href','javascript:Void()');
	},
	// watermark text, adds/removes custom css class based on if input value is 0.
	// set will set the custom class
	// get will return custom class that is set
	WatermarkText: function( options ) {
		if( typeof(options) == 'object' ) {
			if( options.CssClass ) {
				this.__WATERMARK_CLASS = options.CssClass;
			}
			
			if( options.Text ) { 
				this.__WATERMARK_TEXT = options.Text;
			}
			
			// make sure the events weren't already added, it can be called again and be modified
			if( ! this.__WATERMARK_EVENT ) {	
				this.addEvents({
					'focus': function() {
						// if we set a watermark class then remove it
						if( this.__WATERMARK_CLASS ) {
							this.removeClass( this.__WATERMARK_CLASS );
						}
						
						// if there's text, then hide it
						if( this.__WATERMARK_TEXT ) {
							if( this.value == this.__WATERMARK_TEXT ) { this.value = ''; }
						}
							
					},
					'blur': function() {
						// the whole point of the script, if its empty show it
						if (this.value.length == 0) {
							if( this.__WATERMARK_CLASS ) {
								this.addClass( this.__WATERMARK_CLASS );
							}
							
							if( this.__WATERMARK_TEXT ) {
								this.set( 'value', this.__WATERMARK_TEXT );
							}
						}
					}
				});
				
				this.__WATERMARK_EVENT = true;
				
				// fire it so that it shows current state
				this.fireEvent('blur');
			}
		} else if( this.__WATERMARK_EVENT ) {
			return this.__WATERMARK_TEXT || this.__WATERMARK_CLASS;
		}
	},
	Hide: function() {
		this.addClass('hidden')
		return this;
	},
	Show: function() {
		this.removeClass('hidden');
		return this;
	},
	IsHidden: function() {
		return this.hasClass('hidden') || this.getStyle('display') == 'none';
	},
	getRealSize: function(flag) {
		var theSize = this.getSize();
	    if( theSize.x == 0 || theSize.y == 0 && this.IsHidden() ){
		    this.setStyle('display','block');
		    var oldPosition = this.getStyle('position');
		    this.setStyle('position','absolute');
		    theSize = this.getSize();
		    this.setStyle('display','none');
		    this.setStyle('position', oldPosition );
		}
		return theSize;
	}
});

JSON.handleError = function( request ) { 
	str = 'This is the generic Json.handleError() function. A generic XMLHttpRequest error has occured.\n';
	str += '[ERROR] The XMLHttpRequest has failed!\n';
	var myObj = JSON.decode( request.responseText );
	for( var key in myObj ) {
		str += '[' + key + '] ' + myObj[key] + '\n';
	}
};

window.addEvent('domready', Site.Init );
window.addEvent('domready', Site.Load );