var $j = jQuery.noConflict();

var scroller = function (dest) {
	var destination = dest.href.split('#');
	var topOffset;
	if (isMedia("screen and (max-width:1000px)")) {
	   var topOffset = 0;
	}
	else {
	   var topOffset = 140;
	}
	$j('html, body').animate({scrollTop: (($j('#' + destination[destination.length - 1]).offset().top) - topOffset)}, 500);
}

var scrollToCs = function () {
    var topOffset;
    if (isMedia("screen and (max-width:1000px)")) {
	   var topOffset = 0;
	}
	else {
	   var topOffset = 148;
	}
    $j('html, body').animate({scrollTop: (($j('#loading_bar').offset().top) - topOffset)}, 500);
}

var scrollToTop = function () {
    var topOffset;
    if (!isMedia("screen and (max-width:1000px)")) {
	   var topOffset = 0;
	}
	else {
	   var topOffset = 140;
	}
    $j('html, body').animate({scrollTop: topOffset}, 500);
}

$j(document).ready(function() {

    $j('#contact').jqTransform();
    $j('#footer_form .form_field label').inFieldLabels().addClass('enhanced');
    $j('#more_details').colorbox({
        href: "#about_modal",
        inline: 'true',
        scrolling: false
    });
    $j('#isk_modal').colorbox({
        href: "#isk_modal_content",
        inline: 'true',
        width: '812px'
    });
    
    // FAQ
    var questionAnchors = $j('.questions a');
    var faqGroup = $j('#faq_nav .group');
    $j('.faq_text').hide();
    $j('.questions').hide();
    faqGroup.click(function() {
        var self = $j(this);
        if (self.hasClass('active')) {
            return false;
        }
        else {
            faqGroup.removeClass('active');
            $j('.active_questions').slideUp(function() {
                $j('.active_questions').removeClass('active_questions');
                self.siblings('.questions').slideToggle().addClass('active_questions');
                self.addClass('active');
            });
        }
    });
    questionAnchors.click(function() {
        var hrefString = this.href;
        var idFrag = hrefString.substring(hrefString.indexOf('#'));
        questionAnchors.removeClass('active');
        $j(this).toggleClass('active');
        $j('.faq_text').hide();
        $j(idFrag).show();
        return false;
    });
    
    $j('#sec_nav a').click(function () {
		scroller(this);
		return false;
	});
	
	// Using custom configuration
	$j("#slider_list").carouFredSel({
		items				: 5,
		auto : {
            play            : false
		},
		scroll : {
			items			: 5,
			duration		: 1000							
		},
		next : {
            button          : '#slide_right'
		},
		prev : {
            button          : '#slide_left'
		}					
	});
	
	// Case Studies Viewer
	if ($j('html.ie7, html.ie8').length < 1) {
        var caseHolder = $j('#cs_holder');
        // Load First Case Study on Case Studies Page
    	if ($j('#case_study').length < 1) {
            var firstCaseStudy = $j('.cs_link:first').attr('href');
            $j.get(firstCaseStudy, function (data) {
    			var fetchedData = $j(data).find('#case_study');
    			$j.data(self, 'storage', fetchedData);
    			caseHolder.empty().append(fetchedData); 
    			makeLinkActive();
    		});
    	}
	   // Load chosen Case Study on click
	   $j('#cs_sect').delegate('a.cs_link, #prev_next a', 'click', function() {
            var self = this;
            caseHolder.slideUp('slow');    
    		$j.get(self.href, function (data) {
    			var fetchedData = $j(data).find('#case_study');
    			caseHolder.empty().append(fetchedData);
    			makeLinkActive();
    			scrollToCs();
    			caseHolder.slideDown('slow'); 
    		});
        	return false;
        });
	}
	
	// Approach Sub Nav Sticky
	if (document.getElementById('sub_nav')) {
        var stickyEl = $j('#sub_nav_inner');
        stickyEl.wrap('<div class="sticky_wrapper" />');
        $j('.sticky_wrapper').css('height', stickyEl.height());
        if ($j('section.full_length').length > 0) {
            
            $j('.sticky_wrapper').css('height', $('section.full_length').offset().top - $j('.sticky_wrapper').offset().top - 100 + 'px');
            stickyEl.stickyfloat({
                'lockBottom' : true
            });
        }
        else {
            stickyEl.stickyfloat();
        }      
    }
    
    // Secondary Nav on Homepage 
    if (document.getElementById('sec_nav') && !isMedia("screen and (max-width:1000px)")) {
        var secNav = $j('#sec_nav');
        var secNavOffsetTop = $j('#sec_nav').offset().top - 146;
        $j(window).scroll(function () {
            var secNavOffset = $j('#sec_nav').offset().top - $j(window).scrollTop() - 146; //531
            
            if (secNavOffset < 0) {
                secNav.addClass('fixed');
            }
            
            if ($j(window).scrollTop() < secNavOffsetTop) {
                secNav.removeClass('fixed');
            }
            
        });
    }
    
    // Load First FAQ into content
    $j('.questions:first').slideDown().addClass('active_questions');
    $j('a.group:first').addClass('active');
    $j('.active_questions li a:first').addClass('active');
    $j('.faq_text:first').show();
    
    // Contact Page
    $j('#receive_mail').change(function() {
        $j('#addr_info').slideToggle();
    });
    if ($j('#receive_mail').attr('checked') != 'checked') {
        $j('#addr_info').hide();
    }
    
    // Homepage -- Waypoints
    var secNavLinks = $j('#sec_nav a');
    $j('#about').waypoint(function(event, direction) {
        $j(this).animate({
            opacity: 1
        }, 1000);
    }, {
        offset: '50%'
    });
    $j('#about_container').waypoint(function(event, direction) {
        secNavLinks.removeClass('current');
        $j('#navAbout').addClass('current');
    }, {
        offset: '0%'
    });
    $j('#faq').waypoint(function(event, direction) {
        secNavLinks.removeClass('current');
        $j('#navFaq').addClass('current');
    }, {
        offset: '65%'
    });
    $j('#homeTitle').waypoint(function(event, direction) {
        secNavLinks.removeClass('current');
        $j('#navTop').addClass('current');
    }, {
        offset: '20%'
    });
    
    // External Links
    $j(document).delegate('a[rel*="external"]', 'click', function(e) {
    	e.preventDefault();
    	window.open(this.href);
    });
    
    // Mailto Links
    $j('a[href^="mailto:"]').each(function() {
    	var self = $j(this);
    	var obscuredEmail = this.href.replace(/mailto:/g, '');
    	var unobscuredEmail = obscuredEmail.replace(/\/at\//g, '@');
    	self.attr('href', 'mailto:' + unobscuredEmail).text(self.text().replace(obscuredEmail, unobscuredEmail));
	});
    
});

var makeLinkActive = function() {
    $j('a.cs_link').removeClass('active');
    var csFlag = $j('#case_study').attr('data-casestudy');
    $j('a.cs_link[data-identifier="' + csFlag + '"]').addClass('active');
}

var glider = "";
            
document.observe("dom:loaded", function() {

    if (document.getElementById('glider_container')) {
        var hash = window.location.hash;
        var section = hash.split("_")[1];
        var anchor = (section) ? '#' + section : "#non-technology-improvement";
        
        //console.log(anchor);

        $$('#glider_container .controls li a').each(function(element) {
            element.observe('click', function() { selectSectionTab(element); scrollToTop(); });
        });
      
        var element = $('glider').down('.controls li a[href='+anchor+']');
        if (element) { 
            selectSectionTab(element);
        }
        // JDW - additions
        $j('#sub_nav_inner ul li a').removeClass('active');
        $j('#sub_nav_inner ul li a[href*="' + anchor + '"]').addClass('active');
        // END
        glider = new Glider('glider', {initialSection:section, duration:0.5});
    }
    
});

function replaceClassName(element, className) {
  element.addClassName(className);
}

function selectSectionTab(element) {
  replaceClassName(element, 'active');
}

function refreshSectionTab() {
    var anchor = "#" + glider.current.id;
    // JDW - additions
    $j('#sub_nav_inner ul li a').removeClass('active');
    $j('#sub_nav_inner ul li a[href*="' + anchor + '"]').addClass('active');
    // END
    var element = $('glider').down('.controls li a[href='+anchor+']');
    if (element) {
        console.log('true');
        var subLinks = $('sub_nav').select('a');
        subLinks.each(function(element) {
            element.removeClassName('active');
        });
        selectSectionTab(element);
    }
}

// Extend Effect.SmoothScroll, updating url hash when animation finishes
Object.extend(Effect.SmoothScroll.prototype, {
    finish: function() {
        window.location.hash = "#_"+glider.current.id;
        return false;
    }
});
            

