var currentResult = 0;
var imageDivWidth = 381;
var isSliding = false;
var tickedResults = 0;

var traderLoadedIndex = 2;

function startLoadingTraders()
{
   if(traders[0])
   {
      loadTrader(traders[traderLoadedIndex], false);
   }
   /*for(var i=traderLoadedIndex; i<traders.length; i++)
    {
       loadTrader(traders[i], false);
    }*/
}

function loadNextTrader()
{
   if(traderLoadedIndex <= traders.length)
   {
      traderLoadedIndex++;
      loadTrader(traders[traderLoadedIndex], false);
   }
}

function initHomepage()
{
   $('#home #i-need-a-input').keyup(function()
      {
         filterCategoriesList($(this).attr('value'));
      });
}
function init()
{
   $('#im-a-trader-button').livequery('click', function()
      {
         if($(this).is('.open'))
         {
            $('#im-a-trader-div').fadeOut("fast");
            $('#example-profile-banner').fadeOut("fast");
            //$('#front-example-profile').fadeIn("fast");
            $('#front-example-profile').css('visibility', 'visible');
            $(this).removeClass('open');
         }
         else
         {
            $('#login-form').hide();
            $('#example-profile-banner').fadeIn("fast");
            $('#im-a-trader-div').fadeIn("fast");
            //$('#front-example-profile').fadeOut("fast");
            $('#front-example-profile').css('visibility', 'hidden');
            $(this).addClass('open');
         }
      });


   $('#link-tell-a-friend a').livequery('click', function() {
         if($('#link-tell-a-friend a').is('.open'))
         {
            $('#tell-a-friend-div').fadeOut("fast");
            $('#link-tell-a-friend a').removeClass('open');
         }
         else
         {
            $('#tell-a-friend-div').fadeIn("fast");
            $('#link-tell-a-friend a').addClass('open');
         }
      });

   $('#tell-a-friend-div #submit-button').livequery('click', function()
      {
         $.post('api/wedoo.php?action=tellAFriend', {
               name:$('#tell-your-name').val(),
               email:$('#tell-your-email').val(),
               friendName:$('#tell-friends-name').val(),
               friendEmail:$('#tell-friends-email').val(),
               message:$('#tell-message').val()
            },
            function()
            {
               $('#tell-a-friend-div').fadeOut("fast");
               $('#link-tell-a-friend a').removeClass('open');
               alert("Your recommendation was sent. Thanks!");
            });
      });


   $('#tell-a-friend-div .cancel').livequery('click', function()
      {
            $('#tell-a-friend-div').fadeOut("fast");
            $('#link-tell-a-friend a').removeClass('open');
      });

/*   $('#tell-a-friend-div').livequery('click', function() {
         $('#tell-a-friend-div').fadeOut("fast");
         $('#link-tell-a-friend a').removeClass('open');
      });*/

//$('#tell-a-friend-div').show();

   $('#what-is-wedoo a').livequery('click', function() {
         showWhatIsWedoo(); 
      });

   $('#what-is-wedoo-div').livequery('click', function() {
         $('#what-is-wedoo-div').fadeOut("fast");
         $('#what-is-wedoo a').removeClass('open');
      });

   $('#im-a-trader-login').livequery('click', function()
      {
         $('#login-form').fadeIn("fast");
      });

   $('.coming-soon').livequery('click', function() {
         $('#coming-soon-div').fadeIn("fast");
         setTimeout('$(\'#coming-soon-div\').fadeOut("fast")', 2000);
      });

   $('#im-a-trader-character').livequery('click', function()
      {
         $('#im-a-trader-div').fadeOut("fast");
         $('#im-a-trader-button').removeClass('open');         
      });

   $('.result-link').livequery('click', function() {
         resultClick(this.id);
      });


   $('.result-link input').livequery('change', function() {
         if(this.checked)
         {
            if(tickedResults < 3)
            {
               tickedResults++;
            }
            else
            {
               this.checked = false;
               alert("You can only email up to three traders at the same time!");
            }
         }
         else
         {
            tickedResults--;
         }
      });

   $('.profile-pictures-right').livequery('click', function() {
         slidePictures(this, 1);
      });

   $('.profile-pictures-left').livequery('click', function() {
         slidePictures(this, -1);
      });

   $('.profile-pictures-left').livequery(function() {
         $(this).css('background-position', '-22px');
      });

   $('.pager a').livequery('click', function() {
         var pageNumber = ($(this).html());
         var totalResults = $('#total-results').html();

         $('.results').hide();
         $('#results-'+pageNumber).show();

         $('.pager a').each(function() { $(this).removeClass('current'); });
         $(this).addClass('current');

         var endRange;
         if (pageNumber * 8 > totalResults)
         {
            endRange = totalResults;
         }
         else
         {
            endRange = pageNumber * 8;
         }    
         $('#current-results-range').html(((pageNumber-1)*8)+1 + " &#8211; " + endRange); 

         scroll(0,0);
      });

   $('#send-to-selected').livequery('click', function() {
         document.forms[1].submit();
      });

   $('.click-reveal').livequery('click', function() {
         $(this).hide();
         $(this).parent().children('.click-revealed').show();
         $.post('../api/wedoo.php?action=recordClick', { traderid: $(this).parent().attr('traderid') });
      });

   initStarInputs();
}

function showWhatIsWedoo()
{
   if($('#what-is-wedoo a').is('.open'))
   {
      $('#what-is-wedoo-div').fadeOut("fast");
      $('#what-is-wedoo a').removeClass('open');
   }
   else
   {
      $('#what-is-wedoo-div').fadeIn("fast");
      $('#what-is-wedoo a').addClass('open');
   }
}

function initStarInputs()
{
   $('.star-input span.star').css('cursor', 'pointer');
   $('.star-input span.star').mouseover(function() {
         var num = $(this).attr('id').split('-');
         num = num[num.length - 1];
         setStarValue(num, $(this).parent().attr('id'));
         $(this).parent().attr('stars', num);
      });
   $('.star-input').mouseout(function() {
         setStarValue($(this).children('input').val(), $(this).attr('id'));
      });
   $('.star-input').livequery('click', function() {
         $(this).children('input').val($(this).attr('stars'));
      });

}

function setStarValue(num, objId)
{
   var count = 0;
   $('.star-input#'+objId+' span.star').each(function()
      {
         if(count < num) { $(this).addClass('active'); }
         else { $(this).removeClass('active'); }
         count++;
      });
}

function filterCategoriesList(input)
{
   var roomLeft = true;

   if(input && input.length > 0)
   {
      $('#suggestions li a').each(function()
         {
            if(strstr($(this).html().toLowerCase(), input.toLowerCase()) && roomLeft)
            {
               $(this).parent().show();
               console.log(($(this).parent().offset()["top"] + $(this).parent().outerHeight()) + " " + $(window).height());
               roomLeft = (($(this).parent().offset()["top"] + ($(this).parent().outerHeight()*2)) < $(window).height());
            }
            else
            {
               $(this).parent().hide();
            }
         });
   }
   else
   {
      $('#suggestions li').hide();
   }
}

function slidePictures(currentObject, direction)
{
   if(!isSliding)
   {
      // Change this to calculate on changing div... maybe
      var totalImages = $(currentObject).parent().children('.profile-picture-container').children('div').children('a').children('img').size();
      var currentLeft = parseInt($(currentObject).parent().children('.profile-picture-container').children('div').css('left'));
      var startImage = (((-1 * currentLeft) / imageDivWidth) * 3) + 1;

      var doSlide = false;

      switch(direction)
      {
      case 1:
         doSlide = (startImage + 3 <= totalImages);
         startImage += 3;
         break;
      case -1:
         doSlide = (startImage - 3 > 0);
         startImage -= 3;
         break;
      }

      if(startImage > 3)
      {
         $(currentObject).parent().children('.profile-pictures-left').css('background-position', '0');
      }
      else
      {
         $(currentObject).parent().children('.profile-pictures-left').css('background-position', '-22px');
      }

      if(startImage + 3 <= totalImages)
      {
         $(currentObject).parent().children('.profile-pictures-right').css('background-position', '0');
      }
      else
      {
         $(currentObject).parent().children('.profile-pictures-right').css('background-position', '-22px');
      }

      if(doSlide)    
      {
         isSliding = true;
         var newLeft = currentLeft - (direction * imageDivWidth);
         $(currentObject).parent().children('.profile-picture-container').children('div').animate( {left: newLeft}, "medium", "linear", function() { isSliding = false; });
      }
   }
}

function resultClick(resultId)
{
   resultId = resultId.split('-');
   resultId = resultId[resultId.length-1];
   /* if (!currentResult)
    {
       $('#result-instructions').hide();
    }
    else
    {
       $('#result-'+currentResult).hide();
       $('#result-link-'+currentResult).removeClass('current');
    }
    if($('#result-'+resultId).attr('id'))
    {
       // Trader is loaded
       $('#result-'+resultId).show();
       $('#result-link-'+resultId).addClass('current');
    }
    else
    {
       loadTrader(resultId);
    }*/

   if(!currentResult)
   {
      $('#result-instructions').hide();
   }

   $('#result-'+currentResult).hide();
   $('#result-link-'+currentResult).removeClass('current');

   loadTrader(resultId, true);
}

function loadTrader(id, show)
{
   if(!$('#result-'+id).attr('id'))
   {
      // Not loaded, so load first
      if(show) $('#result-loading').show();
      $.post('../api/wedoo.php?action=getProfile', {id:id},
         function(data)
         {
            $('#results-content').append(data);
            if(show) showTrader(id);
            else loadNextTrader();
         });
   }
   else
   {
      if(show) showTrader(id);
      else loadNextTrader();
   }
}

function showTrader(id)
{
   $('#result-loading').hide();

   $('#result-'+id).show();
   $('#result-link-'+id).addClass('current');

   currentResult = id;
}

function strstr( haystack, needle, bool ) {
   // http://kevin.vanzonneveld.net
   // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
   // *     example 1: strstr('Kevin van Zonneveld', 'van');
   // *     returns 1: 'van Zonneveld'
   // *     example 2: strstr('Kevin van Zonneveld', 'van', true);
   // *     returns 2: 'Kevin '

   var pos = 0;

   pos = haystack.indexOf( needle );
   if( pos == -1 ){
      return false;
   } else{
      if( bool ){
         return haystack.substr( 0, pos );
      } else{
         return haystack.slice( pos );
      }
   }
}

$(document).ready(function() {
      init();

      if($('body').is('.body-results'))
      {
         startLoadingTraders();
      }
   });


function openWindow(url, width, height)
{
   window.open(url, 'popup', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=0, scrollbars=0, width='+width+', height='+height);
}
