var RecaptchaOptions = {
   theme: "white",
   lang: "en"
};

document.observe('dom:loaded', function(){
	ie6FlickerFix();
	ieHover();
	refreshYourList();
	
	// landing page rollovers
	initProductRollovers('product_list');
	initProductRollovers('product_list_nogravy');
	initProductRollovers('gourmet_product_list');
	
	// dynamic tabs on product pages
	initDynamicTabs("info_nav", "panel_box");
	
	// tooltip stuff
	initToolTips();
	moveToolTipStem('listtxt', 'yourListTip', 20, -1);
	moveToolTipStem('emaillist_link', 'emailListTip', 20, -1);
	moveToolTipStem('phonelist_link', 'mobileListTip', 20, -1);
	moveToolTipStem('printlist_link', 'printListTip', 202, -1);
		
	var flashStatus = initFlash();
	if (flashStatus == false)
	{
		var homeSlideshow = new Slideshow('home_flash', 4, 8);	
	}
    // print button on your list page
    initPrintButton();
    
    //Grammy slides
    grammy_carousel();    
    
    // these clear form fields when you click in
	initTextBoxClearer('searchBox');
    initTextBoxClearer('confessBox');
    
    // Setup Search Field
	searchBoxClickListener();
    
    // TWC external open
    twcExternal();

	//Absolute Path

	// Email A Friend modal
	if ($('email_friend') != null ) {
		$('email_friend').hide();
		emailFriendSubmit();
		closeEmailFriend();
	}
	
    var videoId = 6;
});

var Slideshow = Class.create({
		initialize: function(slideshowId, slideshowLength, slideshowSpeed) {
			// break out if the page doesn't contain the slideshow ID
			if ($(slideshowId) == null) {
				return false;
			}
				
			// set variable states
			this.slideshowId = slideshowId;
			this.slideshowLength = slideshowLength;
			this.slideshowSpeed = slideshowSpeed;
			
			// set initial page state
			// set up periodicalExectuter and event handling
			this.loadSlideshow();
			
		},
		
		loadSlideshow: function() {
			var buttonHolder = new Element('div', {id: 'buttonHolder'} );
			$(this.slideshowId).insert(buttonHolder);
			
			// shift from one slide to the next, and then back to 1
			this.pe = new PeriodicalExecuter( (this.shiftSlide).bind(this), this.slideshowSpeed);
						
			// build the buttons.  while we're at it, put an event listener on each one
			for (i = 1; i <= this.slideshowLength; i++)
			{
				// build the new button and add attributes
				var buttonId = 'button' + i;
				var button = new Element('a').update("<span>" + i + "</span");
					
				// writing these attributes as part of building the new element generates a script error in IE6
				$(button).writeAttribute("id", buttonId);
				$(button).addClassName("button");
				$(button).addClassName("css_png");
				// set active class for first button on page load
				if (i == 1)
				{
					button.addClassName("active");
				}
				$(button).writeAttribute("href", "#" + i);
				
				// attach the new button to the container
				$(buttonHolder).insert($(button));
				
				// event handling
				$(button).observe('click', this.clickNewSlide.bindAsEventListener(button, this.slideshowId, this.pe));	

			}
			
		},
		
		clickNewSlide: function(e, slideshowId, pe) {
			// we're passing in the periodicalExectuter object so we can stop it if necessary
			e.stop();
			//pe.stop(); 
			
			// style this to show which slide you're currently on
			var otherButtons = $(this).siblings();
			otherButtons.invoke("removeClassName", "active");
			$(this).addClassName("active");
			 
			var image = $(slideshowId).down("img");
			
			// using the href attribute to hold which slide the button links to
			var newImageNum = this.readAttribute("href").sub("#", ""); 
			
			// using the name attribute to hold which number slide the current image is
			var oldImageNum = image.readAttribute("name"); 
			
			var newSrc = image.readAttribute("src").gsub(oldImageNum, newImageNum);
			image.writeAttribute("src", newSrc);
			image.writeAttribute("name", newImageNum);
			image.fire("slide:changed");
		},
		
		shiftSlide: function() {
						
			var image = $(this.slideshowId).down("img");
			var oldImageNum = parseInt(image.readAttribute("name"));
			if (oldImageNum == this.slideshowLength) {
				var newImageNum = 1;
			} else {
				var newImageNum = oldImageNum + 1;
			}
			var newSrc = image.readAttribute("src").gsub(oldImageNum, newImageNum);
			image.writeAttribute("src", newSrc);
			image.writeAttribute("name", newImageNum);
			
			// need to set the active button
			var buttons = $$(".button");
			var activeButton = buttons.find (function(button) {
				if ( parseInt(button.readAttribute("href").sub("#","")) == newImageNum )
					return true;
			});
			
			// sort out buttons to show what slide you're currently on
			activeButton.addClassName("active");
			var otherButtons = activeButton.siblings();
			otherButtons.invoke("removeClassName", "active");
			image.fire("slide:changed");
		}
});



function captureKey(event, searchBoxId, keyCode)
{
	Event.stop(event);
	if (event == keyCode)
		search($(searchBoxId).value);
	else
		return false;
}

function initPrintButton()
{
	if ($('printlist_link') == null)
	    return false;
	$('printlist_link').observe('click', printWindow);
}

function printWindow()
{
	window.print();
}

function initTextBoxClearer(cssClass)
{
	textBoxClickListener(cssClass);
}

function textBoxClickListener(textBoxes)
{
	$$("." + textBoxes).each( function(textBox) {
        textBox.observe('click', clearTextBox.bindAsEventListener(textBox, textBox));
    });
}

function searchBoxClickListener()
{
	Event.observe('footerSearchButton', 'click', function(event) {
	    search($('txtKeywords').value);
	});
}

function clearTextBox(e, textBox)
{
	textBox.value = "";
}

function ieHover()
{
	//Add IE fake pseudo :hover classes into array on next line. In this case the "hover" class would have to be on the element that you needed to hover.
    var hoverSet = new Array('li#foodnav', 'li#homelink', /*'#topnav ul li',*/ '#topnav #listtxt');
    for (var i=0; i<hoverSet.length; i++)
    {
       $$(hoverSet[i]).each( function(e) {
             Event.observe(e, 'mouseover', function() {
             Element.addClassName(e, 'hover');
             });
             Event.observe(e, 'mouseout', function() {
             Element.removeClassName(e, 'hover');
             });
        });
    }
}

function ie6FlickerFix()
{
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch(err) {}
}

function wPop(url, winName, wWidth, wHeight, scrll)
{
   var scrollB;
   if(!scrll)
   {
      scrollB = 'no';
      var pWidth = wWidth;
      var rSize = 'no'
   }
   else 
   {
      scrollB = scrll;
      wWidth = parseInt(wWidth) + 20;
      var rSize = 'yes'
   }
   var iMyWidth;
   var iMyHeight;
   iMyWidth =(window.screen.width / 2) - (wWidth / 2 + 10);
   //half the screen width minus half the new window width (plus 5 pixel borders).
   iMyHeight =(window.screen.height /2) - (wHeight / 2 + 15);
   //half the screen height minus half the new window height (plus title and status bars).
   var zWin = window.open(url, winName, "status=no,width=" + wWidth + ",height=" + wHeight + ",resizable=" + rSize + ",left=" + iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + ",scrollbars=" + scrollB);
   zWin.focus();
}

function initProductRollovers(product_list)
{
	if ($(product_list) ==  null)
		return false;
	var list_items = $(product_list).childElements();
	list_items.each(function(li)
	{
		li.observe('mouseover', productRollOverListener.bindAsEventListener(li, li));
		li.observe('mouseout', productRollOutListener.bindAsEventListener(li, li));
	});
}

function productRollOverListener(e, li)
{
	if ($(li).identify() == "elegant_medleys_link")
		elegantMedleysRollOver(li);
	else
		productRollOver(li);
}

function productRollOutListener(e, li)
{
	if ($(li).identify() == "elegant_medleys_link")
		elegantMedleysRollOut(li);
	else
		productRollOut(li);
}

function productRollOver(li)
{
	var image = $(li).down("img");
	var image_url_new = image.src.gsub("off", "roll");
	image.src = image_url_new;
}

function productRollOut(li)
{
	var image = $(li).down("img");
	var image_url_new = image.src.gsub("roll", "off");
	image.src = image_url_new;
}

function elegantMedleysRollOver(li)
{
	var fancy_feast = $(li).previous().down("img");
	var gourmet_dry_food = $(li).next().down("img");
	$(fancy_feast).src = fancy_feast.src.gsub("off", "alt");
	$(gourmet_dry_food).src = gourmet_dry_food.src.gsub("off", "alt");
	productRollOver(li);
}

function elegantMedleysRollOut(li)
{
	var fancy_feast = $(li).previous().down("img");
	var gourmet_dry_food = $(li).next().down("img");
	$(fancy_feast).src = fancy_feast.src.gsub("alt", "off");
	$(gourmet_dry_food).src = gourmet_dry_food.src.gsub("alt", "off");
	productRollOut(li);
}

function initDynamicTabs(nav_id, tab_content)
{
	if ( ( $(nav_id) == null ) || ( $(tab_content) == null ) )
		return false;
	var tabs = $(nav_id).childElements();
	tabs.each( function(tab) {
		tab.observe("click", tabListener.bindAsEventListener(tab, tab, tab_content) )
	});
}

function tabListener(e, tab, tab_content)
{
	changeTab(tab, tab_content);
}

function changeTab(tab, tab_content)
{
	var tabs = $(tab).up("ul").childElements();
	tabs.each( function(each_tab) {
		if ($(each_tab).hasClassName("active"))
			$(each_tab).removeClassName("active");
	});
	$(tab).addClassName("active");	
	switchTabContent(tab, tab_content);
}

function switchTabContent(tab, tab_content)
{
	var activeDiv = $(tab).down('a').readAttribute("href").gsub("#", "");
	var contentDivs = $(tab_content).childElements();
	contentDivs.each( function(div) {
			div.hide();
		});
	$(activeDiv).show();
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

function initToolTips()
{
	if (notOnYourListPage())
	{
		var xOffset = 0;
		if ( Browser.isIE() && ($('yourListTipContent').down('p').hasClassName('num_products')) )
			xOffset = -385;
		else
			xOffset = -335; //-350;
		
		var yourListTipOptions = {
		    stem: 'rightMiddle',
		    hook: { target: 'right', tip: 'left'}, 
		    offset: { x: xOffset, y: -17}, 
		    radius: 0,
		    border: 0,
		    className: 'yourListTip'
		}
		var yourListTip = new Tip($('listtxt'), $('yourListTipContent'), yourListTipOptions);
	}
	else
	{
		if ($('emailTipContent'))
		{
			var emailTipOptions = {
				stem: 'rightMiddle',
				hook: { target: 'right', tip: 'left'}, 
				offset: { x: -351, y: -18}, 
				radius: 0,
				border: 0,
				className: 'emailListTip',
				showOn: 'click',
				closeButton: false,
				hideOn: { element: '.close', event: 'click' }
			}
			var emailTipContent = $("emailTipContent");
			var emailListTip = new Tip($('emaillist_link'), emailTipContent, emailTipOptions);
			$('emaillist_link').observe('prototip:shown', refreshEmailTip);
			$('email_close').observe('click', hideEmailTip);
			$('phonelist_link').observe('prototip:shown', hideEmailTip);
			if (isIE6 == true) {
				$('email_form_IE6').removeClassName('hide');
				$('email_form_IE6').addClassName('show');
				$('email_form').removeClassName('show');
				$('email_form').addClassName('hide');
			}
			sendToEmail();
		}
		if ($('mobileTipContent'))
		{
				var mobileTipOptions = {
				stem: 'rightMiddle',
				hook: { target: 'right', tip: 'left'}, 
				offset: { x: -351, y: -17}, 
				radius: 0,
				border: 0,
				className: 'mobileListTip',
				showOn: 'click',
				closeButton: false,
				hideOn: { element: '.close', event: 'click' }
			}
			var mobileTipContent = $('mobileTipContent');
			var mobileListTip = new Tip($('phonelist_link'), mobileTipContent, mobileTipOptions);
			$('mobile_close').observe('click', hideMobileTip);
			$('phonelist_link').observe('prototip:shown', refreshMobileTip);
			$('emaillist_link').observe('prototip:shown', hideMobileTip);
			sendToMobile();
			
		}
	}
}

function refreshEmailTip()
{
   $('email_form').show();
   $('email_thanks').hide();
   $('email_form').down('input').value = '';
   $('error_email').update("");	
	Recaptcha.reload ();
}

function refreshEmailTipIE6()
{
   $('email_form_IE6').show();
}

function refreshMobileTip()
{
    $('mobile_form').show();
    $('mobile_thanks').hide();
    $('mobile_form').down('input').value = '';
    $('mobile_form').down('select').value = 'select carrier';
    $('error_mobile').update("");
}

function hideEmailTip()
{
    $('emaillist_link').prototip.hide();
}

function hideMobileTip()
{
    $('phonelist_link').prototip.hide();
}

function notOnYourListPage()
{
	if ($('your_list_items'))
		return false;
	else
		return true;
}

function moveToolTipStem(targetId, tipClass, topY, leftX)
{
	if ($(targetId) ==  null)
		return false;
	$(targetId).observe('prototip:shown', function() {
		var stem = $$('.' + tipClass)[0].up('.prototip_StemWrapper').adjacent('.prototip_Stem')[0];
		if ($(stem) == null)
			return false;
		$(stem).setStyle({
			top: topY + 'px',
			left: leftX + 'px',
			zIndex: 6000
		});
	});
}

function initFlash1(section,key,div,replay)
{
	var flashvars = {};
	flashvars.xmlPath = root + "_res/xml/galleries.xml";
	flashvars.section = section;
	flashvars.key = key;
	flashvars.played = replay;
	if(document.URL.search('autoPlayVid=true') > 0){
	    flashvars.autoPlayVid = true;
	}
	var params = {};
	params.wmode = "transparent";
	var attributes = {};
	var path = root + "_res/swf/fancy_feast.swf";
	if ($(div) == null)
		return false;
	swfobject.embedSWF(path, div, "872", "460", "9.0.0", "/_res/swf/expressInstall.swf", flashvars, params, attributes);
	var status = "";
	if (swfobject.hasFlashPlayerVersion("9.0.0")) {
  		status = true;
	}
	else {
 		status = false;
	}
	return status;
}

function initFlashHome(section,key,div,replay)
{
    FancyFeast.Web.Utils.AjaxUtility.GetCurrentGallery(function(result) {
        var gallery = ""; 
        gallery = result.value;
        var flashvars = {};
	    flashvars.xmlPath = root + "_res/xml/" + gallery;
	    flashvars.section = section;
	    flashvars.key = key;
	    flashvars.played = replay;
	    flashvars.weborbPath = absolutePath;
	    if(document.URL.search('autoPlayVid=true') > 0){
	        flashvars.autoPlayVid = true;
	    }
	    var params = {};
	    params.wmode = "transparent";
	    var attributes = {};
	    var path = root + "_res/swf/shell2.swf";
	    if ($(div) == null)
		    return false;
	    swfobject.embedSWF(path, div, "872", "460", "10.0.0", "/_res/swf/expressInstall.swf", flashvars, params, attributes);
	    var status = "";
	    if (swfobject.hasFlashPlayerVersion("10.0.0")) {
  		    status = true;
	    }
	    else {
 		    status = false;
	    }
	    return status;
    });
    
}

function initFlash()
{
	if ($('ctl00_bodyTag').hasClassName('home')) {
    	var status = initFlashHome('home','1','home_flash',null);
    	return status;
	} else {
    	var status = initFlash1('home','1','home_flash',null);
    	return status;
	};
}

function loadPandora(div)
{

    var flashvars = {};
    var params = {};
    params.wmode = "transparent";
    params.allowFullScreen = "true";
    var attributes = {};
    var path = root + "_res/swf/more_to_fancy.swf";
    var expressInstallPath = root + "_res/swf/expressInstall.swf";
    swfobject.embedSWF(path, div, "872", "540", "9.0.115.0", false, flashvars, params, attributes);
}

function loadConfessions(div)
{

    var flashvars = {};
    var params = {};
    params.wmode = "transparent";
    params.allowFullScreen = "true";
    var attributes = {};
    var path = root + "_res/swf/ConfessShell.swf";
    var expressInstallPath = root + "_res/swf/expressInstall.swf";
    swfobject.embedSWF(path, div, "872", "685", "9.0.115.0", false, flashvars, params, attributes);
}



// adds product to the shopping list using the product url
function addToList( path, btnToUpdate )
{
    FancyFeast.BLL.ShoppingListBL.AddItem( path, addToList_callback ) ;
    //updateButton( btnToUpdate );
}

// callback that updates the right shopping list callout area in the top nav
function addToList_callback( result )
{
    if ( result.value == 0 )
    {
        $('yourlist').update('<p id="itemcount"></p><p id="listtxt"></p>');
    }
    else
    {
		if ( notOnYourListPage() )
		{
			$('yourlist').update('<a href="../your-list/"><p id="itemcount"><span class="paren">(</span>' + result.value + '<span class="paren">)</span></p><p id="listtxt"></p></a>');
		}
		else
		{
			$('yourlist').update('<p id="itemcount">(' + result.value + ')</p><p id="listtxt"></p>');
		}	
    }
}

// removes product from the shopping list using the product url
function removeFromList( path )
{
    FancyFeast.BLL.ShoppingListBL.DeleteItem( path, removeFromList_callback ) ;
}

// callback that updates the right shopping list callout area in the top nav
function removeFromList_callback( result )
{
    addToList_callback( result ) ;
    
    // update the upper panel
    if ( result.value == 0 )
    {
        // hide the controls panel
        $('ready_wrap').addClassName('empty');        
    }
    
    // update the shopping list div
    refreshYourList();   
}

function sendToMobile()
{
	var image = $("mobileTipContent").down("img.go_button");
	var carrier = $("mobileTipContent").down("select");
	var mobile = $("mobileTipContent").down("input");
	
	image.observe('click', function() {
		// validate sms gateway selection		
		if ( carrier.selectedIndex == 0 )
		{
			$('error_mobile').update("Please select a carrier.");
			return ;
		}
		
		// validate the mobile number
		if ( mobile.value.trim().length == 0 )
		{
			$('error_mobile').update("Please enter your mobile number.");
			return ;
		}
		
		var reg = /^\d{10}$/;
		
		if ( reg.test( mobile.value ) == false )
		{
			$('error_mobile').update("Please enter a valid mobile number.");
			return ;
		}
		
		// send the email
		FancyFeast.BLL.ShoppingListBL.SendToMobile( carrier.selectedIndex, mobile.value, sendToMobile_callback ) ;		
	});
}

function sendToMobile_callback( result )
{
    if ( result.value == 0 )
    {
		// success
	    $('mobile_form').hide();
	    $('mobile_thanks').show();		
    }
    else
	{
		// error
		$('error').update("An error occurred, please try again later.");
	}
}

function sendToEmail()
{
	var image = $("emailTipContent").down("img.send_button");
	var email = $("emailTipContent").down("input");
	
	image.observe('click', function() {
		// validate the email
		if ( email.value.trim().length == 0 )
		{
			$('error_email').update("Please enter your email address.");
			return ;
		}
		
		var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
		
		if ( reg.test( email.value ) == false )
		{
			$('error_email').update("Please enter a valid email address.");
			return ;
		}
		
		// validate reCaptcha
		FancyFeast.BLL.ShoppingListBL.ValidateCaptcha(Recaptcha.get_challenge(), Recaptcha.get_response(), function(result) {    
		    if ( result.value == true ) 
			{ 
				// send the email
				FancyFeast.BLL.ShoppingListBL.SendToEmail( email.value, sendToEmail_callback ) ;
			} 
			else
			{
				// error
				$('error_email').update("Please re-enter the words below."); 
				 Recaptcha.reload ();
			}
    	});
	}); 
}

function sendToEmail_callback( result )
{
    if ( result.value == 0 )
    {
		// success
	    $('email_form').hide();
	    $('email_thanks').show();			
    }
    else
	{
		// error
		$('error_email').update("An error occurred, please try again later.");
	}
}

function refreshYourList()
{
    if ( notOnYourListPage() ) return ;
    new Ajax.Updater(
        {success: 'your_list_items'},
        '/YourListSnippet.aspx?cachebuster=' + Math.random(),
        {method: 'get', onComplete: ffLoadPNGs}
    );
}

function ffLoadPNGs () {
    if (isIE6 == true) {
        fnLoadPngs()
    }
}

// catch the enter key on the search text field
function keyPress( e )
{
	var keycode = ( window.event ? window.event.keyCode : e.which ) ;
	if ( keycode != 13 ) return true;
	search($('txtKeywords').value);
	return false;
}

// perform the search using the atom search engine
function search(keywords)
{
	var clean = Url.encode(keywords.strip());
	if (clean != '' && clean.indexOf('Search') == -1)
	{
		var zWin = window.open('http://search.purina.com/search/?sp_a=sp10033d5f&sp_t=fancyfeast&sp_k=Fancy%32Feast&sp_p=all&sp_f=ISO-8859-1&sp_q=' + clean);
		zWin.focus();
	}
}

// functions for Stay In Touch page
function OfferSubmit(){
    var form = document.forms.OfferForm;
    var offercode = querystring("OfferCode");
    form.action = "EsurveyOfferPage.aspx?OfferCode=" + offercode ;
    if (form !=null){
      document.forms.OfferForm.submit();
    }
}
function purina_window(url) {
    link = window.open(url,"legal","toolbar=1,location=0,directories=0,status=0,menubar=1,scrollbars=yes,resizable=yes,width=640,height=640");
}

/************************************************
	TITLE: Browser Detection Library
	AUTHOR: Nathan Koch
	VERSION: 1.0
	REQUIRES: NONE
************************************************/

var Browser = new Object;

Browser.IE =    !!(window.attachEvent && !window.opera),
Browser.Opera =  !!window.opera,
Browser.WebKit = navigator.userAgent.indexOf('AppleWebKit/') > -1,
Browser.Gecko =  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
Browser.MobileSafari = !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)

Browser.isIE = function()
{
	return (Browser.IE ? true : false)
}

Browser.isGecko = function()
{
	return (Browser.Gecko ? true : false)
}

Browser.isOpera = function()
{
	return (Browser.Opera ? true : false)
}

Browser.isWebKit = function()
{
	return (Browser.WebKit ? true : false)
}

Browser.isMobileSafari = function()
{
	return (Browser.MobileSafari ? true : false)
}

function updateButton( btnToUpdate )
{
    $(btnToUpdate).removeClassName('addtolist');
    $(btnToUpdate).addClassName('seeyourlist');
}

function twcExternal(){
 if ($('ext-twc') == null)
	    return false;
    $('ext-twc').observe('click', function(e){
        e.stop();
        var link = $(this).readAttribute("href");
        //console.log(link);
        window.open(link);
    });
}



function grammy_carousel(){
var theUrl = window.location.toString();

if (theUrl.indexOf("grammy-awards") > 0) // KEEP THIS.  This prevents the code from executing on the homepage and other pages and throwing a ton of null exceptons
{

    
    $$('.slide').each(function(element){
        $(element).hide();
    });
    $('slide1').show();
    
    // hide all groups, show first group
    $('group1').show();
    $$('#group2, #group3, #group4, #group5').each(function(element){
    	$(element).hide();
    });
    
    //setup thumbnail navigation
    $('small_carousel_nav').show();
    $('group1btn').addClassName('on');
    
    
    //create arrows, place on page
    var back = new Element('a');
    back.id = 'large_back';
    back.rel = 'prev';
    back.className = 'carousel-control';
    
    var forward = new Element('a');
    forward.id = 'large_forward';
    forward.rel = 'next';
    forward.className = 'carousel-control';
    
    $('large_carousel_wrapper').appendChild(back);
    $('large_carousel_wrapper').appendChild(forward);
    
    
    //set default state of arrow's rels
    $('large_back').writeAttribute('rel', 'slide0');
    $('large_forward').writeAttribute('rel', 'slide2');
    
    
    
    /* observe each thumbnail for click's to display larger image */
    $$('.thumbnail').each(function(element){
	    
	    element.observe('click', function(event){
	        event.stop();
	        
	        var clickedIndex = $(this).readAttribute('rel');
	        
	        $$('.slide').each(function(element){
	            $(element).hide();
	        });
	        $(clickedIndex).show();
	        
	        /* update arrows */
	        var newValue = parseInt(clickedIndex.replace("slide", ""));
	        
	        if(newValue == 1){
            //grey out prev
	        }
	        else if(newValue == 24){
	            //grey out next
	        }
	        else{
	            $('large_back').writeAttribute('rel', "slide" + (newValue - 1));
	            $('large_forward').writeAttribute('rel', "slide" + (newValue + 1));
	        }
	        
	        if(newValue >= 1 && newValue <= 5){
	        	showGroup1();
	        }
	        else if(newValue >= 6 && newValue <= 10){
	        	showGroup2();
	        }
	        else if(newValue >= 11 && newValue <= 15){
	        	showGroup3();
	        }
	        else if(newValue >= 16 && newValue <= 20){
	        	showGroup4();
	        }
	        else{
	        	showGroup5();
	        }
	    });
    });
    
    $('large_back').observe('click', function(event){
	    event.stop();
	    
	    var clickedIndex = $(this).readAttribute('rel');
	        
        $$('.slide').each(function(element){
            $(element).hide();
        });
        
        $(clickedIndex).show();
        
        var newValue = parseInt(clickedIndex.replace("slide", ""));
        
        if(newValue == 1){
            //grey out prev
        }
        else if(newValue == 24){
            //grey out next
        }
        else{
            $('large_back').writeAttribute('rel', "slide" + (newValue - 1));
            $('large_forward').writeAttribute('rel', "slide" + (newValue + 1));
        }
        
        if(newValue >= 1 && newValue <= 5){
        	showGroup1();
        }
        else if(newValue >= 6 && newValue <= 10){
        	showGroup2();
        }
        else if(newValue >= 11 && newValue <= 15){
        	showGroup3();
        }
        else if(newValue >= 16 && newValue <= 20){
        	showGroup4();
        }
        else{
        	showGroup5();
        }
    });
    
    $('large_forward').observe('click', function(event){
	    event.stop();
	    
	    var clickedIndex = $(this).readAttribute('rel');
	        
        $$('.slide').each(function(element){
            $(element).hide();
        });
        
        $(clickedIndex).show();
        
        var newValue = parseInt(clickedIndex.replace("slide", ""));
        
        if(newValue == 1){
            //grey out prev
        }
        else if(newValue == 24){
            //grey out next
        }
        else{
            $('large_back').writeAttribute('rel', "slide" + (newValue - 1));
            $('large_forward').writeAttribute('rel', "slide" + (newValue + 1));
        }
        
        if(newValue >= 1 && newValue <= 5){
        	showGroup1();
        }
        else if(newValue >= 6 && newValue <= 10){
        	showGroup2();
        }
        else if(newValue >= 11 && newValue <= 15){
        	showGroup3();
        }
        else if(newValue >= 16 && newValue <= 20){
        	showGroup4();
        }
        else{
        	showGroup5();
        }
        
    });
    
    $('group1btn').observe('click', function(e){ 
        e.stop();
        showGroup1();
    });
    $('group2btn').observe('click', function(e){ 
        e.stop();
        showGroup2();
    });
    $('group3btn').observe('click', function(e){ 
        e.stop();
        showGroup3();        
    });
    $('group4btn').observe('click', function(e){ 
        e.stop();
        showGroup4();
    });
    $('group5btn').observe('click', function(e){ 
        e.stop();
        showGroup5();
    });
    }
}

function showGroup1(){
    $('group1').show();
    $$('#group2, #group3, #group4, #group5').each(function(element){
    	$(element).hide();
    });

    $('group1btn').addClassName('on');
    $$('#group2btn, #group3btn, #group4btn, #groupbtn').each(function(element){
    	$(element).removeClassName('on');
    });
}

function showGroup2(){
   $('group2').show();
    $$('#group1, #group3, #group4, #group5').each(function(element){
    	$(element).hide();
    });

    $('group2btn').addClassName('on');
    $$('#group1btn, #group3btn, #group4btn, #group5btn').each(function(element){
    	$(element).removeClassName('on');
    });
}

function showGroup3(){
    $('group3').show();
    $$('#group1, #group2, #group4, #group5').each(function(element){
    	$(element).hide();
    });

    $('group3btn').addClassName('on');
    $$('#group1btn, #group2btn, #group4btn, #group5btn').each(function(element){
    	$(element).removeClassName('on');
    });
}

function showGroup4(){
    $('group4').show();
    $$('#group1, #group2, #group3, #group5').each(function(element){
    	$(element).hide();
    });

    $('group4btn').addClassName('on');
    $$('#group1btn, #group2btn, #group3btn, #group5btn').each(function(element){
    	$(element).removeClassName('on');
    });
}

function showGroup5(){
    $('group5').show();
    $$('#group1, #group2, #group3, #group4').each(function(element){
    	$(element).hide();
    });

    $('group5btn').addClassName('on');
    $$('#group1btn, #group2btn, #group3btn, #group4btn').each(function(element){
    	$(element).removeClassName('on');
    });
}



function openEmailFriend(video) {
	$('email_friend').show().removeClassName('hidden');
	if ($('email_friend_form_controls').hasClassName('hidden')) {
		$('email_friend_form_controls').removeClassName('hidden');
		$('email_friend_thank_you').addClassName('hidden');
	}
	videoId = $(video);
	if($(video) == 1){
    	$('storybook_wedding').removeClassName('hidden');
    }
    else if($(video) == 2){
    	$('wedding_planning').removeClassName('hidden');
    }
    else if($(video) == 3){
    	$('the_registry').removeClassName('hidden');
    }
    else if($(video) == 4){
    	$('the_honeymoon').removeClassName('hidden');
    }
    $('emailFriendError').update('&nbsp;');
	loadRecaptcha();
}

function closeEmailFriend() {
	$('email_friend_close').observe('click', function(e){
		e.stop();
		$('storybook_wedding').addClassName('hidden');
		$('wedding_planning').addClassName('hidden');
		$('the_registry').addClassName('hidden');
		$('the_honeymoon').addClassName('hidden');
		document.getElementById('emailFriendRecieverEmail').value='';
        $('email_friend').hide();
	});
	$('email_friend_thank_you_close').observe('click', function(e){
		e.stop();
		$('storybook_wedding').addClassName('hidden');
		$('wedding_planning').addClassName('hidden');
		$('the_registry').addClassName('hidden');
		$('the_honeymoon').addClassName('hidden');		
		document.getElementById('emailFriendRecieverEmail').value='';
		$('email_friend').hide();
	});
	$('email_friend_form_close').observe('click', function(e){
		e.stop();
		$('storybook_wedding').addClassName('hidden');
		$('wedding_planning').addClassName('hidden');
		$('the_registry').addClassName('hidden');
		$('the_honeymoon').addClassName('hidden');
		document.getElementById('emailFriendRecieverEmail').value='';
		$('email_friend').hide();
	});
}

function loadRecaptcha() {
	var recaptchaKey = $('recaptchaPubKey').getValue();
	Recaptcha.create(recaptchaKey, "recaptcha-div", {theme: "clean"});
}



function emailFriendSubmit() {
	$('emailFriendSubmit').observe('click', function(e){
		e.stop();
		var emailFriendValid = true;
		var emailFriendSenderName = $('emailFriendSenderName').getValue();
		var emailFriendSenderEmail = $('emailFriendSenderEmail').getValue();
		var emailFriendRecieverEmail = $('emailFriendRecieverEmail').getValue();
		var emailFriendSubjectLine = $('emailFriendSubjectLine').getValue();
		var recaptchaResponse = $('recaptcha_response_field').getValue();
		var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var recaptchaPassed = false;
		
		if (emailFriendSenderName == null || emailFriendSenderName == "" || emailFriendSenderEmail == null || emailFriendSenderEmail == "" || emailFriendRecieverEmail == null || emailFriendRecieverEmail == "") {
			emailFriendValid = false;
			$('emailFriendError').update("Please fill out all fields.");
		} else if (emailFriendSenderEmail.match(emailRegEx) && emailFriendRecieverEmail.match(emailRegEx)) {
			if (recaptchaResponse == null || recaptchaResponse == "") {
				emailFriendValid = false;
				$('emailFriendError').update("Please enter the words displayed in the box.");
			} else {	
				
				var challenge = Recaptcha.get_challenge();
				var response = Recaptcha.get_response();
				FancyFeast.Web.Utils.AjaxUtility.Validate(challenge, response, function(result) {
					recaptchaPassed = result.value;
					if (recaptchaPassed) {
						emailFriendValid = true;
						
						FancyFeast.Web.Utils.AjaxUtility.SendToFriendSocial(emailFriendSenderEmail, emailFriendRecieverEmail, emailFriendSubjectLine, videoId, emailFriendSenderName, function(result) {
						
							if (result.value.Pass == true) {
								$('email_friend_form_controls').addClassName('hidden');
								$('email_friend_thank_you').removeClassName('hidden');								
		                        document.getElementById('emailFriendRecieverEmail').value='';                        								
							} else {
								$('emailFriendError').update(result.value.Reason);
							}
						});
					
					} else {
						emailFriendValid = false;
						Recaptcha.reload();
						$('emailFriendError').update("Please enter the words displayed in the box.");
					}
				
				});
			}
		} else {
			emailFriendValid = false;
			$('emailFriendError').update("Please enter valid email addresses. ");
		}
		
		return emailFriendValid;
	});
}

function emailFriendTwitterShareStorybookWedding() {
	window.open('http://twitter.com/share?url=http%3A%2F%2Fbit.ly%2Fpo7Hv0%0A%0A%0A%0A%0A&text=Watch%20the%20special%20role%20Sean%20%26%20Lisa%E2%80%99s%20adorable%20Persian%20kitten%20plays%20in%20the%20new%20%23FancyFeast%20storybook%20wedding%20commercial.', 'tweetThis', 'width=550,height=450,toolbar=no,scrollbars=no');
}

function emailFriendTwitterShareWeddingPlanning() {
	window.open('http://twitter.com/share?url=http%3A%2F%2Fbit.ly%2Fq1Ug6h&text=The%20%23FancyFeast%20kitten%20lends%20a%20playful%20touch%20when%20Lisa%20starts%20planning%20her%20upcoming%20storybook%20wedding.', 'tweetThis', 'width=550,height=450,toolbar=no,scrollbars=no');
}

function emailFriendTwitterShareTheRegistry() {
	window.open('http://twitter.com/share?url=http%3A%2F%2Fbit.ly%2FqGAewP&text=See%20what%20Sean%20%26%20Lisa%20find%20for%20their%20kitten%20while%20selecting%20their%20wedding%20registry%20in%20this%20new%20%23FancyFeast%20video.', 'tweetThis', 'width=550,height=450,toolbar=no,scrollbars=no');
}

function emailFriendTwitterShareTheHoneymoon() {
	window.open('http://twitter.com/share?url=http%3A%2F%2Fbit.ly%2FraV3Mp&text=Watch%20the%20new%20%23FancyFeast%20video%20to%20see%20if%20Sean%20%26%20Lisa%20decide%20to%20bring%20their%20impossibly%20cute%20kitten%20on%20their%20honeymoon.', 'tweetThis', 'width=550,height=450,toolbar=no,scrollbars=no');
}

function emailFriendFacebookShareStorybookWedding() {
	FB.ui({ 
		method: 'feed',
		name: 'Storybook Wedding',
		link: 'http://www.youtube.com/user/PurinaFancyFeast?feature=mhee#p/c/4D37F834684534A3/11/w5YYiPkJ8eE',
		description: 'The Fancy Feast&reg; brand brings you a story of love and devotion. If you thought their engagement was romantic, wait until to you see how Sean and Lisa&rsquo;s storybook wedding unfolds and the special role their adorable Persian kitten plays in it.'
	});
}

function emailFriendFacebookShareWeddingPlanning() {
	FB.ui({ 
		method: 'feed',
		name: 'Wedding Planning',
		link: 'http://www.youtube.com/purinafancyfeast#p/c/4D37F834684534A3/7/9s29r61ioQI',
		description: 'The Fancy Feast&reg; brand brings you a story of love and devotion. Watch how Sean and Lisa&rsquo;s adorable Persian kitten adds a playful touch to their wedding planning. '
	});
}

function emailFriendFacebookShareTheRegistry() {
	FB.ui({ 
		method: 'feed',
		name: 'The Registry',
		link: 'http://www.youtube.com/purinafancyfeast#p/c/4D37F834684534A3/8/ZFEy_9ma_6A',
		description: 'The Fancy Feast&reg; brand brings you a story of love and devotion. Sometimes the perfect gift is the one that&rsquo;s not just for you. See what Sean and Lisa discover for their adorable Persian kitten while selecting their wedding registry.'
	});
}

function emailFriendFacebookShareTheHoneymoon() {
	FB.ui({ 
		method: 'feed',
		name: 'The Honeymoon',
		link: 'http://www.youtube.com/purinafancyfeast#p/c/4D37F834684534A3/9/FlWCBXbFwXE',
		description: 'The Fancy Feast&reg; brand brings you a story of love and devotion. Will Sean and Lisa bring an impossibly cute little guest along on their honeymoon? See what happens when they don&rsquo;t want to leave their kitten behind.'
	});
}

function emailFriendFacebookShare() {
	FB.ui({ 
		method: 'feed',
		name: 'Something Borrowed',
		link: 'http://www.youtube.com/watch?v=aP3gzee1cps',
		description: ''
	});
}


