$(setupSite);

function setupSite()
{
    // set up slider that comes from top of the screen
    setupSaySomethingNewSlider();

       
    // setup individual pages - functions are responsible for bailing asap if they have have nothing to do on the current page
    setupHomePage();
    setupStaffListingPage();
    //setupFullBkgScreenImage();
    //setupAwardSlideshow();
    setupAwards();
    setupMainWorkPage();
    //setupLoginForm();
    
    setupNewsLinks();
    setupNewsMoreLinks();
    
    setupCallToAction();
    
    
    // other setup/adjustments
    adjustWhyPeopleWorkWithUsHeights();
    setupFooterEmailAddress();
}

// set up the sign up form that slides down from the top of the screen
function setupSaySomethingNewSlider()
{
    var sliderHiddenTopValue = '-318px',
        theObj = $('#sign-up-form-slider').css({ 'top' : sliderHiddenTopValue }).show(),
        
        theToggleLink = theObj.find('a'),
        
        showFunc = function () { theObj.animate({ 'top': '0px' }); theToggleLink.addClass('expanded') },
        hideFunc = function () { theObj.animate({ 'top': sliderHiddenTopValue }); theToggleLink.removeClass('expanded') }
    ;
    
    theToggleLink.toggle(showFunc, hideFunc);
}

function setupHomePage()
{
    // on the homepage? set up the slideshow
    var slideshowContainer = $('#slideshowContainer');
    if (slideshowContainer.length > 0)
    {
        $('#slideshowContainer').show();
        $('#slider').orbit( getOrbitSetupOptions() );
    }
}

function setupStudioApproachSpace()
{
	var	container = $('#content').css({'position':'relative', 'min-height' : '400px'}),
	
		pages = $('#studio-card, #approach-card, #space-card'),
		firstPage = $(pages[0]),
		
		slideshowFunc = function (obj) {
			$(obj).find('.slideshowContainer')
					.show()
					.find('.slider')
						.orbit( getOrbitSetupOptions() );
		},
		
		positionFunc = function (idx) {
			var self = $(this);
			
			self
				.show()
				.css({
					'position' : 'absolute',
					'top' : 0,
					'left' : (idx * 100) + '%'
				})
		}
	;
	
	if (pages.length == 0)
		return;
	
	/*
	pages
		.each(slideshowFunc)
		.each(positionFunc);
	*/
	
	slideshowFunc(firstPage);
	pages.each(positionFunc);
	
	container.css({
		'height' : firstPage.outerHeight() + 'px'
	});
}

function getOrbitSetupOptions()
{
	return {
          bullets: true,
          timer: true,
          directionalNav: false,
          captions: true,
          captionAnimation: 'fade',
          bullets: true,
          advanceSpeed: 8000
        };
}

function setupNewsLinks()
{
    if (!$.fancybox)
        return;

    $(".page-news-overview #news-listing a")
        .not('.skip-fancybox')
        /*.fancybox({
        'width'                : 450,
        'height'            : 670,
        'autoScale'         : false,
        'transitionIn'        : 'none',
        'transitionOut'        : 'none',
        'type'                : 'iframe',
        'autoDimensions': false,
        'padding':4
    });*/
        .each(setupNewsLink);
}
function setupNewsLink()
{
    var fancyArgs = {
        'width'                : 450,
        'height'            : 670,
        'autoScale'         : false,
        'transitionIn'        : 'none',
        'transitionOut'        : 'none',
        'type'                : 'iframe',
        'autoDimensions': false,
        'padding':4
    };
    
    try {
        if (this.rel.match(/[0-9]+/))
            fancyArgs.height = Number(this.rel);
    } catch (e) {};
    
    $(this).fancybox(fancyArgs);
}

function setupFooterEmailAddress()
{
    if (!document.getElementById('footer'))
        return;
    
    var theSpan = $('.contact-info span'),
        spanContents = $( $('.contact-info span cufontext')[0] || theSpan[0] ),
        originalAddr = spanContents.html(),
        addr = originalAddr.replace('(at)', '@').replace('(dot)', '.'),
        html = '<a href="mailto:'+addr+'">'+originalAddr+'</a>',
        
        css = $.extend({'position':'absolute'}, theSpan.position()),
     
        otherPageSpans = $('.page-connect #content address span, .page-privacy #content address span')
    ;

    theSpan
        .css(css)
        .html(html);
    
    otherPageSpans.html(html);
    
    Cufon.refresh();
}

function adjustWhyPeopleWorkWithUsHeights()
{
    // need to wait for the fonts to finish loading before we can do this...
    
    $(window).load(function(){
        
        var quotes = $('#why-work-with-us blockquote'),
            getHeightFunc = function(){return this.offsetHeight},
            heightArray = quotes.map(getHeightFunc).toArray(),
            newHeight = Math.max.apply(null, heightArray) + 'px';
        
        quotes.css({'min-height': newHeight});
        
    });
}

// need to set up the mouseovers for the staff page.
// uses the image's alt text as the mouseover text, creates and positions a <p> for this
// positioning happens right *after* we show() the text to force all browsers to calc a height first
function setupStaffListingPage()
{    
    $('#staff img').each(function () {

        var self = $(this),
            newHTML = $('<p><b>' + this.alt.replace(' | ', '</b><em>') + '</em>click for more</p>').hide(),
            parent = self.closest('a'),
            
            positionLabelFunc = function (self) {
                var /*self = $(this),*/
                    middpoint = self.closest('li').height() / 2,
                    text = self.siblings('p'),
                    textMiddpoint = text.height() / 2,
                    newY = Math.floor(middpoint - textMiddpoint) + 'px';
                
                text.css({'top':newY});
            },
            
            enterFunc = function () { self.css({'opacity' : .25}); newHTML.show(); positionLabelFunc(self) },
            leaveFunc = function () { self.css({'opacity' : 1.0}); newHTML.hide(); positionLabelFunc(self) };
            
        parent
            .mouseenter(enterFunc)
            .mouseleave(leaveFunc)
            .append(newHTML);

    });
}

function setupMainWorkPage()
{    
    var theImages = $('.page-work-main #content img').not('.page-work-main #content h2 ~ ul img'),
    
        fireLeaveEventForOthers = function (excludeThisItem) {
            
            theImages.not(excludeThisItem).parent().has('p:visible').mouseleave();
            
        };
    
    theImages.each(function () {

        var self = $(this),
            toOpacity = .925,
            newHTML = $('<p><b>' + this.alt.replace(' | ', '</b><b>') + '</b>click here</p>').css({'opacity' : 0}).hide(),
            parent = self.closest('a'),
            
            imgH = self.height(),
            imgW = self.width(),
            dimensions = {height: imgH + 'px', width:imgW + 'px', 'top':'0px', 'left':'0px'},
            newDimensions = {height: Math.floor(imgH * 1.2) + 'px', width: Math.floor(imgW * 1.2) + 'px', 'top': Math.floor(imgH * (-.1)) + 'px', 'left':Math.floor(imgW * (-.1)) + 'px'},
            
            enterFunc = function () {
                
                fireLeaveEventForOthers(self);
                
                newHTML
                    .stop(true)
                    .show()
                    .css({'bottom':( -1 * Math.floor(newHTML.outerHeight() /2) ) + 'px'})
                    .animate({'bottom':'0px', opacity: toOpacity}, {duration: 200});
                
                self
                    .stop(true)
                    .animate(newDimensions, {duration: 200});
            },
            leaveFunc = function () {
                
                var newBottom = -1 * newHTML.outerHeight();
                if (!$.browser.msie) // alpha AND gradients don't play well together for IE
                    newBottom = Math.floor(newBottom / 2);
                
                newHTML
                    .stop(true)
                    .animate({'bottom': newBottom + 'px', opacity: 0}, {duration: 200, complete: function (){$(this).hide()} });
                    
                self
                    .stop(true)
                    .animate(dimensions, {duration: 200});
            }
        ;
            
        parent
            .css(dimensions)
            .mouseenter(enterFunc)
            .mouseleave(leaveFunc)
            .append(newHTML);

    });
}

// creates div positioned behind everything else
// scales image proportionally so no bkg color is showing
function setupFullBkgScreenImage()
{
    if (!document.getElementById('useAsSiteBkg'))
        return;
    
    var theBody = $('body'),
        theImage = $('#useAsSiteBkg').detach();
    
    theBody.css({'background-image':'url('+theImage[0].src+')', 'background-position':'top center', 'background-repeat':'no-repeat'});
    
    return;
    
    // img was being stretched to cover whole bkg.
    /****************************************************************************************/
    var theBody = $('body'),
        theDiv = $('#sitebkg'),
        theImage = $('#useAsSiteBkg').data('resizeTimer', null).detach(),
        
        theBodyWidth = theBody.outerWidth(),
        theBodyHeight = theBody.outerHeight(),
        theBodyRatio = theBodyWidth / theBodyHeight,
        
        imgHeight = 2560, // all bkg images are the same dimensions, so height/width/ratio are hardcoded
        imgWidth = 1600,
        imgRatio = 1.6,
        
        theCSS = {
            'position':'absolute',
            'top':0,
            'right': 0
        },
        
        resizeFunc = function () {
            
            clearTimeout(theImage.data('resizeTimer'));
            theImage.data('resizeTimer', setTimeout('setupFullBkgScreenImage()', 250))
            
        };
    
    
    // no image? nothing to do, bail.
    if (theImage.length == 0)
        return;
    
    // make sure none of the background every shows through
    if (theBodyWidth >= theBodyHeight && theBodyRatio >= imgRatio)
    {
        $.extend(theCSS, {
            'width' : '100%',
            'height': 'auto'
        });
    }
    else
    {
        $.extend(theCSS, {
            'width' : 'auto',
            'height': '100%'
        });
    }
    
    // remove div if it already exists. create the container and add to DOM.
    theDiv.remove();
    theDiv = $('<div id="sitebkg"></div>').css({'position':'fixed', 'top':0, 'bottom':0, 'left':0, 'right':0, 'zIndex': -1});
    theBody.prepend(theDiv);
 
    
    // add the image to the new div and resize it to suit our needs
    theDiv.append(
        theImage.css(theCSS).show()
    );
    
    
    // we might need to change our styles if the browser resizes
    $(window).resize(resizeFunc);
    
    
    // if we need to reposition the image after loading, use the snippet below:
    /*
    theImage.one("load",function(){
        // now we can be sure to know what the image dimensions are, so center it.
        
    })
    .each(function(){
        if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
            $(this).trigger("load");
    }); 
    */
}

function setupAwards()
{    
    if (!document.getElementById('award_slider'))
        return;
    
    var slider = $('#award_slider')
        firstDD = slider.children('dd:first'),
        getNewSliderHeight = function (obj) {
            return (obj.addClass('show').outerHeight() + obj.position().top) + 'px';
        },
        resetImages = function (obj) {
            var theDiv = obj.find('.award-images');
            
            theDiv.find('img').removeClass('show');
            theDiv.find('img:first').addClass('show');
        };
    
    // rearrange year links - move to top. markup was written to be semantically correct, but we need to move things to make it look good now.    
    $('#award_slider dt:first').addClass('current').after(
            $('#award_slider dt:not(:first)').detach()
    );
    
    slider.css('height', getNewSliderHeight(firstDD));
    
    
    
    // enable portfolio item links
    $('.award-desc > a[href^=#]').click(function (event) {

        event.preventDefault();
        $('.award-images img')
            .removeClass('show')
            .filter( this.href.replace(/^[^#]*#/, '#') )
            .addClass('show');

    });
    
    
    
    // set up year changes
    $('#award_slider dt a').click(function (event) {
        
        event.preventDefault();
        
        $(this).addClass('current').closest('dt').siblings().find('a').removeClass('current');
        
        var theDD = $('#award_slider dd' + this.href.replace(/^[^#]*#/, '#'));
        
        resetImages(theDD);
        
        theDD
            .css({'left': '831px', 'zIndex': '1'})
            .addClass('show')
            .animate({
                'left': '0px'},{
                'complete' : function () {
                    $(this).css({'zIndex': '', 'left':''}).siblings().removeClass('show');
                }
            });
        
        slider.animate({'height': getNewSliderHeight(theDD)});
        
    });
}

function setupLoginForm()
{
    if (!document.getElementById('createacctform'))
        return;
    
    var theDL = $('#createacctform').closest('dl'),
        theDTs= theDL.children('dt'),
        setupFormLinks = function () {
            var self = $(this),
                aTag = self.children('a').attr('href', '#'),
                theDD = self.next();
            
            aTag.click(function (event) {
                event.preventDefault();
                theDD
                    .show()
                    .siblings('dd')
                        .hide();
                
                aTag.addClass('current');
                theDL.find('> dt > a').not(aTag).removeClass('current');
            });
        },
        
        deepLink = location.href.replace(/^[^#]*(#([a-z]+))?$/, '$2'),
        initialScreenIndex = 0
    ;
    
    location.href = location.href.match(/^[^#]*/)[0] + '#';
    
    theDTs
        .each(setupFormLinks)
        .detach()
        .prependTo(theDL);
    
    switch (deepLink)   // will probably need to add in the request pwd screen too
    {
        case 'login':
            initialScreenIndex = 1;
            break;
        default:
            initialScreenIndex = 0;
    }
    
    $(theDTs[initialScreenIndex]).children('a').click();
    
    
    $('#content dl form').submit(submitLoginForm);
}

function submitLoginForm(event)
{
    event.preventDefault();
    
    var currentForm = $('#content dl dd:visible form');
    
    currentForm.children('p.errMsg').remove();
    
    $.post(
        location.href,
        currentForm.serialize(),// submit the currently visible form
        function (data) {
            
            if (data.success)
            {
                if (!data.url)
                    data.url = '/blog/';
                
                location.href = data.url;
                return;
            }
            
            // there was a problem. let the user know what's up.
            if (data.errMsg == undefined)
                data.errMsg = 'Uh oh! There was a problem... Please check your information and try again.';

            currentForm.prepend('<p class="errMsg">'+data.errMsg+'</p>');
            
        },
        'json'
    );
}

function fixCareerMailto()
{
    var email = $('.page-careers #content p strong, .page-disclosure #content p span')[0];
    if (!email)
        return;
    
    var addr = email
                .innerHTML
                .replace(/[ ]*\(at\)[ ]*/, '@')
                .replace(/[ ]*\(dot\)[ ]*/, '.');
    
    $(email).wrap('<a href="mailto:'+addr+'"></a>');
}

function setupNewsMoreLinks()
{
    if (!document.getElementById('news-listing'))
        return;
    
    var theDDs = $('#news-listing dd'),
        heights = theDDs.map(function () {return $(this).outerHeight()});
    
    theDDs
        .each(function (idx) {
            var self = $(theDDs.get(idx)),
                start = Math.floor(idx / 3) * 3,
                rowHeight = Math.max(heights[start], heights[start+1]||0, heights[start+2]||0);
           
            self.css({'height': rowHeight + 'px', 'position': 'relative'});
        })
        .find('p:last a')
            .css({'position':'absolute', 'bottom':'20px'});
}

function setupCallToAction()
{
    // setup the "open" link 
    $('#calltoaction-toggle').click(showCallToActionForm);
    
    // ...and the "close"
    $('#calltoaction-close-btn').click(hideCallToActionForm);
    
    // also, remove the form tips when you enter the field
    $('#calltoaction-form input, #calltoaction-form textarea')
        .focus(function(){
            $(this).siblings().stop().fadeOut(200);
        })
        .blur(function(){
            
            var self = $(this),
                val = self.val(),
                required = (val.match(this.Flip_ValidateRule)) ? 'hide':'show';
            
            self.prev().find('b')[required]();
            
            if (val.length == 0)
                self.siblings().stop().fadeIn(200);
        })
        .focus()
        .blur();    // run the focus/blur funcs to remove the tips for fields that already have values in them
                    // this shouldn't really happen, but sometimes the browser holds on to old form values
                    // when refreshing/using back/forward arrows.
    
    
    
    // create elements for the "required" fields, and setup validation
    var formLabels = $('#calltoaction-form label'),
        validation = {
            'fname': /[a-z]/i,
            'lname': /[a-z]/i,
            'email': /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i,
            'company': /.*/,
            'website': /.*/,
            'comments': /.*/
        };
    
    formLabels
        .find('span')
            .append('<b style="display:none">required</b>');
    
    for (fieldName in validation)
    {
        formLabels
            .has('*[name='+fieldName+']')
            .find('input,textarea')[0].Flip_ValidateRule = validation[fieldName];
    }
    
    
    // finally, set up what happens when we post the form
    $('#calltoaction-form').submit(function(e){
        
        e.preventDefault();
        
        var self = $(this);
        
        if (self.find('label b:visible').length > 0)
            return;
        
        $.post(
            '/call-to-action.html',
            $(this).serialize()
        ).success(function () {
            
            var formContents = self.find('> div > *'),
                thanksMsg = $('<p id="calltoaction-thanks"><b>Thank You!</b>Your message has been sent.</p>');
            
            formContents.css({'visibility':'hidden'}); // want the form to maintain the same height
            
            self.append(thanksMsg);
            
        });
        
    });
}

function showCallToActionForm(e)
{
    e.preventDefault();
    
    var obj = $('#calltoaction-form:not(:visible):not(:animated)'),
        type = 'fade';

    if (obj.length == 0)
        return false;
        
    switch (type)
    {
        case 'slide':        
            if (!obj.data('animateToHeight'))
                obj.data('animateToHeight', obj.outerHeight() + 'px');
                
            obj
                .css({'height':'0px'})
                .addClass('show')
                .animate({
                    'height': obj.data('animateToHeight')
                });
            
            break;
        
        default:
        case 'fade':
            
            obj.fadeIn();
            
            $('#calltoaction-form input, #calltoaction-form textarea').focus().blur();
            
            break;
    }
    
    return false;
}

function hideCallToActionForm(e)
{
    e.preventDefault();
    
    $('#calltoaction-form')
        .stop(true, true)
        .fadeOut()
}
