var deleteConfirmContent = '<p>Are you sure you want to remove this event from your itinerary?</p><a href=\"#\" class=\"button-delete\">delete</a><a class=\"cancel\" href=\"#\">CANCEL</a><div class=\"clear\"></div>';
var clickTrap;
var clickTrapHeight;

function PrototypeDomLoadedEvtHandler() {
/*document.observe('dom:loaded', function() {*/

	var elemClickTrap = $$('.clickTrap')[0];
	if( elemClickTrap ) return;
	
	clickTrap = $(document.createElement("div"));
	 clickTrapHeight = $$('.page')[0].getHeight() + 'px';
	clickTrap.addClassName('clickTrap');
	clickTrap.setStyle({
		height: clickTrapHeight
	})

	clickTrap.setAttribute("id", 'clickTrap_1');	
	clickTrap.hide();
	document.body.appendChild(clickTrap);

    /* Trip Questionnaire Progress Bar */
    var progressBarOverlay = $$('.questionnaireProgress .step_status')[0];
    if (progressBarOverlay) {
        FormProgressIndicator = new ProgressSlider(progressBarOverlay);
    }
    
    /* Trip Questionnaire - various utility for the UI behaviors */
    QuestionnaireFormUI = new QuestionnaireFormSupport();
        
    /* Trip Questionnaire Carousel Interface */
    var sliderOuter = $$('.formCarouselPaneWrapOuter')[0];
    var sliderInner = $$('.formCarouselPaneWrapInner')[0];

    if (sliderOuter && sliderInner) {

	FormCarouselPane_Slider = new SlideRule(sliderOuter, sliderInner, { pageForeward: false, pageBackward: false, transition: true });
    FormCarouselPane_Slider.goToPage(1);

    }
    /* end Trip Questionnaire Carousel Interface */

    /* Trip Questionnaire - Drag Slider */

    var travelStyleEl = $$('.formSectionTravelStyle')[0];
    if (travelStyleEl) {
        FormDragSlider_travelStyle = new DragSlider({ sliderOffset: 85,
                                        sliderElPrimaryOffset: $$('.page')[0],
                                        sliderElOuter: $$('.formSectionTravelStyle .sliderWrapInner')[0],
                                        sliderElInnerTagName: 'li',
                                        sliderElCursor: $$('.formSectionTravelStyle .slider_control')[0]
                                        });
    }
    var visitedChicagoEl = $$('.formSectionVisitedChicago')[0];
    if (visitedChicagoEl) {
        FormDragSlider_visitedChicago = new DragSlider({ sliderOffset: 85,
                                        sliderElPrimaryOffset: $$('.page')[0],
                                        sliderElOuter: $$('.formSectionVisitedChicago .sliderWrapInner')[0],
                                        sliderElInnerTagName: 'li',
                                        sliderElCursor: $$('.formSectionVisitedChicago .slider_control')[0]
                                        });
    }

	var effects = [];

	$$('.accordionToggle').invoke('observe','click',function(e){
		if (this.hasClassName('accordionToggle_active')) {
			$$('.accordionToggle').each(function(node){
				node.removeClassName('accordionToggle_active');
				effects.push(
					new Effect.Morph(node.getOffsetParent(),{ sync: true, style: { width: "160px" } })
				)
			});
		} else {
			$$('.accordionToggle').each(function(node){
				node.removeClassName('accordionToggle_active');
			});
			this.addClassName('accordionToggle_active');
			$$('.accordionToggle').each(function(node){
				if (!(node.hasClassName('accordionToggle_active'))) {
					effects.push(
						new Effect.Morph(node.getOffsetParent(),{ sync: true, style: { width: "50px" } })
					)
				}
			});
			effects.push(
				new Effect.Morph(this.getOffsetParent(),{ sync: true, style: { width: "604px" } })
			)
		}
		new Effect.Parallel(effects, { duration: .45 });
	});
		
// Drag and Drop
	rebindSchedulingDraggable();
	
	rebindDroppables();
	
	setupNotesAreaForEventHandling();
	
	$$('.lightBox').each(function(node) {
		node.observe('click',function(e){
			Event.stop(e);
			lightBox(node.next().className, node.next().innerHTML, 'true', node.next());
			node.next().innerHTML='';
		})
	})
	rebindDatePicker();
	
/* CVLX - 3 */
//call the function
	rebindMapViewEvents();
		
/* END CVLX - 3 */
	var factoidElement = $$('.content .factoid')[0];
    var insertElement = $$('.rightCol')[0];
 
    /* require both .factoid and the standard right column, 2-col layout */
    if (factoidElement && insertElement) {
	
        var classname = factoidElement.className;

    var factoidSpace = $(document.createElement("div"));
	    factoidSpace.addClassName(classname).addClassName('rightMod');
	    $$('.rightCol')[0].appendChild(factoidSpace);
	    
	    $$('.content .factoid').each(function(node) {
	    		node.removeClassName('hidden');	
				
	    });
	   
    }


	if($$('.changePhoto').length > 0) {
		var changePhotoSrc = $$('.changePhoto li a')[0].select('img')[0].src;

		$$('.changePhoto li a').each(function(node) {
		
			node.observe('click',function(e){
				$$('.changePhoto li a').each(function(node){
					node.removeClassName('selected');
				})
				node.addClassName('selected');
				changePhotoSrc = node.select('img')[0].src;
				setDirtyFlag();
				return false;
			})
		});

		$$('.itineraryImage a.changePhotoLink')[0].observe('click',function(node){
		
		$$('.changePhoto')[0].show();
		
		});
	
		$$('.changePhoto .choosePhoto')[0].observe('click',function(node){
			$$('.itineraryImage img')[0].src = changePhotoSrc.replace('.jpg','_large.jpg');
			$$('.changePhoto')[0].hide();
		});
	}
	
	$$('div.listControl').each(function(node){
		if (node.select('a').length > 0){
			node.select('a')[0].observe('click', function(e){
				Event.stop(e);
				var clicked = this;
				
				if ( IsClientIdInItineraryList(getNodeClientID(node)) == true )
				{
					clicked.hide();
					if( node.select('span').length == 0 ) node.insert('<span>Added</span>');
					node.select('span')[0].observe('click', function(el){
						OnClickRemoveItem(node, this,el);
						/*newlyAdded.remove();
						this.remove();
						clicked.show();
						if ($$('.additions ul li').length <= 1) {
							$$('.additions ul li.empty')[0].show();
						}*/
					})
					return false;
				}
				var newlyAdded = $(document.createElement("li"));
				newlyAdded.id = getNodeClientID(node);
				newlyAdded.insert('<a href=\"' + node.next('.name').select('.attraction')[0].href + '\" class=\"attraction\">' + node.next('.name').select('.attraction')[0].innerHTML + '</a>');
				newlyAdded.insert('<div class=\"location\">' + node.next('.location').innerHTML + '</div>')
				if ($$('.additions ul li.empty').length > 0) {
					$$('.additions ul li.empty')[0].hide();
				}
				$$('.additions ul')[0].appendChild(newlyAdded);
				clicked.hide();
				if( node.select('span').length == 0 ) node.insert('<span>Added</span>');
				node.select('span')[0].observe('click', function(el){
					newlyAdded.remove();
					this.remove();
					clicked.show();
					if ($$('.additions ul li').length <= 1) {
						$$('.additions ul li.empty')[0].show();
					}
				})
			})
		}
	})
	
	
	$$('.button-addToItinerary').each(function(node){
		node.observe('click', function(e){
			var clicked = this;
			
			var newlyAdded = $(document.createElement("li"));
			newlyAdded.id = getNodeClientID(node);
			var idN=getCliNumFromUrl(node.href);
			
			newlyAdded.id=idN;
			newlyAdded.insert(node.next().innerHTML);
			$$('.additions ul')[0].appendChild(newlyAdded);
			this.hide();
			this.previous().show().observe('click',function(el){
				newlyAdded.remove();
				this.hide();
				clicked.show();
			})
			
			
		})
	})
	
	$$('a.shareWithFriend').each(function(node){
		node.observe('click', function(e){
			Event.stop(e);
			if ($$('.shareWithFriendForm div.eventName').length > 0) {
				$$('.shareWithFriendForm div.eventName')[0].update(node.getOffsetParent().previous('dt').select('a')[0].innerHTML);
			}

			lightBox('shareWithFriendForm', $$('.shareWithFriendForm')[0].innerHTML, 'true',$$('.shareWithFriendForm')[0]);
			$$('.shareWithFriendForm')[0].innerHTML='';

		})
	})
	
	$$('a.saveTrip').each(function(node){
		node.observe('click', function(e){
			Event.stop(e);
			
			if(showLoginBox() == true) 
			{
				lightBox('saveTrip', $$('div.saveTrip')[0].innerHTML, 'true', $$('div.saveTrip')[0]);
				$$('div.saveTrip')[0].innerHTML='';
				
			}
		})
	})
	
	
	
	/* *************************************************************************
	=INIT INPUT TEXT SWAP
	Inits the focus and blur functions of the text field
	************************************************************************* */

	$$('input.text').each(function(node){
		
		initSwapInput(node);
	})
	
	$$('a.tooltip').each(function(node){
		new Tooltip(node, node.next().innerHTML, 'true');
	});
	
/*}); */
/* end PrototypeDomLoadedEvtHandler() */

}
	function rebindDatePicker()
	{
    /* special lightBox for date picker plugin */
	$$('.lightBox-datePicker').each(function(node) {
		node.observe('click',function(e){
			Event.stop(e);
			lightBox(node.next().className, node.next().innerHTML, 'true', node.next());
            var newTimeFrameContent = $$('.lightBox .timeFrameContent')[0];
            if (newTimeFrameContent) {
                var Timeframe_Questionnaire =  new Timeframe(newTimeFrameContent, {
                                                    format: '%m/%d/%y',
                                                    startField: 'start',
                                                    endField: 'end',
                                                    earliest: new Date(),
                                                    resetButton: 'reset' });
            }
            var lightBoxEl = $$('.lightBox')[0];
            resizeLightBox(lightBoxEl);
			
			if( jQuery.browser.msie && jQuery.browser.version.indexOf("8.") != -1 )
			{
				/*In IE8, calendar control does not apply styles properly */
				jQuery('div.clickTrap div.timeframe_calendar ul').css('display','none');
				jQuery('div.clickTrap div.timeframe_calendar div#end_field_container').css('display','none');
				jQuery('div.clickTrap div.timeframe_calendar div#start_field_container').css('display','none');
				jQuery('div.clickTrap div.timeFrameWrap div.shadowRight').css('display','none');
			}
			
            /* add action to lightBox Apply button */
            $$('.timeFrameWrap .button-apply').each(function(button) {
                button.observe('click',function(e) {
                    Event.stop(e);
                    var inputSourceStart = $$('#start_field_container input')[0];
                    var inputSourceEnd = $$('#end_field_container input')[0];
                    var inputDestinationStart = $$('.formSectionTripDates input.trip_arrival')[0];
                    var inputDestinationEnd = $$('.formSectionTripDates input.trip_departure')[0];
					var themedItin=false;
                    /* require all form elements before working with them */
                    if (inputSourceStart && inputSourceEnd && inputDestinationStart && inputDestinationEnd) {
                        /* copy the input values set by the timeframe JS Calendar Picker */
                        inputDestinationStart.value = inputSourceStart.value;
                        inputDestinationEnd.value = inputSourceEnd.value;

                        /* close the lightBox */
                        lightBoxEl.remove();
                        clickTrap.hide();
                    }
					else
					{
						if( typeof inputDestinationStart == 'undefined' || 
							typeof inputDestinationEnd == 'undefined' )
						{
							inputDestinationStart = $$('input.trip_arrival')[0];
							inputDestinationEnd = $$('input.trip_departure')[0];
							themedItin=true;
						}
                        inputDestinationStart.value = inputSourceStart.value;
                        inputDestinationEnd.value = inputSourceEnd.value;
						if(inputDestinationStart.value != '' && inputDestinationEnd.value != '')
						{
							/* close the lightBox */
							lightBoxEl.remove();
							clickTrap.hide();
							
							/** themed itineary page apply button pressed, call themed itinerary postback function **/
							SetThemedItineraryTimeFrame();
						}
					}
					if(inputDestinationEnd && inputDestinationEnd.style.display != 'none' && themedItin == false) inputDestinationEnd.focus();					
                });
            });

		});
	});
	}
	
    function resizeLightBox(lightBox) {
        /* copied from lightbox function, for asynchronous
           call from lightbox invoke */
		var windowHeight;
		
		if (window.innerHeight) {
			windowHeight = window.innerHeight;
		} else {
			windowHeight = document.documentElement.clientHeight;
		}

		var lightBoxTop = Math.round(document.viewport.getScrollOffsets().top + ((windowHeight - lightBox.getHeight()))/2)+'px';
		lightBox.setStyle({'top':lightBoxTop});

		var shadowHeight = lightBox.getHeight() - 11 + 'px';
		var shadowWidth = lightBox.getWidth() - 10 + 'px';
		lightBox.select('div.shadowRight')[0].setStyle({'height':shadowHeight});
		lightBox.select('div.shadowBottom')[0].setStyle({'width':shadowWidth});
    }


	function lightBoxShadows(lightBox){
		var windowHeight;

		lightBox.insert('<div class=\"shadows shadowTopRight\"></div><div class=\"shadows shadowRight\"></div><div class=\"shadows shadowBottomRight\"></div><div class=\"shadows shadowBottom\"></div><div class=\"shadows shadowBottomLeft\"></div>')
		
		if (window.innerHeight) {
			windowHeight = window.innerHeight;
		} else {
			windowHeight = document.documentElement.clientHeight;
		}

		var lightBoxTop = Math.round(document.viewport.getScrollOffsets().top + ((windowHeight - lightBox.getHeight()))/2)+'px';
		lightBox.setStyle({'top':lightBoxTop});

		var shadowHeight = lightBox.getHeight() - 11 + 'px';
		var shadowWidth = lightBox.getWidth() - 10 + 'px';
		lightBox.select('div.shadowRight')[0].setStyle({'height':shadowHeight});
		lightBox.select('div.shadowBottom')[0].setStyle({'width':shadowWidth});
		
		if (document.attachEvent) {
			lightBox.select('.shadows').each(function(node){
				var shadowURL = node.getStyle('background-image');
				var shadowSizeMethod = 'crop';
				if (node.hasClassName('shadowRight') || node.hasClassName('shadowBottom'))
					shadowSizeMethod = 'scale';
				node.setStyle({ 'background': 'none' });
				node.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="' + shadowSizeMethod + '", src="' + shadowURL.substring(5,shadowURL.length - 2)  + '")'
			})
		}
	}


// lightBox script
	function lightBox(elClass, content, closeButton, node)
	{
		var lBox = $(document.createElement("div"));
		lBox.addClassName('lightBox').addClassName(elClass);

		var cA = content.split('{}');
		if( elClass == 'chooseDates')
		{
			lBox.insert(cA[0]);
		}
		else
		{
			lBox.insert(content);
		}

		if (lBox.select('a.cancel').length > 0) {
			lBox.select('a.cancel').invoke('observe','click',function(e)
		{
				if( elClass == 'chooseDates')
				{
					if(node!=null)
					{
						node.innerHTML=cA[0];
					}
					Event.stop(e);		
					var dateSelected = cA[1] + ',' + cA[2];
					//clone nodes to user selected dates boxes
					CopyItemsIntoDates(dateSelected);
					rebindSchedulingDraggable();
					
					lBox.remove();
					clickTrap.hide();
					if( typeof( setDirtyFlag ) != 'undefined' ) setDirtyFlag();
				}
				else
				{
					if(node!=null)
					{
					node.innerHTML=content;
					}
					Event.stop(e);		
					lBox.remove();
					clickTrap.hide();
				}
			})
		}
		
			if (lBox.select('a.register-now').length > 0)
			{
				if( elClass == 'saveTrip')
				{
					lBox.select('a.register-now').invoke('observe','click',function(e) {
						if(node!=null)
						{
							node.innerHTML=content;
						}
						Event.stop(e);		
						lBox.remove();
						clickTrap.hide();
						collectPostBackData('userregistration');
					});
				}
			}
			
		if (lBox.select('input.text').length > 0) {
			lBox.select('input.text').each(function(node){
				initSwapInput(node);
			})
		}

		if (closeButton == 'true') {
			lBox.insert({top: '<a href=\"#\" class=\"closeButton\">close</a><div class=\"clear\"></div>'});
			lBox.select('a.closeButton').invoke('observe','click',function(e){
				if(node!=null)
				{
				node.innerHTML=content;
				}
				Event.stop(e);
				lBox.remove();
				clickTrap.hide();
			});
		}

		if (lBox.select('a.button-savePassword').length > 0) {
			lBox.select('a.button-savePassword').invoke('observe','click',function(e){
// Send Password form submit should go here
				if(node!=null)
				{
				node.innerHTML=content;
				}
				//lightBox.update($$('div.changePassword')[0].innerHTML);
				

			})
			}
			
		if (lBox.select('a.button-sendPassword').length > 0) {
			lBox.select('a.button-sendPassword').invoke('observe','click',function(e){
// Send Password form submit should go here

				/*lightBox.update($$('div.sendPassword')[0].innerHTML);
				lightBox.insert({top:'<a href=\"#\" class=\"closeButton\">close</a>'});
				lightBoxShadows(lightBox);
				lightBox.select('a.closeButton').invoke('observe','click',function(e){
					Event.stop(e);
					lightBox.remove();
					clickTrap.hide();
				});*/
			})
		}

		if (lBox.select('a.forgotPassword').length > 0) {
			lBox.select('a.forgotPassword').invoke('observe','click',function(e){
			Event.stop(e);
					lBox.remove();
					clickTrap.hide();
			lightBox('forgotPassword', $$('div.forgotPassword')[0].innerHTML, 'true',$$('div.forgotPassword')[0]);
			$$('div.forgotPassword')[0].innerHTML=''
// Send Password form submit should go here
				/*ForgotPwdContent=$$('div.forgotPassword')[0].innerHTML;
				//lightbox.removeChild();
				lightBox.update($$('div.forgotPassword')[0].innerHTML);
				$$('div.forgotPassword')[0].innerHTML=''
				lightBox.insert({top:'<a href=\"#\" class=\"closeButton\">close</a>'});
				lightBoxShadows(lightBox);
				lightBox.select('a.closeButton').invoke('observe','click',function(e){
					Event.stop(e);
					lightBox.remove();
					clickTrap.hide();
					});*/
				});
			
		}
		
		clickTrap.appendChild(lBox);

		var iframe = '<!--[if ie]><iframe id=\"ttFrame\" style=\"filter:mask(); position: absolute; top: 0; left: 0; z-index: -1; width: 100%;\" src=\"javascript:\'<html></html>\';\" frameborder=\"0\" scrolling=\"no\"></iframe><![endif]-->';
		clickTrap.insert(iframe);
		
		clickTrap.show();
		
		if (clickTrap.select('iframe')[0]) {
			clickTrap.select('iframe')[0].setStyle({ height: clickTrapHeight })
		}
		lightBoxShadows(lBox);
	}



	function setupNotesAreaForEventHandling()
	{
		$$('div.draggable div.note textarea').each(function(node)
		{
		var charCount = 45;
		
		node.observe('focus',function(e){
			
			this.setStyle({background: '#eeeeff'});
			if (this.value == 'click to add a note') {
				this.value = '';
			}
			node.getOffsetParent().insert('<span class=\"charCount\"></span><span class=\"addButton\">&laquo; add</span>')
			node.next('span.charCount').update('(' + (45 - node.value.length) + ')');
			
			node.next('span.addButton').observe('click',function(el){
				this.previous('textarea').setStyle({background: 'none'});
				if (this.previous('textarea').value == '') {
					this.previous('textarea').value = 'click to add a note'
				}
				this.remove();
				this.previous('span.charCount').remove();
			})
		})
		
		node.observe('blur',function(e){
			this.setStyle({background: 'none'});
			if (this.value == '') {
				this.value = 'click to add a note'
			}
			node.next('span.addButton').remove();
			node.next('span.charCount').remove();
		})

		node.observe('keydown', function(e){
			if ((45 - node.value.length) >= 0) {
				charCount = 45 - node.value.length;
			} else {
				charCount = 0;
			}
			if( typeof( setDirtyFlag ) != 'undefined' ) setDirtyFlag();
			node.next('span.charCount').update('(' + charCount + ')');
			if (!(e.keyCode == 8)){
				if (this.value.length >= 45) {
					Event.stop(e)
					this.value = this.value.substr(0,45);
				}
			}
		})
		
		node.observe('keyup', function(e){
			if ((45 - node.value.length) >= 0) {
				charCount = 45 - node.value.length;
			} else {
				charCount = 0;
			}
			setDirtyFlag();
			node.next('span.charCount').update('(' + charCount + ')');
		})

		node.observe('paste', function(e){
			new PeriodicalExecuter(function(pe) {
				if (node.value.length >= 45) {
					node.value = node.value.substr(0,45);
				}
				pe.stop();
				if ((45 - node.value.length) >= 0) {
					charCount = 45 - node.value.length;
				} else {
					charCount = 0;
				}
				setDirtyFlag();
				node.next('span.charCount').update('(' + charCount + ')');
			}, .25);
			
		})
		})

	}


	function rebindMapViewEvents()
	{
		$$('.itineraryDetail dl dt a').each(function(node) {
		
			node.observe('click',function(e){
				var nodeName = node.text;
				if( nodeName === undefined )
				{
					nodeName = node.innerText;//For IE
				}
				/*$$('.itineraryDetail dl dd div').each(function(node2){
					node2.hide();
				})*/
				$$('.itineraryDetail dl dd *').each(function(node2){
					node2.hide();
				})				
				
				$$('.itineraryDetail dl dt a').each(function(node3){
					node3.toggleClassName('on');
				})
				if( nodeName !== undefined )
				{
					if( nodeName.indexOf('Map') >= 0 )
					{
						GoogleMapInitialize();
						$$('.itineraryDetail dl dd.mapContent')[0].show();
						$$('.itineraryDetail dl dd.mapContent *').each(function(node){
							node.show();
						})
						//for map, do not handle close in same way as it is handled in scheduling section of this page
						rebindMapDraggableEvents();

					}
					else
					{
						$$('.itineraryDetail dl dd.scheduleContent *').each(function(node)
						{
							var classname = node.className;
							if( classname.indexOf('veil') < 0 && classname.indexOf('mastercopy') < 0 )
							{
								node.show();
							}
							if( classname.indexOf('mastercopy') >= 0 )
							{
								if( node.up(0).hasClassName('unscheduledItems') ) node.show();
							}
						})
					}
				}
				return false;
			})
		});
	}

	function rebindSchedulingDraggable()
	{
		var veilHeight;
		$$('.draggable').each(function(node){

			node.insert('<a href=\"#\" class="close">close</a><div class=\"roundedTop\"></div><div class=\"roundedBottom\"></div>')

			new Draggable(node, {
				revert: 'true',
				scroll: window,
				onStart: function(){					
					if (node.ancestors()[0].className == 'droppable') {
						veilHeight = $$('.unscheduledItems')[0].getHeight() - 22 + 'px'
						veil.setStyle({
							height: veilHeight
						})
						veil.show()
					}
				}
			});
			
			bindBehaviorToCloseBtn(node, deleteConfirmContent);

		});
	}
	
	function bindBehaviorToCloseBtn(node, deleteConfirmContent)
	{
		
		
		node.select('a.close').invoke('observe','click',function(e){
			Event.stop(e);
			if ( node.ancestors().length > 0 && node.ancestors()[0].hasClassName('unscheduledItems') ) 
			{
				if( $$('.clickTrap .closeConfirmation').length == 0 )
				{
					lightBox('closeConfirmation', deleteConfirmContent, 'false', deleteConfirmContent);
				}
				else
				{
					$$('.clickTrap .closeConfirmation')[0].show();
				}
				$$('div.lightBox a.button-delete')[0].observe('click', function(elCancel){
					Event.stop(elCancel);
					$$('div.lightBox')[0].remove();
					$$('.clickTrap')[0].hide();
					updateRecommendedItemsList(node.id);
					node.remove();
				})
			}
			else 
			{
				var parentID = this.getOffsetParent().readAttribute("original");
				if( parentID != null )
				{
					var count=0;
					var itemId = parentID.split('_')[1];
					
					if(this.getOffsetParent().up()!= null && typeof(this.getOffsetParent().up().innerHTML)!='undefined')
					{
						
					this.getOffsetParent().up().up().select('div.draggable').each(function(node1){
					
						
						
						var idA = node1.id.split('_');
						if( idA[1] == itemId )
						{
							count++;
						}
						
					})
					//This length == 2 includes parent(original node) + cloned node
					
					}
					if( count == 2 )
					{
						$$('.unscheduledItems')[0].insert($(parentID));
						$(parentID).show();
						if( $(parentID).select('span.dragged').length > 0 ) $(parentID).select('span.dragged')[0].remove();
					}
					//remove cloned copy
					if (this.next('.dragged')) { this.next('.dragged').remove(); }
					if (this.next('.cloned')) { this.next('.cloned').remove(); }
					if(this.getOffsetParent !=null)
					{						
						this.getOffsetParent().remove();
					}
				}
				else
				{
					if( this.getOffsetParent().select('textarea').length >  0 )
					{
						//this is the draggable from scheduling area, return it to unscheduleditems
						$$('.unscheduledItems')[0].insert(this.getOffsetParent());
					}
					else
					{
						//this is the draggable from google map area of trip scheduling page, 
						//remove marker and  remove node too
						hideMarker(this.getOffsetParent().select('.red')[0].innerHTML);
						this.getOffsetParent().remove();
					}
					if (this.next('.dragged'))
					{
						this.next('.dragged').remove(); 
					}
				}
			}
			if( typeof( setDirtyFlag ) != 'undefined' ) setDirtyFlag();
		});	
	}

	function rebindMapDraggableEvents()
	{
		/* This will ensure the grid is drawn poperly after refresh */
		$$('.results .detail .detailWrapper .draggable').each(function(node){

			if( node.select('a.close').length == 0 ) node.insert('<a href=\"#\" class="close">close</a><div class=\"roundedTop\"></div><div class=\"roundedBottom\"></div>')
			node.setStyle({position: 'relative'})
			
			new Draggable(node, {
				revert: 'true',
				scroll: window,
				onStart: function(){
					if (node.ancestors()[0].className == 'droppable') 
					{
						veilHeight = $$('.unscheduledItems')[0].getHeight() - 22 + 'px'
						veil.setStyle({
							height: veilHeight
						})
						veil.show()
					}
				}
			});
			
			node.select('a.close').invoke('observe','click',function(e){
				Event.stop(e);
				hideMarker(this.getOffsetParent().select('.red')[0].innerHTML);
				node.remove();
			});	
			
		});		
	}
	
	var veil;
	/* bind dates blocks which are droppables */
	function rebindDroppables()
	{
		if ($$('.unscheduledItems').length > 0) {
			if(!veil) veil = $(document.createElement("div"));
			veil.addClassName('veil');
			if (document.attachEvent) {
				veil.setStyle({
					top: '242px',
					left: '265px',
					border: '1px #cbcaca solid'
				})
			} else {
				veil.insert('<div class=\"veilTop\"></div><div class=\"veilBottom\"></div>')
			}
			veil.hide();
			$$('.unscheduledItems')[0].appendChild(veil);
		}
	
		$$('.droppable').each(function(drop){
		
		if (!(drop.hasClassName('unscheduledItems'))){
			drop.insert('<div class=\"roundedTop\"></div><div class=\"roundedBottom\"></div>');
			
		}

		Droppables.add(drop, {
			onDrop: function(drag){
				
				if ((drag.select('.dragged').length < 1) && (!(drop.hasClassName('unscheduledItems')))) 
				{
					lightBox('chooseDates', $$('.chooseDates')[0].innerHTML + '{}' + drag.id + '{}' + drop.id, 'true', $$('.chooseDates')[0]);
					drag.insert('<span class=\"dragged\"></span>')
					
					$$('.clickTrap .chooseDates .selectAll .checkBox').each(function(node){
						node.observe('click', function(e){
							var checkValue = node.checked;
							$$('.dates input').each(function(node){
								node.checked = checkValue;
							})
							
						})
					})
/*CVLX added */
					$$('.clickTrap .chooseDates .button-addToItinerary2').each(function(node)
					{
						node.observe('click', function(e)
						{
							var bCheck=false;
							var dateSelected = drag.id + ',';
							$$('.clickTrap .chooseDates .dates input').each(function(node2){
								if( node2.checked == true )
								{
									if(dateSelected.indexOf(node2.id) < 0 ) dateSelected = dateSelected + node2.id + ',';
									bCheck=true;
								}
							})
							if( bCheck == false )
							{
							
							
								$$('.datemsg')[1].innerHTML='Please select atleast one date';
								
								return false;
							}
							else
							{
								Event.stop(e);							
							}
							
							//clean up old checkmarks if any
							$$('.clickTrap .chooseDates .dates input').each(function(node3){
								node3.checked = false;
							})
							$$('.clickTrap .chooseDates .selectAll .checkBox').each(function(node4){
								node4.checked = false;
							})
							$$('div.lightBox')[0].remove();
							$$('.clickTrap')[0].hide();
							
							//clone nodes to user selected dates boxes
							CopyItemsIntoDates(dateSelected);
							
							//bind behavior to cloned nodes.
							$$('div.scheduledItems div.draggable').each(function(node)
							{
								
								bindBehaviorToCloseBtn(node, deleteConfirmContent);
							});
							$$('div.scheduledItems div.draggable div.note textarea').each(function(node)
							{
								setupNotesAreaForEventHandling(node);
							});
						});
					})
				}
				veil.hide()
				
				if ((drag.select('.dragged').length > 0) && (drop.hasClassName('unscheduledItems'))) 
				{
					alert('Use Close button \'X\' to unschedule recommendations');
					return false;
				}
/*CVLX added END */				
				
				

				drop.setStyle({
					'opacity': '1',
					'filter': 'alpha(opacity = 100)'
				})
				
				var offTotalPar = drop.cumulativeOffset();
				var offTotalEle = drag.cumulativeOffset();

			// Include 2x 2px border
				drag.setStyle({
					top:  offTotalEle.top -offTotalPar.top -1*2+'px',
					left: offTotalEle.left-offTotalPar.left-1*2+'px'
				});

				drop.insert(drag);

			},
			onHover: function(){
				if(drop.className == 'droppable') {
					drop.addClassName('over');
				}
			},
			onUnhover: function(){
				if(drop.hasClassName('droppable')) {
					drop.removeClassName('over');
				}
			}
		});
		
	});
	}


/* END LOAD FUNCTION */
function initSwapInput(node){
	node.setAttribute("initValue", node.value);
	node.onfocus = function(){ swapFocus(this); }
	node.onblur = function(){ swapBlur(this); }
	node.onclikc = function(){alert('hi');}
}
/* *************************************************************************
=SWAP FOCUS/SWAP BLUR
resets input text when users clicks in/out of input field
*
************************************************************************ */
var input2;
function swapFocus(input){
    var value = input.readAttribute("initValue");
	//input.setAttribute('type', 'password');

	if(value=='password')
	{
		
		input2= input.cloneNode(false);
		input2.type='password';	

		input.parentNode.replaceChild(input2,input);	
		input2.value = "";
		
		setTimeout(timeoutFun, 10);
		
		
	}
    else if(input.value == value){
		
        input.value = "";
    }
}
function timeoutFun()
{

input2.focus();
}
function swapBlur(input, value){
	var value = input.readAttribute("initValue");
    if(input.value == ""){
        input.value = value;
    }
}

/*************************************
= Preoad Images
*************************************/
var preloaded = new Array();
function preload_images() {
    for (var i = 0; i < arguments.length; i++){
        preloaded[i] = document.createElement('img');
        preloaded[i].setAttribute('src',arguments[i]);
    };
};

preload_images(
    '/_layouts/1033/images/MyChicagoTrip/objects/hotdog-o.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/bball-o.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/baseball.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/baseball-o.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/football-o.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/hockey-o.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/bean-o.png',
    '/_layouts/1033/images/MyChicagoTrip/objects/picasso-o.png'
);



var QuestionnaireFormSupport = Class.create();
QuestionnaireFormSupport.prototype = {
	initialize: function(element) {
        /* set properties */
        this.pageValidation = { 
            1: { 
                valid: false,
                containerEl: $('formCarouselPane_1'), 
                validationObjs: new Array() 
            },
            2: { 
                valid: false,
                containerEl: $('formCarouselPane_2'),
                validationObjs: new Array()
            },
            3: {
                valid: false,
                containerEl: $('formCarouselPane_3'),
                validationObjs: new Array() 
            }
        };
        this.validationClassNames = new Array('validate_number','validate_required');
        this.setupValidation();

        /* Questionnaire Step 1 */
        this.selectReasonBusiness = $$('.trip_select_reason_business')[0];
        this.selectReasonBusiness_level2 = $$('.trip_reason_business')[0];
        this.businessContent_level2 = $$('.trip_content_reason_business')[0];
        this.businessContent_level3 = $$('.trip_content_reason_business_2');
        this.selectReasonPersonal = $$('.trip_select_reason_personal')[0];
        this.selectReasonPersonal_level2 = $$('.trip_reason_personal')[0];
        this.personalContent_level2 = $$('.trip_content_reason_personal')[0];
        this.personalContent_level3 = $$('.trip_content_reason_personal .option-description');
        
        /* Questionnaire Step 2 */
        this.interestsCheckAll = $$('.trip_category_check_all')[0];
        this.interestsCheckBoxes = $$('.formSection .checkboxGrid input.checkbox');
        /* filter out the check_all checkbox */
        this.interestsCheckBoxes = this.spliceOutHavingClassName(this.interestsCheckBoxes,'trip_category_check_all');
        this.travelCompanions = $$('ul.travelCompanions li label');

        /* Questionnaire Step 3 */
        this.homeLocations = $$('ul.homeLocation li label');
        

        if (this.selectReasonBusiness && this.selectReasonBusiness_level2 && this.selectReasonPersonal && this.selectReasonPersonal_level2) {

            this.registerEvents();
        }

		if ($$('.valueVisitReason').length > 0) {
			var visitReason = $$('.valueVisitReason')[0].value.split(' ')

			if (visitReason[0]  == 'business') {
				if(visitReason[1] = 3)
					this.showBusiness(2);
				this.showBusiness(visitReason[1]);
			} else if (visitReason[0]  == 'personal') {
				if(visitReason[1] = 3)
					this.showPersonal(2);
				this.showPersonal(visitReason[1]);
			}
		}
		
		this.interestsCheckBoxes.each( function(el){
			if (el.checked)
				el.previous('label').addClassName('checked');
		})

		this.travelCompanions.each( function(el){
			if (el.previous('input').getValue() == 'on')
				el.addClassName('active');
		});

		this.homeLocations.each( function(el){
			if (el.next('input').getValue() == 'on')
				el.addClassName('active');
		});

    },
    setupValidation: function() {
        var validations;
        var container;
        var validationEls;
        var validationObjs;
        var vf;
        var classGroup;
        var nodeMatches; 
        var validationByType;

        for (step in this.pageValidation) {
            validationObjs = {};
            validations = this.pageValidation[step];
            container = validations['containerEl'];

            if (container) {
                //var classNameSelectors = this.getValidatorClassNames(container);
                //console.log("classNameSelectors: %a, container: %o",classNameSelectors,container);
                var classNamesByElement = this.getValidatorClassNames(container);
                //console.log("classNamesByElement: %o",classNamesByElement);

                for (el_type in classNamesByElement) {
                    validationEls = new Array();
                    nodeMatches = new Array();
                    classGroup = classNamesByElement[el_type]; 
                    //console.log("working over classname type %o, validationEls: %a, nodeMatches %a",classGroup,validationEls,nodeMatches);

                    //classNameSelectors.each(function(selector) {
                    for (i=0, j=classGroup.length; i<j; i++) {
                        nodeMatches = $$(classGroup[i]); 
                        //console.log("Matching %a nodeMatches for selector '%s'",nodeMatches,classGroup[i]);
                        nodeMatches.each(function(match) {
                            validationEls.push(match);
                        });
                        //console.log('validationEls: %a, nodeMatches: %a',validationEls,nodeMatches);
                    }
               
                    if (el_type === "radio" || el_type === "checkbox") {
                        validationObjs[el_type] = {};
                        validationByType = validationObjs[el_type];
                        //console.log("validationByType: %o",validationByType);
                        for(i=0, j=validationEls.length; i<j; i++) {
                            var el = validationEls[i];
                            var name = el.name;
                            //console.log('looking at form element name attribute as "%s" for el %o',name,el);
                            var type = typeof validationByType[name];
                            //console.log('typeof validationByType[name] "%s"',type);
                            if (type === "undefined") {
                                validationByType[name] = new Array();
                                if ((el.nodeName)) {
                                    validationByType[name].push(el);
                                }
                                //var vBT = validationByType[name];
                                //console.log('vBT as %o',vBT);
                                //vBT[name].push(el);
                                //console.log('testing reference to validationObjs[el_type][name]: %a',validationByType[name]);
                            } else {
                                if ((el.nodeName)) {
                                    validationByType[name].push(el);
                                }
                            }
                            //console.log('*** For el_type %s, we built validationByType[name] %a',el_type,validationByType[name]);
                        }
                        //console.log('*** We built validationByType %o',validationByType);
                        for(inputName in validationByType) {
                            var elements = validationByType[inputName];
                            //console.log('+++iterating over inputName %s, with elements %o',inputName,elements);
                            if ((typeof elements != "function") && (elements.length > 0)) { // AVOID prototype.js collision
                                //console.log('++checkbox and radio arrays: setting up validation instance: %a',elements);
                                vF = new ValidatedField({ elementDOM: elements, parentDOM: container });
                                validationObjs[el_type][inputName]['__object'] = vF;
                                //validationObjs[el_type][inputName].push(vF);
                            }
                        }
                    } else {
                        validationObjs[el_type] = new Array();
                        //create individual validation objects for each field
                        validationEls.each(function(el) {
                            vF = new ValidatedField({ elementDOM: el, parentDOM: container });
                            validationObjs[el_type].push(vF);
                        });
                    }


                }
                
                //update property
                validations.validationObjs = validationObjs;
            }
        }
    },
    getValidatorClassNames: function(container) {
        var formSelectorStr;
        var validationFormRefs = { 
            radio: new Array(),
            checkbox: new Array(),
            select: new Array(),
            input_text: new Array(),
            input_hidden: new Array(),
            textarea: new Array()
        }
        this.validationClassNames.each(function(className){
            //console.log('validator: %o',this.validators[validator]);
            //var formSelectorStr = '#' + container.id + ' .' + className;
            //validationFormRefs.push(formSelectorStr);

            /* radio */
            formSelectorStr = '#' + container.id + ' input[type=radio].' + className;
            validationFormRefs['radio'].push(formSelectorStr);

            /* checkbox */
            formSelectorStr = '#' + container.id + ' input[type=checkbox].' + className;
            validationFormRefs['checkbox'].push(formSelectorStr);

            /* select */
            formSelectorStr = '#' + container.id + ' select.' + className;
            validationFormRefs['select'].push(formSelectorStr);

            /* input_text */
            formSelectorStr = '#' + container.id + ' input[type=text].' + className;
            validationFormRefs['input_text'].push(formSelectorStr);

            /* input hidden */
            formSelectorStr = '#' + container.id + ' input[type=hidden].' + className;
            validationFormRefs['input_hidden'].push(formSelectorStr);

            /* textarea */
            formSelectorStr = '#' + container.id + ' textarea.' + className;
            validationFormRefs['textarea'].push(formSelectorStr);
        });
        return validationFormRefs;
    },
    registerEvents: function() {
        var self = this;

        /* Business */
		Event.observe(this.selectReasonBusiness, "mouseover", function(){ self.selectReasonBusiness.addClassName('reason_business_hover'); });
		Event.observe(this.selectReasonBusiness, "mouseout", function(){ self.selectReasonBusiness.removeClassName('reason_business_hover'); });
		Event.observe(this.selectReasonBusiness, "click", function(){ self.showBusiness(2); });

		Event.observe(this.selectReasonBusiness_level2, "change", function(){ self.showBusiness(3); });

        /* Personal */
		Event.observe(this.selectReasonPersonal, "mouseover", function(){ self.selectReasonPersonal.addClassName('reason_personal_hover'); });
		Event.observe(this.selectReasonPersonal, "mouseout", function(){ self.selectReasonPersonal.removeClassName('reason_personal_hover'); });
		Event.observe(this.selectReasonPersonal, "click", function(){ self.showPersonal(2); });

		Event.observe(this.selectReasonPersonal_level2, "change", function(){ self.showPersonal(3); });

        /* Interests */
		Event.observe(this.interestsCheckAll, "click", function(){
			self.toggleCheckBoxElements(self.interestsCheckAll,self.interestsCheckBoxes);
		});
		
		this.interestsCheckBoxes.invoke('observe','click',function(e){
			if (this.checked) {
				this.previous('label').addClassName('checked');
			} else {
				this.previous('label').removeClassName('checked');
			}
		})

        /* Travel Companions */
        this.travelCompanions.each( function(el){
		    Event.observe(el, "mouseover", function(){ this.addClassName('hover'); });
		    Event.observe(el, "mouseout", function(){ this.removeClassName('hover'); });
		    Event.observe(el, "click", function(){ self.makeRadioSelection(this,self.travelCompanions); });
        });

        /* Home Location */
        this.homeLocations.each( function(el){
		    Event.observe(el, "mouseover", function(){ this.addClassName('hover'); });
		    Event.observe(el, "mouseout", function(){ this.removeClassName('hover'); });
		    Event.observe(el, "click", function(){ self.makeRadioSelection(this,self.homeLocations); });
        });

    },
    goToStep: function(nextStep) {
        var step = nextStep - 1;
        this.doValidations(step);

        var validation = this.pageValidation[step];
        var valid = validation['valid'];
        //console.log('goToStep(): testing against validation value %o, value %s',validation,valid);

       /* does our current step pass validation? */
        if (valid) {
            /* external object */
            if (typeof FormCarouselPane_Slider != "undefined") { 
                FormCarouselPane_Slider.goToPage(nextStep);
            }
            if (typeof FormProgressIndicator != "undefined") {
                FormProgressIndicator.animateToStep(nextStep);
            }

        }
    },
    doValidations: function(step) {
        //console.log('doValidations(%s)...',step);
        var validationStep = this.pageValidation[step];
        var validationObjs = validationStep['validationObjs'];
        //console.log('LOOKING for in %o validationStep[\'validationObjs\'] %o',validationStep,validationObjs);
        //console.log('validationStep: %o',validationStep);
        var valid;
        var validatorsCollected = new Array();
        
        //set validation to pass so we can 'cancel' at any time
        //validationStep.valid = true;
        validationStep.valid = true;

        /* collect validator objects from hash */
        for (type in validationObjs) {
            //console.log('working with type %s',type);
            if ((type === "checkbox") || (type === "radio")) {
                //console.log('working with validator %o',validator);
                for (name in validationObjs[type]) {
                    var validator = validationObjs[type][name]['__object'];
                    //console.log('working with validator %o',validator);
                    validatorsCollected.push(validator);
                }
            } else {
                validationObjs[type].each(function(validator){
                    //console.log('working with validator %o',validator);
                    validatorsCollected.push(validator);
                });
            }
        }

        /* access validator objects, do the validation */
        //console.log('&&&&& validatorsCollected as %a',validatorsCollected);
        validatorsCollected.each(function(validator){
            validator.validate();
            if (!(validator.valid)) {
                validationStep.valid = false;
                //console.log('QuestionnaireFormUI: validator %o is not valid.',validator);
            }
        });
          
    },
    makeRadioSelection: function(el,group) {
        var self = this;
        //console.log("makeRadioSelection(): running with %o and %a",el,group);

        /* remove any other active states */
        group.each(function(el){ 
            el.removeClassName('active');
            self.checkRadios(el,false);
        }); 
        /* set new active state */
        el.addClassName('active');
        this.checkRadios(el,true);

    },
    checkRadios: function(el,newCheckedState) {
        /* find associated radio 
           identify by markup order and element type instead of id
           in case id is changed during integration */
        
        el.siblings().each(function(sibling) {
            var sib_tag = sibling.nodeName.toLowerCase();

            if (sib_tag === 'input') {
                var sib_type = sibling.type.toLowerCase();

                if (sib_type === "radio") {
                    //console.log("checking %s state of radio %o",newCheckedState,sibling);
                    //alert("checking "+newCheckedState+" state of radio "+sibling);
                    sibling.checked = newCheckedState;
                }
            }
        });

    },
    showBusiness: function(level) {
        /* disable personal section */
        this.personalContent_level2.hide();
        this.selectReasonPersonal.removeClassName('reason_personal_active');

        /* activate business section */
        this.selectReasonBusiness.addClassName('reason_business_active'); 

        var index = this.selectReasonBusiness_level2.selectedIndex;

        if (level == 2) {
            this.businessContent_level2.show();
            this.businessContent_level3.each( function(el){ el.hide(); });
			if (index > 0)
				this.businessContent_level3[index-1].show();
        } else if (level == 3) {
            this.businessContent_level3.each( function(el){ el.hide(); });
            /* avoid first dropdown option as it is default 'Select' */
			if(index==1)	
				FillConvDropdown();
            if (index > 0)
            	this.businessContent_level3[index-1].show();
        }

		$$('.valueVisitReason')[0].value = 'business ' + level;
    },
    showPersonal: function(level) {
        /* disable business section */
        this.businessContent_level2.hide();
        this.selectReasonBusiness.removeClassName('reason_business_active');
        this.businessContent_level3.each( function(el){ el.hide() });

        /* activate personal section */
		
        this.selectReasonPersonal.addClassName('reason_personal_active'); 
        if (level == 2) {
            this.personalContent_level2.show();
        } else if (level == 3) {
            var index = this.selectReasonPersonal_level2.selectedIndex;
            this.personalContent_level3.each( function(el){ el.hide(); });
            /* avoid first dropdown option as it is default 'Select' */
            if (index > 0) {
                this.personalContent_level3[index-1].show();
            }
        }
		$$('.valueVisitReason')[0].value = 'personal ' + level;
    },
    spliceOutHavingClassName: function(elements,className) {
        var elementsCopy = elements.slice(0);
        var spliceIndices = new Array();
        elementsCopy.each( function(el,i){
            if (el.hasClassName(className)) {
                spliceIndices.push(i); 
            }
        });
        spliceIndices.each ( function(index){
            elementsCopy.splice(index,1);
        });
        return elementsCopy;
    }, 
    toggleCheckBoxElements: function(parent,elements) {
        elements.each( function(el) {
            if (parent.checked)
			{
                if( el.disabled == false )
				{
					el.checked = "checked";
					if (!(el.previous('label').hasClassName('checked'))) {
						el.previous('label').addClassName('checked')
					}
				}
            } else {
                el.checked = "";
				if (el.previous('label').hasClassName('checked')) {
					el.previous('label').removeClassName('checked')
				}
            }
        });
    },
	destroy: function() {
    }
}

var ValidatedField = Class.create();
ValidatedField.prototype = {
	initialize: function(ArgumentsObj) {
        /* Argument Defaults */
        var NewArguments = {
            elementDOM: false,
            parentDOM: false,
            msgClassName: 'jsvalidation' 
        }

        /* Replace Default Args */
        for (var argName in ArgumentsObj) {
            NewArguments[argName] = ArgumentsObj[argName];
        }
        
        /* Set Properties */
        this.elementDOM = NewArguments['elementDOM'];
        this.parentDOM = NewArguments['parentDOM'];
        this.msgClassName = NewArguments['msgClassName']; 
        this.customMessage = false;
        this.msgDOM = false;
        this.valid = false;
        this.validators =  {
            validate_number: {
                defaultMessage: "This field must have a numerical value.",
                regExp: /^[-]?\d+(\.\d+)?$/
            },
            validate_required: {
                defaultMessage: "Please answer all questions",
                regExp: /^.+$/
            }
        };
        //console.log('ValidatedField: init new object for element %o',this.elementDOM); 
        this.createMessageHTML();

    },
    validate: function() {
        var self = this;
        var el_type;
        var el_tag;
        var el_case;
        var usingValidatorType;
        var el_value;
        var elRef;

        /* re-set default state in case form element 
           has changed since last validation */
        this.valid = false;

        //console.log('ValidatedField: object for el %o doing validation',this);
        //console.log("this.elementDOM: %o,",this.elementDOM);
        if (this.elementDOM.nodeName) {
            elRef = this.elementDOM;
        } else {
            elRef = this.elementDOM[0];
        }
        el_tag = elRef.nodeName.toLowerCase();
        el_type = elRef.type.toLowerCase();

        if (el_tag === "input") {
            el_case = el_type;
        } else {
            el_case = el_tag;
        }

        //Early return: pass validation for fields that are hidden and not <input type="hidden" />
        if (el_case != "hidden") {
            if ((elRef.style.display === 'none') || (elRef.parentNode.style.display === 'none')) {
                //console.log('ValidatedField.validate(): either field or parent is hidden, passing validation on %o',this);
                this.valid = true;
                return;
            }
        }

        //console.log('el_type: "%s"; el_tag "%s"',el_type,el_tag);
        if (el_case === "radio" || el_case === "checkbox") {
                if (usingValidatorType = this.elementDOM[0].className.match(/validate_\w+/)) {
                    /* ignore specific validator class assigned, just require 
                    one radio or checkbox in the set to be checked */
                    //console.log('ValidatedField.validate(): validating a %s...',el_case);

                    var self = this;
                    this.elementDOM.each(function(input){
                        //console.log("checking radio %o for checked value %s",input,input.checked);
                        if (input.checked == true) { 
                            //console.log("mark it valid!");
                            self.valid = true;
                        }
                    });

                    //console.log("this.valid %s",this.valid);
                    if (this.valid == true) {
                        this.updateMessageHTML(' ');
                        this.msgDOM.style.display = 'none';
                    } else {
                        this.updateMessageHTML(this.validators[usingValidatorType].defaultMessage);
                        this.msgDOM.style.display = '';
                    }
                }
        } else if (el_case === "select") {
                if (usingValidatorType = this.elementDOM.className.match(/validate_\w+/)) {
                    /* ignore specific validator class assigned , just require anything
                    but the first and default option */
                    var selectOrig = this.elementDOM.options[0];
                    var selectActive = this.elementDOM.options[this.elementDOM.selectedIndex];

                    //console.log('ValidatedField.validate(): validating a select, set to option "%s", orig val "%s".',selectActive.text,selectOrig.text);
                    if (selectActive.text === selectOrig.text) {
                        this.updateMessageHTML(this.validators[usingValidatorType].defaultMessage);
                        this.msgDOM.style.display = '';
                    } else {
                        this.valid = true;
                        this.updateMessageHTML(' ');
                        this.msgDOM.style.display = 'none';
                    }
                }
        } else {
                if (usingValidatorType = this.elementDOM.className.match(/validate_\w+/)) {
                    /* general case, text input and textarea */
                    var regex = this.validators[usingValidatorType].regExp;
                    //console.log('ValidatedField.validate(): usingValidatorType "%s", testing field value "%s" against regex "%s"',usingValidatorType,this.elementDOM.value,regex); 
                    if (this.elementDOM.value.match(regex)) {
                        this.valid = true;
                        this.msgDOM.style.display = 'none';
                        this.updateMessageHTML(' ');
                    } else {
                        this.updateMessageHTML(this.validators[usingValidatorType].defaultMessage);
                        this.msgDOM.style.display = '';
                    }
                }
        }
    },
    createMessageHTML: function() {
        var msgEl = document.createElement('span');
        var msgTxt = document.createTextNode(' ');
        msgEl.appendChild(msgTxt);
        msgEl.className = this.msgClassName;
        this.insertMessageHTML(msgEl);
    },
    updateMessageHTML: function(message) {
        if (!(this.customMessage)) {
            this.msgDOM.innerHTML = message;
        }
    },
    insertMessageHTML: function(msg){
        //console.log('ValidatedField(): for object %o, this.elementDOM: %o',this,this.elementDOM);
        var customClassName = 'validate_custom_message';
        var customMessage = false;
        var elRef;
        var elMsg;

        if (this.elementDOM.nodeName) {
            elRef = this.elementDOM;
           //console.log('1:1 form element: have elRef as %s; classNames: %s',elRef.nodeName,elRef.className);
        } else {
            /* is checkbox or radio array */
            var lastChild = this.elementDOM.length - 1;
            if (this.elementDOM[lastChild].hasClassName(customClassName)) {
                lastChild = this.elementDOM.length - 2;
            }
            elRef = this.elementDOM[lastChild];
           //console.log('ValidatedField(): have elRef as %o, from this.elementDOM %a',elRef,this.elementDOM);
        }

        var peers = $(elRef.parentNode).childElements();
        var indexElementDOM = false;
        //console.log('peers.length %s as %a',peers.length,peers);

        var nextSibling = elRef.nextSiblings()[0];
        //console.log("...nextSibling as %o",nextSibling);

        // only append message element if we don't have a custom message element
        // already in the document identified as the next sibling with matching className
        if ((nextSibling) && (nextSibling.hasClassName(customClassName))) {
            this.customMessage = true;
            //console.log('found custom message element for elRef %o',elRef);
        } else {
            if (peers.length == 1) { 
                /* for single-field validation: append to end of parent */
                elRef.parentNode.appendChild(msg); 
                //console.log('elMsg in soup as %o, among peers %a',elMsg,elRef.parentNode.childElements());
            } else {
                /* within a collection of elements: append right after the 
                   form element node, after working out a reference to the position */
                for(i=0, j=peers.length; i<j; i++) {
                    if ((peers[i].nodeType == 1) && (peers[i].id === elRef.id)) {
                        indexElementDOM = i;
                    }
                }
                //console.log('indexElementDOM: %s, in peers as peers[indexElementDOM] %o',indexElementDOM,peers[indexElementDOM]);
                if (indexElementDOM) {
                    if (indexElementDOM == (peers.length-1)) {
                        /* form el is the last child, append to the end */
                        //console.log('last child, appending to end...');
                        elRef.parentNode.appendChild(msg); 
                    } else {
                        /* form el is surrounded by peers, append after form el */
                        var index = indexElementDOM + 1;
                        //console.log('doing insertBefore with content %o before el %o, ahead of %o',msg,peers[index],peers[indexElementDOM]);
                        elRef.parentNode.insertBefore(msg,peers[index]); 
                    }
                }
            }
        }

        /* refence message DOM object for assign as property */ 
        elMsg = $(elRef.parentNode).getElementsByClassName(this.msgClassName)[0];
        this.msgDOM = elMsg; 
        this.msgDOM.style.display = 'none';
    },
    destroy: function() {
        this.ArgumentsObj = null;
        this.NewArguments = null;
        this.valid = null;
        this.elementDOM = null;
        this.msgDOM = null;
    }
}
 
var ProgressSlider = Class.create();
ProgressSlider.prototype = {
	initialize: function(element) {
        this.element_status = element;
        this.element_parent = element.parentNode;
        this.determineNumberSteps();
        this.currentStep = 0;
        this.goToStep(0);
    },
    determineNumberSteps: function() {
        var adjacentElements = this.element_status.adjacent('li');
        this.numberSteps = adjacentElements.length;
        this.totalWidth = this.element_parent.offsetWidth;
        this.stepWidth = parseInt(this.totalWidth/this.numberSteps);
        //console.log("have adjacentElements as %a, numberSteps as %s, stepWidth: %s",adjacentElements,this.numberSteps,this.stepWidth);
    },
    goToStep: function(step) {
        var newTotalWidth = this.stepWidth * step;
        var newTotalWidthStr = newTotalWidth+'px';
        this.element_status.style.width = newTotalWidthStr;
        this.currentStep = step;
    },
    animateToStep: function(step) {
        var newTotalWidth = this.stepWidth * step;
        var newTotalWidthStr = newTotalWidth+'px';
        new Effect.Morph(this.element_status, {
            style: {
                width: newTotalWidthStr
            }, // CSS Properties
            duration: 0.8 // Core Effect properties
        });
        this.currentStep = step;
    },
    stepForward: function() {
        if (this.currentStep < this.numberSteps) {
        this.goToStep(this.currentStep + 1);
        }
    },
    stepBackward: function() {
        if (this.currentStep > 0) {
            this.goToStep(this.currentStep - 1);
        }
    },
	destroy: function() {
        this.element_status = null;
        this.element_parent = null;
        this.currentStep = null;
        this.numberSteps = null;
        this.totalWidth = null;
        this.stepWidth = null;
	}
}

var Tooltip = Class.create();
Tooltip.prototype = {

	initialize: function(element, tool_tip) {

		var tailFlipPosition;
		var leftPosition;
	
		if (element.descendantOf($$('.header')[0])) {
			tailFlipPosition = 107;
			leftPosition = 0;
		}
		else if ($$('.factoid_chicagoSign').length > 0 && element.descendantOf($$('.factoid_chicagoSign')[0])) {
			tailFlipPosition = 40;
			leftPosition = -110;
		}
		 else {
			tailFlipPosition = 0;
			leftPosition = 0;
		}
		
		var options = Object.extend({
			default_css: false,
			margin: "0px",
			padding: "5px",
			backgroundColor: "#d6d6fc",
			min_distance_x: 5,
			min_distance_y: 5,
			delta_x: leftPosition,
			delta_y: tailFlipPosition,
			zindex: 1000
		}, arguments[2] || {});

		this.element      = $(element);

		this.options      = options;

		// use the supplied tooltip element or create our own div
		if($(tool_tip)) {
			this.tool_tip = $(tool_tip);
		} else {
			this.tool_tip = $(document.createElement("div")); 
			document.body.appendChild(this.tool_tip);
						
			if (element.descendantOf($$('.header')[0])) {
				this.tool_tip.addClassName("tooltipFlip");
				
			} 
			else if ($$('.factoid_chicagoSign').length > 0 && element.descendantOf($$('.factoid_chicagoSign')[0])) {
				this.tool_tip.addClassName("tooltipLeft");
			}
			else {
				this.tool_tip.addClassName("tooltip");
			}

			this.tool_tip.insert(tool_tip);

		}

	// hide the tool-tip by default
		this.tool_tip.hide();

		this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
		this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
		this.eventMouseMove  = this.moveTooltip.bindAsEventListener(this);

		this.registerEvents();
	},

	destroy: function() {
		Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
		Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
		Event.stopObserving(this.element, "mousemove", this.eventMouseMove);
	},

	registerEvents: function() {
		Event.observe(this.element, "mouseover", this.eventMouseOver);
		Event.observe(this.element, "mouseout", this.eventMouseOut);
		Event.observe(this.element, "mousemove", this.eventMouseMove);
	},

	moveTooltip: function(event){
		Event.stop(event);
		// get Mouse position
		var mouse_x = Event.pointerX(event);
		var mouse_y = Event.pointerY(event);

		// decide if we need to switch sides for the tooltip
		var dimensions = Element.getDimensions( this.tool_tip );
		var element_width = dimensions.width;
		var element_height = dimensions.height;

		mouse_x = mouse_x + this.options.min_distance_x;
		mouse_y = mouse_y + this.options.min_distance_y;

		// now set the right styles
		this.setStyles(mouse_x, mouse_y);
	},


	showTooltip: function(event) {
		Event.stop(event);
		this.moveTooltip(event);
		iframe = '<!--[if lt ie 7]><iframe id=\"ttFrame\" style=\"filter:mask(); position: absolute; top: 0; left: 0; z-index: 999; width: 100%; height: ' + this.tool_tip.getHeight() + 'px;\" src=\"javascript:\'<html></html>\';\" frameborder=\"0\" scrolling=\"no\"></iframe><![endif]-->';
		this.tool_tip.insert({top:iframe});
		this.tool_tip.insert('<div class=\"ttTail\"></div>')
		new Element.show(this.tool_tip);
		
	},

	setStyles: function(x, y){

		//for the header tool tips, this checks their height
	
		var topPosition;
		if(this.options.delta_y == 107){
			topPosition = y + 28 +"px";
		}
		else{ topPosition = y + this.options.delta_y - this.tool_tip.getHeight() - 28 + "px"; }
	

		// set the right styles to position the tool tip
		Element.setStyle(this.tool_tip, {
			position:'absolute',
			//top:y + this.options.delta_y - this.tool_tip.getHeight() - 28 + "px",
			top: topPosition,
			left:x + this.options.delta_x - 78 + "px",
		    zindex:this.options.zindex
		});

		// apply default theme if wanted
		if (this.options.default_css){
			Element.setStyle(this.tool_tip, {
				margin:this.options.margin,
				padding:this.options.padding,
				backgroundColor:this.options.backgroundColor,
				zindex:this.options.zindex
			});	
		}	

	},

	hideTooltip: function(event){
	    if($('ttFrame')){
			$('ttFrame').remove();
		}
		new Element.hide(this.tool_tip);
	},

	getWindowHeight: function(){
		var innerHeight;
		if (navigator.appVersion.indexOf('MSIE')>0) {
			innerHeight = document.body.clientHeight;
		} else {
			innerHeight = window.innerHeight;
		}
		return innerHeight;	
	},

	getWindowWidth: function(){
		var innerWidth;
		if (navigator.appVersion.indexOf('MSIE')>0) {
			innerWidth = document.body.clientWidth;
		} else {
			innerWidth = window.innerWidth;
		}
		return innerWidth;	
	}
	
}
