/*
if (window['loadFirebugConsole']) {
    window.loadFirebugConsole();
} else if (!window['console']) {
    window.console = {};
    window.console.info =
    window.console.log =
    window.console.warn =
    window.console.error = function(){}
} */
//(function ($) {
var RecaptchaOptions = {
    theme : 'clean'
};
    
    function createCookie( name, value, days) {
	if( days ) {
	    var date = new Date();
	    date.setTime( date.getTime() + (days * 24 * 60 * 60 * 1000) );
	    var expires = '; expires=' + date.toGMTString();
	} else {
	    expires = '';
	}

	document.cookie = name + '=' + value + expires + '; path=/';
    } // createCookie

    function readCookie( name ) {
	var nameEQ = name + '=';
	var ca = document.cookie.split( ';' );
	for( var i = 0; i < ca.length; i++ ) {
	    var c = ca[i];
	    while( c.charAt(0) == ' ' ) c = c.substring( 1, c.length );
	    if( c.indexOf( nameEQ ) == 0 ) return c.substring( nameEQ.length, c.length );
	}

	return null;
    } // readCookie

    function setRandomBodyBackground()
    {
	/* attempt to read the bg value from the cookie, otherwise randomize
	   and save our settings to a session cookie */
	var idx = readCookie( 'body-idx' );
        var bgSize   = backgrounds.length;
    if( idx == null && bgSize > 0 ) {
	    var idx = Math.floor( Math.random() * bgSize );
	    createCookie( 'body-idx', idx );
	}
	if( idx  != null) {
            var img_link = backgrounds[idx];
	    $('body').css( 'background-image', "url('" + img_link + "')" );
	}

        return;
    } // setRandomBodyBackground

    function setRandomFooterBackground()
    {
	var idx = readCookie( 'footer-idx' );
        var colorSize = footers.length;

	if( idx == null && colorSize > 0 ) {
	    idx = Math.floor( Math.random() * colorSize );
	    createCookie( 'footer-idx', idx );
	}
	if( idx !=null ) {
            color = footers[idx];
	    $('#footer .panel, #nav li .drop').css( 'background-color', color );
	}
	
        return;
    } // setRandomFooterBackground

    function initRoadblock()
    {
	//var roadblock_check = readCookie( 'roadblock-check' );
    var roadblock_check = false;
	if( (!roadblock_check || roadblock_check == null) ){
        if( (typeof roadblock_link) != 'undefined' && roadblock_link != '' ) {
    	 	$( '.home.roadblock .box' ).bind( 'click.roadblock', function () {
	    		window.location = roadblock_link; 
	        });
        }
        else{
            $( '.home.roadblock .box' ).bind( 'click.roadblock', function () {
                $( '.roadblock' ).removeClass( 'roadblock' );
                $(this).unbind('click.roadblock');	
            });
        }
  		//createCookie( 'roadblock-check', 1 );
	}
	else {
            $( '.roadblock' ).removeClass( 'roadblock' );
            $(this).unbind('click.roadblock');	
	}
    } // initRoadblock

    function positionColorbox() {
	$('#colorbox').css('left', (( ( $(window).width() - ($(window).width() - $("#wrapper").width())  )- $('#colorbox').width()) / 2));
	$('#colorbox').css('top', 100);
        //reposition title
        var caption_height =  $("#cboxTitle").height();
        if(caption_height == 0){return;}
        var colorbox_height = $('#colorbox').height() + 40 + caption_height;
        $('#colorbox').css("height", colorbox_height);
        $('#cboxContent').css("height", colorbox_height);
        $('#cboxWrapper').css("height", colorbox_height);
    }
    
    function initPhotoSlideshow()
    {
        $( '.gallery li a' ).colorbox({
            title: function(){
                var title = $(this).find(".caption");
                return title.text();
            },
            loop: false,
            rel: 'group1',
            transition: 'none',
			onLoad: function () {
				//positionColorbox();
			
			},
			onComplete: function () {
				$(window).unbind('resize.cbox');
				positionColorbox();
			
			},
            onOpen: function () {
                $( '#cboxDownload' ).remove();
                var downloadHTML = '<div id="cboxDownload">DOWNLOAD</a>';
                $( '#cboxContent' ).append( downloadHTML );
                $( '#cboxDownload' ).click( function () {
                    var item = $.colorbox.element();
                    var originalImage = item.find( '.original-image' );
                    var originalImageURL = originalImage.text();
                    
                    window.open( originalImageURL );
                    return false;
                } );

            }
        });
        //INITIALIZING PAGER for slideshow
        $('.paginate-container').variablePaginate({
            limiter:4,
            paginateHandler: "li"
        });
    } // initPhotoSlideshow

    function initSearchBox()
    {
	if($('.search input[type=text]').attr('value') != '' && $('.search input[type=text]').attr('value') != 'Search'){
		$('.search input[type=text]').css('color','#000000');
	}
        $('.search input[type=text]').focus( function () {
            if( this.value == 'Search'){
                this.value = '';
		$(this).css('color',"#000000");
	    }
        }).blur( function () {
            if( this.value == '' ){
                this.value = 'Search';
		$(this).css('color',"#A1A3A5");
	    }
        });
        
    } // initSearchBox

    function initSideBarAlign(){
	if($('.aside').length == 0 || $('.aside > h3 + * ').length == 0 || $('.alignment_header').length == 0){
		return false;
	}
	var padding_adjust = $('.aside > h3 + *').position().top;
	padding_adjust -= ($('.alignment_header + *').position().top );
	padding_adjust -= parseInt($('.alignment_header+ *').css('margin-top').substr(0,($('.alignment_header+ *')).css('margin-top').length-2));
	padding_adjust = parseInt($('.aside').css('padding-top').substr(0, $('.aside').css('padding-top').length-2)) - padding_adjust;
	padding_adjust = Math.round(padding_adjust);
	$('.aside').css('padding-top', padding_adjust);
    } // initSideBarAlign

    var newsletter_def_vals = ['Email address', 'First Name','Last Name', 'Address', 'Second Address', 'City', 'Zip Code'];
    function initNewsLetterForm(){
	$('.input_additional').hide();
	if($('.input_checkbox').attr('checked')){
		$('.input_additional').show();
		$('.input_email').addClass('input_email_wide');
		$('.input_email').removeClass('input_email');
		$('.input_join').hide();
	}
	
	$('.input_checkbox').bind('click', function(){
		if($(this).attr('checked')){
			$('.input_additional').show();
			$('.input_email').addClass('input_email_wide');
			$('.input_email').removeClass('input_email');
			$('.input_join').hide();
		}
		else{
			$('.input_additional').hide();
			$('.input_email_wide').addClass('input_email');
			$('.input_email_wide').removeClass('input_email_wide');
			$('.input_join').show();
		}
	});
	$('.signup_box form input[type=text]:not(#recaptcha_response_field').each(function(index, element){
		var temp_value;
		temp_value = newsletter_def_vals[index];
		/*dealing with color if the form has content when user refreshes page*/
		if(element.value!='' && element.value != temp_value){
			$(element).css('color','#000000');
		}
		$(element).focus( function(){
			if(this.value == temp_value){
				this.value='';
				$(this).css('color',"#000000");
			}
		}).blur(function (){
			if(this.value == ''){
				this.value = temp_value;
				$(this).css('color',"#A1A3A5");
			}
		}).change(function(){
			if(this.value == ''){
				this.value = temp_value;
				$(this).css('color',"#A1A3A5");
			}
		}).bind("ajaxComplete", function(){
            //on AjaxSend, trigger blur
            $(this).trigger("blur");
        }).trigger('blur');
	});
	$('.input_signup, .input_join').click(function(index, element){
		$('.signup_box form input[type=text]').each(function(index, element2){
			if(element2.value ==  newsletter_def_vals[index]){
				element2.value = '';
			}
            
		});
	});
    } // initNewsletterForm

    function showBody(){
	//s.parentNode && s.parentNode.removeChild( s ); 
	$('body').css("visibility","visible");
    } 
	
    // prevent the "Flash of Unstyled Text" (FOUT) in Firefox
    // adapted from http://paulirish.com/2009/fighting-the-font-face-fout/#defeatthefout
	
    function preventFOUT() {
	// if firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
	var d = document;
	var e = d.documentElement;
	var s = d.createElement( 'style' );
	if( e.style.MozTransform === '' ) { // gecko 1.9.1 inference
	    s.textContent = 'body{visibility:hidden}';
	    e.firstChild.appendChild( s );
	    function f() { s.parentNode && s.parentNode.removeChild( s ); }
	    addEventListener( 'load',f,false );
	    setTimeout( f, 3000 );
	}
    } // preventFOUT
	
	/*
	calculateHeightByLines takes an element (text_container) and iterates over all of its children. 
	It finds the total sum of all outHeight's of all of the children (essentially the height of the text_container.
	We then find the exact height that fit the lines neatly. 
	*/
	function calculateHeightByLines(text_container, target_height){
		var available_line_heights = [];
		var last_line_height;
		var ret_height = 0;
		var height_counter = 0;
		$(text_container).children('*').each(function(index, element){
			height_counter += $(element).outerHeight(true);
			last_line_height = parseInt($(element).css("line-height"));
			if(height_counter <= target_height){
				ret_height = height_counter; //only save height if its less than target height, finish 
				available_line_heights.push( parseInt($(element).css("line-height")));
			}
		});
		
		ret_height = ret_height + Math.ceil((target_height-ret_height)/last_line_height) * last_line_height;
		return {height: ret_height, line_height:last_line_height/2}; // divide by 2 is NEEDED FOR FLOORING because of custom font file
	}
	var def_dotify_height = 75;
	/*
	dotify expects 2 elements: <div class="dotify_item"><div class="dotify_bio"></div></div>
	it may or may not have an image withing the first div. If it does, the truncated height will match that
	of the image. If it does not have an image, it will use the default height specified above.

	Dotify also expects two anchor elements <a class=".more_btn"> and <a class=".less_btn"> respectively
	The default method of truncating the content is to stick both buttons within the content. 
	The more button is hidden when the full content is displayed, and vice versa.
	If the class "dotify_exception" is included within the root node (dotify_item), then the more and less btn
	will not be moved, and rather it is kept where it is originally placed. This is useful for cases
	when the buttons are part of a menu of sorts.

	If the truncated height happens to be larger than the available content, the function simply returns 
	without modification
	*/
	function dotify(element, index){
		var static = false;
		if($(element).hasClass("dotify_static")){ static=true;} 
			//if the node is static, we won't have javascription animate the truncation,rather, the link is a static link
			/*figuring out dotify exception*/
			var dotify_exception = false;
			var dotify_exception_height = 0;
		
			if($(element).find(".dotify_exception").length > 0){ 
				/*
				if theres an exception, then the element with that class 
				is a menu link element with more and less tags, these tags won't be
				inserted into the content
				*/
				dotify_exception = true;
				
			}
			/*figuring out img_height, or rather the height of content truncation*/
			var img_height;
			if($(element).find("img").length ==0){ img_height=def_dotify_height;}
			
			else if( ($(element).find("img").hasClass('additional-height')) ){
				img_height= $($(element).find("img")[0]).height() + def_dotify_height;
			}
			else{ img_height= $($(element).find("img")[0]).height();}
			
				img_height -= dotify_exception_height; 
				//if the menu is static, we need to account for the menu IF its within the truncated div
			var line_height; // = parseInt($($(element).find(".dotify_bio p")[0]).css("line-height"));
			var p_height = $(element).find(".dotify_bio").height(); 
				//The p_height is the total height of the content
			
			var target_height = calculateHeightByLines($(element).find(".dotify_bio"), img_height);
				//target_height is an obj with calculated line height and the trunc'd height
			line_height = target_height.line_height;
			
			var short_height = target_height.height;

			if(p_height<= short_height){ //if the target height is taller than the content, just return
				$(element).find(".less_btn").remove();
				$(element).find(".more_btn").remove();
				return; //if theres nothing to shrink or hide, just return

			} 
			
			//---- Finding the last word in the visible content box ----//
			var temp_obj = $(element).find(".dotify_bio"); //this is the obj we're truncating
			
			var more_tag = $('<div>').append($(element).find(".more_btn").clone()).remove().html();
				//save the html for the more_tag
			var more_string = dotify_exception? '' :$(element).find(".more_btn").html();
			var more_string_text = $(element).find(".more_btn").text();

			var less_tag = '';
			if(!static){
				less_tag = $('<div>').append($(element).find(".less_btn").clone()).remove().html();
				//if the menu isn't static, we also want to keep track of the less tag
			}

			
			if(!dotify_exception){
				//if we're not inserting the anchor/buttons within the content, 
				//we don't want to insert the less tag at the end of the content
				var less_inject_index = temp_obj.html().lastIndexOf("<");
				temp_obj.html(temp_obj.html().substr(0,less_inject_index)+less_tag + temp_obj.html().substr(less_inject_index));
			}
			var char_length = (parseInt(temp_obj.find("p").css("font-size"))/2);
				//an approximation/average of character width
			var temp_html = $(element).find(".dotify_bio").html();
				//we want to keep track of the html as text

	
			var approx_length_needed = parseInt($(element).find(".more_btn").outerWidth(true)) +parseInt( char_length);
				//used to keep track of the width of the element, only an approximation
			
			var done = false;
			var temp_html_1 = '';
			var temp_html_2 = temp_html;
			var temp_index;
			
			var target_height = short_height+$(element).find(".dotify_bio").offset().top;
			var letter_count = 10; //NOTE: we need the span class to be inserted inside the P tag
				//letter_count is a var holding a simple heuristic that allows the algorithm to jump by many characters instead of one by one, decreasing calculation time
			//var letter_count = temp_obj.width()/(parseInt(temp_obj.find("p").css("font-size"))/2)*(Math.ceil(img_height/line_height) - 1);
			temp_html_1 += temp_html_2.substring(0, letter_count+1);
			temp_html_2 = temp_html_2.substring(letter_count+1);
				/*--- finding next available word to insert span tag ---*/
				temp_index = temp_html_2.indexOf(' ');
				temp_html_1 += temp_html_2.substring(0, temp_index+1);
				temp_html_2 = temp_html_2.substring(temp_index+1);
			/*
			split the html text in tween, the 
			the way it works is that some text will be transferred from the right element to the left element;
			The span tag/more button is inserted between the two strings and the html element is rebuilt.
			The location of the button is grabbed and checked for whether it has surpassed the target truncated height
			*/
			
			//RESETTING P_HEIGHT; this is necessary because the more_string overflows letters at the end of the paragraph and may be on the next line, which the height does not take into account of
			//console.log(more_string);
				temp_obj.html(temp_html_1+"<span class='locator'>"+more_string+"...</span>"+temp_html_2);
				//temp_obj.html(temp_html_1+temp_html_2);
				if(!dotify_exception){	
					p_height = temp_obj.height();
				}
		
			//letter_count = letter_count/28;
			//letter_count = (letter_count/(temp_obj.width()/(parseInt(temp_obj.find("p").css("font-size"))/2)))/5;
			var previous_top_position = 0; 
			var temp_position;
			
			while( temp_html_2.length > 10){ //while its not done, keep on moving text from the right to the left
					temp_html_1 += temp_html_2.substring(0, letter_count+1);
					temp_html_2 = temp_html_2.substring(letter_count+1);

					temp_index = temp_html_2.indexOf(' ');
					temp_index2 = temp_html_1.lastIndexOf('</'); //we need to check for this because it might look like this: 'some text.</p>', we need to inject the locator right before the closing tag
					if(temp_index2 > temp_index){
						temp_index = temp_index2;
					}
					temp_html_1 += temp_html_2.substring(0, temp_index+1);
					temp_html_2 = temp_html_2.substring(temp_index+1);

				temp_obj.html(temp_html_1+"<span class='locator'/>"+temp_html_2);
				temp_position = $(element).find("span.locator").offset();
					//reinsert the span tag and grab at its location
				
				
				//console_text +="<br/> LOCATOR left: "+ temp_position.left;
				
				if(previous_top_position == 0){
					//if the prev location is 0, the loop just started
					previous_top_position = temp_position.top;
				}
				else if(previous_top_position == temp_position.top){
					//if the previous location is the same as the current location
					//it is on the same line
					letter_count+= temp_index;
				}
				else{
					//the tag just encountered a new line, reduce the amount of characters
					//to skip cause we might be going to fast
					letter_count-= temp_index;

					if((temp_position.top + line_height) > target_height){
						//the tag has surpassed the target truncate height and 
						//we must backtrack
						done = true;
						break;
					}
					previous_top_position = temp_position.top;
				}
			}
			//backtrack;
			
			done = false;

				/*
				we now reverse traverse the content, but instead at one word at a time
				We rely on the fact that the previous loop stopped right after surpassing the 
				line we want to button to be located at, so we need to backtrack until
				we change lines once
				*/
			
            var more_string_length_mod = more_string_text.length/3 ;
            var more_string_mod = more_string.substr(0, more_string_length_mod);
			while( temp_html_1.length > 100){ //while its not done, keep on moving text from the right to the left
				var single_word;
				temp_index = temp_html_1.lastIndexOf(' ');
				temp_index2 = temp_html_1.lastIndexOf('</'); //we need to check for this because it might look like this: 'some text.</p>', we need to inject the locator right before the closing tag
				temp_index3 = temp_html_1.lastIndexOf('<br'); //we need to check for this because it might look like this: 'some text.</p>', we need to inject the locator right before the closing tag
                if(temp_index3 < 0){
				    temp_index3 = temp_html_1.lastIndexOf('<BR'); //used to check for BR tags in ie, since ie reports them UC style
                }
				if(temp_index2 > temp_index){
					temp_index = temp_index2;
				}
                if(temp_index3 > temp_index){
                    temp_index = temp_index3;
                }
				single_word = temp_html_1.substring(temp_index);
				temp_html_2 = temp_html_1.substring(temp_index) + temp_html_2;
				temp_html_1 = temp_html_1.substring(0, temp_index);
				temp_obj.html(temp_html_1+" <span class='locator'>"+more_string+more_string_mod+"</span>"+temp_html_2);
					//we need to stick the more string here because the more string will take up some space so it emulates the actual position of the button
				
				//console.log(temp_obj.html());
				temp_position = $(element).find(".locator").offset();
				//console.log(temp_position.top +" TARGET HEIGHT "+ target_height);
				
				
				if($(element).find(".locator").offset().top +line_height >= target_height){
					continue;
				}
				else{
					done = true;
					break;
				}
			}
			/*	because of the inaccuracy of each browser's ability to report the location of the element, 
				even if we pad it to the full extent of the length of the button, 
				we must traverse back (half/all of the letter length of the button, then look for a space or .);
			*/
		
			if(!dotify_exception){ //we remove the buttons if they are going to be placed in content
				$(element).find(".more_btn").remove();
				$(element).find(".less_btn").remove();
				temp_obj.html(temp_html_1+more_tag+" <span class='filler' style='display:block;'>&nbsp;&nbsp;</span>"+temp_html_2); //kill the locator, insert more tag
			}
			else {
				//temp_obj.html(temp_html_1+temp_html_2); //kill the locator
				temp_obj.html(temp_html_1+" <span class='filler' style='display:block;'>&nbsp;&nbsp;</span>"+temp_html_2); //kill the locator, insert more tag
			}
				$(element).find(".less_btn").hide();

			short_height -= 1; //Forcing short_height to be one less pixel
                //a fix for only calendar pages
                if($(".calendar").length > 0){
                    var add_trunc = 0;
                    var temp_header = $(element).find("h4");
                    add_trunc = temp_header.height() / parseInt(temp_header.css("line-height"));
                    short_height -= (add_trunc-1);
                }
			$(element).find(".dotify_bio").height( short_height);



			var padding = (temp_obj.offset().left + temp_obj.width() - $(element).find(".more_btn").offset().left) - approx_length_needed - char_length*2;
				//pad the right side of the more button as sometimes the more button is slightly
				//left so the next word might show on the same line
			
			if(padding<0){padding=0;}//ie hack cause ie doesn't like negative margins
			
			if(!static){ //we animate only if its not static
			$(element).find(".more_btn").click(function(){
				//setting up more button
				var temp_height = $(element).find(".dotify_bio").height();
					($(element).find(".dotify_bio")).css("overflow","visible");
					
					($(element).find(".dotify_bio")).animate({height:p_height}, "slow");
					//$(element).find(".dotify_bio").css("height","auto");
				$(this).hide();
					$(element).find(".filler").hide();
				$(element).find(".less_btn").show();
			});
			$(element).find(".less_btn").click(function(){
				($(element).find(".dotify_bio")).css("overflow","hidden");
				($(element).find(".dotify_bio")).animate({height:short_height}, "slow", function(){
				
					$(element).find(".more_btn").show();
					$(element).find(".filler").show();
				});
				$(this).hide();
			});
			}
	}
	function initDotify() {
		if($('.dotify_item').length == 0){return;}
		//dotify($($('.dotify_item')[2]),0); return;
		$('.dotify_item' ).each(function(index, element){
			dotify(element, index);
		});
	}
	function initHomepageEvents(){
		if($.browser.mozilla) {

			$('.left-column-flash_inner').mouseenter(function(){ this.StopPlay();});
			$('.left-column-flash_inner').mouseleave(function(){ this.Play();});
					

		}
		else{
			$('.left-column-flash_outer').each(function(index, element){
					$(element).mouseenter(function(){ this.StopPlay();});
					$(element).mouseleave(function(){ this.Play();});
					});
		}
	}
	function popWindow(element){
		$(element).click(function(){
			
			window.open(this.href);
			return false;
		});
	}
	function initPopupWindows(){
		$('a.popup, a.target-blank').each(function(index, element){popWindow(element);});
	}
	function initDropDowns(){
		$('select').selectmenu({style:'dropdown', maxHeight:262 });
		$('.ui-selectmenu-icon.ui-icon').addClass("ui-icon-triangle-2-n-s");
		$('.ui-selectmenu-icon.ui-icon').removeClass("ui-icon-triangle-1-s");
		

		
		$('.newsletter select#state').change(function(){
			var tempobj = $(this).next().find('.ui-selectmenu-status');
			if($(this).val() == ''){
				tempobj.addClass('clear-input');
			}
			else{
				tempobj.removeClass('clear-input');
			}
		});
		$('.newsletter select#state').trigger('change');
	}
	function initRSVPDropDowns(){
		$('select#selected_event').change(function(){
			if($(this).val() != ''){
				changeEventDate(event_dates[$(this).val()].start_date, event_dates[$(this).val()].end_date, event_dates[$(this).val()].tba_flag);
			}
		});
		// Multi-rsvp page
		if(typeof start_date == 'undefined' || typeof end_date == 'undefined'){
			$('select#selected_event').trigger('change');
		}
		// Single rsvp page
		else{
			changeEventDate(start_date, end_date, 0); // Okay to hardcode tba. Will be overwritten by single event RSVP anyway
		}
	}
	function changeEventDate(start, end, tba){
		$('select#custom_input_1 option:not(:first_child)').remove();
		var temp_obj = $('select#custom_input_1');
		temp_obj.selectmenu('destroy');
/*
        if(!start){
            $("#custom_input_1-field").hide();
            return;
        }
*/
            $("#custom_input_1-field").show();
        if (start == '' || tba == 1) {
            temp_obj.append('<option value="TBA">TBA</option>');
        }
        else {
    		var temp_date = Date.parseExact(start, "yyyy-MM-dd");
    		var temp_end_date = Date.parseExact(end, "yyyy-MM-dd");
            while( temp_date.compareTo(temp_end_date) <= 0){
             temp_obj.append('<option value="'+ temp_date.toString("yyyy-MM-dd") +'">'+ temp_date.toString("MMMM dd, yyyy") +'</option>');
             temp_date = temp_date.addDays(1);
            }
        }
		temp_obj.selectmenu({style:'dropdown', maxHeight:262 });
		temp_obj.next().find('.ui-selectmenu-icon.ui-icon').addClass("ui-icon-triangle-2-n-s");
		temp_obj.next().find('.ui-selectmenu-icon.ui-icon').removeClass("ui-icon-triangle-1-s");
	}

	function isIphone(){
		var agent = navigator.userAgent.toLowerCase();
		if( !agent.match(/iPhone/i) && !agent.match(/iPad/i)){
			return 0;
		}
			return 1;
	}	
	function isChrome(){
		var agent = navigator.userAgent.toLowerCase();
		if( !agent.match(/Chrome/i)){
			return 0;
		}
			return 1;
	}	
	function initIphone(){
		if(isIphone()){
            //$("video").css("display","none");
			$('#footer').addClass("iphone-fix");       
            $("video").css("visibility","hidden");
		}
	}
    function initRequired(){
        $('.rtg-widget.required .rtg-label label').each(function(i, e){
            $(e).append("*");
        });
    }
	function externalLinkInit(){
		$('a:not(.target-blank)').each(function(index, element){
			var temp_str = $(element).attr('href');
			if(temp_str == undefined){return;}
			if(temp_str.charAt(0)!= "#" && !temp_str.match(location.host) && temp_str.charAt(0)!="/" && !temp_str.match("mailto:")){
				$(element).click(function(){window.open(this.href); return false;});
			}
		});
	}

    function initChromeQTScroller(){
        if(!isChrome()){return;}
        var embeds = $(".text-box object");
        if(embeds.length == 0){return;}
        //var page_height = $("#wrapper").height();
        var page_height = $(document).height();
        var footer_height = $("#footer").height()+20;
        //console.log("document height:" + $(document).height()+" window_height:"+$(window).height());
        var scroll_top_max;
        $(window).scrollTop(99999);
        scroll_top_max = $(window).scrollTop();
        $(window).scrollTop(0);
        embeds.each(function(i,e){
            var p_wrapper = $(e).parent();
            p_wrapper.css({
                "overflow":"hidden",
                "display":"block",
                height : parseInt($(e).attr("height"))+"px",
                width: "500px"
            });
        });
        $(window).scroll(function(event){
            //console.log(event, $(window).scrollTop());
            var window_height = $(window).height(); 
            //console.log("offset_scroll", (page_height-window_height) * ($(window).scrollTop()/scroll_top_max));
            var offset_scroll = -1 * ((page_height-window_height) * ($(window).scrollTop()/scroll_top_max));
            // window_height + scrollTop = document height
            
                //console.log((page_height-$(window).scrollTop()));
            embeds.each(function(i,e){
                //console.log($(e).offset().top + ($(window).scrollTop()-page_height));
                //if(i == 0){return;}
                var p_wrapper= $(e).parent();
                    //console.log($(e).offset().top - $(window).scrollTop());
                    //console.log("height", $(e).attr("height"));
                    //console.log($(e).offset().top + offset_scroll - parseInt($(e).attr("height")));
                    var bottom_embed_position = $(e).offset().top + offset_scroll;
                    //console.log("embed offset", $(e).offset().top, "offset_scroll", offset_scroll, "scroll_top_max", scroll_top_max,"bottom_embed", bottom_embed_position, " elment height", $(e).attr("height"));
                    if(1 || bottom_embed_position > (window_height-footer_height)){
                        var new_padding =  bottom_embed_position -  window_height + footer_height;
                        var new_height;
                        //console.log("new_height", new_height);
                        new_height = parseInt($(e).attr("height")) - new_padding;
                        //console.log("new_height_2", new_height);
                        if(new_height <= parseInt($(e).attr("height"))){
                            if(new_height < 0){
                                new_height = 0;
                            }
                            p_wrapper.css({
                                "height": new_height+"px"
                            });
                        }
                        else{
                            p_wrapper.css({
                                "height": parseInt($(e).attr("height"))+"px"
                            });

                        }
                    }
            });
        });
        setTimeout(function(){
                $(window).scrollTop(10);
                $(window).scrollTop(0);
        }, 1000);
        $(window).resize(function(){
            //return;            
            $(window).scrollTop(99999);
            for(var i=0 ; i<embeds.length; i++){
                var e = embeds[i];
                var p_wrapper = $(e).parent();
                p_wrapper.css({
                    "overflow":"hidden",
                    height : parseInt($(e).attr("height"))+"px",
                    width: "500px"
                });
            }
            scroll_top_max = $(window).scrollTop();
            $(window).scrollTop(0);
            
        });
    }

	preventFOUT(); //must be called before document is ready
    $( document ).ready( function () {

	
        setRandomBodyBackground();
        setRandomFooterBackground();
	
        initRoadblock();
	
        initPhotoSlideshow();
        initSearchBox();
        initSideBarAlign();
        initDropDowns();
       	initRSVPDropDowns();
        initRequired();
	initNewsLetterForm();
	initHomepageEvents();
	initPopupWindows();
	//externalLinkInit();
	$( '.signup_box' ).frontendForm(); //enable right column ajax form submission for newsletter

        initIphone();
        // HTML5 Video
        $( '.fe-video' ).frontendVideo({
            jwplayer_params:{
            skin: '/images/flash/beelden/beelden.xml',
            playerready: 'playerReadyOverlay'
            }
        });
        if(typeof jwplayer() != "undefined"){
            jwplayer().onReady(function(){
                var video_id = jwplayer().id;
                var fullscreen_button = $("#"+video_id+"_jwplayer_controlbar_fullscreenButton");

                $.browser.safari = ( $.browser.safari && /chrome/.test(navigator.userAgent.toLowerCase()) ) ? false : true; 
                if(fullscreen_button.length > 0 && !$.browser.safari){
                    fullscreen_button.mouseup(function(){
                        
                        $("#footer").hide();
                    });
                    $("#"+video_id+"_jwplayer_controlbar_normalscreenButton").mouseup(function(){
                        $("#footer").show();
                    });
                }
            });
        }
    });
	window.onload= function(){

        initChromeQTScroller();
		initDotify();
		showBody();
    	initIphone();


	};//this should be called right after preventFOUT
	
/* JWPlayer Overlay */
function playerReadyOverlay(obj)
 {
    player = gid(obj.id);
    addListeners();
};
function addListeners()
 {
    playlist = player.getPlaylist();

    if (playlist.length > 0)
    {
        player.addModelListener('STATE', 'stateMonitor');
    }
    else
    {
        setTimeout('addListeners()', 1000);
    }
};
function stateMonitor(obj)
 {
    if (obj.newstate == 'COMPLETED' || obj.newstate == 'PAUSED')
    {
        gid('overlay').style.display = 'block';
    }
    else
    {
        gid('overlay').style.display = 'none';
    }
}
function gid(name)
 {
    return document.getElementById(name);
};
/* End JWPlayer Overlay */

function initVideoPlayer( ref ) {
    var playerOptions = {
	flashplayer: '/images/flash/player.swf',
	skin: '/images/flash/five/five.xml',
	autostart: false,
	width: 304,
	height: 166,
	image: '/images/video/Vilcek_Commercial-home.png'
    };
    
    /* override player height for MSIE */
    var v = document.createElement( 'video' );
    if( v && !v.canPlayType ) { /* then this is MSIE 6/7/8 */
	playerOptions.height = 189;
    }

    $(ref).jwplayer( playerOptions );
} // initVideoPlayer
//})(jQuery);

