﻿
try { console.log('init console... done'); } catch(e) { console = { log: function() {} } }

//*****************************************************************************************//
//*******PRELOAD AND ROLLOVER FUNCTIONS START********//

//This function preloads the global navigation elements
var navRoll = false; //Set this variable to false so no global rollovers will work until all preloading is done.
function plGnav()
{
	imgRoll();
	navRoll = true;
}

function uPreload(imgObjName,path,ext)
{
	eval( imgObjName + "a = new Image();" );
	eval( imgObjName + "a.src = '" + path + "/" + imgObjName + "a" + ext + "';");
}
 
//This function works in conjuction with the uPreload function to automatically preload images on a page.
//Images with the "roll" class in the HTML markup will be preloaded using "uPreload" and must be named accordingly.
//Ex. <img src="myimagei.gif" alt="my image alt" class="roll" />
function imgRoll()
{
	var linkArray = document.getElementsByTagName("img");
    for (var loop=0; loop<linkArray.length; loop++)
    {
    	imgClassArray = linkArray[loop].className.split(' ');
        for (var i=0; i<imgClassArray.length; i++)
        {
         	if (imgClassArray[i] == "roll")
         	{
    			var imgWithPath = linkArray[loop].src;
    			var imgPath = imgWithPath.substring( 0, imgWithPath.lastIndexOf( '/' ));
    			var imgName = imgWithPath.substring( imgWithPath.lastIndexOf( '/' ) + 1);
    			var imgObjName = imgName.substring( 0, imgName.lastIndexOf( '.' ) ) ;
    			var fileExt = imgWithPath.substring(imgWithPath.lastIndexOf('.'), imgWithPath.length); //file extension
    			if(imgObjName.substring(imgObjName.length -1)!= 'o')
    			{
    				uPreload(imgObjName.substring(imgObjName.length - 1,0),imgPath,fileExt);
    			}
    			linkArray[loop].parentNode.onmouseover=function(){roll(this);};
				linkArray[loop].parentNode.onmouseout=function(){roll(this);};
         	}
        }
    }
}
 
//This function is for navigation rollover images; uName is name of graphic, uState is on, off or over state
//This function only works for images that have been preloaded using the "uPreload" function.
//usage: <a href="myPage.aspx" onmouseover="nr('myimage','a')" onmouseout="nr('myimage','i')"><img src="myimagei.gif" alt="my image alt" id="myimage" class="pl" /></a>
function roll(o)
{
	if(navRoll)
	{
	var i,isnode,src,ftype,fsuffix,newsrc,nownode;
	for (i=0;i<o.childNodes.length;i++) // loop through all childNodes
	{
		nownode=o.childNodes[i];
		// if the node is an element and an IMG set the variable and exit the loop
		if(nownode.nodeType==1 && /img/i.test(nownode.nodeName))
		{
			isnode=i;
			break;
		}
	}
	// check src and do the rollover
	src = o.childNodes[isnode].src; //full src with path
	fsrc = src.substring(src.lastIndexOf('.'), 0); //full src with path without file extension
	ftype = src.substring(src.lastIndexOf('.'), src.length); //file extension
	fsuffix = src.substring(src.lastIndexOf('.'), src.length - 5); //type of item ex.'i', 'a' or 'o'
	if(fsuffix == 'a')
	{
		newsrc = fsrc.substring(fsrc.length-1,0)+ 'i' + ftype;
	}
	else if(fsuffix == 'i')
	{
		newsrc = fsrc.substring(fsrc.length-1,0)+ 'a' + ftype;
	}
	else
	{
		newsrc = fsrc.substring(fsrc.length-1,0)+ 'o' + ftype;
	}
	o.childNodes[isnode].src=newsrc;
	}
}

Event.observe(window, "load", plGnav);
//*******PRELOAD AND ROLLOVER FUNCTIONS END********//
//*****************************************************************************************//

function legal_window(url)
{
    var link = window.open(url,"legal",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,top=(20),left=(20),screenX=(20),screenY=(20),width=560,height=450');
    link.focus();
}

function setFlashVar(flashObjId, flashVar, flashVarValue)
{
    window.document[flashObjId].SetVariable(flashVar,flashVarValue);
}

//Clears default value of input textfield when field is clicked by user.
function doClear(theText)
{
	if (theText.value == theText.defaultValue)
	{
		theText.value = ""
	}
}

//Validates the footer search textbox
function verifyAskPurina( f ) {
	if ( f.sp_q.value != "" )
		f.submit();
	else {
		alert("Please enter a keyword.");
		f.sp_q.focus();
		return false;
	}
}

function showTexture(toShow)
{
   toShow = 'texture' + toShow;
   var divArray = $w('textureLoaf textureFlaked textureCarved textureFineCuts texturePrimeFilets textureSearedFilets textureShredded textureSliced textureTenderCuts');
   for (var i=0; i<divArray.length; i++)
   {
        if(divArray[i] == toShow)
        {
           $(divArray[i]).show();
        }
        else
        { 
           $(divArray[i]).hide();
        }
   }
}

function headerLoginDrop(direction)
{
    switch(direction)
    {
    case 'dwn':
        $('logInDrop').show();
        $('logInDropBlocker').show();
        $$('.btnMastLogInOff').each(function(s) {
          s.toggleClassName('btnMastLogInOn');
        });
        break    
    default:
        $('logInDrop').hide();
        $('logInDropBlocker').hide();
        $$('.btnMastLogInOff').each(function(s) {
          s.toggleClassName('btnMastLogInOn');
        });
        break 
    }
}

function headerLoginDropExtend()
{   
    $('dropDownHaveOldLogin').toggle();
    $('btnDropDownToggle').toggleClassName('btnDropDownToggleOn');
}

function headerLogin(webRoot)
{
    pauseComp(1000); //Brief pause before doing anything.
    var email = $('Email').value; //Get the value of this form element from the page.
    var password = $('Password').value; //Get the value of this form element from the page.
	var checkboxValue = $('cbxRemember').value; //Get the value of this form element from the page.
	var result = Friskies2007.Web.AjaxUtility.LogUserIn(email, password, checkboxValue); //Call .NET method passing values from form.
	switch(result.value)
    {
        case "Success":
            this.location.href = webRoot + "/Explorers/Your-Account/Default.aspx?&aj";
            break;
        case "FailedRecordMatch":
            this.location.href = webRoot + "/Explorers/Log-In/Default.aspx?NoUser=true&aj&em=" + email;
            break;
        case "InvalidEmail":
            this.location.href = webRoot + "/Explorers/Log-In/Default.aspx?BadEmail=true&aj&em=" + email;
            break;
        default:
            window.location.href = webRoot + "/Explorers/Log-In/Default.aspx?BlankVal=true&aj";
            break; 
    }
}

//START Send to Friend dropdown stuff
function sendFriendInitState()
{
    if ($('sndFrndContent'))
    {
        var rootUrl = Friskies2007.Web.AjaxUtility.GetAjaxRootURL();
        var rootUrl = rootUrl.value;
		if (rootUrl.indexOf('localhost', 0) > 0 )
		{
		    updateWithFile(rootUrl + '/Controls/SendToFriend.aspx', 'sndFrndContent');
		}
		else
		{
		    updateWithFile('/Controls/SendToFriend.aspx', 'sndFrndContent');
        }
    }
}

function sendFriend(typeOfSend)
{
	//Check to see if user is logged in or not.
    var loggedIn = Friskies2007.Web.AjaxUtility.UserIsAuthenticated(); //Get boolean response back from server after calling .NET method
    var url = document.location.href;
    var title = document.title;
	var recipients = $('ToEmails').value; //Get the value of this form element from the page.
	var sender = $('FromEmail').value; //Get the value of this form element from the page.
	var comments = $('Message').value; //Get the value of this form element from the page.
	if (!loggedIn.value)
	{
	    var checkboxValue = $('Signup').value; //Get the value of this form element from the page.
	}
	else
	{
	    var checkboxValue = null;
    }
	var res = Friskies2007.Web.AjaxUtility.SendEmail(recipients, sender, comments, checkboxValue, url, title, typeOfSend); //Call .NET method passing values from form.
	setSendFriendMsg(res.value); //Get response back from server after calling .NET method and pass to setSendFriendMsg function.
}

function setSendFriendMsg(msg)
{   
	switch(msg)
	{
		case 'Success': //Success show Thank You message
		    var rootUrl = Friskies2007.Web.AjaxUtility.GetAjaxRootURL();
            var rootUrl = rootUrl.value;
		    if (rootUrl.indexOf('localhost', 0) > 0 )
		    {
		        updateWithFile(rootUrl + '/Controls/SendToFriendThanks.aspx', 'sndFrndContent');
		    }
		    else
		    {
		        updateWithFile('/Controls/SendToFriendThanks.aspx', 'sndFrndContent');
            }
		    break;
		case 'An exception occurred while sending your message. Please try again later': //Failed at server; show generic error message
		    console.log(msg);
		    $('validationErrors').show();
		    break;
		default: //This catches the remaining reponses which can only be form validation errors.
		    $('validationErrors').show(); //Show Validation Errors Div
		    console.log(msg);
		    $('sndFrndValidationError').update(msg); //Write validation response error into Validation Errors Div
		    break;
	}
}

//To update content area with a file using AJAX. url = file to get, dId = id to update to. Relies on the Javascript Prototype library.
function updateWithFile(url, dId)
{
	var myAjax = new Ajax.Updater(
				{success: dId}, 
				url, 
				{method: 'get', parameters: '', onFailure: reportError,evalScripts: false, onException: reportError}
				);
}

//Reports generic error on Ajax Updater failure
function reportError(request)
{
	console.log('We are sorry there was an error. Please try again later.');
}
//END Send to Friend dropdown stuff

//START Food Tooltips stuff
function balloon(bElmnt, bType, foodID, imgPath)
{
    switch (bType)
    {
        case "textToolTip":
            //Update Content inside #balloonContent
            var innrContent = imgPath;
			toolTip(bElmnt, innrContent, 220);
        break;
        
        case "food":
			//Update Content inside #balloonContent
			var prodTitle = Friskies2007.Web.AjaxUtility.GetProductTitle(foodID);
		    var prodText = Friskies2007.Web.AjaxUtility.GetBubbleText(foodID);
		    var innrContent = '<div id="balloonContentLeft">';
			    innrContent += '<h2>' + prodTitle.value + '</h2>';
			    innrContent += '<p>' + prodText.value + '</p>';
			    innrContent += '</div>';
			    innrContent += '<img id="balloonThumb" class="block" src="' + imgPath + '/_res/i/food/med_' + foodID + '.jpg" alt="" />';
			    innrContent += '<div class="clearer"><!-- --></div>';
			    toolTip(bElmnt, innrContent, 390);
        break;
        
        default :
			blckr.style.left = "-400px";
			wrp.style.left = "-400px";
			wrp.style.height = "1px";
			pntr.style.left = "-400px";
		break;
    }
}
//END Food Tooltips stuff

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 KeyDownHandler(e, btn)    
{
   if( !e ) {
    //if the browser did not pass the event information to the
    //function, we will have to obtain it from the event register
    if( window.event ) {
      //Internet Explorer
      e = window.event;
    } else {
      //total failure, we have no way of referencing the event
      return;
    }
  }

  if( typeof( e.keyCode ) == 'number'  ) {
    //DOM
    val = e.keyCode;
  } else if( typeof( e.which ) == 'number' ) {
    //NS 4 compatible
    val = e.which;
  } else if( typeof( e.charCode ) == 'number'  ) {
    //also NS 6+, Mozilla 0.9+
    val = e.charCode;
  } else {
    //total failure, we have no way of obtaining the key code
    return;
  }
        
  if (val == 13)           
  {        
        // cancel the default submit            
		e.returnValue = false;            
		e.cancel = true;         
		var obj = document.getElementById(btn);
		//make sure we found something
		if (obj!=null && obj["click"]!=null)
		{	
			obj.click();
		}
	} 
}

function initPixModal(target_class)
{	
	if ( $$(target_class) )
	{
		var modalLinks = $$("a." + target_class);
		for (i = 0; i < modalLinks.length; i++)
		{
			new Control.Modal(modalLinks[i],{
			    opacity: 0.7,
			    fade: true,
			    width: 881,
			    height: 534,
			    onSuccess: function()
			    {  
                    initPixModal("modal") 
                }
	        });
		}
    }
	modalFromQuery();
}

// Modal for Commercial TV Spot modal on homepage
function initCommercialTVSpotModal()
{	
	  new Control.Modal($('launchCommercialModal'),{
            opacity: 0.7,
            fade: true,
            width: 594,
            height: 414         
        });
   
}

// Modal for new TV Spot modal on homepage
function initHomePageTVSpotModal()
{	
	if($$('.homePg').length > 0)
	{
	    new Control.Modal($('launchTvModal'),{
            opacity: 0.7,
            fade: true,
            width: 594,
            height: 414,
            beforeOpen: function(){
                $('homeFlash').setStyle({opacity: 0});
            },
            afterClose: function(){
                $('homeFlash').setStyle({opacity: 1});
            }
        });
    }
}

//Following is to open Modal on page load based on existence of "pix" querystring	
function modalFromQuery()
{
    var qs = new Querystring();
    var modalQuery = qs.get("pix");
    
    if(modalQuery !=null)
	{
	    Control.Modal.open(" ",{  
            opacity: 0.7,
	        fade: true,
		    width: 881,
		    height: 514,
            beforeOpen: function()
            {  
                updateWithFile("DetailYourPix.aspx?id=" + modalQuery, "modal_container");
            },
            afterClose: function()
            {  
                var coreUrl = window.location.toString().split("?");
                window.location = coreUrl[0];
            } 
        });
    }
}

//Following is to open Modal on page load based on existence of "tv-spot" querystring	
function tvSpotModalFromQuery()
{   
    var qs = new Querystring();
    var modalQuery = qs.get("tv-spot");
    
    if(modalQuery !=null)
	{   
	    Control.Modal.open(" ",{
            opacity: 0.7,
            fade: true,
            width: 594,
            height: 414,
            beforeOpen: function(){
                
                var rootUrl = Friskies2007.Web.AjaxUtility.GetAjaxRootURL();
                var rootUrl = rootUrl.value;
		        if (rootUrl.indexOf('localhost', 0) > 0 )
		        {
		            updateWithFile(rootUrl + "Snippets/HomeTVSpot.aspx", "modal_container");
		        }
		        else
		        {
		            updateWithFile("/Snippets/HomeTVSpot.aspx", "modal_container");
                }
            },
            afterClose: function(){
                var coreUrl = window.location.toString().split("?");
                window.location = coreUrl[0];
            }
        });
    }
}

var videoNumber = 'firstVideoNumber=1';
function initTVSpotModalLink()
{
    if ( $('tvSpotModalLink') )
    {
        var h1 = $$('#prodDetTxt > h1');
        if(h1[0].innerHTML == 'Seafood Sensations®')
        {
            $('tvSpotModalLink').innerHTML = 'See the beautiful beaches of Seafood Sensations';
            $('tvSpotModalLink').show();
            videoNumber = 'firstVideoNumber=1';
        }
        if(h1[0].innerHTML == 'Grillers\' Blend®')
        {
            $('tvSpotModalLink').innerHTML = 'Watch the world of Grillers\' Blend come to life';
            $('tvSpotModalLink').show();
            videoNumber = 'firstVideoNumber=2';   
        }
        if(h1[0].innerHTML == 'Indoor Delights®')
        {
            $('tvSpotModalLink').innerHTML = 'Experience Indoor Delights in 15 seconds';
            $('tvSpotModalLink').show();
            videoNumber = 'firstVideoNumber=3';  
        }
        if(h1[0].innerHTML == 'Surfin\' & Turfin\' Favorites®')
        {
            $('tvSpotModalLink').innerHTML = 'Discover the Surfin\' & Turfin\' Favorites fantasy world';
            $('tvSpotModalLink').show();
            videoNumber = 'firstVideoNumber=4';
        }
    }
}

function initTVSpotModal(webRoot)
{	
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
    var transparencyMode = 'transparent';
    if(navigator.platform.indexOf("Mac") >= 0)
    {
        transparencyMode = 'opaque';
    }
    webRoot = window.location.hostname + webRoot;
    Control.Modal.open(" ",
    {
	    opacity: 0.7,
	    fade: true,
	    width: 510,
	    height: 380,
	    afterOpen: function()
        {
            if (isIE6 && $('tvSpotModalCallout'))
            {
                $('tvSpotModalCallout').hide();
            }
            var x='<div id="tvSpotModal" class="tvSpotModal">';
            x+= '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,00,0" width="510" height="380" id="tvModalSwf">';
            x+= '<param name="movie" value="http://' + webRoot + '/_res/swf/TVSpotModal/swf/friskiesModalFlash.swf" />';
            x+= '<param name="quality" value="high" />';
            x+= '<param name="flashVars" value="' + videoNumber + '" />';
            x+= '<param name="wmode" value="' + transparencyMode + '" />';
            x+= '<param name="bgcolor" value="#4C4C4C" />';
            x+= '<embed src="http://' + webRoot + '/_res/swf/TVSpotModal/swf/friskiesModalFlash.swf" quality="high" flashVars="' + videoNumber + '" wmode="' + transparencyMode + '" bgcolor="#4c4c4c" width="510" height="380" name="tvModalSwf" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>';
            x+= '</object>';
            x+= '</div>';
            $('modal_container').innerHTML = x;
        },
        afterClose: function()
        {  
            if (isIE6)
            {
                $('tvSpotModalCallout').show();
            }
        }
    })
}

function setHomepageColors()
{
    var bodySelect = $$('body.homePg');
    if ( bodySelect.length > 0 )
    {
        var colorScheme = new Array();
        colorScheme[0] = "Red";
        colorScheme[1] = "Orange";
        colorScheme[2] = "Purple";
        colorScheme[3] = "Green";
        colorScheme[4] = "Blue";
        var ran_number=Math.floor(Math.random()*colorScheme.length);
        bodySelect[0].addClassName(colorScheme[ran_number])
    }
}

/* Client-side access to querystring name=value pairs
	Version 1.2.3
	22 Jun 2005
	Adam Vandenberg
*/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}

function initFeaturedPixRollover(rolloverId, magnifyIcon)
{
	if ($(rolloverId) == null || $(magnifyIcon) == null)
		return false;
	else
		rolloverId = $(rolloverId);
	magnifyIcon = $(magnifyIcon);
	rolloverId.observe('mouseover', featuredPixRolloverListener.bindAsEventListener(rolloverId, magnifyIcon));
	rolloverId.observe('mouseout', featuredPixRolloutListener.bindAsEventListener(rolloverId, magnifyIcon));		
}

function featuredPixRolloverListener(e, magnifyIcon)
{
	featuredPixRollover(magnifyIcon);
}

function featuredPixRolloutListener(e, magnifyIcon)
{
	featuredPixRollout(magnifyIcon);
}

function featuredPixRollover(magnifyIcon)
{
	$(magnifyIcon).setStyle({ backgroundImage: 'url(../_res/i/pix/magnifyOn.png)'});
}

function featuredPixRollout(magnifyIcon)
{
	$(magnifyIcon).setStyle({ backgroundImage: 'url(../_res/i/pix/magnifyOff.png)'});
}

function fieldCharCount(userLength, max)
{
    if (userLength <= max)
    {
        $('charCount').innerHTML = max - userLength;
    }
    else if (userLength >= max)
    {
        var fieldToCount = $$('textarea.textarea');
        fieldToCount[0].value = fieldToCount[0].value.substring(0,max);
    }
}

function blockKeyboard()
{
    var fieldToCount = $$('textarea.textarea');
    fieldToCount[0].value = fieldToCount[0].value.substring(0,maxLength);
}

function joinFormdogsFeedingListener()
{
    if($$('.haveDogsYes input').length > 0)//observe dogs feeding question on Join form
    {
        $$('.haveDogsYes input')[0].observe('click', joinFormdogsFeeding);
        $$('.haveDogsYes input')[1].observe('click', joinFormdogsFeeding);
        joinFormdogsFeeding();
    }
}

function joinFormdogsFeeding()
{
    $$(".haveDogsYes input").each( function(e)
    {
        if (e.checked)
        {
            var chosen = e.value;
            if (chosen == 0)
            {
                $('dogsFeedingFull').show();
            }
            else
            {
                $('dogsFeedingFull').hide();
            }
        }
    });
}

document.observe("dom:loaded", function()
    {
        setHomepageColors();
        
        setTimeout(function()
        {
            tvSpotModalFromQuery();
            
            initPixModal("modal");
	        initHomePageTVSpotModal();	   
	        initCommercialTVSpotModal(); 
	        //Write in content for Send To Friend dropdown
	        sendFriendInitState();
	        initFeaturedPixRollover('mastheadFeatPix', 'pixFeatMagnify');
	        initTVSpotModalLink();
	        if($('add_photo_open'))
	        {
	            $$('input.hiddenFileUpload')[0].observe('change', getFileInformation);
	        }
	        joinFormdogsFeedingListener();
        }, 100);
    }
);