/*
 *	Fix IE6 bg flicker
 */
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}



/*
 * main nav functionality
 */
var mainNav = {
	Init: function()
	{
		$("#nav-main>ul>li").hover(function(){
			$(this).addClass("hover");
		}, function(){
			$(this).removeClass("hover");
		});
	}
};

var holidayTab = {

    Init: function showTab()
    {
        $("div#holiday-elegance").show();
        $("div#holiday-friendship").hide();
        $("div#holiday-love").hide();
        $("div#holiday-warmth").hide();
        $("div#holiday-togetherness").hide();
    }
};



/*
 * methods to run on DOM ready
 */
$(document).ready(function() {
	mainNav.Init();
	holidayTab.Init('elegance');
});

/*
 *	detach all handlers
 */
$(window).unload(function(){
    $("*").unbind();
});

function showTab(type)
{
    $("div#holiday-elegance").hide();
    $("div#holiday-friendship").hide();
    $("div#holiday-love").hide();
    $("div#holiday-warmth").hide();
    $("div#holiday-togetherness").hide();
    
    $("div#holiday-" + type).show();
}


function swapProductImage(id, swapName, catID, flavFeatSrc, flavFeatText)
{
    if (document.images) {
	    document.largeImage.src = swapName + ".jpg";
	    if (flavFeatSrc != '')
	    {
	        document.flavorFeature.src = flavFeatSrc + ".gif";
	        document.flavorFeature.alt = flavFeatText;
	    }	    
    }
    
    var nutritionLink = document.getElementById('lnkNutrition');
    if (id==120798 || id==120799 || id==120800 || id==11843 || id==11845 || id==11608) //Coming soon products
    {
        nutritionLink.style.display = 'none';
    }
    else
    {
        nutritionLink.style.display = 'block';
        nutritionLink.onclick = function() { nutritionPopUp(id, catID); return false; }
    }
}

// link style change
var cur_link;
function doLinkClass(lnk)
{
  if (lnk && lnk.blur) lnk.blur();	// remove marquee
  if (!lnk || cur_link == lnk) return;
  if (cur_link) document.getElementById(cur_link).firstChild.className = "";
  lnk.className = "on";
  document.getElementById(lnk).firstChild.className = "on";
  cur_link = lnk;
}

var cur_lyr;	// holds id of currently visible layer
function swapLayers(lnk,id)
{
  doLinkClass(lnk);
  if (cur_lyr) hideLayer(cur_lyr);
  showLayer(id);
  cur_lyr = id;
}

function swapRecipeNav(id)
{
  if (cur_lyr) hideLayer(cur_lyr);
  showLayer(id);
  cur_lyr = id;
}

function showLayer(id)
{
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.display = "block";
}

function hideLayer(id)
{
  var lyr = getElemRefs(id);
  if (lyr && lyr.css) lyr.css.display = "none";
}

function getElemRefs(id)
{
    var el = (document.getElementById)? document.getElementById(id): (document.all)? document.all[id]: (document.layers)? getLyrRef(id,document): null;
    if (el) el.css = (el.style)? el.style: el;
    return el;
}

// get reference to nested layer for ns4
// from old dhtmllib.js by Mike Hall of www.brainjar.com
function getLyrRef(lyr,doc)
{
    if (document.layers) {
	    var theLyr;
	    for (var i=0; i<doc.layers.length; i++) {
  	    theLyr = doc.layers[i];
		    if (theLyr.name == lyr) return theLyr;
		    else if (theLyr.document.layers.length > 0) 
    	    if ((theLyr = getLyrRef(lyr,theLyr.document)) != null)
				    return theLyr;
      }
	    return null;
  }
}

function hideLink() {
	var myObj;
	myObj = document.getElementById("flavorFeature");
	myObj.style.display="none";
}

function windowPop(id, catId) {
    newwindow=window.open('printingTips.html','name','height=475,width=375');
	if (window.focus) { newwindow.focus() }
	return false;
}

function nutritionPopUp(id, catId) {
    newwindow=window.open('PopNutrition.aspx?prdID=' + id + '&catID=' + catId,'name','height=475,width=375');
	if (window.focus) { newwindow.focus() }
	return false;
}

function openUPC() {
    var wt=325;
    var ht=195;
    var str="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,screenx=30,screeny=20,width="+wt+",height="+ht+",top=50,left=50";
    HomePop=window.open("upc.aspx","upcPop",str);
    HomePop.focus();
}

function openManuCode() {
    var wt=450;
    var ht=300;
    var str="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,screenx=30,screeny=20,width="+wt+",height="+ht+",top=50,left=50";
    HomePop=window.open("manufacturingCode.aspx","manuPop",str);
    HomePop.focus();
}

function openTAF(recID, refURL) {
	var wt=466;
	var ht=400;
	var str="toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,screenx=30,screeny=20,width="+wt+",height="+ht+",top=50,left=50";
	TAF=window.open('TAF.aspx?id=' + recID + '&refURL=' + escape(refURL),"TAF",str);
	TAF.focus();
}

function popWin() {
    window.open("printingTips.html","","menubar=1, resizable=1, width=403, height=543")
}

function ShowNoImageAvailable()
{
    if (document.images) {
	    document.recipeImage.src = "Images/imgNotAvailable.gif";
	}
}

//
// openPopUps v1.01 Copyright (c) 2006 openWebWare.com
// This copyright notice MUST stay intact for use.
//
// The perfect pop up window replacement for your advertisements and web 
// applications. Pop up blockers will fail to prevent an openPopUp window 
// from opening. 
//
// This library is free software; you can redistribute it and/or modify 
// it under the terms of the GNU Lesser General Public License as published 
// by the Free Software Foundation; either version 2.1 of the License, or 
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but 
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along 
// with this library; if not, write to the Free Software Foundation, Inc., 59 
// Temple Place, Suite 330, Boston, MA 02111-1307 USA 

// CSS Diretory
cssDir = "styles/";

// Images Directory
imageDir = "images/";

/* ---------------------------------------------------------------------- *\
  Function    : JSWindow()
  Description : creates a new window
  Usage       : JSWindow("title", oContent, [x], [y], [id], [width])
  Arguments   : title    - The title of the window as displayed in the titlebar
	            oContent - The content of the Div called using getElementbyID
				x        - The number of pixels from the left the window appears when first open
				y        - The number of pixels from the top the window appears when first open
	            id       - The <div> this window will use for its content
                width    - The default width of the window                
\* ---------------------------------------------------------------------- */

function JSWindow(title, oContent, x, y, id, width, popupColor, minimizeIcon)
{
	// define variables
	this.title = title;
	this.oContent = oContent;
    this.width = width;
	this.x = x;
	this.y = y;
    this.id = id;
	this.bgcolor = popupColor;
	
	
	// create the table window and define CSS properties
	this.oTable = document.createElement("table");
    this.oTable.id = "Window " + this.id;
	this.oTable.style.width = this.width + "px";
	this.oTable.style.border = "1px solid #000000";
    this.oTable.cellSpacing = 0;
	this.oTable.cellPadding = 2;
	this.oTable.border = 0;
	this.oTable.style.backgroundColor = "#FFFFFF";

	// determine the windows position when first open
	this.oTable.style.position = "absolute";
	this.oTable.style.left = this.x + "px";
	this.oTable.style.top = this.y + "px";

	// link from the table to the JSWindow object
	this.oTable.jsWindow = this;

	// if the table is clicked anywhere, show the table in front of other open windows
	this.oTable.onmousedown = JSWindow.prototype.onBringToFront;

	// append to document body
	document.body.appendChild(this.oTable);

	// add a row for the titlebar
	var oTR = this.oTable.insertRow(0);
	oTR.className = "JSWindowTitleStyle";
	
	
	// Title: add the title to the titlebar	
	oTD = oTR.insertCell(0);
	oTD.innerHTML = title;
	oTD.jsWindow = this;
	oTD.onmousedown = JSWindow.prototype.tdOnMouseDown;
	oTD.style.borderBottom = "0px";
	oTD.style.borderLeft = "1px solid #000000";
	oTD.style.borderTop = "1px solid #000000";
	oTD.style.color = "#000000";
	oTD.style.fontWeight = "bold";x
	oTD.style.backgroundColor = "#fbeddb";
	oTD.height = "20";
	oTD.width = "98%";
	
	// Minimize: add the minimize button to the titlebar
	if (minimizeIcon == 1) {
        this.oMinTD = oTR.insertCell(1);
        this.oMinTD.innerHTML = "<img src='" + imageDir + "minimize.jpg'>";
        this.oMinTD.onmousedown = JSWindow.prototype.onMinimize;
        this.oMinTD.jsWindow = this;
        this.oMinTD.style.borderBottom = "1px solid #000000";
        this.oMinTD.style.backgroundImage = "url(" + imageDir + "title_bg.jpg)";
        this.oMinTD.width = "1%";
        this.oMinTD.style.paddingRight = "1px";	
    }
	
	// Close: add the close button to the titlebar
	if (minimizeIcon == 1) {
	  oTD = oTR.insertCell(2);
	}
	else {
	  oTD = oTR.insertCell(1); 
	}
	oTD.innerHTML = "<img src='" + imageDir + "close.png' class='png'>";
	oTD.jsWindow = this;
	oTD.onmousedown = JSWindow.prototype.onClose;
	oTD.style.borderBottom = "0px";
	oTD.style.borderTop = "1px solid #000000";
	oTD.style.borderRight = "1px solid #000000";
	oTD.style.backgroundColor = "#fbeddb";
	oTD.width = "1%";
	oTD.style.paddingLeft = "1px";
	oTD.style.paddingRight = "5px";
	
	// add a row for the window's content
	oTR = this.oTable.insertRow(1);
	
	this.oContentTD = oTR.insertCell(0);
	if (minimizeIcon == 1) {
	  this.oContentTD.colSpan = 3;
	}
	else {
	  this.oContentTD.colSpan = 2;
	}  
	this.oContentTD.style.backgroundColor = this.bgcolor;
	this.oContentTD.className = "JSWindowContentStyle";
 
 
	// use the content from the referenced div as the content for the window
	if (document.getElementById("Div" + this.id))
	    this.oContentTD.innerHTML = document.getElementById("Div" + this.id).innerHTML;
	
}

JSWindow.prototype.onBringToFront = function()
{
	this.jsWindow.bringToFront();
}

JSWindow.prototype.bringToFront = function()
{
	// if not already the last child of the document.body, make it so
	if ( document.body.childNodes[document.body.childNodes.length-1] !== this.oTable )
	{
		// move to bottom of document
		document.body.appendChild(this.oTable);
	}
}

JSWindow.prototype.tdOnMouseDown = function()
{
	this.jsWindow.onMouseDown();
}

JSWindow.prototype.onMouseDown = function()
{
	// record that an onmousedown has just occurred
	this.bDown = true;
	
	// link from body to this JSWindow object
	document.body.jsWindow = this;

	// save body mouse handlers
	this.saveMouseMove = document.body.onmousemove;
	this.saveMouseUp = document.body.onmouseup;

	// set new handlers.
	document.body.onmousemove = JSWindow.prototype.bodyOnMouseMove;
	document.body.onmouseup = JSWindow.prototype.bodyOnMouseUp;
}

JSWindow.prototype.bodyOnMouseMove = function(evt)
{
	var e = window.event ? window.event : evt;
	this.jsWindow.onMouseMove(e);
}

JSWindow.prototype.onMouseMove = function(evt)
{
	// if mouse not down, stop the move (for IE only)
	if ( (document.all) && !(evt.button & 1) )
	{
		this.onMouseUp();
		return;
	}
	if ( this.bDown )
	{
		this.dx = parseInt(this.oTable.style.left, 10) - evt.clientX;
		this.dy = parseInt(this.oTable.style.top, 10) - evt.clientY;
		this.bDown = false;
	}
	else
	{
		this.oTable.style.left = Math.max((this.dx + evt.clientX),0) + "px";
		this.oTable.style.top = Math.max((this.dy + evt.clientY),0) + "px";
	}
}

JSWindow.prototype.bodyOnMouseUp = function()
{
	this.jsWindow.onMouseUp();
}

JSWindow.prototype.onMouseUp = function()
{
	document.body.onmouseup = this.saveMouseUp;
	document.body.onmousemove = this.saveMouseMove;
	document.body.jsWindow = null;
}


JSWindow.prototype.onMinimize = function()
{
  this.jsWindow.minimize();
}

JSWindow.prototype.minimize = function()
{
	// hide the content
	this.oContent.style.visibility = "hidden";
	this.oContent.style.position = "absolute";
	document.body.appendChild(this.oContent);
	
	this.oTable.deleteRow(1);
	
	// save current position
	this.saveX = this.oTable.style.left;
	this.saveY = this.oTable.style.top;
	
    // get the "window bar"
	if ( !window.jsWindowBar ) {
		window.jsWindowBar = document.createElement("span");
	    document.body.appendChild(window.jsWindowBar);
	}
	
	window.jsWindowBar.appendChild(this.oTable);
	this.oTable.style.position = "static";
	this.oTable.style.left = "0px";
	this.oTable.style.top = "0px";
	
	this.oMinTD.innerHTML = "<img src='" + imageDir + "maximize.jpg'>";
	this.oMinTD.onmousedown = JSWindow.prototype.onMaximize;
	this.oTable.style.width = "220px";
    this.oTable.style.borderBottom = "0px";
}


JSWindow.prototype.onMaximize = function()
{
	this.jsWindow.maximize();
}

JSWindow.prototype.maximize = function()
{
	document.body.appendChild(this.oTable);
	this.oTable.style.position = "absolute";
	
	this.oTable.style.left = this.saveX;
	this.oTable.style.top = this.saveY;
	this.oTable.style.width = this.width + "px"
	this.oTable.style.borderBottom = "1px solid #000000";
	
	// add the content again.
	oTR = this.oTable.insertRow(1);
	
    this.oContentTD = oTR.insertCell(0);
	this.oContentTD.colSpan = 3;
	this.oContentTD.innerHTML = document.all["Div" + this.id].innerHTML;
	
	//oTD.appendChild(this.oContent);
	this.oContent.style.position = "static";
	this.oContent.style.visibility = "visible";
	this.oContentTD.style.backgroundColor = this.bgcolor;
	this.oContentTD.className = "JSWindowContentStyle";
	
  this.oMinTD.style.paddingRight = "1px";	
	this.oMinTD.innerHTML = "<img src='" + imageDir + "minimize.jpg'>";
	this.oMinTD.onmousedown = JSWindow.prototype.onMinimize;

}

JSWindow.prototype.onMaximize = function()
{
	this.jsWindow.maximize();
}

JSWindow.prototype.close = function()
{	
	// remove from browser document
	this.oTable.parentNode.removeChild(this.oTable);
}

JSWindow.prototype.onClose = function()
{
	this.jsWindow.close();
}



/* ---------------------------------------------------------------------- *\
  Function    : hideDiv()
  Description : Hides all Divs on the page.
  Usage       : hideDiv([divNumber])
  Arguments   : divNumber - The number of Divs in the page that must be hidden
\* ---------------------------------------------------------------------- */

function hideDiv(divNumber) {
	for (var count = 1; count <= divNumber;) {
        if (document.getElementById('Div' + count))
            document.getElementById('Div' + count).style.display = 'none';
		count++;
	}
}



/* ---------------------------------------------------------------------- *\
  Function    : createWindows()
  Description : determines if Window already exists, else calls JSWindow
  Usage       : createWindows([windowID], [width], "title")
  Arguments   : windowID - The <div> this window will use for its content
                width    - The default width of the window
                title    - The title of the window as displayed in the titlebar
\* ---------------------------------------------------------------------- */

function createWindow(title, width, popupColor, windowID, minimizeIcon, x, y)
{
    if (document.getElementById('Div' + windowID)) {
        new JSWindow("&nbsp;" + title, document.getElementById("Div" + windowID), x, y, windowID, width, popupColor, minimizeIcon); 
    }
}


/* ---------------------------------------------------------------------- */

/* Create a namespace for jQuery functions */
var CampbellsSoup = {};

/* Feedback form show/hide functionality */
CampbellsSoup.enableFeedbackForm = function() {
	// Set up default view on page load
	$("fieldset.productfeedback").hide();
	
	// Use url to config feedback form
	if(window.location.hash) 
	{
	    var target = (window.location.hash).split('#')[1];
	    this.buildFeedbackForm(target);
	}
	
	// Set up subject switch
	$("table.formsubject input").click(function() {
	    CampbellsSoup.buildFeedbackForm(this);
	});
	
	this.brandDropdown = $(".brandSelect");
	this.productsDropdown =  $(".productsSelect");

};

CampbellsSoup.buildFeedbackForm = function(selection) {

    var selection = ( $(selection).val() ) ? $(selection).val() : selection;

    // Can pass in feedback form state directly or by getting from input element value 
    var feedbackFormState = selection;
	if (feedbackFormState == 'shop') {
		// Code for handling value "shop"
		$("fieldset.productfeedback").hide();
		$("fieldset.contact div.default").hide();
		$("fieldset.contact div.shop").show();
	
	} else if (feedbackFormState == 'product') {
		// Code for handling value "product"
		$("fieldset.productfeedback").show();
	
	} else {
		// Code for handling values "question, compliment, website, promotion"
		$("fieldset.productfeedback").hide();
		$("fieldset.contact div.default").show();
	};

    $("table.formsubject input[value='" + feedbackFormState + "']").attr("checked", true);
    window.location.hash = feedbackFormState;
    
    if(feedbackFormState == "product") this.onProductFeedbackClick(this.brandDropdown, this.productsDropdown);
};

CampbellsSoup.onProductFeedbackClick = function() {
    if(this.buildDropdownComplete == true) return;
    $.ajax({
        url : 'UI/Handlers/BrandsHandler.ashx',
        type : 'GET',
        dataType : 'json',
        error : function(){
            CampbellsSoup.onProductFeedbackFailure();
        },
        success : function(data){
            CampbellsSoup.initBrandInfo(data);
        }
    });
};

CampbellsSoup.initBrandInfo = function(data) {
    this.cacheElements(data);
    this.buildDropdown(this.data);
};

CampbellsSoup.cacheElements = function(data) {
    this.data = data;
    this.buildDropdownComplete;
};

CampbellsSoup.buildDropdown = function(data) {
    var options;
    $.each(data, function(key, value){
        options += '<option value="' + key + '">' + value + '</option>';
    });
    $(options).appendTo(this.brandDropdown);
    this.buildDropdownComplete = true;
};

CampbellsSoup.updateDependentDropdown = function() {
    var brandId = this.brandDropdown.val();
    $.ajax({
        url : 'UI/Handlers/ProductsHandler.ashx',
        type : 'GET',
        dataType : 'json',
        data : {id:brandId},
        error : function(){
            CampbellsSoup.onProductFeedbackFailure();
        },
        success : function(data){
            CampbellsSoup.initProductInfo(data);
        }
    });

};

CampbellsSoup.initProductInfo = function(data){
    var options;
    $.each(data, function(name, value){
        options += '<option value="' + value + '">' + value + '</option>';
    });

    $(this.productsDropdown).empty();
    $(options).appendTo(this.productsDropdown);
};

CampbellsSoup.onProductFeedbackFailure = function() {
    //$('#failedToLoadMsg').append('<p>Failed to load some product information.</p>').show(); 
};

/* Initialize everything when page is ready */
$(document).ready(function() {
	
	$("dl.accordion").accordion({
		autoHeight:false,
		alwaysOpen: false,
		header:"dt",
		icons: { 
			'header': 'icon-accordion-closed', 
			'headerSelected': 'icon-accordion-open' 
		}
	});

    //Foundation tab calls
    var $tabOne = $("div#tabs").tabs(); // first tab selected        
    $('#grant-guidelines-link').click(function() { // bind click event to link
        $tabOne.tabs('select', 1); // switch to second tab
        tagTab(document.title.replace('About Us','Grant Guidelines'));
        return false;
    });
    
    $('#tabs-1 #eligibility-questionnaire-link').click(function() { // bind click event to link
        $tabOne.tabs('select', 2); // switch to third tab
        tagTab(document.title.replace('About Us','Eligibility Questionnaire'));
        tagQuestion(eligibilityQuestionnaireQuestions[0], 'Foundation', 'Eligibility Questionnaire');
        return false;
    });
    
    var $tabTwo = $("div#tabs").tabs('select', 1); // second tab selected
    $('#tabs-2 #eligibility-questionnaire-link-2').click(function() { // bind click event to link
        $tabTwo.tabs('select', 2); // switch to second tab
        tagTab(document.title.replace('About Us','Eligibility Questionnaire'));
        tagQuestion(eligibilityQuestionnaireQuestions[0], 'Foundation', 'Eligibility Questionnaire');
        return false;
    });      

    $("div#tabs").tabs('select', 0);             	
	
	//fix problem with Firefox not checking radio buttons on load
	if($.browser.mozilla) $("form").attr("autocomplete", "off"); 
	
	CampbellsSoup.enableFeedbackForm();
	
	$("form").validate({
		errorLabelContainer: "#messageBox",
		wrapper: "p"

	});	

});


function tagDownload(obj, type){
	var s_click = s_gi(s_account);
	s_click.events='event14';
	s_click.linkTrackVars = 'events,eVar9';
	s_click.linkTrackEvents = 'event14';
	s_click.eVar9 = type;
	s_click.tl(this, 'd', type);
}

function tagPDF(obj, type){
	var s_click = s_gi(s_account);
	s_click.events='event15';
	s_click.linkTrackVars = 'events,eVar9';
	s_click.linkTrackEvents = 'event15';
	s_click.eVar9 = type;
	s_click.tl(this, 'd', type);
}

function tagExit(obj, type){
	var s_click = s_gi(s_account);
	s_click.tl(this, 'e', type);
}

function tagQuestion(questionName, pageName, tab){
	var s_click = s_gi(s_account);
	s_click.events='event8';
	s_click.linkTrackVars = 'events,eVar30,prop25';
	s_click.linkTrackEvents = 'event8';
	s_click.eVar30 = pageName + ': ' + tab + ': ' + questionName;	
	s_click.prop30 = s_click.eVar30;
	s_click.prop25 = pageName + ' Expansion';
	s_click.tl('','o','click tag');
}

function tagAccordian(obj, pageName, tab){

    var innterTagName = obj.innerText || obj.textContent;
    innterTagName = (innterTagName).replace(/^\s*|\s*$/g,'');
  
	var s_click = s_gi(s_account);
	s_click.events='event8';
	s_click.linkTrackVars = 'events,eVar30,prop25';
	s_click.linkTrackEvents = 'event8';
	s_click.eVar30 = pageName + ': ' + tab + ': ' + innterTagName;
	s_click.prop30 = s_click.eVar30;
	s_click.prop25 = pageName + ' Expansion';
	s_click.tl('','o','click tag');
}

function tagPrint(obj, pageName, tab){

    var innterTagName = obj.innerText || obj.textContent;
    innterTagName = (innterTagName).replace(/^\s*|\s*$/g,'');
  
	var s_click = s_gi(s_account);
	s_click.events='event16';
	s_click.linkTrackVars = 'events,eVar31';
	s_click.linkTrackEvents = 'event16';
	s_click.eVar31 = pageName + ': ' + tab + ': ' + innterTagName;
	s_click.prop30 = s_click.eVar31;
	s_click.tl('','o','click tag');
}

function tagStartForm(title){
	var s_click = s_gi(s_account);
	s_click.events='event14';
	s_click.pageName = title;
	s_click.linkTrackVars = 'events,eVar26';
	s_click.linkTrackEvents = 'event14';
	s_click.eVar26 = s_click.pageName;
	s_click.t();
}

function tagTab(title){
	var s_click = s_gi(s_account);
	s_click.events='event9';
	s_click.pageName = title;
	s_click.linkTrackVars = 'events,eVar26';
	s_click.linkTrackEvents = 'event9';
	s_click.eVar26 = s_click.pageName;
	s_click.t();
}
