$(document).ready(function(){
	
	// #########################################################
	// to show hide grid - only for development
	/*
	if (String(location.href).indexOf('grid')!=-1) {
        $('body').prepend('<a href="#" id="grid">Show/Hide</a>')
        $('#overlay').hide();
        $('#grid').click(function(){
            $('#overlay').toggle()
            return false
        });
    };
	*/

	/*
	$('#comment-form').submit(function(e){
		e.preventDefault;
		alert('oi')
		//alert($(this).find('input:first').attr('value'))
	});
	*/
									

	// #########################################################

	//transcript
	$('.video_transcript a').text('[+] View Transcript').data('otherText', '[-] Hide Transcript').click(function(e) {
		e.preventDefault();
		var $this = $(this),
			newText = $this.data('otherText');

		$this.parents('.video_transcript').find('.transcript_text')[$this.hasClass('expanded') ? 'hide' : 'show']();
		$this.data('otherText', $this.text()).text(newText);
        $this.toggleClass('expanded');
	});
	
	$('.transcript_text').each(function(index, el) {
        // $(el).css('height', transcriptText.height()).hide();
		$(el).hide();
	})
	
	$('.media-video').each(function(index, el) {
	    var $el = $(el),
	        width = $el.find('object').width();
	    
	    if (width > 0) {
	        $el.css('width', width);
	    }
	})

	if ($('ul.nav li a.dropdown-trigger').length) { 
		//$('.nav').PLnav(); 
		$('ul.nav li a.dropdown-trigger').each(function() {
			if ( $(this).parent('li').attr('id') != 'nav_home') {
				slideNavigationContent($(this))
			}
		})	
	}
	
	if ($('div.bd-other-links div.newsletter-sign-up a.trigger-link').length) {
		// get the regions with an ajax request and populate the select box
		var sign_up_container = $('div.bd-other-links div.newsletter-sign-up div.sign-up-content div.shadow-container');
		$.ajax({
			url: "/ajax/get_regions",
			context: document.body,
			success: function(data) {
				sign_up_container.html($(data))
			}
		})
		$('div.bd-other-links div.newsletter-sign-up a.trigger-link').click(function(e) {
			$(this).toggleClass('open')
			e.preventDefault();
			headerNewsletterForm($(this), $('div#footer div.newsletter-sign-up'), 'div.newsletter-sign-up div.sign-up-content')
		});
		
		// have to attach this to live because the form isn't loaded into the dom on page load
		$('div.newsletter-sign-up form.header-newsletter-form').live("submit", function() {
			
			// perform some basic validation
			form = $('div.newsletter-sign-up form.header-newsletter-form')
			valid = validateNewsletterForm(form)
			
			if (!valid) {
				$(this).find('span.validation').css('display','block');
			}
			else {
				form.submit()
			}			
			
			return false
		});
	}
	
	if ($('div.browse-facets form.facet-form').length) {
		$('form.facet-form input[type=checkbox]').each(function() {
			$(this).change(function() {
				// submit the form parent
				$(this).closest('form').submit()
			})
		})
	}
	
	// if ($('div#footer div.newsletter-sign-up a.trigger-link').length) {
	// 	$('div#footer div.newsletter-sign-up a.trigger-link').click(function(e) {
	// 		e.preventDefault();
	// 		$(this).toggleClass('open')
	// 		headerNewsletterForm($(this), $('div.bd-other-links div.newsletter-sign-up'), 'div.newsletter-sign-up div.sign-up-content')
	// 	})
	// }
	
	if ($('.lb').length) { $('.lb').PLlightbox(); }
	
	if ($('.tabBox').length) { $('.tabBox').PLtab(); }

	if ($('.eligibility-wizard').length) { $('.eligibility-wizard').PLwizard(); }

	if ($('#finder #carousel').length) { $('#finder').find('#carousel').PLhome({autoPlay: false}); }
	
	if ($('#miniCarousel #carousel').length) { $('#miniCarousel').find('#carousel').PLhome({'title':'h2 a', autoPlay: false}); }

	if ($('.contentAcc').length){
		$('.contentAcc').click(function(e){
			e.preventDefault();
			if($(this).next('.contentAccBody').is(':visible')){
				$(this).next('.contentAccBody').slideUp(300);
				$(this).find('a').removeClass('on');
			} else {
				$(this).next('.contentAccBody').slideDown(300);
				$(this).find('a').addClass('on');
			}
		});
	}
	
	if($('ul.accordion').length) {
		accordionAnimator($('ul.accordion li h4'), 'ul.accordion-content');
		openSubAccordion($('ul.accordion-content ul.accordion-content'));
	}

function accordionAnimator(accordionLinks, elementStringToShow) {
   accordionLinks.each(function (index) {
       $(this).click(function () {
           //$(this).next($(elementStringToShow)).slideToggle("medium");
           $(this).next($(elementStringToShow)).animate({ height: 'toggle' }, 500);
           $(this).toggleClass('selected');
           return false;
       });
   });
}

// function to open a sub accordion if it has checked inputs inside it - can't be done in the template
function openSubAccordion(sublist) {
	var checked = false;
	sublist.each(function() {
		actual_sublist = $(this)
		actual_sublist.find('input').each(function() {
			if($(this).attr('checked')) {
				checked = true;
			}
		})
		if (checked) {
			actual_sublist.toggleClass('open')
			actual_sublist.prev('h4').toggleClass('selected')
		}
		checked = false;
	})

}


// function which moves the sign up form from header to footer or vice versa.
// if no movement needed then we just show and hide the form as usual.

function moveSignUpForm(linkClicked, otherFormPosition) {

	// check if the form is next to the link clicked. 
	if (linkClicked.next('div.sign-up-content').length) {
		//yes it is, so toggle the display of it.
		linkClicked.next('div.sign-up-content').toggle()
	}
	else {
		//no it isn't so we need to grab it from the other position, and show it.
		form = $(otherFormPosition.find('div.sign-up-content'))

		form.css('display', 'none') //in case it is open at time of clicking other position
		form = form.detach()
		
		// now that it's detached we can append it to where we want.
		linkClicked.after(form)
		// and show it
		form.toggle()
	}
}

function validateNewsletterForm(form) {
	//select box
	select = form.find('select')
	selectVal = $(select).val()
	
	//name input box
	name = form.find('input#first_name').val()
	
	//email
	email = form.find('input#email_address').val()
	
	// if any of them are blank return false
	if (!selectVal || !name || !email) {
		return false
	}
	
	return true
}

function headerNewsletterForm(linkClicked, otherFormPosition, container) {
	// first of all, show the form or move it
	moveSignUpForm(linkClicked, otherFormPosition)
	
	//find the select box and on change, enable the corresponding address book form field
	container = $(container)
	container.find('select').change(function(e) {
		chosenVal = $(this).val()
		
		// update the user id form item
		container.find('input#id_userid').val(chosenVal)
		
		// disable all the inputs and enable the one that matches
		container.find('input.addressBook').each(function() {
			$(this).attr('disabled',true)
			if ($(this).attr('id') == chosenVal) {
				$(this).removeAttr('disabled')
			}
		})
	})
} 

function slideNavigationContent(dropDownSelector) {
    //the link that has been clicked
    dropDownSelector.click(function(){
	
        //get its id to be used as the class for the sub navigation div

		var id = $(this).parent('li').attr('id')
		
    
        link = $(this);

        //get the div element using the id above as its class

        var container = $('div.'+id);
	
        //if the container is already displayed then hide it, else display it
        if(container.css('display') == 'block'){
            //container.siblings('div.nav-secondary-container').css('display','none');
            container.animate({ height: 'toggle' }, 500,function() {
                link.toggleClass('clicked');
				link.prev('a').toggleClass('clicked')
            });
        } else {
            var visibleDropDown = false;
            var dropDownList;
            // Currently not using drop down highlight
            // link.parent().css('border-bottom','5px solid #FFFFFF');
            container.siblings('div.subNav').each(function(intIndex) {
                if ($(this).css('display') == 'block'){
                    dropDownList = $(this);
                    visibleDropDown = true;
                }
            });

            if (visibleDropDown) {
				dropDownList.animate({ height: 'toggle' }, 500,function() {
                    container.animate({ height: 'toggle' }, 500,function() {
                        $('ul.nav li a.clicked').toggleClass('clicked');
                        link.toggleClass('clicked');
						link.prev('a').toggleClass('clicked')
                    });
                });
            } else {
                container.animate({ height: 'toggle' }, 500,function() {
                    $('ul.nav li a.clicked').toggleClass('clicked');
                    link.toggleClass('clicked');
					link.prev('a').toggleClass('clicked')
                });
            }
        }

        return false;
    })
}

function hasPlaceHolder() {
    return 'placeholder' in document.createElement('input');
}

function html5forms() {
    var formPlaceholder = hasPlaceHolder();
    if(formPlaceholder === false) { // Fallback for non-supporting browsers
        $('form[name=search] input#query, input#findLocation[type=text], input#geo-search, input#q[type=text], #search-orgs .input-text').each(function(){
            if($(this).attr('placeholder')) {
                var placeholderText = $(this).attr('placeholder');
                $(this).attr('value',placeholderText);
            }
        });
        emptyTextBox();
    }
}

function emptyTextBox() {
	$('form[name=search] input#query, input#findLocation[type=text], input#geo-search, input#q[type=text], #search-orgs .input-text').each(function(){
		if($(this).attr('value')){
			var inputText = $(this).attr('value');
			$(this).focus(function(){
				if($(this).attr('value') == inputText){
					$(this).val('');
				}
			}).blur(function(){
				if($(this).attr('value') == ''){
					$(this).val(inputText);
				}					
			});
		} // end if
   }); // end each
} // end function

html5forms();
// Clear search form on focus


}); 
// end document.ready 
// #############################

