﻿/*
 * brand-section JavaScript file for Kelloggs.com
 * requires: jQuery.js (written and tested against jQuery version 1.4.2)
 * requires: bgc.js
 */
 
$(document).ready(function () {
	// initialization for brand pages
	var $body = $("body");
	
	if ( $body.hasClass("landing") ) {
		// brand carousel
		Kellogg.UI.Carousel.init(".carousel", 4000);
		
		$(".slide a").click(function (e) {
			BGC.track("carousel|link|brands");
		});
		
		// "sidetabs" UI for "find products" feature
		Kellogg.UI.Sidetabs.init( $("#product-finder") );
		
		// product not found?
		if (BGC.query.notfound === "true") {
			$("#overlay-notfound").jqmShow();
		}
		
	} else if ( $body.hasClass("wtb") ) {
		// set the document.domain property to allow the dynamic iframe scripting to work
        // get the current hostname and strip off the subdomain
        var dd = location.hostname.split(".");
        dd.shift();
        document.domain = dd.join(".");
        
		// get search params from the querystring and pass through to WTB launcher
		if(BGC.query.brand) {
			$("#brand").val(BGC.query.brand);
		}
		
		if(BGC.query.product) {
			$("#product").val(BGC.query.product);
		}
		
		if(BGC.query.zip) {
			$("#zip").val(BGC.query.zip);
		}
		
		// csr view?
		if(BGC.query.csr) {
			$("#locator").val("1");
			$("#csrsearch").val("1");
		}
          
		$("#wtb_form").trigger("submit");
	} else if ( $body.hasClass("search") ) {
		Kellogg.UI.RemoveAllFilters.init();
	} else if ( $body.hasClass("brand") ) {
		// brand landing page
		
		// divide product list into multiple cols if taller than 360px
		var $c1 = $("#brand-products .col1"), $c2, $ul;
		if ($c1.height() > 360 ) {
			$c2 = $('<div class="col2"></div>').insertAfter($c1),
			$ul = $('<ul></ul>').appendTo($c2);
			// remove empty H3 elements
			$c1.css({width: 350}).find("h3:empty").parent().remove();
			while ( $c1.height() > ($c2.height() + 90) ) {
				$c1.find("li:last").prependTo($ul);
			}
			if ( $c1.find("li:last h3").length ) {
				// ensure no orphaned header at bottom of col1
				$c1.find("li:last").prependTo($ul);
			}
			if ( !$c2.find("li:first h3").length ) {
				// clone last header from col1 into col2
				$c1.find("h3:last").parent().clone().prependTo($ul).find("h3").append('<span> continued</span>');
			}
		}
		
		// tooltip bubbles for products
		var $b = $('<div id="product-bubble" class="solid rounded-7777"><h3></h3><img/><p></p></div>').insertBefore($c1),
			$bc = $('<img src="img/icon_bubble.png" alt="" id="product-bubble-connector"/>').insertBefore($c1),
			$container = $("#brand-products"),
			$trigger,
			scrolltimer;
			
		$b.title = $b.find("h3");
		$b.image = $b.find("img");
		$b.description = $b.find("p");
		
		function loadTooltip (e) {
			var $img = $('<img/>');
			$trigger = $(e.target).closest("a");
			$b.title.html( $trigger.html() );
			$b.description.html( decodeURIComponent( $trigger.attr("data-description") ).replace(/style="[^"]+"/g, "") );
			if ( $trigger.data("tooltip-image") ) {
				$b.image.attr( "src", $trigger.data("tooltip-image") );
			} else {
				$b.image.attr( "src", "/img/blank.gif" ).css({minHeight: 80});
				setTimeout(function () {
					$img
						.one("load", function () {
							setTimeout(function () {
								$trigger.data( "tooltip-image", $img.attr("src") );
								$b.image.attr( "src", $img.attr("src") ).css({minHeight: 1, maxHeight: 160});
								moveTooltip();
							}, 500);
						})
						.unbind("error")
						.bind("error", function () {
							// replace image
							Kellogg.UI.Image.missing($img[0], 150, true);
						})
						.attr( "src", $trigger.attr("data-image") );
				}, 500);
			}
			
			showTooltip();
		}
			
		function showTooltip () {
			var pos = $trigger.position();
			$b.stop().css({left: pos.left - 200, top: $trigger.data("tooltip-top") || pos.top - 30, opacity: 0}).fadeTo(300, 1, function () {
				if ($.browser.msie) {
					this.style.removeAttribute('filter');
				}
			});
			$bc.stop().css({left: pos.left - 28, top: pos.top, opacity: 0}).fadeTo(300, 1, function () {
				if ($.browser.msie) {
					this.style.removeAttribute('filter');
				}
			});
			moveTooltip();
		}
		
		function hideTooltip (e) {
			$bc.stop().fadeOut(100);
			$b.stop().fadeOut(100);
		}
		
		function moveTooltip () {
			if (!$trigger) {
				return;
			}
			var pos = $b.position(),
				lpos = $trigger.position(),
				vtop = BGC.getScrollOffset().y,
				vbottom = BGC.getViewportSize().y + vtop,
				top = BGC.getElemPosition($b[0]).y,
				height = $b.height() + 30,
				newtop;
			
			// ensure the tooltip remains in the viewport
			if (vbottom <  top + height) {
				newtop = pos.top - (top + height - vbottom);
			} else if (vtop > top) {
				newtop = pos.top + 8 + (vtop - top)
			}
			
			if (newtop) {
				newtop = Math.min(lpos.top - 3, newtop); // don't let the tooltip's top slide below the link
				newtop = Math.max(lpos.top - height + 33, newtop); // don't let the tooltip's bottom slide above the link
				$b.animate({top: newtop}, 100);
				$trigger.data( "tooltip-top", newtop );
			}
		}
		
		$("a.tooltip").hoverIntent({
			interval: 300,
			over: loadTooltip,
			out: hideTooltip,
			timeout: 200
		});
		
		$(document).bind("fontresize", moveTooltip);
		
		$(window).bind("scroll", function () {
			clearTimeout(scrolltimer);
			scrolltimer = setTimeout(moveTooltip, 200);
		});
		
	} else if ( $body.hasClass("detail") ) {
		// "view sizes" link
		$("#view-sizes").click(function (e) {
			$(this).hide().next().show();
			e.preventDefault();
		});
	}
	
	$(".view-more").listViewMore({
		label: "More Brands"
	});
});

Kellogg.Brand = {};


/*************************************************************
 *    DYNIFS - Dynamic IFrame Auto Size v1.0.0
 *
 *    Copyright (C) 2006, Markus (phpMiX)
 *    This script is released under GPL License.
 *    Feel free to use this script (or part of it) wherever you need
 *    it ...but please, give credit to original author. Thank you. :-)
 *    We will also appreciate any links you could give us.
 *    http://www.phpmix.org
 *
 *    Enjoy! ;-)
*************************************************************/

var DYNIFS = {
    // Storage for known IFrames.
    iframes: {},
    // Here we save any previously installed onresize handler.
    oldresize: null,
    // Flag that tell us if we have already installed our onresize handler.
    ready: false,
    // The document dimensions last time onresize was executed.
    dim: [-1,-1],
    // Timer ID used to defer the actual resize action.
    timerID: 0,
    // Obtain the dimensions (width,height) of the given document.
    getDim: function(d) {
        // added try/catch in case our framed document is not sharing our domain!
        try {
          var w=200, h=200, scr_h, off_h;
          if( d.height ) { return [d.width,d.height]; }
          with( d.body ) {
              if( scrollHeight ) { h=scr_h=scrollHeight; w=scrollWidth; }
              if( offsetHeight ) { h=off_h=offsetHeight; w=offsetWidth; }
              if( scr_h && off_h ) h=Math.max(scr_h, off_h);
          }
          return [w,h];
        } catch(err) {return [650,500]}
    },
    // This is our window.onresize handler.
    onresize: function() {
        // Invoke any previously installed onresize handler.
        if( typeof this.oldresize == 'function' ) { this.oldresize(); }
        // Check if the document dimensions really changed.
        var dim = this.getDim(document);
        if( this.dim[0] == dim[0] && this.dim[1] == dim[1] ) return;
        // Defer the resize action to prevent endless loop in quirksmode.
        if( this.timerID ) return;
        this.timerID = setTimeout('DYNIFS.deferred_resize();', 10);
    },
    // This is where the actual IFrame resize is invoked.
    deferred_resize: function() {
        // Walk the list of known IFrames to see if they need to be resized.
        for( var id in this.iframes ) this.resize(id);
        // Store resulting document dimensions.
        this.dim = this.getDim(document);
        // Clear the timer flag.
        this.timerID = 0;
    },
    // This is invoked when the IFrame is loaded or when the main window is resized.
    resize: function(id) {
        // added try/catch in case our framed document is not sharing our domain!
        try {
          // Browser compatibility check.
          if( !window.frames || !window.frames[id] || !document.getElementById || !document.body )
              return;
          // Get references to the IFrame window and layer.
          var iframe = window.frames[id];
          var div = document.getElementById(id);
          if( !div ) return;
          // Save the IFrame id for later use in our onresize handler.
          if( !this.iframes[id] ) {
              this.iframes[id] = true;
          }
          // Should we inject our onresize event handler?
          if( !this.ready ) {
              this.ready = true;
              this.oldresize = window.onresize;
              window.onresize = new Function('DYNIFS.onresize();');
          }
          // This appears to be necessary in MSIE to compute the height
          // when the IFrame'd document is in quirksmode.
          // OTOH, it doesn't seem to break anything in standards mode, so...
          //if( document.all ) div.style.height = '0px';
          //div.style.height = '0px'; DISABLED as the W2B module doesn't use quirksmode
          // Resize the IFrame container.
          if (window.opera || /Apple/.test(navigator.vendor)) {
             // Opera 9 needs a slight delay, so getDim can get the correct dimensions.
             setTimeout('var dim = DYNIFS.getDim(window.frames[\''+id+'\'].document); document.getElementById(\''+id+'\').style.height = (dim[1]+30) + \'px\';$(document).trigger("iframeResize");', 1);
          }
          else {
             var dim = this.getDim(iframe.document);
             div.style.height = (dim[1]+30) + 'px';
             $(document).trigger("iframeResize");
          }
        } catch(err) {}
    }
};
