
  checkForCookies();

  var themes = [ "Frighteningly Funny", "Ghoulish Groups", "Terrorific Toddlers", "Spine-tingling Scary" ];
  var themeId = getQuerystringValue( "themeId" ),
      winnerId,
      matchup,
      results,
      redirectURL = "",
      imagePath = "http://family.go.com/images/faceoff/halloween-costume/photos/",
      vsFields,
      roundText;

  matchup = getQuerystringValue( "m" );
  if( matchup != "" ) { matchup = parseInt( matchup ); }
  else { matchup = 1; }
  
  
  String.prototype.trim = function () { return this.replace(/^\s*/, "").replace(/\s*$/, ""); }

  function evaluateJSON( passBack ) { return eval( '(' + passBack.responseText.replace(/^\s*/, "").replace(/\s*$/, "") + ')' ); }

  function getTheme( tempThemeId )
  {
    themeId = tempThemeId;
    matchup = 1;
    
    var ajGetPoll = new Ajax.Request(
      'http://family.go.com/ffCakeContest.do',
      {
        method: 'get',
        parameters: 'themeId=' + themeId + '&phase=one',
        onComplete: returnResults
      });
  }


  function castVote( itemId )
  {
    var ajGetPoll = new Ajax.Request(
      'http://family.go.com/ffCakeContest.do',
      {
        method: 'get',
        parameters: 'chosenEntryId=' + itemId + '&phase=two',
        onComplete: returnResults
      });
  }


  function getFinalResults()
  {
    var ajGetPoll = new Ajax.Request(
      'http://family.go.com/ffCakeContest.do',
      {
        method:'get',
        parameters:'themeId=' + themeId + '&phase=three',
        onComplete: showWinner
      });
  }


  // capitalize all first letters of the value and make the rest lower case  
  function capitalizeFirstLetters( value )
  {
    value = value.toLowerCase();

    var filterIndex = 0;
    var firstChar = value.substring( 0, 1 ),
        remaining = value.substring( 1, value.length ),
        prepend;

    value = firstChar.toUpperCase() + remaining;
    filterIndex = value.indexOf( " " );

    while( filterIndex != -1 )
    {
      prepend = value.substring( 0, filterIndex );
      firstChar = value.substring( filterIndex + 1, filterIndex + 2 );
      remaining = value.substring( filterIndex + 2, value.length );
      value = prepend + " " + firstChar.toUpperCase() + remaining;

      filterIndex = value.indexOf( " ", filterIndex + 1 );
    }
    
    // special cases - characters following ( and "
    filterIndex = value.indexOf( "(" );
    while( filterIndex != -1 )
    {
      prepend = value.substring( 0, filterIndex );
      firstChar = value.substring( filterIndex + 1, filterIndex + 2 );
      remaining = value.substring( filterIndex + 2, value.length );
      value = prepend + "(" + firstChar.toUpperCase() + remaining;
      filterIndex = value.indexOf( "(", filterIndex + 1 );
    }


    filterIndex = value.indexOf( "&quot;" );
    while( filterIndex != -1 )
    {
      filterIndex += 6;
      prepend = value.substring( 0, filterIndex );
      firstChar = value.substring( filterIndex, filterIndex + 1 );      
      asciiCode = firstChar.charCodeAt( 0 );
      if( ( asciiCode > 64 && asciiCode < 91 ) || ( asciiCode > 96 && asciiCode < 123 ) )
      {
        remaining = value.substring( filterIndex + 1, value.length );
        value = prepend + firstChar.toUpperCase() + remaining;
      }
      filterIndex = value.indexOf( "&quot;", filterIndex );
    }


    filterIndex = value.indexOf( "&quot" );
    while( filterIndex != -1 )
    {
      filterIndex += 5;
      prepend = value.substring( 0, filterIndex );
      firstChar = value.substring( filterIndex, filterIndex + 1 );      
      asciiCode = firstChar.charCodeAt( 0 );
      if( ( asciiCode > 64 && asciiCode < 91 ) || ( asciiCode > 96 && asciiCode < 123 ) )
      {
        remaining = value.substring( filterIndex + 1, value.length );
        value = prepend + firstChar.toUpperCase() + remaining;
      }
      filterIndex = value.indexOf( "&quot", filterIndex );
    }
    
    return value;
  }
  
  
  function filterCityState( city, state, containerId )
  {
    var cityState = "";

    if( city != null && city.trim() != "" ) cityState = capitalizeFirstLetters( city ).split( "," ).join( ", " ).split( "  " ).join( " " ).trim();
    
    if( state != null && state.trim() != "" )
    {
      if( cityState != "" ) cityState = cityState + ", " + state.toUpperCase().trim();
      else cityState = state.trim();
    }

    if( containerId != null && containerId != "" )
    {
      if( cityState == "" ) document.getElementById( containerId ).style.marginRight = "0";
      else document.getElementById( containerId ).style.marginRight = "22px";
    }
    
    return cityState;
  }


  function filterTitle( title )
  {    
    if( winnerId != undefined )
      return capitalizeFirstLetters( title ).trim().split( "" ).join( "'" );
    else
      return capitalizeFirstLetters( title ).trim().split( "" ).join( "'" ).split( "&quot" ).join( "&quot;" );
  }
  
  
  function urlFriendly( title ) { return title.trim().toLowerCase().split( ", " ).join( "-" ).split( "," ).join( "-" ).split( " " ).join( "-" ).split( ":" ).join( "" ).split( "'" ).join( "" ).split( "!" ).join( "" ).split( "&" ).join( "-and-" ); }

  function removeQuotes( value ) { return value.split( "'" ).join( "" ).split( "\"" ).join( "" ); }  
      
  
  function showWinner( passBack )
  { 
    results = evaluateJSON( passBack );
    var winner = getWinnerFromFinalResults(),
        winnerTitle = filterTitle( winner.ffTitle ),
        html = "";    

    document.getElementById( "winnerThemeTitle" ).innerHTML = themes[ parseInt( winner.ffgetThemeId ) - 11 ];
    document.getElementById( "faceoffWinnerPhoto" ).src = imagePath + winner.ffImageURLLarge.replace( "http://family.go.com/images/upload/contest/halloween-costume/", "" );
    document.getElementById( "faceoffWinnerPhoto" ).alt = removeQuotes( winnerTitle );
    document.getElementById( "faceoffWinnerPhotoLink" ).href = winner.ffUrl;
    document.getElementById( "faceoffWinnerLink" ).href = winner.ffUrl;
    document.getElementById( "faceoffWinnerLink" ).innerHTML = winnerTitle;
    document.getElementById( "faceoffWinnerUser" ).href = "http://family.go.com/userprofile/" + winner.ffuserId;
    document.getElementById( "faceoffWinnerUser" ).innerHTML = winner.ffuserId;
    
    listAllItemResults();
  }
  
  
  function getWinnerFromFinalResults()
  { 
    winnerId = getQuerystringValue( "wid" );
    for( var i = 0; i < results.ffSortedContestEntryList.length; i++ )
    {
      var item = results.ffSortedContestEntryList[ i ];
      
      if( winnerId == item.ffid ) return item;
    }
  }
  
  
  function listAllItemResults()
  {
    var resultSide = "left";
    var html = "";
    var itemTitle = "";
    
    for( var i = 0; i < results.ffSortedContestEntryList.length; i++ )
    {  
      var item = results.ffSortedContestEntryList[ i ];
      
      itemTitle = filterTitle( item.ffTitle );

      html += '<div class="faceoffResult">';
      html += '  <div class="faceoffResultPhoto">';
      html += '    <a href="' + item.ffUrl + '"><img src="' + imagePath + item.ffImageURLSmall.replace( "http://family.go.com/images/upload/contest/halloween-costume/", "" ) + '" alt="' + removeQuotes( itemTitle ) + '" width="134" height="93" border="0">';
      html += '    <div class="roundedBorder_small"></div></a>';
      html += '  </div>';
      html += '  <div class="faceoffResultDetails">';
      html += '    <div class="faceoffResultTitle">' + ( i + 1 ) + '. ' + itemTitle + '</div>';
      html += '    Costume by: <a href="http://family.go.com/userprofile/' + item.ffuserId + '" class="profileURL">' + item.ffuserId + '</a> <br>';
      html += '    ' + filterCityState( item.ffCity, item.ffState );
      html += '    <div class="seeFaceoffItemDetails"><a class="faceoffItemURL" href="' + item.ffUrl + '">See Costume &gt;</a></div>';
      html += '    <div class="votePercentage" style="width: ' + item.ffVotesPercent + 'px;">&nbsp;</div>';
      html += '    <div class="votePercentageTextDisplay">' + item.ffVotesPercent + '%</div>';
      html += '    <br clear="all">';
      html += '  </div>';
      html += '</div>';
      
      if( ( i + 1 ) % 3 == 0 )
      {
        html += '<br clear="all">';
      }
    }
    
    html += '<br clear="all">';
    
    document.getElementById( "faceoffAllResultsCategory" ).innerHTML = themes[ parseInt( themeId ) - 11 ];
    document.getElementById( "resultList" ).innerHTML = html;
    
    document.getElementById( "faceoffAllResults" ).style.display = "block";
  }
      
  
  function returnResults( passBack )
  { 
    results = evaluateJSON( passBack );        
    var leftItem,
        rightItem;

    // see if we first show the intermediate round card
    if( matchup == "1" ) redirectURL += "http://family.go.com/holidays/pkg-halloween-costume-face-off-round/?r=1&redirectURL=";
    else if( matchup == "9" ) redirectURL += "http://family.go.com/holidays/pkg-halloween-costume-face-off-round/?r=2&redirectURL=";
    else if( matchup == "13" ) redirectURL += "http://family.go.com/holidays/pkg-halloween-costume-face-off-round/?r=3&redirectURL=";
    else if( matchup == "15" ) redirectURL += "http://family.go.com/holidays/pkg-halloween-costume-face-off-round/?r=4&redirectURL=";;

    
    if( results.winner == "true" )
    {      
      redirectURL += "http://family.go.com/holidays/pkg-halloween-costume-face-off-results/?themeId=" + themeId + "&wid=" + results.ffContestEntryPair[ 0 ].ffid;      
    }
    else if( results.ffContestEntryPair.length == 2 )
    {
      leftItem = results.ffContestEntryPair[ 0 ];
      rightItem = results.ffContestEntryPair[ 1 ];
            
      redirectURL += "http://family.go.com/holidays/pkg-halloween-costume-face-off-vs/?themeId=" + themeId + "&m=" + matchup;

      // make sure there are no semicolons in this string since browser cookies are semicolon separated
      cookieVal = "f_" + leftItem.ffid +
                  "f_" + ( leftItem.ffTitle + "" ).split( "&quot;" ).join( "&quot" ) +
                  "f_" + leftItem.ffCity +
                  "f_" + leftItem.ffState +
                  "f_" + leftItem.ffuserId +
                  "f_" + ( leftItem.ffImageURLLarge + "" ).replace( "http://family.go.com/images/upload/contest/halloween-costume/", "" ) +
                  "_i2_" +
                  "f_" + rightItem.ffid +
                  "f_" + ( rightItem.ffTitle + "" ).split( "&quot;" ).join( "&quot" ) +
                  "f_" + rightItem.ffCity +
                  "f_" + rightItem.ffState +
                  "f_" + rightItem.ffuserId +
                  "f_" + ( rightItem.ffImageURLLarge + "" ).replace( "http://family.go.com/images/upload/contest/halloween-costume/", "" );
      
      setFamilyCookie( "faceOff", cookieVal, null, "/" );
    }

    window.location.href = redirectURL;
  }
  
  
  function initFaceoffUI()
  {
    matchup = getQuerystringValue( "m" );
    
    var vsItems;

    if( matchup != "" )
    {
      vsFields = getFamilyCookie( "faceOff" )
      vsItems = vsFields.split( "_i2_" );
      vsFields = [ vsItems[ 0 ].split( "f_" ), vsItems[ 1 ].split( "f_" ) ];
      
      vsFields[ 0 ][ 2 ] = filterTitle( vsFields[ 0 ][ 2 ] );
      vsFields[ 1 ][ 2 ] = filterTitle( vsFields[ 1 ][ 2 ] );

      matchup = parseInt( matchup );
      
      if( matchup > 14 ) { roundText = "Final<br>Round"; }
      else if( matchup > 12 ) { roundText = "Round 3"; }
      else if( matchup > 8 ) { roundText = "Round 2"; }
      else { roundText = "Round 1"; }

      matchup++;
    }
    else
    {
      window.location.href = "http://family.go.com/holidays/pkg-halloween-costume-face-off/";
    }
  }


  function redirectToMatchup( round )
  {
    var redirectURL = window.location.href;
    
    window.location.href = redirectURL.replace( "http://family.go.com/holidays/pkg-halloween-costume-face-off-round/?r=" + round + "&redirectURL=", "" );
  }

  
  // utility
  function getQuerystringValue( name )
  { 
    var value;

    try { value = unescape( location.search.match( new RegExp( name + "=+([^&]*)" ) )[ 1 ] ); } 
    catch( e ) { value = ""; } 

    return value;
  }
  
  
  function checkForCookies()
  {
    setFamilyCookie( "cookiesEnabled", "true", null, "/" );
    
    if( getFamilyCookie( "cookiesEnabled" ) != "true" ) { window.location.href= "http://family.go.com/holidays/pkg-halloween-costume-face-off-error/"; }
  }
  