$(document).ready(function() {
      initProfileWizard();
      initEditFields();
      $('.admin-email-link').click(function() { openEmailWindow(); return false; });
      //initSortable();
      initSignup();
      initMainCategory();
   });

function openEmailWindow()
{
   window.open('/admin/email-popup.php', 'email-window', 'status=0, toolbar=0, location=0, menubar=0, directories=0, resizable=1, scrollbars=0, height=440, width=508');
}

function initSortable()
{
   $('#photo-edit-container').Sortable(
      {
         accept : 		'sortable',
         helperclass : 	'sorthelper',
         activeclass : 	'sortableactive',
         hoverclass : 	'sortablehover',
         opacity: 		0.8,
         /*fx:				200,*/
revert:			true,
floats:			true,
tolerance:		'pointer'
         }
      )
   }


   function initEditFields()
   {
      $('.delete').click(function() { return confirm ("Really delete this item?"); });
      $('.cancel').click(function() { window.location.reload(true); });

      $('.edit').click(function() {
            if($(this).is('.save'))
            {
               $('#profile-form').submit();
               $(this).attr('href', "javascript:document.forms[0].submit()");
            }
            else
            {
               $('.upload').click(function()
                  {
                     if(!($(this).is('.photo-upload')))
                     {
                        alert("You need to save any changes to your profile before uploading your logo");
                     }
                  });
               $(this).addClass('save');
               $(this).html('<strong>Save</strong>');
               $(this).parent().children('.cancel').css('display', 'block');
               var areaName = '#' + ($(this).attr("id").split('-')[0]);
               $(areaName + '-view').css('display', 'none');
               $(areaName + '-edit').css('display', 'block');

               $('#availability-save').css('display', 'none');
            }
         });

      $('#profile-edit-button').click(function() { editAvailability(); $('#best-time-edit').show(); $('.best-time').hide(); });

      $('.availability').css('cursor', 'pointer');
      $('.availability').click(function() { 
            editAvailability();
            $('#availability-save').css('display', 'block');
         });

      $('#upload-button').click(function() {
            $('#uploading').show();
         });

      $('.click-reveal').unbind('click');
      $('.click-reveal').click(function() {
            $(this).hide();
            $(this).parent().children('.click-revealed').show();
         });

      $('.recommendation-edit .change').livequery('click', function()
         {
            var id = $(this).attr('id').split('-');            
            id = id[id.length - 1];
            window.open('search-for-trader.php?recommendationid='+id, 'searchfortrader', 'status=1,location=0,toolbar=0,menubar=0,directories=0,resizable=0,scrollbars=0,width=450,height=326');
         });
   }

   function editAvailability()
   {
      $('.availability').css('display', 'none');
      //$('.availability').parent().children('p').html('Availability:');
      $('.availability').parent().children('p').css('width', 'auto');
      $('#availability-dropdown').css('display', 'block');
   }

   function initProfileWizard()
   {
      $('.profile-wizard-services input, #profile-wizard-invite input').each(function()
         {
            $(this).click(function()
               {
                  if($(this).is('.unclicked'))
                  {
                     this.value = '';
                     $(this).css('color', '#000');
                     $(this).removeClass('unclicked');
                  }
               });
            /* this.blur */
      });

}

var errorCount = 0;
var step = 0;

function initSignup()
{
   if(document.getElementById('initial-error-count'))
   {
      errorCount = document.getElementById('initial-error-count').value;
   }

   if( document.getElementById('step'))
   {
      step = document.getElementById('step').value;
   }

   $('#errors ul li').each(function() {
         if($(this).css('display') == 'list-item')
         {
            $(this).addClass('visible');
         }
      });

   $('.form input').each(function() { 
         $(this).change(function() {
               var fieldName = this.name;
               var input = this.value;

               if(this.type == 'text' || this.type == 'password')
               {
                  if(fieldName == "password" || fieldName == "password-confirm")
                  {
                     // Could create an array of errors via php inline instead and check that way -
                     // more robust and simpler?
                     if(document.forms[0].password.value != document.forms[0]["password-confirm"].value)
                     {
                        // Passwords don't match
                        if($('#error-li-password-match').css('display') == 'none')
                        {
                           $('#password-match').css('background-image', 'url(images/error.png)');
                           $('#error-li-password-match').css('display', 'list-item');
                        }
                     }
                     else
                     {
                        $('#password-match').css('background-image', 'none');
                        if($('#error-li-password-match').css('display') != 'none')
                        {
                           $('#error-li-password-match').css('display', 'none');
                           $('#error-li-payment-method').removeClass('visible');
                        }
                     }
                  }

                  $.post("signup-functions.php?action=ajaxvalidate",
                     { fieldname: fieldName, input: input, step: step },
                     function(data)
                     {
                        if(data == '1')
                        {
                           $('#'+fieldName).css('background-image', 'none');
                           $('#error-li-'+fieldName).css('display', 'none');
                           $('#error-li-'+fieldName).removeClass('visible');
                           // Is this right?
                        }
                        else
                        {  
                           $('#'+fieldName).css('background-image', 'url(images/error.png)');
                           $('#error-li-'+fieldName).css('display', 'list-item');
                           $('#error-li-'+fieldName).addClass('visible');
                        }
                        updateErrorCount();
                     });
               }
               else if (this.type == "checkbox" && this.name == "terms-and-conditions")
               {
                  if(this.checked)
                  {
                     if($('#error-li-terms-and-conditions').css('display') != 'none')
                     {
                        $('#terms-and-conditions').css('background-image', 'none');
                        $('#error-li-terms-and-conditions').css('display', 'none');
                        $('#error-li-terms-and-conditions').removeClass('visible');
                     }
                  }
                  else
                  {
                     if($('#error-li-terms-and-conditions').css('display') == 'none')
                     {
                        $('#terms-and-conditions').css('background-image', 'url(images/error.png)');
                        $('#error-li-terms-and-conditions').css('display', 'list-item');
                        $('#error-li-terms-and-conditions').addClass('visible');
                     }
                  }
               }

               updateErrorCount();
            });
      });
}

// Need to do better with error capturing

function updateErrorCount()
{
   var errorCount = $('#errors ul li.visible').length;
   if (errorCount > 0)
   {
      $('#errors').css('display', 'block');
   }
   else
   {
      $('#errors').css('display', 'none');
   }
}

function clearCategoryList()
{
   $('.split-category-list input[type=checkbox]').each(function()
      {
         this.checked = "";
      });
   $('.other-category-input').each(function()
      {
         this.value = "";
      });
}

function changeHearAbout(a)
{
   if(a == "Trader")
   {
      $('#another-trader').show();
      $('#hear-about-other').hide();

   }
   else if(a == "Other")
   {
      $('#hear-about-other').show();
      $('#another-trader').hide();
   }
   else
   {
      $('#hear-about-other').hide();
      $('#another-trader').hide();
   }
}

function recommendedTraderSelected(id, companyname, username, recommendationid)
{
   //alert(id + " " + companyname + " " + username + " " + recommendationid);
   $('#recommendation-'+recommendationid+'-p').html('<a href="http://www.Carwash-Valeting-Detailing.com/'+username+'" target="_blank">'+companyname+'</a>');
   $('#recommendation-'+recommendationid+'-name').val(companyname);
   $('#recommendation-'+recommendationid+'-url').val(username);
}

function initMainCategory()
{
   fillCategorySelectBox();
   $('.category-div input').livequery('change', function()
      {
         fillCategorySelectBox(this);
      });
   $('.main-category select').livequery('change', function()
      {
         $('#main-category-id-current').val($('.main-category select option:selected').val());
      });
}

function fillCategorySelectBox()
{
   $('.main-category select').empty();
   $('.main-category select').append('<option value="0">Click here to select your main category</option>'); 
   var count = 1;
   var selected = 0;
   $('.category-div input:checked').each(function() 
      { 
         $('.main-category select').append('<option value="'+$(this).val()+'">'+($(this).next('label').html())+'</option>'); 
         if($(this).val() == $('#main-category-id-current').val()) 
         {
            selected = count;
         }
         count++;
      });
   $('.main-category select')[0].selectedIndex = selected;
}
