(function(){
	
	// jQuery plugins

	// Stack window.onload functions
	$.fn.addLoad = function(func){
		var old = window.onload;
		func instanceof Function
			&& (window.onload = 
				old instanceof Function
					? function(){func();old()}
					: func);
		return $(this);
	};

	// Cross-browser outerHTML 
	$.fn.outerHTML = function(arg){ 
		var $el = this;

		return arg 
			? $el.replaceWith(arg) 
			: $el.clone().wrap('<b>').parent().html(); 
	}; 

	// Return all attributes, optionally as an object (obj: boolean) 
	// by default as a matrix, optionally filtered by a regexp (expr)
	$.fn.attrs = function(array,expr){ 
		var 
			el = this[0], 
			$el = this, 
			attrArray = [],
			attrObj = {};

		for(var i=0, attrs = el.attributes; i<attrs.length; ++i){ 
			var attrKey = [
				attrs.item(i).nodeName, 
				attrs.item(i).nodeValue
			];

			if(!expr || expr.test(attrKey[0])){
				attrArray.push(attrKey);
				attrObj[attrKey[0]] = attrKey[1];
			}
		};

		return array ? attrArray : attrObj;
	};

	// Force hasLayout: wait til after page load, toggle zoom moments later
	$.fn.hasLayout = function(){
		var 
			$el = $(this),
			zoom = function(){
				$el.css('zoom','0').css('zoom','100%');
			},
			delay = function(x){
				setTimeout(x,60);
			};

		$().addLoad(function(){delay(zoom)});

		return $el;
	};

}());



$(function () {

    /* <careers> */

    // Overlays / event application
    (function () {
        var 
			$overlay = $('.g_overlayWrapper1'),
			$wash = $overlay.find('.g_overlayDecoration'),
			$close = $overlay.find('.g_overlayClose'),
			$content = $overlay.find('.g_overlayContent'),
			overlayClose = function () {
			    $overlay.fadeOut();
			    $content.empty();
			};

        $overlay.appendTo('form').eq(0);
        $wash.click(overlayClose);
        $close.click(overlayClose);

        $('.gEvent_eventItem').each(function () {
            var 
				el = this,
				$el = $(this),
				$form = $el.find('.gEvent_formWrapper2'),
				$formClone = $form.clone(),
				$inputOn = $el.find('.inputRegister'),
				$inputOff = $el.find('.inputClose');

            $inputOn
				.attr('href', '#')
				.click(function () {
				    $content.append($formClone);
				    $overlay.fadeIn();
				});

            $inputOff.click(overlayClose);

            $('.gEvent_formWrapper2 :text, .gEvent_formWrapper2 label span').live('focus blur', function (e) {
                var 
					el = this,
					$el = $(this),
					$span = $el.prev('span');

                if ($el.is('span')) {
                    $el.next(':text').click();
                    return;
                };

                if (!$el.val().match(/^\s*$/) || e.type == 'focusin') {
                    $span.hide()
                }
                else {
                    $span.show()
                };
            });

            $('.gEvent_formWrapper2 :text').each(function () { $(this).click() });

            //SH - removed this because it doesn't work
            /*$('.gEvent_formWrapper2 .inputButton').live('click',function(e){
            e.preventDefault();

            var
            $form = $('form').eq(0),
            form = $form[0];

            $.ajax({
            type: form.method,
            cache: false,
            url: form.action,
            data: $form.serialize(),
            success: overlayClose
            });

            $content.animate('opacity','0');
            });*/
        });
    } ());

    // FAQs mechanism 
    $('.gFAQ_wrapper').each(function () {
        var 
			el = this,
			$el = $(this),
			$input = $el.find('.gFAQ_input'),
			$answer = $el.find('.gFAQ_answer'),
			on = false,
			onClass = 'gFAQ_active',
			offClass = 'gFAQ_inactive';

        $answer.css('display', 'none');

        $input.click(function () {
            $el
				.toggleClass(onClass)
				.toggleClass(offClass);

            $answer.slideToggle();
        });
    });

    // Convert youtube embeds with custom attribute to allow custom play button
    $('body.Graduates iframe, body.Graduates embed').each(function () {
        return;

        var 
			el = this,
			$el = $(this),
			$replace =
				el.tagName == 'embed'
					? $el.parent('object')
					: $el;

        var 
			attrs = $el.attrs(),
			params = {
			    initialVideo: attrs.src.split('embed/')[1].substring(0, 11),
			    height: attrs.height,
			    width: attrs.width,
			    onPlay: function () {
			        $button.fadeOut();
			    }
			};

        if (attrs.width < 200)
            params.showControls = 0;

        var 
			$wrap1 = $('<div>').addClass('customVideoWrapper1'),
			$wrap2 = $('<div>').addClass('customVideoWrapper2').appendTo($wrap1),
			$button = $('<img>').addClass('customVideoButton').attr('src', danone.root + 'SiteImages/graduates.sprite.play.png').hasLayout().appendTo($wrap1);

        $wrap1.insertAfter($el);
        $wrap2.tubeplayer(params);

        $replace.remove();

        $button.click(function (e) {
            e.preventDefault();
            $wrap2.tubeplayer('play');
        });

    });

    /*
    // Make text content fit to one line
    $('.maximizeFontSize').each(function(){
    var
    el = this,
    $el = $(this),
    width = $el.width(),
    maxWidth = $el.parent('.line').width(),
    resize = function(negative){
    var increment = negative ? -1 : 1;

    $el.css('font-size',
    ~~$el.css('font-size').split('px')[0]
    + increment
    + 'px'
    );
    };

    console.log(maxWidth);

    while(width < maxWidth)
    resize();
    });
    */

    /* </careers> */

    /* <legacy> */

    $('a.lb').box({ close: 1, animate: 0 });

    $.fn.box.getFlashSize = function (elem) {
        return [640, 400];
    };

    $('.hasToggle div').filter(function () {
        return this.className.search(/hr|toggle|blueBox/g) === -1;
    }).hide();

    $('.hasToggle h4').click(function () {
        var div = $(this).next();
        if (div.hasClass('active')) {
            div.removeClass('active').slideUp();
            $('span', this).css({ backgroundPosition: 'left top' });
        } else {
            div.addClass('active').slideDown();
            $('span', this).css({ backgroundPosition: 'left bottom' });
        };
        return false;
    });


    // CMS hack layout hack;
    $('.doubleColumn').each(function () {
        if ($(this).children('img').length === 0) {
            $(this).children().css("width", "100%");
        };
    });

    /* </legacy> */

});
