pageEls = [];
bgImageRatio = 1;

$(document).ready(function(){
    
    $(window).resize(resizeImage); 
    
    pageEls['carousel_nav_a']     = $("#carousel_navigation a");
    pageEls['carousel_ul']        = $("#carousel ul");
    pageEls['newsletter_trigger'] = $("#newsletter_trigger");
    pageEls['newsletter_form']    = $("#newsletter_form");
    pageEls['footer_bubble']      = $("#footer_bubble");
    
    $("input[type='text']", "#contact_page").clearfield();
    $("input[type='text']", "#newsletter_form").clearfield();
    
    $("#caseStudiesNav").selectmenu();
    
    $("#nav li.selected a").fadeTo('fast', 0.5); 
    
    $("#nav li a").hover(function(){
        $(this).fadeTo('fast', 0.5); 
    }, function(){
        $(this).fadeTo('fast', 1);  
    });

	// handle the resizing of the background image
	pageEls['backgroundImage'] = $('#fauxbackground img');
    
	if (pageEls['backgroundImage'].length) {
        
        pageEls['backgroundImage'].load(function() {
            pageEls['backgroundImage'].show();
            bgImageRatio = pageEls['backgroundImage'].width() / pageEls['backgroundImage'].height();
            resizeImage();  
        });
	}
    
    $("#caseStudiesNav").change(function(){
        window.location = $(this).val();
    });
    
    pageEls['carousel_ul'].cycle({
        'after' : function() {
            updateCarouselNav();
        }
    });
    
    pageEls['carousel_nav_a'].click(function(e){
        var id = $(this).attr('id').replace("carousel_nav_", "") -1;
        pageEls['carousel_ul'].cycle(id);
        e.preventDefault();
    });
    
    pageEls['newsletter_trigger'].click(function(e) {
        
        if (pageEls['newsletter_form'].find('input').is(":visible"))
        {
            pageEls['newsletter_form'].find('input').animate({width:'hide'}, 800);
            pageEls['newsletter_form'].find('button').hide();
            pageEls['newsletter_form'].find('#pipes').hide();
            e.preventDefault();
        }
        else
        {
            pageEls['newsletter_form'].find('input').animate({width:'show'}, 800);
            pageEls['newsletter_form'].find('button').show();
            pageEls['newsletter_form'].find('#pipes').show();
            e.preventDefault();
        }
        
        e.preventDefault();
        
    });
    
    pageEls['newsletter_form'].submit(function(e) {
        
        e.preventDefault();
        
        $.post($(this).attr('action'), $(this).serialize(),
            function(data){
                if (data == "Success") {
                    
                    pageEls['footer_bubble'].css('background', 'transparent url(images/success_popup.png) no-repeat');
                    pageEls['footer_bubble'].find("p").text("Thank you for joining our newsletter.");
                    pageEls['footer_bubble'].show();
                    $("input[type='text']", pageEls['newsletter_form']).val('');
                    
                    setTimeout(function() {
                        pageEls['footer_bubble'].hide();
                        pageEls['footer_bubble'].css('background', 'transparent url(images/footer_bubble.png) no-repeat');
                        pageEls['newsletter_form'].fadeOut();
                    }, 2500);
                } else {
                    pageEls['footer_bubble'].find("p").text(data);
                    pageEls['footer_bubble'].show();
                }
        });
    
    });
    
    $("input[type='text']", pageEls['newsletter_form']).focus(function(){
        pageEls['footer_bubble'].fadeOut();
    });
    
    $("#case_studies_stacked a:nth-child(3n)").addClass('last');
	
});

/**
* This function joins the carousel nav with the carousel items
* it will highlight the currently shown item on the nav with
* it's associated item.
*/
function updateCarouselNav() {
    
    pageEls['carousel_li'] = $("#carousel ul li");
    
    pageEls['carousel_li'].each(function(){
        
       if ($(this).is(":visible")) {
           
           var id = $(this).attr('id').replace("#nav_", "");
           $("#carousel_nav_"+id+"").addClass('carousel_selected');
       } else {
           var id = $(this).attr('id').replace("#nav_", "");
           $("#carousel_nav_"+id+"").removeClass('carousel_selected');
       }
        
    });
    
}

function resizeImage() {
	windowWidth = $(window).width();
	windowHeight = $(window).height();
	windowRatio = windowWidth / windowHeight;
	
	var width = 'auto';
	var height = 'auto';
	if (windowRatio >= bgImageRatio) {
		width = windowWidth;
	} else {
		height = windowHeight;
	}
	pageEls['backgroundImage'].css({'width': width, 'height': height});
	var top = 0;
	var left = 0;
	if (width != 'auto') {
		left = 0;
		top = (windowHeight - pageEls['backgroundImage'].height()) / 2;
	} else {
		top = 0;
		left = (windowWidth - pageEls['backgroundImage'].width()) / 2;
	}
	pageEls['backgroundImage'].css({'top': top, 'left': left});
}

/* Clear Text Field on Input Plugin */
$.fn.clearfield = function() {
    return this.focus(function() {
        if( this.value == this.defaultValue ) {
            this.value = "";
        }
    }).blur(function() {
        if( !this.value.length ) {
            this.value = this.defaultValue;
        }
    });
};

(function ($, undefined) {
    $.each({
    load: function (el) { return el.complete || el.complete === undefined; },
    error: function (el) { return el.readyState === 'uninitialized' && el.src.indexOf('data:') === 0; }
    }, function (eventName, isReady) {
    $.event.special[eventName] = {
    add: function (handleObj) {
    var el = this, flag = eventName + '-guid', old_handler = handleObj.handler;

    if ( el.nodeType === 1 && el.nodeName.toUpperCase() === 'IMG' && el.src !== '' ) {
    // Check if the image is already loaded or if data URI images are supported
    // Trigger the event handler if necessary
    if ( isReady(el) ) {
    handleObj.handler = function () {
    var guid = $.data(el, flag), ret;
    if ( guid === old_handler.guid || guid === undefined ) {
    ret = old_handler.apply(el, arguments);
    }
    return ret;
    };

    // Let jQuery finish binding the event handler
    setTimeout(function () {
    $(el)
    .data(flag, old_handler.guid)
    .trigger(eventName)
    .removeData(flag);
    }, 0);
    }
    }
    }
    };
    });
}(jQuery))

