/* Declare a namespace for the site */
var Site = window.Site || {};

/* from HTML5 book - not actually using this now ... */
function elementSupportsAttribute(element, attribute) {
    var test = document.createElement(element);
    if (attribute in test) {
        return true;
    } else {
        return false;
    }
}

/* Create a closure to maintain scope of the '$'
   and remain compatible with other frameworks.  */

(function($) {
	
	//same as $(document).ready();
	$(function() {
		
        $("input[type=text][placeholder],textarea[placeholder]")
            .each( showPlaceholder ) // initialize each control on page load
            .blur( showPlaceholder )
            .focus( hidePlaceholder );
     
        $("form").submit( function() {
            $( "input[type=text][placeholder],textarea[placeholder]", this ).each( hidePlaceholder );
        } );
     
        function showPlaceholder() {
            var $control = $(this);
            var placeholderText = $control.attr("placeholder");
            if ( $control.val() === "" || $control.val() === placeholderText ) {
                $control.addClass("placeholder");
                $control.val(placeholderText);
            }
        };
     
        function hidePlaceholder() {
            var $control = $(this);
            if ( $control.val() === $control.attr("placeholder") ) {
                $control.removeClass("placeholder");
                $control.val("");
            }
        }

        // Home Page Slideshow
        $('#slideshow .slide:first').fadeIn(1000, function() {
            $('#slideshow').cycle({
                delay: 1000, // extra delay b4 1st slide (can be negative!)
                speed:	(typeof pngfix == 'function') ? 0 : 1000,  // speed (MS) of transition. Serve up 0 for IE < 7 if PNGFIX in place
                timeout: 7000, // 7 sec between slide changes
                cleartypeNoBg: 1
            });
        });

        // Sponsors on Street Faire page
        $('#bigsponsors .slide:first').fadeIn(0, function() {
            $('#bigsponsors').cycle({
                speed:	(typeof pngfix == 'function') ? 0 : 1000,  // speed (MS) of transition. Serve up 0 for IE < 7 if PNGFIX in place
                timeout: 6000, // 6 sec between slide changes
                cleartypeNoBg: 1
            });
        });

        // advertising on directory pages
        $('.directory .slide:first').fadeIn(0, function() {
            $('.directory .ad').cycle({
                delay: 1000, // extra delay b4 1st slide (can be negative!)
                speed:	(typeof pngfix == 'function') ? 0 : 1000,  // speed (MS) of transition. Serve up 0 for IE < 7 if PNGFIX in place
                timeout: 8000, // 8 sec between slide changes
                cleartypeNoBg: 1
            });
        });
        
        $('<div id="wrapper" style="display:none"></div>').appendTo('form#signup');
        
        $('.desktop .compact #moreinfo').hide();
        
        $('#button-signup').attr('href', '').attr('title', '');
        
        
        // http://trevordavis.net/blog/ajax-forms-with-jquery/
        $("#signup").submit(function(){	
            $(".error").hide();
            var hasError = false;
            var emailReg = /^.+@.+\..+$/;
            
            var emailFromVal = $("#email").val();
            if(emailFromVal == '') {
                $("label[for=email]").show().addClass('error').html($.err.missing);
                hasError = true;
            } else if(!emailReg.test(emailFromVal)) {	
                $("label[for=email]").show().addClass('error').html($.err.invalid);
                hasError = true;
            }
                    
            /* Not using a honeypot, but I'm leaving this here for reference.
            var caught = $("#honey").val();
            if(caught !== '') {
                $("label[for=email]").html('<b>Something went wrong. Please <a href="">reload this page.</'+'a><'+'/b>');
                hasError = true;
            }*/
            
            if(hasError == false) {
                $('#signup #submit').hide();
                $('#signup aside').fadeOut('fast');
                $('<img src="/_/img/loading.gif" alt="Loading" id="loading" />').appendTo('label[for=email]');
                var signupform = "/_/signupform.php";
                $.post(signupform,
                    { email: emailFromVal, ajax: 'TRUE' },
                        function(data){
                            // testing - alert("Data Loaded: " + data);
                            $("#signup fieldset").fadeOut("fast", function() {				   
                                $("#signup").html('<h1>'+$.ty.head+'</h1><p>'+$.ty.message+'</p>');
                            });
                        }
                     );
            }
            
            return false;
        });						   
    
        // fancy aside for non-mobile users
        $('.desktop .compact form#signup').hover(
        function(e) {
            $('#signup aside, #signup #wrapper').fadeIn('fast');
        },
        function(e) {
            $('#signup aside, #signup #wrapper, #signup label').fadeOut('fast');
        }
        );
        
        $('#signup #example').colorbox({width:"740px", height:"90%", iframe:true});
 	$('#slideshow .slides').each(function() {
		/*	We have to use 'visibility: hidden' rather than 'display: none'
			so IE will be able to pick up the image heights and apply them.
			Doing this to the .slides div caused errors, but applying to 
			individual slides worked fine. So, to fade in, we have to hide
			the parent DIV, then render the slides visible, then fade in...
		*/
//		$(this).hide();
	//	$('.slide').css({'visibility':'visible'});
	//	$(this).fadeIn(1500);
	});

       // We'd like to pause if we're over any links ...
        $("#slideshow a").hover(
        function(e) {
            $(this).parents('.slides').cycle('pause');
        },
        function(e) {
            $(this).parents('.slides').cycle('resume');
        }
        );


        // Seem to need to declare var first, then set height from that
        $('#directory').each(function(){
            if($('body').hasClass('mobile')) {
                $('<a href="#" id="back">Back</a>').prependTo($(this));
            }
            var ht = $(this).height();
            $(this).height(ht);
        });

        // Define doc title globally so we can prepend (or not) as needed
        $.ldba = {
            ptitle : document.title,
            phead : $('#directory h2').text()
        };

        // May need to load specific subcategory
        $('#subcats').ready(function() {
        
            if(window.location.hash) {
                var target = window.location.hash.replace('#/','');
                target = target.replace('/','');
                
                // Would like to just do this, but not working...
                // Went crazy trying to avoid duplicating code here.
                // $('#subcats li#'+target+' a').live(linkfocus);

                // Have to repeat what I'm up to below ...
                $('#subcats a.focus').removeClass('focus');
                $('#subcats li#'+target+' a').addClass('focus');

                $('#directory li:not(.'+target+')').hide();
                $('#directory li.'+target).each(function() {
                    if( $(this).is(":hidden") ) {
                       $(this).show();
                    }
                });
                document.title = $('#subcats li#'+target+' a').text() + ' | ' + $.ldba.ptitle;
            }
        });
        
        $('.mobile #back').click(function(e) {
            e.preventDefault();
            $('#main h1, #main .lead, #subcats').animate({
                left: '0'
            });
            $('#directory').animate({
                left: '570px'
            });
        });
        
        $('#subcats a').click(linkfocus);
        // This should somehow come in handy for making this function
        // Available onload in above function, but it isn't...
        // $('#subcats a').bind('click', linkfocus);

        var diroff = $('#directory').offset();

        function linkfocus(e) {
            // console.log(e.type);
            if($('#subcats').hasClass('subcat')) {
                // Change HREF to include hash, so main page gets loaded
                linked = $(this).attr('href').split('/');
                if(linked[2]) { // only change if subfolder present - not 'all' @ top
                    $(this).attr('href', '/'+linked[1]+'/#/'+linked[2]+'/');
                    // window.location = '/'+linked[1]+'/#/'+linked[2]+'/'
                }
            } else {

                e.preventDefault(); // mostly, don't scroll us...

                // Do special stuff for mobile site
                if($('body').hasClass('mobile')) {
                    var offset = $(window).scrollTop();
                    if ( offset - diroff.top > 0 ) {
                        var dirtop = offset - diroff.top
                    } else {
                        var dirtop = 0;
                    }
                    $('#directory').css({'padding-top': dirtop + 'px'});
                    $('#main h1, #main .lead, #subcats').animate({
                        left: '-570px'
                    });
                    $('#directory').animate({
                        left: '0'
                    });
                } else { // if not mobile ...
                    $('#subcats a.focus').removeClass('focus');
                    $(this).addClass('focus');
                }

                var target = $(this).parent().attr('id');
                if(target == 'all') {
                $('#directory li').each(function() {
                        if( $(this).is(":hidden") ) {
                            $(this).show();
                        }
                    });
                    var subhead = $.ldba.phead; // subhead on page
                    var doctitle = $.ldba.ptitle; // page title
                    var urlhash = '/'; // URL hash
                } else {
                $('#directory li:not(.'+target+')').hide();
                $('#directory li.'+target).each(function() {
                        if( $(this).is(":hidden") ) {
                            $(this).show();
                        }
                    });
                    var subhead = $.ldba.phead + $(this).text(); // subhead
                    var doctitle = $(this).text() + ' | ' + $.ldba.ptitle; // page title
                    var urlhash = '/'+target+'/'; // URL hash
                }
                $('#directory h2').text(subhead); // update subhead on page
                if($('body').hasClass('desktop')) { // don't update for mobile
                    document.title = doctitle; // update page title
                    window.location.hash = urlhash; // update URL hash
                }
            }
        }

        $('.join').each(function() {
            $('#getlisted, #altemail, #buttons').hide();
            //$('<a href="#" id="continue-link">Continue</a>').appendTo('#begin');
            
            $('#continue-link').live('click', function(event){ // Need live() b/c element non-existent @ doc.ready()
                event.preventDefault();
                $('#continue, #buttons').slideDown();
                $(this).slideUp();
                $('#continue input:first').focus();
            });
            
            $('#PublishDirectory').click(function() {                     // <-- DOES THIS WORK x-BROWSER?
                if( $(this).is(':checked') ) {
                    $('#getlisted').slideDown();
                } else {
                    $('#getlisted').slideUp();
                }
            });

            $('input[name="directoryEmail"]').click(function() {                     // <-- DOES THIS WORK x-BROWSER?
                if( $('#directoryEmail_1').is(':checked') ) {
                    $('#altemail').slideDown();
                } else {
                    $('#altemail input').attr({'value':''});
                    $('#altemail').slideUp();
                }
            });
        });

	});

	$(window).bind("load", function() {
	});
	
})(jQuery);
