//Last Updated: 2010-10-05
//Developer: Dave McDermid

//document init events
$(function() {
    //make the content around the news item clickable
    makeLargeClickArea('.newsItem');
    //provides cross-browser hover info boxes
    makeHoverBox('.tnHoverInfo', true, false);
    makeHoverBox('.wmLocationInfo', false, true);
    //footer share-links menu
    makeSlideMenu('#shareLinksButton', '#shareLinks');
    //expandable list on Global Network page
    makeExpandableList('.elOverview', '.elDetail');
    //quicklinks on nestleSupportTools
    makeAccordian('.#quickLinksSide .quickLinks>ul>li>a', '.qlList ul');
    //radio buttons with extra sub-options
    makeRadioExpandableList('.expandingList', 'radioGroup00', '.subOptions');
    //make popup buttuns trigger the showing of the popup
    initPopUps();
    //character countdown for textareas
    initTextareaCounter('.fTextArea', '.charCounter');
    //setup scrollers
    makeScroller('#timelineNav ul', '#timelineNav .prevNav', '#timelineNav .nextNav', '#tnCurrent');
    makeScroller('.imageScroller ul', '.imageScroller .prevNav', '.imageScroller .nextNav');
    makeScroller('#brandsSelector ul', '#brandsSelector .prevNav', '#brandsSelector .nextNav');
    //setup carousels (like on the brands page)
    makeCarousel('.brandsContainer', '#brandsSelector ul a', 'selectedBrand');
    makeCarousel('#newsSelectorContainer', '#newsSelectorArticlesList ul a', 'selectedNewsItem', 'selected');
    makeCarousel('#pressReleaseDetails', '#paginatorOne a.num', 'selected', 'selected');
    //setup collapsibles
    makeCollapsibleTree('#siteMap', '.parent', function(item) {
        item.parents('.siteMapRow').find('dd').setToEqualHeight();
    });
    //left/right shortcuts for clicking on links
    makeLinkNavigators('#paginatorOne li:has(a.num)', '.selected', '#paginatorOne .back', '#paginatorOne .next');
    //hides default text in fields
    makeDefaultTextSwap('.swapDefault');
    //radio buttons with icons
    makeRadioIconCheck('.fRadio.withIcon');
    //attach nav items to links at the top of the nav
    makeNavQuickLink('#pageContentTools .iconShare', '#shareLinksSide');
    makeNavQuickLink('#pageContentTools .iconDownload', '#downloads');
    //sometimes we want to use js to align an item in the center
    centerChild('#brandsSelector ul');
	$('#siteMap .firstRow').find('dd').setToEqualHeight();
	$('#siteMap .secondRow').find('dt').setToEqualHeight();
	$('#siteMap .secondRow').find('dd').setToEqualHeight();
});

//window.load happens after images have finished loading, so that our min-height takes them into account
$(window).load(function() {
    $('.mainColHalf .container').setToEqualHeight();
    $('#templateTwoCol .featuresRow .container').setToEqualHeight();
    $('.centerColHalf .container').setToEqualHeight();
    $('.firstRow .centerColHalf .container').setToEqualHeight();
    $('.secondRow .centerColHalf .container').setToEqualHeight();
    $('.contentIntroForm:not(.unBalanced) .container').setToEqualHeight();
});

function initPopUps() {
    $('#help').click(function() { $('#whatAreThese').show(); return false; });
    $('#helpFooter').click(function() { $('#whatAreThese').show(); return false; });
    $('.showPopUp').click(function() { $('.showVideo').show(); return false; });
    $('.sendToFriendPopUp').click(function() { $('#prSendToFriend').show(); return false; });
    $('.subscribePopUp').click(function() { $('#prSubscribe').show(); return false; });
    $('.relatedImages').click(function() { $('#relatedImages').show(); return false; });
    $('.enlargeImage').click(function() { $('#recipeZoom').show(); return false; });
    $('.recipeCard').click(function() { $('#recipeCard').show(); return false; });
    $('.recipeCardSend').click(function() { $('#recipeCardSend').show(); return false; });
    $('.recipeCardRate').click(function() { $('#recipeCardRate').show(); return false; });
    $('.showVideoPub').click(function() { $('.multimedia').show(); return false; });
    $('.cRecipe').click(function() { $('#recipeSearchCard').show(); return false; });
    $('.cGlossary').click(function() { $('#recipeSearchCard').show(); return false; });
    $('.viewData').click(function() { $('#csvKpiData').show(); return false; });
    $('.showContactCard').click(function() { $('#relatedContacts').show(); return false; });
    $('.showChemicalCard').click(function() { $('#chemicalCard').show(); return false; });
    $('.showMeasurementCard').click(function() { $('#measurementCard').show(); return false; });
    $('#helpFooter').click(function() { $('#whatAreThese').show(); return false; });
    $('.popUpBox .closeBox,.popUpBox .close,.popUpBox .pubFade,.surveyNo').click(function() {
        //the fade out is more than aesthetic. Opera doesn't seem to re-render the page with a simple hide.
        $(this).closest('.popUpBox').hide().children().hide().show();
        //$(this).closest('.popUpBox .pubBlock').fadeOut(function(){$('.popUpBox').hide(); $(this).show();});
        return false;
    });

    $('a.ajaxPopup').live('click', function() {
        $('.popUpBox').addClass('loading').show().find('.pubContent').hide().load($(this).attr('href') + ' .pubContent >*', function() {
            $('.popUpBox').removeClass('loading').find('.pubContent').slideDown();
        });
        return false;
    });
}

//when an anchor containing the given element is hovered over, shows the element
//box: the box to show when the A is hovered
//separate: reattach the box to the body tag during hover (to counter overflow:hidden situations)
//hides all others (for situations where older browsers struggle with zIndex
function makeHoverBox(box, separate, hideOthers) {
    var myChild;
    $('a:has(' + box + ')').hover(function() {
        myChild = $(this).children(box);
        if (separate) myChild.appendTo('body').css({ position: 'absolute', left: $(this).offset().left + 'px', top: $(this).offset().top + $(this).outerHeight() + 10 + 'px' })
        myChild.show();
        if (hideOthers) $('a:has(' + box + ')').not(this).hide();
    }, function() {
        if (separate) myChild.css({ left: '', top: '', zIndex: 200 }).appendTo(this)
        myChild.hide();
        if (hideOthers) $('a:has(' + box + ')').not(this).show();
    });
}

//adds a checked class to a label when checked
function makeRadioIconCheck(e) {
    $(e).click(function() {
        $(e).siblings('label').removeClass('checked');
        if ($(this).attr('checked'))
            $(this).siblings('label').addClass('checked');
        else
            $(this).siblings('label').removeClass('checked');
    });
}

//When the given element is clicked, the first anchor tag within the element is triggered
function makeLargeClickArea(e) {
    $(e).click(function() {
        document.location = $(this).find('a:first').attr('href');
        return false;
    });
}

function makeAccordian(a, c) {
    $(c).hide();
    $(a).click(function() {
        var s = $(this).parent().find(c);
        if (s.is(':visible')) {
            s.slideUp();
            $(this).parent().removeClass('selected');
        }
        else {
            s.slideDown();
            $(this).parent().addClass('selected');
        }
        return false;
    });
}

//makes an expandable list for given pairs of overview/detail items
//each pair are expected to be within a list item.
//a class of selected is applied to the parent list item currently selected
function makeExpandableList(o, d) {
    $(d).hide();
    $(o).click(function() {
        $('li.selected:has(' + o + ')').find(d).slideUp();
        if (!$(this).parent().hasClass('selected')) {
            $(this).siblings(d).slideDown().parent().addClass('selected');
        }
        else {
            $(this).parent().removeClass('selected');
        }
        $(this).parent().siblings().removeClass('selected');
        return false;
    });
}
function makeRadioExpandableList(container, group, sub) {
    //attach event to all radio buttons for this group
    $(':radio[name=' + group + ']').click(function() {
        //loop over all of them, hiding options if unselected, showing if selected
        $(':radio[name=' + group + ']').each(function() {
            if ($(this).attr('checked')) {
                $(this).parents(container).find(sub).slideDown().find(':radio:first').attr('checked', true);
            }
            else {
                $(this).parents(container).find(sub).slideUp().find(':radio').attr('checked', false);
            }
        });
    }).filter(':checked').triggerHandler('click');
}

//makes a hide/show sliding menu for the given button, content
//any .closeBox inside the content will also hide the content
function makeSlideMenu(b, c) {
    $(c).hide();
    $(b).click(function() {
        $(c).slideDown();
        return false;
    });
    $(c + ' .closeBox').click(function() {
        $(c).slideUp();
        return false;
    });
}

//when the link is clicked, the taget slides down below the link
function makeNavQuickLink(link, target) {
    $(link).click(function() {
        $(target).css({ position: 'absolute', left: $("#pageContentTools .iconContact").position().left + 'px', top: $(link).position().top + 'px' })
		.slideDown();
        $(this).blur();
        return false;
    });
    $(target).hide().find('.closeBox').click(function() {
        $(this).closest(target).slideUp();
        return false;
    });
}



//container: the textarea / chars container
//chars: the element containing the number of remaining characters
function initTextareaCounter(container, chars) {
	$(container).each(function() {
		var maxChars = $(this).find(chars).text() * 1;
		$(this).find('textarea').bind('keyup blur', function() {
		    if ($(this).val().length > maxChars){
				$(this).val($(this).val().substring(0, maxChars))}
				
			$(this)
				.parents(container).find(chars).text(maxChars - $(this).val().length)
				.parent().removeClass('fErrorMessage').addClass(((maxChars - $(this).val().length) < 0 ? 'fErrorMessage' : ''));
		}).blur();
	});
}


//scroller: the parent of the items that should scroll (typically a UL)
//left: the link to navigate left
//right: the link to navigate right
//step: the number of items to scroll at one time
//speed: the speed of the animation
function makeScroller(scroller, left, right, current) {
    //check we have a scroller, if not: bail.
    if ($(scroller).length == 0) return;
    var index = 0;
    var step = 1;
    var speed = 200;
    //remember the width of the scroller, so we can set the wrapper
    var width = $(scroller).outerWidth();
    var childWidths = $(scroller).childWidths();
    // This is a fix for aboutus page to work in IE 6
    if (scroller.indexOf('timelineNav') > 0) {
        childWidths = 689;
    }
    // Fix end
    //make our scroller wide enough for its children
    $(scroller).css({ width: childWidths + 'px' });
    //wrap our target element in a container that hides overflow
    var scrollWrapper = $('<div></div>').css({
        display: 'block',
        position: 'relative',
        width: width + 'px',
        height: $(scroller).outerHeight() + 'px',
        float: $(scroller).css('float'),
        overflow: 'hidden'
    });
    $(scroller).wrap(scrollWrapper);
    //check we even need a scroller, and hide buttons if we don't
    if (childWidths <= width) {
        $(left).add(right).addClass('hidden');
        return;
    }
    //add disabled class if either button is unclickable
    var checkDisabled = function() {
        if (index == 0) {
            $(left).addClass('disabled');
        }
        else {
            $(left).removeClass('disabled');
        }
        if ($(scroller).width() - $(scroller).parent().scrollLeft() <= $(scroller).parent().width()) {
            $(right).addClass('disabled');
        }
        else {
            $(right).removeClass('disabled');
        }
    };
    checkDisabled();
    //setup prev / next click events
    $(left).click(function() {
        //check there is an item to scroll to
        if ($(scroller).children().eq(index - step).position()) {
            $(scroller).parent().animate({ scrollLeft: $(scroller).children().eq(index -= step).position().left }, speed, 'swing', checkDisabled);
        }
        return false;
    });
    $(right).click(function() {
        //check we still have distance to scroll
        if ($(scroller).width() - $(scroller).parent().scrollLeft() > $(scroller).parent().width()) {
            //check there is an item to scroll to
            if ($(scroller).children().eq(index + step).position()) {
                $(scroller).parent().animate({ scrollLeft: $(scroller).children().eq(index += step).position().left }, speed, 'swing', checkDisabled);
            }
        }
        return false;
    });
    //make sure the 'current' item is visible
    if (current != undefined) {
        while (($(current).position().left + $(current).width()) > (width + $(scroller).parent().scrollLeft())) {
            $(scroller).parent().scrollLeft($(scroller).children().eq(index += step).position().left);
            checkDisabled();
        }
    }
}

//container: a wrapper round the items that are selectable
//links: the anchor tags that switch the selected item
//activeClass: a class to be applied to the currently active item
//linkActiveClass: adds this class to the aprent of the selected link
//				   defaults to fading out parent if none supplied
function makeCarousel(container, links, activeClass, linkActiveClass) {
    //setup
    $(container).scrollTop(0);
    $(container).css({ position: 'relative' }).find('>*').css({ position: 'absolute', top: '0px' });
    //attach click events
    $(links).click(function() {
        var id = $(this).attr('hash');
        if (!id) return false;
        if ($(id).hasClass(activeClass)) {
            var link = $(id).find('a:first').click();
            return false;
        }
        $(this).blur()
        //set active class, or default to fade
        if (linkActiveClass)
            $(this).parent().addClass(linkActiveClass).siblings().removeClass(linkActiveClass);
        else
            $(this).parent().fadeTo('fast', .3).siblings().fadeTo('fast', 1);
        //set the new front item
        $(id).siblings().not('.' + activeClass).hide();
        var old = $(container).find('.' + activeClass).removeClass(activeClass).css({ zIndex: 99 });
        //fade it in
        $(id).css({ zIndex: 100 }).addClass(activeClass).fadeIn(function() { old.hide(); });
        return false;
    });
    //set default link style / jump to correct item
    var defLink;
    if (location.hash) {
        defLink = $(links).filter('[href=' + location.hash + ']');
    }
    if (!defLink) defLink = $(links).eq(0);
    $(container).find('.' + activeClass).removeClass(activeClass);
    defLink.triggerHandler('click');
}

//links: the links to be triggered
//selected: the currently selected link
//back: trigger the link to the left
//forward: trigger the link to the right
function makeLinkNavigators(links, selected, back, forward) {
    links = $(links);
    $(back).click(function() {
        if (links.filter(selected).length > 0)
            $(links[(links.index(links.filter(selected)) + links.length - 1) % links.length]).find('a').click();
        return false;
    });
    $(forward).click(function() {
        if (links.filter(selected).length > 0)
            $(links[(links.index(links.filter(selected)) + 1) % links.length]).find('a').click();
        return false;
    });
}

function makeCollapsibleTree(container, selector, callBack) {
    $(container).find(selector).prepend('<a class="expandCollapse" href="#">&#160;</a>')
    $(container).find('ul ul').hide();
    $(container).find(selector).addClass('collapsed');
    $(container).find('.expandCollapse').click(function() {
        var item = $(this).blur().parent();
        if (item.hasClass('collapsed')) {
            item.removeClass('collapsed');
            item.children('ul').show();
        }
        else {
            item.addClass('collapsed');
            item.children('ul').hide();
        }
        if (typeof callBack == 'function') callBack(item);
        return false;
    });
}

function makeDefaultTextSwap(field) {
    if ($(field).length == 0) return;
    $(field).data('defaultText', $(field).val())
	.focus(function() {
	    $(this).css({ color: '#000' });
	    if ($(this).val() == $(this).data('defaultText'))
	        $(this).val('');
	})
	.blur(function() {
	    if ($(this).val() == '' || $(this).val() == $(this).data('defaultText')) {
	        $(this).css({ color: '#777' });
	        $(this).val($(this).data('defaultText'));
	    }
	}).triggerHandler('blur');
}

function centerChild(item) {
    item = $(item);
    if (item.outerWidth() < item.parent().width())
        item.css('marginLeft', (item.parent().width() - item.outerWidth()) / 2);
}

/*
jQuery Extensions
*/


$.fn.extend({
    //gets the sum of the widths (inc. padding/margin) of an element's children
    'childWidths': function() {
        var width = 0;
        $(this).children().each(function() {
            width += $(this).outerWidth(true);
        });
        return width;
    },
    //sets all elements matching the given selector to the same (max) height
    'setToEqualHeight': function() {
        this.css({ minHeight: 0 });
        var maxHeight = 0;
        this.each(function() {
            maxHeight = Math.max(maxHeight, $(this).height());
        });
        return this.css({ minHeight: maxHeight + 'px' });
    }
});


