/**
 *	primary JavaScript file for HeinzSoups.com
 *	requires: jquery.js (written and tested against jQuery version 1.6.2)
 *	requires: bgc.js
 */

// create CSS hook for JavaScript-enabled clients
if ( $.browser.msie ) {
	$( 'html' ).removeClass( 'no-js' ).addClass( 'js ie ie' + parseInt ( $.browser.version ) );
} else {
	$( 'html' ).removeClass ( 'no-js' ).addClass( 'js not-ie' );
}

// prevent background image flicker in IE
try {
	if (!window.opera) document.execCommand("BackgroundImageCache", false, true);
} catch(err) {};

// GA initialization and pageview tracking
BGC.track.init("UA-9175922-4", "UA-13071338-1");
BGC.track();

// Creates method on global string object for scrubbing purposes
String.prototype.cleanLabel = function () {
	return this.replace(/\W/g, "");
};

var HeinzSoups = HeinzSoups || {};

jQuery.fn.reverse = [].reverse;

$(function() {

	HeinzSoups.Tracking.init();
	HeinzSoups.Navigation.init();
	HeinzSoups.UI.init();
	HeinzSoups.FixIE.init();
	
	// Fixes bug with IE, after styling
	$('a#fancybox-close').live('click', function(e) {
		e.preventDefault();
		$.fancybox.close();
	});

});

HeinzSoups.FixIE = {

	settings : {
		'browserVersion' : 0
	},

	init : function ( options ) {
	
		if ( options ) {
			$.extend ( HeinzSoups.FixIE.settings, options );
		}
		
		if ( ! $.browser.msie ) {
			return;
		} else {
			HeinzSoups.FixIE.browserVersion = parseInt ( $.browser.version );
		}
	
	}

};


HeinzSoups.Home = {

	settings : {
	
	},

	init : function ( options ) {
		
		if ( options ) {
			$.extend ( HeinzSoups.FreeSoups.settings, options );
		}
		
		HeinzSoups.Home.footer();
		
		$( '#slides').slides({
			pagination: true,
			generatePagination: true,
			preload: true,
			preloadImage: '/img/ajax_loader.gif',
			play: 5000,
			pause: 2500,
			hoverPause: true,
			effect: 'fade'
		});
		
		$( '#callouts .callout p' ).equalizeCols();
		
		$( '#show_quick_newsletter_preview' ).live( 'click', function ( e ) {
			e.preventDefault();
			HeinzSoups.Home.openNewsletterPreview();
		});
		
		$( '#close_quick_newsletter_preview' ).live( 'click' , function ( e ) {
			e.preventDefault();
			HeinzSoups.Home.closeNewsletterPreview();
		});
		
	},
	
	openNewsletterPreview : function() {
		$( 'aside, article' ).removeAttr( 'style' );
			
		$( '#show_quick_newsletter_preview' ).parent().css({
			'display' : 'none'
		});
		
		$( '#quick_newsletter_preview' ).css({
			'display' : 'block'
		});
			
		$( 'aside, article' ).equalizeCols();
	},
	
	closeNewsletterPreview : function() {
		$( 'aside, article' ).removeAttr( 'style' );
			
		$( '#close_quick_newsletter_preview' ).parent().css({
			'display' : 'none'
		});
		
		$( '#module_newsletter_signup' ).css({
			'display' : 'block'
		});
		
		$( 'aside, article' ).equalizeCols();
	},
	
	footer : function () {
		
		var siteFooter = $('.site_footer').html();
		$('.site_footer').remove();
	
		$('<footer/>', {
			"class" : "site_footer",
			"html" : siteFooter
		}).appendTo('.body_container_top');
		
	}

};

HeinzSoups.FreeSoups = {
    settings: {
        thanksPage: false
    },
    nativeListPosition: null,
    init: function (options) {
        if (options) $.extend(HeinzSoups.FreeSoups.settings, options);

        if (!HeinzSoups.FreeSoups.showPreselected()) { //only load from cookie if no preselected var
            HeinzSoups.FreeSoups.loadFromCookie();
        }

        if (options && options.thanksPage) setTimeout('eraseCookie("Products")', 500);
        else {
            $('.accordion .item_checkbox_image input[type="checkbox"]').live('click', function (e) {
                var sku = $(this).parent().parent().parent().find('input[type="hidden"]').val();
                var name = $(this).parent().parent().parent().find('.free-soup-title').text();
                if ($(this).prop('checked')) HeinzSoups.FreeSoups.addSoup(sku, name);
                else HeinzSoups.FreeSoups.removeSoup(sku, name);
            });
            $('#free-soup li').click(function (e) {
                if (e.target.tagName != "A" && e.target.tagName != "INPUT") {
                    $checkbox = $(e.currentTarget).find('input[type="checkbox"]');

                    var sku = $checkbox.parent().parent().parent().find('input[type="hidden"]').val();
                    var name = $checkbox.parent().parent().parent().find('.free-soup-title').text();
                    if (!$checkbox.prop('checked')) {
                        HeinzSoups.FreeSoups.addSoup(sku, name); //OPPOSITE of real click
                        $checkbox.prop('checked', true);
                    }
                    else {
                        HeinzSoups.FreeSoups.removeSoup(sku, name);
                        $checkbox.prop('checked', false);
                    }
                }
            });

            $('#free-soups-submit').click(function (e) {
                if ($(this).hasClass('disabled')) e.preventDefault();
            });

            HeinzSoups.FreeSoups.nativeListPosition = $('#free-soups-list').offset().top;
            $(window).scroll(function () {
                HeinzSoups.FreeSoups.updateListPosition($(window).scrollTop());
            });
        }

        $('#SoupFilter select').change(function () {
            var selectedPlatform = $(this).val();
            if (selectedPlatform == "All") $('#free-soup li').show();
            else {
                selectedPlatform = ".platform_" + selectedPlatform;
                $('#free-soup li:not(' + selectedPlatform + ')').hide();
                $('#free-soup li.' + selectedPlatform).show();
            }
        });
    },

    loadFromCookie: function () {
        var productsList = readCookie("Products");
        if (productsList && productsList.length > 0) {
            productsList = productsList.split("|");
            $(productsList).each(function (i, e) {
                var product = e.split(",");
                HeinzSoups.FreeSoups.addSoup(product[0], product[1], true);
            });
        }
        if ($('#list-box ul').children().length < 1) $('#free-soups-submit').removeClass('enabled').addClass('disabled');
    },

    updateListPosition: function (scrollPos) {
        if (scrollPos > HeinzSoups.FreeSoups.nativeListPosition - 10) {
            $('#free-soups-list').addClass('fixed').css('top', 10);
        }
        else {
            $('#free-soups-list').removeClass('fixed').removeAttr('style');
        }
    },

    addSoup: function (sku, name, fromCookie) {
        name = name.replace(/[^a-zA-Z0-9 &]/g, '');
        if (!(sku.toString().length > 0 && name.length > 0)) return;
        if (!fromCookie) BGC.track("addSoup|" + name + "|SKU|" + sku);

        var $list = $('#list-box ul');
        var alreadyInList = false;
        $list.find('li').each(function (i, e) {
            if ($(e).attr('id') == "list-soup_" + sku) alreadyInList = true;
        });
        if (alreadyInList) return;

        var $li = $("<li></li>")
            .attr("id", "list-soup_" + sku)
            .append(
                $("<span></span>")
                .addClass("soup-name")
                .text(name)
            );
        /*if (HeinzSoups.FreeSoups.listCount / 2 != Math.floor(HeinzSoups.FreeSoups.listCount / 2))
        $li.addClass("even");*/
        $li.addClass("even");
        var $cancel = $("<span></span>")
            .attr("class", "remove-soup")
            .click(function (e) {
                //var sku = $(this).parent().attr("id");
                //sku = sku.substr(sku.indexOf("_") + 1);
                HeinzSoups.FreeSoups.removeSoup(sku, name);
            })
            .appendTo($li);
        var $bullet = $("<span class='bullet'></span>")
            .appendTo($li);
        $li.prependTo($list);

        HeinzSoups.FreeSoups.updateListEvens();

        if (!fromCookie) { $li.effect('highlight', {}, 2000); }
        if (fromCookie) $('input[value="' + sku + '"]').parent().find('input[type="checkbox"]').prop('checked', true);

        $('#free-soups-explanation').hide();
        $('#free-soups-submit').addClass('enabled').removeClass('disabled');
        setTimeout("HeinzSoups.FreeSoups.rewriteCookie()", 100);
    },

    removeSoup: function (sku, name) {
        BGC.track("removeSoup|" + name + "|SKU|" + sku);

        var $list = $('#list-box ul');
        var $li = $list.find('#list-soup_' + sku);
        $li.remove();

        HeinzSoups.FreeSoups.updateListEvens();

        $('input[value="' + sku + '"]').parent().find('input[type="checkbox"]').prop('checked', false);

        if ($list.children().length < 1) $('#free-soups-explanation').show();
        if ($list.children().length < 1) $('#free-soups-submit').removeClass('enabled').addClass('disabled');
        setTimeout("HeinzSoups.FreeSoups.rewriteCookie()", 100);
    },

    updateListEvens: function () {
        var $list = $('#list-box ul');
        $list.find('li').each(function (i, e) {
            if (i != 0) $(e).stop(true, true).removeAttr('style');
            $(e).removeClass('even');
            if (i / 2 == Math.floor(i / 2)) $(e).addClass('even');
        });
    },

    rewriteCookie: function () {
        var $list = $('#list-box ul');

        var cookieString = "";
        //go through, add ids
        $($list.find('li').reverse()).each(function (i, e) {
            cookieString += e.id.substr(10) + "," + $(e).find('.soup-name').text() + "|";
        });
        cookieString = cookieString.substr(0, cookieString.length - 1);

        createCookie("Products", cookieString, 1);
    },

    showPreselected: function () { // ex: /free-soup-samples.aspx?preselected=416080
        var preselectedValue = urlVar('preselected');
        if (preselectedValue === '' || $('#free-soup li[rel="' + preselectedValue + '"]').length == 0)
            return false

        $checkbox = $('#free-soup li[rel="' + preselectedValue + '"] input[type="checkbox"]');
        var sku = $checkbox.parent().parent().parent().find('input[type="hidden"]').val();
        var name = $checkbox.parent().parent().parent().find('.free-soup-title').text();

        HeinzSoups.FreeSoups.addSoup(sku, name, true);

        return true
    },

    resizeWindow: function () {
        /*$('.body_container').removeAttr('style');
        HeinzSoups.UI.resizeBodyContainer();*/
    }
};

HeinzSoups.ProductTabs = {

	settings : {
		defaultTab : 'product'
	},

	init : function ( options ) {
		if ( options ) {
			$.extend ( HeinzSoups.ProductTabs.settings, options );
		}
		var tab = urlVar( 'tab' );
		tab = tab === '' ? HeinzSoups.ProductTabs.settings.defaultTab : tab;
		$('body').attr( 'class', 'products ' + tab );
		
		$( 'section#'+tab).css({
			'display' : 'block'
		});
		
		$('div.body_container').removeAttr('style');
		HeinzSoups.UI.resizeBodyContainer();
		
		
	}

};

HeinzSoups.Navigation = {

	settings : {
		'selector' : '#primary-nav ul:first',
		'jsonFile' : '/js/mylibs/navigation.json'
	},
	
	init : function ( options ) {
		
		if ( options ) {
			$.extend ( HeinzSoups.Navigation.settings, options );
		}
		
		HeinzSoups.Navigation.highlightTrail();
		
		$( '#primary-nav ul:first li' ).hover(function(e) {
		
				if ( jQuery.browser.msie ) {
				
					var browserVersion = parseInt ( jQuery.browser.version );
				
					if ( browserVersion < 8 && $.trim( $(this).children('a:first').text() ) == 'Contact Us' ) {
						$('div.quick_contact_links').css('display', 'none');
					}
				
				}
		
				$(this).children('.nav-submenu').css({
					'display' : 'block'
				});
				
		}, function(e) {
		
				if ( jQuery.browser.msie ) {
				
					var browserVersion = parseInt ( jQuery.browser.version );
				
					if ( browserVersion < 8 && $.trim( $(this).children('a:first').text() ) == 'Contact Us' && ! $('body').hasClass('home') ) {
						$('div.quick_contact_links').css('display', 'block');
					}
				
				}

				$(this).children('.nav-submenu').css({
					'display' : 'none'
				});

		});
		
	},
	
	highlightTrail : function() {
		
		var bodyClass = $.trim ( $( 'body' ).attr( 'class' ) ).split ( ' ' );
		
		if ( bodyClass.length == 0 ) {
			return;
		}
		
		$( 'nav#primary-nav li a.'  + bodyClass + ':first' ).each(function(i) {
			
			var parentClass = $.trim ( $(this).attr('class') );
			
			if ( $( 'body' ).hasClass ( parentClass ) ) {
				
				$( this ).addClass ( 'active' );
				
				if ( $( this ).parent().children ( 'ul.nav-submenu' ).length > 0 ) {
					
					$( this ).parent().children ( 'ul.nav-submenu' ).find('a').each(function(j) {
						
						var submenuItemClass = $.trim ( $( this ).attr( 'class' ).replace ( parentClass, '' ) );
						
						if ( $( 'body' ).hasClass( submenuItemClass ) ) {
							$ ( this ).addClass ( 'active' );
						}
						
					});
					
				}
				
			}
			
		});
		
	}

};

HeinzSoups.Tooltip = {
	
	settings : {
		openDelimiter : '<p class="tooltip">',
		closeDelimiter : '</p>'
	},
	
	init : function ( options ) {
		
		if ( options ) {
			$.extend ( HeinzSoups.ProductTabs.settings, options );
		}
		
		if ( $( '*[title]' ).length == 0 ) {
			return;
		}
		
		$( '*[title]' ).each( function ( i ) {
			var txt = $.trim ( $( this ).attr( 'title' ) );
			$( this ).removeAttr( 'title' );
			$ ( this ).attr ( 'rel', 'tooltip-' + i );
			HeinzSoups.Tooltip.create ( i, txt );
		});
		
		$( 'ul#dietary_needs li' ).hover( function( e ) {
			var myrel = $( this ).attr('rel');
			var myOffset = $(this).offset();
			var myWidth = $(this).width();
			var myHeight = $( '.tooltip' ).outerHeight() - 6;
			var tooltipHeight = $( 'div.tooltip[rel="'+ myrel + '"]' ).height();
			
			$( 'div.tooltip[rel="'+ myrel + '"]' ).css({
				'top' :  ( myOffset.top - tooltipHeight - ( myHeight / 3) ) + 'px',
				'left' : ( myOffset.left + ( myWidth / 2 ) ) + 'px',
				'display' : 'block'
			});
			
		}, function ( e ) {
			var myrel = $( this ).attr('rel');
			$( 'div.tooltip[rel="'+ myrel + '"]' ).css({
				'display' : 'none'
			});	
		});
		
	},
	
	create : function ( idx, txt ) {
		$( 'body' ).append ( '<div class="tooltip" rel="tooltip-' + idx + '"><span>' + txt +'</span></div>' );
	}
	
};

HeinzSoups.UI = {

	settings : {
		minBodyHeight : 932
	},

	init : function() {
	
		HeinzSoups.UI.resizeBodyContainer();
		
		if ( ! $('body').hasClass('free_soup_samples') ) {
		$(window).resize(function(e) {
			HeinzSoups.UI.resizeBodyContainer();
		});
		}
		
		//$('article, aside').equalizeCols();
		
		$('a[rel="fancybox"]').fancybox({
			'opacity' : true,
			'overlayShow' : true,
			'transitionIn' : 'fade',
			'transitionOut' : 'fade',
			'autoScale' : false,
			'type' : 'inline',
			'titlePosition' : 'outside',
			'autoDimensions' : false,
			'width' : 604,
			'height' : 'auto',
			'padding' : 0,
			'hideOnOverlayClick' : false,
			'centerOnScroll' : true
		});
				
		$('.toggle_block h2').live('click', function(e) {
			
			e.preventDefault();
			
			if ( $(this).parent().hasClass('expand') ) {
				$(this).parent().removeClass('expand').addClass('contract');
			} else {
				$(this).parent().removeClass('contract').addClass('expand');
			}
			
		});
		
		if ( $( 'body' ).hasClass ( 'products' ) && $( 'body' ).hasClass ( 'search' ) ) {
			$( '#content aside .toggle_block[id!="product_name_ingredient_filters"]' ).removeClass ( 'expand' ).addClass ( 'contract' );
		}
		
		if ( $( 'input[name="product_category"]' ).length > 0 ) {
		
			$( 'input[name="product_category"]' ).each(function(i) {
				$(this).removeAttr('checked');
			});
			
			$( 'input#product_category_all').attr('checked', 'checked');
		
			/*
			if ( $( 'input[name="product_category"]' ).val() == '2' ) {
				
				//$( 'ul#soup_type, #product_category_soup_type_filters p:first, select#brand, select#format' ).css({
				$( 'ul#soup_type, section #product_category_soup_type_filters p:first' ).css({
					'display' : 'none'
				});
			} else {
				//$( 'ul#soup_type, #product_category_soup_type_filters p:first, select#brand, select#format' ).css({
				$( 'ul#soup_type, section #product_category_soup_type_filters p:first' ).css({
					'display' : 'block'
				});		
			}
			*/
		}
		
		$( 'input[name="product_category"]' ).change(function(e) {
			if ( $(this).val() === '2' ) {
				//$( 'ul#soup_type, #product_category_soup_type_filters p:first, select#brand, select#format' ).css({
				$( 'ul#soup_type, section #product_category_soup_type_filters p:first' ).css({
					'display' : 'none'
				});	
			} else {
				$( 'ul#soup_type input' ).each( function( i ) {
					$( this ).removeAttr('checked');
				});
				$( 'ul#soup_type input#soup_type_all' ).attr( 'checked', 'checked' );
				//$( 'ul#soup_type, #product_category_soup_type_filters p:first, select#brand, select#format' ).css({
				$( 'ul#soup_type, section #product_category_soup_type_filters p:first' ).css({
					'display' : 'block'
				});				
			}
		});
		
		$( "input[placeholder], textarea[placeholder]").placeholder();
	
	},
	
	resizeBodyContainer : function( options ) {
		
		if ( options ) {
			$.extend ( HeinzSoups.UI.settings, options );
		}
		
		var footerHeight = $('footer.site_footer').outerHeight();
		var bodyContainerHeight = $('div.body_container').outerHeight();
		var documentHeight = $(document).height();
		var wholeHeight = footerHeight + bodyContainerHeight;
		var articleHeight = $('aside').length > 0 ? $('article').outerHeight() : 0;
		var asideHeight = $('aside').length > 0 ? $('aside').outerHeight() : 0;
		
		if ( ( wholeHeight < documentHeight ) ) {
			var newHeight = bodyContainerHeight + ( documentHeight - wholeHeight );
			$('article').css ( 'height', newHeight + 'px' );
		}
		
	}

};

HeinzSoups.ProductSearch = {

    settings: {

        productNames: [],
        keyIngredients: []

    },

    init: function(options) {

        if (options) {
            $.extend(HeinzSoups.ProductSearch.settings, options);
        }

        HeinzSoups.ProductSearch.toggleSortFilters();

        $('#product_name_item_number').autocomplete({
            source: HeinzSoups.ProductSearch.settings.productNames
        });

        $('#primary_ingredient').autocomplete({
            source: HeinzSoups.ProductSearch.settings.keyIngredients
        });

        $('input[name="sort_by"]').change(function(e) {
            HeinzSoups.ProductSearch.toggleSortFilters();
        });
        
        $('.product_and_brand_search aside input:checked, .product_and_brand_search aside input:selected').parents('.toggle_block').removeClass('contract').addClass('expand');

        if (window.location.search) {
            var filter = urlVar('f');
            var quest  = urlVar('v');

            switch(filter)
            {
              case 'b':
                $('#brand').val(quest).parents('.toggle_block').removeClass('contract').addClass('expand');        
                break;
              case 't':
                $('#soup_type').val(quest).parents('.toggle_block').removeClass('contract').addClass('expand');        
                break;
              case 'f':
                $('#format').val(quest).parents('.toggle_block').removeClass('contract').addClass('expand');        
                break;
              case 'd':
              case 's':
                $('#' + quest).attr('checked', true).parents('.toggle_block').removeClass('contract').addClass('expand');
                break;
            }
            HeinzSoups.ProductSearch.search();
        } else {
            HeinzSoups.ProductSearch.search();
        }
        
        $('aside input.button.search').live('click', function(e) {
            e.preventDefault();
            $('div.body_container, article, aside').removeAttr('style');
            HeinzSoups.ProductSearch.search();
        });

        $('aside input[type="radio"], aside input[type="checkbox"]').live('click', function(e) {
            HeinzSoups.ProductSearch.search();
        });

        $('aside select').change(function(e) {
            HeinzSoups.ProductSearch.search();
        });

        $('select#general_characteristics, select#nutritionals').change(function(e) {
            HeinzSoups.ProductSearch.search();
        });

        $('input[name="product_name_item_number"], input[name="primary_ingredient"]').bind('keypress', function(e) {
            var code = (e.keyCode ? e.keyCode : e.which);
            if (code == 13) {
                e.preventDefault();
                HeinzSoups.ProductSearch.search();
            }
        });

    },

    search: function() {



        $('#loading_indicator').css({
            'display': 'block',
            'height': $('#search_results').outerWidth() + 'px'
        });

        var productNameItemNumber = $.trim($('input[name="product_name_item_number"]').val().toLowerCase());
        var primaryIngredient = $.trim($('input[name="primary_ingredient"]').val().toLowerCase());
        //var productCategory = $.trim ( $( 'input[name="product_category"]:checked' ).val().toLowerCase() );
        var soupType = $.trim($('select#soup_type option:selected').val().toLowerCase());
        var brand = $.trim($('select#brand option:selected').val().toLowerCase());
       	var format = $.trim($('select#format option:selected').val().toLowerCase()); 
        
        if ( brand === '8' ) {
            soupType = '';
            $( 'select#soup_type option:selected' ).removeAttr( 'selected' );
            $( 'select#soup_type option:first' ).attr( 'selected', 'selected' );
            $( 'select#soup_type' ).attr( 'disabled', 'disabled' );
            $( 'select#soup_type' ).addClass('disabled');
        } else {
        	$( 'select#soup_type' ).removeAttr( 'disabled', 'disabled' );
            $( 'select#soup_type' ).removeClass('disabled');
        }

        productNameItemNumber = productNameItemNumber == '' || productNameItemNumber == 'all' || productNameItemNumber == 'product name/item #' ? null : productNameItemNumber;
        primaryIngredient = primaryIngredient == '' || primaryIngredient == 'all' || primaryIngredient == 'primary ingredient' ? null : primaryIngredient;

        var productCategory = null;
        brand = brand == '' || brand == 'all' ? null : brand;
        format = format == '' || format == 'all' ? null : format;
        soupType = soupType == '' || soupType == 'all' ? null : soupType;

        if (productCategory == '2') {
            //brand = null;
            //format = null;
            soupType = null;

            /*
            $('select#brand option[value=""]').attr('selected', 'selected');
            $('select#format option[value=""]').attr('selected', 'selected');
            */

        }

        if ($('#sort_by_general_characteristics').attr('checked') === 'checked') {
            var sort = $.trim($('select#general_characteristics option:selected').val());
        } else {
            var sort = $.trim($('select#nutritionals option:selected').val());
        }

        var dietaryNeeds = new Array();
        $('input[id^="dietary_needs"]:checked').each(function(i) {
            dietaryNeeds.push($(this).val());
        });

        var seasons = new Array();
        $('input[id^="season"]:checked').each(function(i) {
            seasons.push($(this).val());
        });

        var ajax_data = {
            productNameOrSKU: productNameItemNumber,
            primaryIngredient: primaryIngredient,
            category: productCategory,
            type: soupType,
            brand: brand,
            format: format,
            dietaryNeeds: dietaryNeeds,
            seasons: seasons,
            sort: sort
        };

        ajax_data = JSON.stringify(ajax_data);

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/product-search.asmx/SearchProducts',
            dataType: 'text',
            data: ajax_data,
            async: true,

            success: function(data) {
                var json = jsonParse(data);
                $('#search_results').empty();

                if (json !== null && json.d !== null) {
                
                	/*
                	if ( json.d.DisableTypeSearch === true ) {
                		$( 'select#soup_type option:selected' ).removeAttr( 'selected' );
                		$( 'select#soup_type option:first' ).attr( 'selected', 'selected' );
                		$( 'select#soup_type' ).attr( 'disabled', 'disabled' );
                		$( 'select#soup_type' ).addClass('disabled');
                	} else {
                		$( 'select#soup_type' ).removeAttr( 'disabled', 'disabled' );
                		$( 'select#soup_type' ).removeClass('disabled');
                	}
                	*/

                    $.each(json.d.Groups, function(i, brand) {

                        if (brand !== null) {


                            if (brand.BrandNameParsed == 'chef-francisco') {
                                var brandImg = "/img/brands/chef-francisco-by-heinz-Logo-Alpha.png";
                            } else if (brand.BrandNameParsed == 'true-soups') {
                                var brandImg = "/img/brands/truesoups-by-heinz-Logo-Alpha.png";
                            } else if (brand.BrandNameParsed == 'heinz-smart-savory') {
                                var brandImg = "/img/brands/smart-and-savory.png";
                            } else if (brand.BrandNameParsed == 'todds') {
                                var brandImg = "/img/brands/todds-Logo-Alpha.png";
                            } else if ( brand.BrandNameParsed == 'quality-chef' ) {
                            	var brandImg = "/img/brands/Quality-Chef-Logo-Alpha.png"
                            } else {
                                var brandImg = "";
                            }

                            var append = '<section id="search_results_' + brand.BrandNameParsed + '"><h3><img src="' + brandImg + '" alt="' + brand.BrandName + '"></h3><ul>';

                            $.each(brand.Products, function(x, p) {

                                append += '<li>';

                                append += '<a href="/' + p.Path + '" style="background: url(' + p.ImagePathSmall + ') top center no-repeat transparent;">';

                                append += '<span>' + p.Name + '</span>';
                                append += '<span>' + p.SKU + '</span>';

                                append += '</a>';

                                append += '</li>';

                            });

                            append += '</ul></section>';

                        }

                        $('#search_results').append(append);
                        $('#loading_indicator').css({
                            'display': 'none'
                        });

                    });

                    $('div.body_container, article, aside').removeAttr('style');
                    //HeinzSoups.UI.resizeBodyContainer();

                    var searchResultsHeight = $('#search_results').height();
                    var articleHeight = $('article').height();
                    var newHeight = (searchResultsHeight + articleHeight) + 'px';

                    $('article').height(newHeight);


                } else {

                    $('#loading_indicator').css({
                        'display': 'none'
                    });

                    $('div.body_container, article, aside').removeAttr('style');
                    //HeinzSoups.UI.resizeBodyContainer();

                }

            },

            error: function(jqxhr, txt, err) {
                alert(err);
                $('#search_results').empty().append('<p>' + err + '</p>');
                $('#loading_indicator').css({
                    'display': 'none'
                });
            }


        });

    },

    toggleSortFilters: function() {

        var checkedValue = $.trim($('input[name="sort_by"]:checked').val().toLowerCase());

        if (checkedValue === 'general characteristics') {
            $('select#general_characteristics').removeAttr('disabled');
            $('select#nutritionals').attr('disabled', 'disabled');
        } else {
            $('select#nutritionals').removeAttr('disabled');
            $('select#general_characteristics').attr('disabled', 'disabled');
        }

    }

};

HeinzSoups.Tracking = {
	init: function () {
		// class-based GA tracking hooks
		// link tracking (finds and tracks links with class="track category|action|label" applied)
		jQuery("a.track").live("click", function (e) {
			var ev = getEventString(this.className), target = null, callback = null, href = null;
			if (ev) {
				if (this.className.match(/action/)) { // use "action" rather than "event" tracking
					ev = "/" + ev.replace(/\|/g, "/");
				}
				target = this.target;
				if ( !target || target.match(/^_(self)|(top)$/i) ) {
					href = jQuery(e.target).closest("a")[0].href;
					callback = function () {
						if ( target.match(/^_top$/i) ) {
							top.location.href = href;
						} else {
							location.href = href;
						}
					};
					e.preventDefault();
				}
				BGC.track(ev, callback);
			}
		});
		
		// form view/submit "action" (virtual pageview) tracking
		jQuery("form.track").each(function () {
			var ev = getEventString(this.className).replace(/\|/g, "/");
			if (ev) {
				BGC.track(ev + "/view");
				jQuery(this).submit(function (e) {
					if (Page_IsValid) { // only track the submit action if the .NET validation routine passed
						BGC.track(ev + "/submit");
					}
				});
			}
		});
		
		function getEventString (s) {
			var ev = "";
			s = s.split(" ");
			jQuery.each(s, function () {
				if (this.indexOf("|") > -1) {
					ev = this.toString();
					return;
				}
			});
			return ev;
		}
	}
};

function urlVar ( name ) {
	var urlVars = getUrlVars();
	
	if ( urlVars[name] !== undefined ) {
		return ( urlVars[name] );
	} else {
		return ( '' );
	}
	
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/**
 *
 * Copyright (c) 2007 Tom Deater (http://www.tomdeater.com)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 * 
 */
 
(function($) {
	/**
	 * equalizes the heights of all elements in a jQuery collection
	 * thanks to John Resig for optimizing this!
	 * usage: $("#col1, #col2, #col3").equalizeCols();
	 */
	 
	$.fn.equalizeCols = function(){
		var height = 0,
			reset = $.browser.msie && $.browser.version < 7 ? "1%" : "auto";
  
		return this
			.css("height", reset)
			.each(function() {
				height = Math.max(height, this.offsetHeight);
			})
			.css("height", height)
			.each(function() {
				var h = this.offsetHeight;
				if (h > height) {
					$(this).css("height", height - (h - height));
				};
			});
			
	};
	
})(jQuery);

/*! http://mths.be/placeholder v1.8.5 by @mathias */
(function(g,a,$){var f='placeholder' in a.createElement('input'),b='placeholder' in a.createElement('textarea');if(f&&b){$.fn.placeholder=function(){return this};$.fn.placeholder.input=$.fn.placeholder.textarea=true}else{$.fn.placeholder=function(){return this.filter((f?'textarea':':input')+'[placeholder]').bind('focus.placeholder',c).bind('blur.placeholder',e).trigger('blur.placeholder').end()};$.fn.placeholder.input=f;$.fn.placeholder.textarea=b;$(function(){$('form').bind('submit.placeholder',function(){var h=$('.placeholder',this).each(c);setTimeout(function(){h.each(e)},10)})});$(g).bind('unload.placeholder',function(){$('.placeholder').val('')})}function d(i){var h={},j=/^jQuery\d+$/;$.each(i.attributes,function(l,k){if(k.specified&&!j.test(k.name)){h[k.name]=k.value}});return h}function c(){var h=$(this);if(h.val()===h.attr('placeholder')&&h.hasClass('placeholder')){if(h.data('placeholder-password')){h.hide().next().show().focus().attr('id',h.removeAttr('id').data('placeholder-id'))}else{h.val('').removeClass('placeholder')}}}function e(){var l,k=$(this),h=k,j=this.id;if(k.val()===''){if(k.is(':password')){if(!k.data('placeholder-textinput')){try{l=k.clone().attr({type:'text'})}catch(i){l=$('<input>').attr($.extend(d(this),{type:'text'}))}l.removeAttr('name').data('placeholder-password',true).data('placeholder-id',j).bind('focus.placeholder',c);k.data('placeholder-textinput',l).data('placeholder-id',j).before(l)}k=k.removeAttr('id').hide().prev().attr('id',j).show()}k.addClass('placeholder').val(k.attr('placeholder'))}else{k.removeClass('placeholder')}}}(this,document,jQuery));
