
var myheinz = myheinz || {};


BGC.track.init('UA-2390333-1','UA-23391427-1');
BGC.track("_setDomainName|" + getDomainName());
BGC.track("_addIgnoredRef|myheinz");
BGC.track();

function getDomainName () {
    var d = location.host.split(".");
    while (d.length > 2) {
                    d.shift();
    }
    return d.join(".");
}


// start document ready
$(function() {
  // 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 = $(e.target).closest("a")[0].href;
					callback = function () {
						if ( !href.match(/#$/) ) {
							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;
	}
	
	myheinz.UI = {
		
		Overlay: {
			init: function (options) {
				var $o = jQuery("#" + options.id);
				if ( !$o.length ) { // create the overlay content container if it doesn't exist already
					$o = jQuery('<div id="' + options.id + '" class="' + (options.overlayClass || "overlay-window") + '"></div>').appendTo("body");
				}

				$o.empty();
				
				$o.append('<div id="overlay-controls"><a href="#" class="jqmClose">Close</a></div>');
				$o.append('<div class="content"></div>');
				
				
				
				if (options.overlayStyle) {
					$o.css(options.overlayStyle);
					$o.css({display: "block"}); // element must be "block" to get the offsetWidth
					$o.css({marginLeft: -($o[0].offsetWidth / 2)}); // center the overlay
					$o.css({display: "none"});
				}
				
				$o.jqm({
					modal: true,
					//trigger: options.trigger, see addTrigger()
					overlay: 80,
					onShow: loadContent,
					onHide: function (hash) {
						$o.slideUp("fast", function () {
							$o.children(".content").empty();
							hash.o.remove();
							jQuery.scrollTo(0, 0);
							// publish "overlayHide" notification
							$o.trigger("overlayHide");
							// tracking
							BGC.track("overlay|" + $o.attr("id") + "|close");
						});
					}
				});
				
				myheinz.UI.Overlay.addTrigger(null, options.id);
				
				jQuery(document).bind("megamenuLoad", myheinz.UI.Overlay.addTrigger); // megamenus may contain overlay "triggers", so we need to check their content after loading
				
				function loadContent (hash) {
					var $c = $o.children(".content"), $i;
					
					switch (options.type) {
						case "iframe":
							var $i = jQuery('<iframe src="' + hash.t.href + '" frameborder="0" marginwidth="0" marginheight="0"></iframe>').appendTo($c);
							if (options.iframeWidth) {
								$i.css({width: options.iframeWidth});
							}
							if (options.iframeHeight) {
								$i.css({height: options.iframeHeight});
							}
							break;
						case "inline":
							jQuery( options.src.clone(true) ).appendTo($c).show();
							break;
					}
	
					$o.slideDown("fast");
					
					jQuery.scrollTo($o, 600);
					
					// publish "overlayShow" notification
					$o.trigger("overlayShow");
					
					// tracking
					BGC.track("overlay|" + $o.attr("id") + "|open");
				}
			},
			
			addTrigger: function (e, id) {
				if (id) {
					var $t = jQuery("." + id).removeClass("overlay-trigger");
					jQuery("#" + id).jqmAddTrigger($t)
				} else {
					jQuery(e.target).find(".overlay-trigger").each(function () {
						id = jQuery(this).removeClass("overlay-trigger")[0].className;
						jQuery("#" + id).jqmAddTrigger(this);
					});
				}
			}
		}
	}
	

	
	$('a.checkoutLink').live('click', function(e) {
		e.preventDefault();
		flashlogin(); 
	});
	
	
});

// end document ready	

	/*
	 * jqModal - Minimalist Modaling with jQuery
	 *   (http://dev.iceburg.net/jquery/jqModal/)
	 *
	 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
	 * Dual licensed under the MIT and GPL licenses:
	 *   http://www.opensource.org/licenses/mit-license.php
	 *   http://www.gnu.org/licenses/gpl.html
	 * 
	 * $Version: 03/01/2009 +r14
	 */
	(function($) {
		$.fn.jqm=function(o){
		var p={
		overlay: 50,
		overlayClass: 'jqmOverlay',
		closeClass: 'jqmClose',
		trigger: '.jqModal',
		ajax: F,
		ajaxText: '',
		target: F,
		modal: F,
		toTop: F,
		onShow: F,
		onHide: F,
		onLoad: F
		};
		return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
		H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
		if(p.trigger)$(this).jqmAddTrigger(p.trigger);
		});};
		
		$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
		$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
		$.fn.jqmShow=function(t){return this.each(function(){t=t||window.event;$.jqm.open(this._jqm,t);});};
		$.fn.jqmHide=function(t){return this.each(function(){t=t||window.event;$.jqm.close(this._jqm,t)});};
		
		$.jqm = {
		hash:{},
		open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/100});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
		 if(c.modal) {if(!A[0])L('bind');A.push(s);}
		 else if(c.overlay > 0)h.w.jqmAddClose(o);
		 else o=F;
		
		 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
		 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}
		
		 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
		  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
		 else if(cc)h.w.jqmAddClose($(cc,h.w));
		
		 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
		 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
		},
		close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
		 if(A[0]){A.pop();if(!A[0])L('unbind');}
		 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
		 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
		},
		params:{}};
		var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
		i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
		e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
		f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
		L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
		m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
		hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
		 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
	})(jQuery);
	
	/**
	 * jQuery.ScrollTo - Easy element scrolling using jQuery.
	 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
	 * Dual licensed under MIT and GPL.
	 * Date: 5/25/2009
	 * @author Ariel Flesler
	 * @version 1.4.2
	 *
	 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
	 */
	;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
	
	/*
	  jQuery MegaMenu Plugin
	  Author: GeekTantra
	  Author URI: http://www.geektantra.com
	*/
	var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;

jQuery.fn.megamenu = function(options) {
  options = jQuery.extend({
                              activate_action: "mouseover",
                              deactivate_action: "mouseleave",
                              show_method: "slideDown",
                              hide_method: "slideUp",
                              justify: "left",
                              enable_js_shadow: true,
                              shadow_size: 3,
                              mm_timeout: 250
                          }, options);
  var $megamenu_object = this;
  if( options.activate_action == "click" ) options.mm_timeout = 0;
  $megamenu_object.children("li").each(function(){
    jQuery(this).addClass("mm-item");
    jQuery(".mm-item").css({ 'float': options.justify });
    
    jQuery(this).find("div:first").addClass("mm-item-content");
    jQuery(this).find("a:first").addClass("mm-item-link");
    var $mm_item_content = jQuery(this).find(".mm-item-content");
    var $mm_item_link = jQuery(this).find(".mm-item-link");
    $mm_item_content.hide();
    
    jQuery(document).bind("click", function(){
      jQuery(".mm-item-content").hide();
      jQuery(".mm-item-link").removeClass("mm-item-link-hover");
    });
    jQuery(this).bind("click", function(e){
      //e.stopPropagation(); WHY IS HE DOING THIS?!?
    });
    $mm_item_content.wrapInner('<div class="mm-content-base"></div>');
    if(options.enable_js_shadow == true) {
      $mm_item_content.append('<div class="mm-js-shadow"></div>');
    }
    var $mm_timer = 0;
    // Activation Method Starts
    jQuery(this).bind(options.activate_action, function(e){
      e.stopPropagation();
      var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
      var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
      clearTimeout($mm_timer);
      $mm_timer = setTimeout(function(){ //Emulate HoverIntent
        mm_item_link_obj.addClass("mm-item-link-hover");
        //apply on state to nav - added my MO
        mm_item_link_obj.addClass("on");
        mm_item_content_obj.css({
          'top': ($mm_item_link.offset().top + $mm_item_link.outerHeight()) + 1 +"px",
          'left': ($mm_item_link.offset().left) - 5 + 'px'
        })
        
        if(options.justify == "left"){
          var mm_object_right_end = $megamenu_object.offset().left + $megamenu_object.outerWidth();
                                    // Coordinates of the right end of the megamenu object
          var mm_content_right_end = $mm_item_link.offset().left + $mm_item_content.outerWidth() - 5 ;
                                    // Coordinates of the right end of the megamenu content
          if( mm_content_right_end >= mm_object_right_end ) { // Menu content exceeding the outer box
            mm_item_content_obj.css({
              'left': ($mm_item_link.offset().left - (mm_content_right_end - mm_object_right_end)) - 2 + 'px'
            }); // Limit megamenu inside the outer box
          }
        } else if( options.justify == "right" ) {
          var mm_object_left_end = $megamenu_object.offset().left;
                                    // Coordinates of the left end of the megamenu object
          var mm_content_left_end = $mm_item_link.offset().left - mm_item_content_obj.outerWidth() + 
                                    $mm_item_link.outerWidth() + 5;
                                    // Coordinates of the left end of the megamenu content
          if( mm_content_left_end <= mm_object_left_end ) { // Menu content exceeding the outer box
            mm_item_content_obj.css({
              'left': mm_object_left_end + 2 + 'px'
            }); // Limit megamenu inside the outer box
          } else {
            mm_item_content_obj.css({
              'left': mm_content_left_end + 'px'
            }); // Limit megamenu inside the outer box
          }
        }
        if(options.enable_js_shadow == true) {
          mm_item_content_obj.find(".mm-js-shadow").height( mm_item_content_obj.height() );
          mm_item_content_obj.find(".mm-js-shadow").width( mm_item_content_obj.width() );
          mm_item_content_obj.find(".mm-js-shadow").css({
            'top': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
            'left': (options.shadow_size) + (isIE6 ? 2 : 0) + "px",
            'opacity': 0.5
          });
        }
        switch(options.show_method) {
          case "simple":
                mm_item_content_obj.show();
                break;
          case "slideDown":
                mm_item_content_obj.height("auto");
                mm_item_content_obj.slideDown('fast');
                break;
          case "fadeIn":
                mm_item_content_obj.fadeTo('fast', 1);
                break;
          default:
                mm_item_content_obj.each( options.show_method );
                break;
        }
      }, options.mm_timeout);
    });
    // Activation Method Ends
    // Deactivation Method Starts
    jQuery(this).bind(options.deactivate_action, function(e){
      e.stopPropagation();
      clearTimeout($mm_timer);
      var mm_item_link_obj = jQuery(this).find("a.mm-item-link");
      var mm_item_content_obj = jQuery(this).find("div.mm-item-content");
//      mm_item_content_obj.stop();
      switch(options.hide_method) {
        case "simple":
              mm_item_content_obj.hide();
              mm_item_link_obj.removeClass("mm-item-link-hover");
              //remove on state from nav - added my MO
        		mm_item_link_obj.removeClass("on");
              break;
        case "slideUp":
              mm_item_content_obj.slideUp( 'fast',  function() {
                mm_item_link_obj.removeClass("mm-item-link-hover");
                //remove on state from nav - added my MO
        		mm_item_link_obj.removeClass("on");
              });
              break;
        case "fadeOut":
              mm_item_content_obj.fadeOut( 'fast', function() {
                mm_item_link_obj.removeClass("mm-item-link-hover");
                //remove on state from nav - added my MO
        		mm_item_link_obj.removeClass("on");
              });
              break;
        default:
              mm_item_content_obj.each( options.hide_method );
              mm_item_link_obj.removeClass("mm-item-link-hover");
              //remove on state from nav - added my MO
        		mm_item_link_obj.removeClass("on");
              break;
      }
      if(mm_item_content_obj.length < 1) mm_item_link_obj.removeClass("mm-item-link-hover");
      if(mm_item_content_obj.length < 1) mm_item_link_obj.removeClass("on");
    });
//    Deactivation Method Ends
  });
  this.show();
};


	//logic check for background image.	
	function bgCookie(){	
		var cookieValue = BGC.cookie('MyHeinz_Theme');
		if(cookieValue){
				jQuery('#wrapper').removeClass();
				jQuery('#wrapper').addClass(cookieValue);
		} else {
				var cookieOptions = BGC.cookie.options;
				cookieOptions.path = "/";
				BGC.cookie('MyHeinz_Theme', 'just-because', cookieOptions);	
				jQuery('#wrapper').removeClass();
				jQuery('#wrapper').addClass(cookieValue);
		}
	};
	
	//Shuffle function for word cloud,
	// written by Ca-Phun Ung, here: http://yelotofu.com/2008/08/jquery-shuffle-plugin/	
  $.fn.shuffle = function() {
    return this.each(function(){
      var items = $(this).children();
      return (items.length)
        ? $(this).html($.shuffle(items))
        : this;
    });
  }
 
  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }
  
  // sets email cookie on LoginOrderStatus and LoginOrderStatusSA
	function orderStatusEmailCookie(email, checked){
		if (checked == "checked"){
			BGC.cookie("orderStatusEmailCookie", email, 365);	
		}
	}  
	
	
	// Star Rating system, taken from http://orkans-tmp.22web.net/star_rating/

  function starsPrep(){
        // hide input submit buttons
        jQuery(".ratings").children().not(":radio").hide();
 	       // Create stars
        jQuery(".ratings").each(function(index) {
            var $that = $(this),
            		formID = $that.attr('id'),
            		formVote = "#votes_" + $that.attr('id'),
            		formThanks =  "#thanks_" + $that.attr('id');
            $that.stars({
                cancelShow: false,
                callback: function(ui, type, value) {
                    $that.fadeOut(function() {
                    		$that.siblings('.voteThanks').fadeIn();
                        $.post('/ratinghandler.ashx',
										{ projectID: formID,
											 ratingValue: ui.options.value
										},
										function(data) {
											 var status = data.status;
											 var average = data.average;
											 var count = data.count;
											 if (status == '0') {
												  ui.select(average);
												  $(formVote).children('.votecount').html(count);
												  //$that.delay('1750').fadeIn();
											 }
											 //else {
												//$that.fadeIn();
											 //}
											 //$that.siblings('.voteThanks').delay('1700').fadeOut();
										}, "json");
                    }
						);
                }
            });
        });
      }
