﻿/* Keeps browsers without firebug from throwing an error */
if (!("console" in window) || !("firebug" in console))
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = 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;
	}
}
//*******PRELOAD AND ROLLOVER FUNCTIONS END********//
//*****************************************************************************************//

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();
}

//*****************************************************************************************//
//*******PETCHARTS GLOBAL FUNCTIONS START********//
function onloadEvents()
{
    if($('links')) // Check to see if we're on the default page because we don't want to fire off all this stuff otherwise
    {
        plGnav(); // Initialize rollover preload/setup
        setupCalendar();
        checkCookies();// User must allows cookies on their browser; this makes sure.
        navDate();
        setColors();
        getThumbnailLists();
        voteButtonState();
        initShareThis();
        imageControlInit();
    }
}
Event.observe(window, "load", onloadEvents);

function initShareThis()
{
    if ($('share') == null)
        return false;
    $('share').show();
    $('share').down('img').observe('mouseover', mouseOverShareThis);
    $('share').down('img').observe('mouseout', mouseOutShareThis);
}

function mouseOverShareThis()
{
    var image = $('share').down('img');
    image.src = image.src.sub('off', 'over');
}

function mouseOutShareThis()
{
    var image = $('share').down('img');
    image.src = image.src.sub('over', 'off');
}

function setupCalendar()
{
    function dateStatus(date)
    {
	    var min = new Date(2007,10,09);// Start date of Pet Charts Program
	    var max = new Date();
	    if (date.getTime() < min.getTime() ||
	        date.getTime() > max.getTime())
		    return true; // true says "disable"
	    else
		    return false; // leave other dates enabled
    };
    
    function dateChanged(Calendar)
    {
        // Beware that this function is called even if the end-user only
        // changed the month/year.  In order to determine if a date was
        // clicked you can use the dateClicked property of the calendar:
        if (Calendar.dateClicked)
        {
            var y = Calendar.date.getFullYear();
            var m = Calendar.date.getMonth() + 1;     // integer, 0..11
            var d = Calendar.date.getDate();      // integer, 1..31
            // redirect...
            var qs = new Querystring();
            var type = qs.get("animal");
            var coreUrl = window.location.toString().split("/");
            coreUrl = coreUrl[0] + "//" + coreUrl[2] + "/";
            if (type != null)
            {
                window.location = coreUrl + "Default.aspx?day=" + y + '-' + m + '-' + d + "&animal=" + type;
            }
            else
            {
                window.location = coreUrl + "Default.aspx?day=" + y + '-' + m + '-' + d;
            }
        }
    };
    
    Calendar.setup({
        inputField     :    "f_date_c",     // id of the input field
        ifFormat       :    "%Y-%m-%d",      // format of the input field
        button         :    "ctl00_MastHead_TopNav_Nav1",  // trigger for the calendar (button ID)
        align          :    "Br",           // alignment (defaults to "Bl")
        singleClick    :    true,
        weekNumbers    :    false,
        dateStatusFunc :    dateStatus,
        onSelect       :    dateChanged,
        cache          :    true
    });
}

// Present visual "loading" status for AJAX events. 
function loadingStatus(statusType)
{
    {
        var c = 0;
        AjaxPro.onLoading = function(b)
        {
            if (statusType)
            {
                c++;
                if (b == true)
                {
                   $(statusType).style.display = "block";
                }
                else
                {
                   Effect.Fade($(statusType),{duration: 1});
                }
            }
        }
    }
}

// See if browser is allowing cookies, if not notify the user.
function checkCookies()
{
    setCookie('PetChartsTest', 'true', null, '/', '', ''); //Try to drop a cookie
    var cookieTest = getCookie('PetChartsTest'); // See if the cookie has a value/exists
    if (cookieTest)
    {
        deleteCookie('PetChartsTest');
    }
    else
    {
        window.location = "NoCookies.aspx";
    }
}

// Asynchronous call to the backend. Gets thumbnail lists for Videos and Images
function getThumbnailLists()
{
    var qs = new Querystring();
    var day = qs.get("day") ;
    var type = qs.get("animal") ;
    
    Purina.LongTail.Web.Controls.YouTubeControl.GetVideoList( day, type, getVideoList_callback ) ;
}

// Gets the page type from the querystring and sets classname on the body for color schemes
function setColors()
{
    var qs = new Querystring();
    var type = qs.get("animal");
    $('body').className = type;
}

// Function is run after thumbnails are written into page. Calculates total width of thumbnail list and enables thumbnail side scroller.
function initializeScrollers()
{
    var innerScroll = $('lCol').getElementsByClassName('thumbScroll');
    var innerScrollWidth = 0;
    for (i=0;i<innerScroll.length;i++)
    {
        var thumbArray = innerScroll[i].getElementsBySelector('a');
        innerScrollWidth = (thumbArray.length * 99) + 8 + "px";
        innerScroll[i].style.width = innerScrollWidth;
    }
    var scrollWrappers = $('lCol').getElementsByClassName('thumbScrollWrap');
    for (i=0;i<scrollWrappers.length;i++)
    {
        scrollWrappers[i].style.overflow = 'auto';
    }
}

// Submits votes for all content types and changes the voting state for that item.
function vote(feedId,feedType)
{
    var voteCookie = getCookie(feedId); // See if this item has already been voted on
    if ( voteCookie == null ) // If not voted on already, submit vote and drop already voted cookie.
    {
        if (feedType == 'v')//For voting on Video items.
        {
            var voteStatus = new loadingStatus("videoPlayerStatus");
            Purina.LongTail.Web.Controls.YouTubeControl.VoteVideo( feedId, voteVideo_callback );
        }
        else if (feedType == 'i')//For voting on Image items.
        {
            var voteStatus = new loadingStatus("imageDisplayStatus");
            Purina.LongTail.Web.Default1.VoteImage( feedId, voteImage_callback );
        }
        else if (feedType == 'a')//For voting on Article items.
        {
            var voteStatus = new loadingStatus("linksDisplayStatus");
            Purina.LongTail.Web.Default1.VoteArticle( feedId, voteArticle_callback) ;
        }
        setCookie(feedId, 'true', null, '/', '', ''); //Drop a cookie to set this item to already voted
        Effect.Fade($('btn' + feedId)); //Changes button to already voted state.
    }
}

// Sets the active/currently viewing thumbnail for videos and images.
function setThumbState(thumbObj)
{
    var thumbsParent = thumbObj.parentNode.parentNode;
    var thumbsArray = thumbsParent.getElementsBySelector('a');
    for (i=0;i<thumbsArray.length;i++)
    {
        thumbsArray[i].className = 'thumb';
    }
    thumbObj.className = 'thumbOn';
}

//*******PETCHARTS GLOBAL FUNCTIONS END********//
//*****************************************************************************************//

//*****************************************************************************************//
//*******VIDEO FUNCTIONS START********//

// Called by getThumbnailLists(). Writes Video thumbnail list into the page. Also calls getVideo() to get the video window content.
function getVideoList_callback( result )
{
    if ( result.value != null )
    {
        var list = ''
        var length = result.value.length ;
        
        // initialize the first movie
        if ( length > 0 )
        {
            getVideo( result.value[ 0 ].FeedId, result.value[ 0 ].FeedRating ) ;
        }
        
        // update the scrolling list
        for ( var i = 0 ; i < length ; i++ )
        {
            if (i == 0)
            {
                var thumbState = 'thumbOn';
            }
            else
            {
                var thumbState = 'thumb';
            }
            list += '<div class="thumbWrap">';
            list += '<a class="' + thumbState + '" href="javascript:void(0)" onclick="getVideo(' + result.value[ i ].FeedId + ', ' + result.value[ i ].FeedRating + ', this)"><img src="' + result.value[ i ].ImageUrl + '" alt="' + result.value[ i ].Title + '" /></a>';
            list += '<div class="thumbRank">'+ result.value[ i ].FeedRating + '</div>';
            list += '</div>';
        }
        list += '<div class="clearer"><!-- --></div>';
        $('videoThumbs').update(list);
        
        // update the scroll bar
        initializeScrollers();       
    }
}

// Asynchronous call to the backend. Gets the video window content.
function getVideo( feedId, feedRating, thumbObj )
{
    var videoStatus = new loadingStatus("videoPlayerStatus");
    $('vidRank').update( feedRating ) ;
    Purina.LongTail.Web.Controls.YouTubeControl.GetVideo( feedId, getVideo_callback ) ;
    if (thumbObj)
    {
        setThumbState(thumbObj);
    }
}

// Writes content into the video window.
var firstVideo = true; //Global var so that the first video on page load doesn't autoplay.
// the callback once the method is finished running
function getVideo_callback( result )
{
    if ( result.value != null )
    {
        var voteCookie = getCookie( result.value.FeedId ); // See if this item has already been voted on
        $('vidName').update( result.value.Title ) ;
        $('vidPubDate').update( result.value.ScheduleDate ) ;
        $('vidSource').update( '<a href="' + result.value.ProviderUrl + '" target="_blank">' + result.value.Provider + '</a>' ) ;
        $('vidTotal').update( result.value.TotalScore ) ;        
        $('vidVote').update( '<a href="javascript:void(0)" class="vote" id="btn' + result.value.FeedId + '" onclick="vote(' + result.value.FeedId + ', \'v\')"><span>Vote Now</span></a><div class="voted"><span>Vote Now</span></div>' ) ;
        if ( voteCookie == null ) // If not voted on already, set the enable the vote button
        {
            var voteBtn = $('vidVote').getElementsByClassName('vote');
            voteBtn[0].style.display = 'block';
        }
        else    // else disable the vote button
        {
            var voteBtn = $('vidVote').getElementsByClassName('vote');
            voteBtn[0].style.display = 'none';
        }
        
        var vidUrl = result.value.Url ;
        vidUrl = vidUrl.replace( "?", "" ) ;
        vidUrl = vidUrl.replace( "=", "/" ) ;
        var autoPlay = (firstVideo) ? '' : '&autoplay=1';
        firstVideo = false;
        var so = new SWFObject( vidUrl + autoPlay + '&rel=0', "videoPlayerSWF", "423", "354", "8", "#ffffff" ) ;
        so.addParam( "quality", "high" ) ;
        so.addParam( "wmode", "transparent" ) ;
        so.addParam( "autoplay", "true" ) ;
        so.write( "videoPlayer" ) ;
        //Write Hitbox gif
        //Convert spaces from Title into plus signs
        result.value.Title = result.value.Title.replace(/ /g, "+");
        $('vidHBX').update('<img src="http://ehg-nestleusainc.hitbox.com/HG?hc=we89&cd=1&hv=6&ce=u&hb=' + hbx.acct + '&n=Video+'+result.value.FeedId+'+'+result.value.Title+'+'+result.value.ScheduleDate+'&vcon=/PetCharts;/Purina/PetCharts&seg=&cmp=&gp=&fnl=&pec=&dcmp=&ra=&gn=&cv=&ld=&la=&c1=&c2=&c3=&c4=" border="0" width="1" height="1" />');
    }
}

// Updates the video vote total for this item.
function voteVideo_callback( result )
{
    if ( result.value != null )
    {
         $('vidTotal').update( result.value.TotalScore ) ;
    }
}

//*******VIDEO FUNCTIONS END********//
//*****************************************************************************************//

//*****************************************************************************************//
//*******IMAGE FUNCTIONS START********//

function imageControlInit(feedID)
{ 
    $("imageDisplayStatus").style.display = "block";
    
    //Set up day querystring
    var qsDay = new Querystring();
    var day = qsDay.get("day");
    if (day != null)
    {
       var dayQuery = 'day=' + day;
    }
    else
    {
        var dayQuery = 'day=';
    }
    
    //Set up feedID querystring
    if (feedID == null)
    {
		var feedIdQuery = '';
    }
    else
    {
        var feedIdQuery = '&feedId=' + feedID;
    }
    
    //Set up animal querystring
    var qsAnimal = new Querystring();
    var animal = qsAnimal.get("animal");
    if (animal != null)
    {
       var animalQuery = '&animal=' + animal;
    }
    else
    {
        var animalQuery = '&animal=';
    }
    
    //Set up item querystring
    var qsItem = new Querystring();
    var item = qsItem.get("item");
    if (item != null)
    {
       var itemQuery = '&item=' + item;
    }
    else
    {
        var itemQuery = '&item=';
    }
    
    //Update content
    new Ajax.Updater(
        {success: 'imageControl'},
        '/Controls/ImageArea.aspx?' + dayQuery + feedIdQuery + animalQuery + itemQuery,
        {
            method: 'get',
            onComplete: imageControlLoaded,
            onFailure: ajaxFailed
        }
    );
}

function imageControlLoaded()
{
    initializeScrollers(); //Setup the scroller
    voteButtonState(); //Set the vote state
    
    var thumbIndex = 1;
    var thumbsParent = $('imageThumbs')
    var thumbsArray = thumbsParent.getElementsBySelector('a');
    for (i=0;i<thumbsArray.length;i++)
    {
        var activeThumb = $(thumbsArray[i]).hasClassName('thumbOn');
        if(activeThumb)
        {
            thumbIndex = i;   
        }  
    }
    $('imageScrollWrap').scrollLeft = thumbIndex * 100;
    Effect.Fade($("imageDisplayStatus"),{duration: 1});
}

//Resize the preview image to correct size/aspect ratio
function resizeImage(imgToResize)
{               
    var resizeImage = $('imageDisplayInner');
    
    var actualWidth = imgToResize.width;
    var actualHeight = imgToResize.height;
    
    var x1 = 423; // container width
    var y1 = 317; // container height
    var x1y1 = x1 / y1; // container width and height ratio
    var x2y2 = actualWidth / actualHeight; // Actual image width and height ratio
    var ratio = 0;

    if (x1y1 >= x2y2)
    {
        ratio = y1 / actualHeight;                   
    }
    else
    {
        ratio = x1 / actualWidth;
    }
    
    var newWidth = Math.round(actualWidth * ratio);
    var newHeight = Math.round(actualHeight * ratio);
    
    resizeImage.width = newWidth;
    resizeImage.height = newHeight;
    
    Effect.Fade($("imageDisplayBlocker"),{duration: 1});
}

// Updates the image vote total for this item.
function voteImage_callback( result )
{
    if ( result.value != null )
    {
        $('imgTotal').update( result.value.TotalScore ) ;        
    }
}

//*******IMAGE FUNCTIONS END********//
//*****************************************************************************************//

//*****************************************************************************************//
//*******ARTICLE FUNCTIONS START********//
// Submits votes for article content and changes the voting state for that item.

//Sets the initial state of the vote buttons in the article section
function voteButtonState()
{
    var voteButtons = $('mainContent').getElementsByClassName('vote');
    for ( var i = 0 ; i < voteButtons.length ; i++ )
    {
        var btnId = voteButtons[i].readAttribute('id');
        btnId = btnId.replace(/btn/,"");
        var voteCookie = getCookie(btnId); // See if this item has already been voted on
        if ( voteCookie != null ) // If not voted on already change vote button state.
        {
            voteButtons[i].style.display = 'none' //Changes button to already voted state.
        }
    }
}

// Updates the article vote total for this item.
function voteArticle_callback( result )
{
    if ( result.value != null )
    {
        $('article'+ result.value.FeedId).update( result.value.TotalScore ) ;
    }
}

//*******ARTICLE FUNCTIONS END********//
//*****************************************************************************************//

function navDate()
{
    tNav1 = true;
    tNavItems = $('tNav').getElementsBySelector('a');
    for ( var i = 0 ; i < tNavItems.length ; i++ )
    {
        var navItemsOn = tNavItems[i].hasClassName('on');
        if (navItemsOn)
        {
            tNav1 = false;
        }
    }
    if (tNav1)
    {
        var qs = new Querystring();
        var day = qs.get("day");
        if (day)
        {
            day = qs.get("day").toString().split("-");
            var monthName = "";
            if (day[1]==1) monthName=("Jan.");
            else if (day[1]==2) monthName =("Feb.");
            else if (day[1]==3) monthName =("Mar.");
            else if (day[1]==4) monthName =("Apr.");
            else if (day[1]==5) monthName =("May");
            else if (day[1]==6) monthName =("Jun.");
            else if (day[1]==7) monthName =("Jul.");
            else if (day[1]==8) monthName =("Aug.");
            else if (day[1]==9) monthName =("Sep.");
            else if (day[1]==10) monthName =("Oct.");
            else if (day[1]==11) monthName =("Nov.");
            else monthName = ("Dec.");
            day = monthName + ' ' + day[2] + ', ' + day[0];
            $('navDate').update(day);
        }
    } 
}

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 ajaxFailed()
{
    console.log('failed');
}