var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

$(document).ready(function()
{
  $('#global_search_form li.button a').click(function()
  {
    //if example or empty, show some message/error about entering something to search for first...
    $(this).parents('form').submit();
    return false;
  });

  var keywordExample = $('#keyword').attr('title');
  //$('#keyword').val('');
  $('#keyword').example(keywordExample);

  $('.top .search input[title!=""]').each(function()
  {
    var example = $(this).attr('title');
    $(this).example(example);
  });
  
  $('.widget input').each(function()
  {
    var value = $(this).val();
    $(this).val('');
    $(this).example(value);
  });

  $('.widget form ul li a[href="#"], .main-content form ul li a[href="#"]:not("no-auto-submit"), .competition-enter-details form ul li a[href="#"]').live('click', function()
  {
    $(this).parents('form').each(function()
    {
      $(this).submit();
    });
    return false;
  });

  $('.widget form input').keyup(function(e)
  {
    if (e.keyCode == 13) //enter
      {
      $(this).parents('form').each(function()
      {
        $(this).submit();
      });
    }
  })

  $('.widget #recommend-a-listing li a').click(function()
  {
    var form = $(this).parents('form');
    var name = form.find('input[name="recommend[name]"]');
    if ($(name).hasClass('example'))
    {
      name = '';
    }
    else
    {
      name = $(name).val();
    }
    var location = form.find('input[name="recommend[location]"]');
    if ($(location).hasClass('example'))
    {
      location = '';
    }
    else
    {
      location = $(location).val();
    }
    
    var errorMessage = '';
    if (name == '')
    {
      errorMessage = errorMessage + 'Please enter the name of the listing.<br />';
    }
    if (location == '')
    {
      errorMessage = errorMessage + 'Please enter the location of the listing.<br />';
    }
    
    if (errorMessage != '')
    {
      if (jQuery.browser.msie && ie6)
      {
        $('select').css('visibility', 'hidden');
      }
      
      $('body').append('<div id="error-dialog" title="Submitting form"><p>'+errorMessage+'</p></div>');
      var errorDialog = $('#error-dialog');
      errorDialog.dialog(
      {
        buttons: { "OK": function() { $(this).dialog("close"); } },
        draggable: false,
        modal: true,
        resizable: false,
        close: function(event, ui)
        {
          $('select').css('visibility', 'visible');
          errorDialog.remove();
        }
      });
      
      return false;
    }
    
    var queryString = '';
    
    queryString += 'subject=Recommend a Venue, Supplier or Activity&body=We love discovering new event venues and suppliers just as much as you! If there is somewhere or someone that you have recently worked with that is not already featured in A LIST Guide please let us know about it by clicking here and putting the contact details or weblink in the email below.';
    queryString += '%0D%0AName: '+name;
    queryString += '%0D%0ALocation: '+location;
    queryString += '%0D%0ALink: ';
    
    window.location = ($(form).find('li a').attr('href')+'?'+queryString);
    
    return false;
  });
  
  $('.images .thumbnail img').each(function()
  {
    $(this).click(function()
    {
      var id = $(this).attr('id');
      id = id.split('thumbnail-');
      id = id[1];

      $('.images .large-images img').each(function()
      {
        var lid = $(this).attr('id');
        lid = lid.split('image-');
        lid = lid[1];
        if (id != lid)
          {
          $(this).hide();
        }
      });

      $('#image-'+id).show();

      $('.images .thumbnail.selected').removeClass('selected');
      $(this).parent().addClass('selected');
    });
  });
  $('.images .thumbnail img:first').trigger('click');

  $('select.state-change').change(function()
  {
    var parentForm = $(this).parents('form');
    parentForm.attr('action', '');
    parentForm.attr('method', 'post');
    parentForm.submit();
  });
  
  $('form a.go-button[href="#"]').click(function()
  {
    $(this).parents('form').submit();
    return false;
  });

  //textarea limiting and character counting
  $('form textarea.textCounter').each(function()
  {
    var name = $(this).attr('name');
    var spanID = 'textarea-counter-'+name;
    var counter = '<span><span class="characters-remaining" id="'+spanID+'"></span> characters remaining. <em>This includes spaces and line breaks</em>.</span>';
    
    var classes = $(this).attr('class');
    classes = classes.split(' ');
    for (i in classes)
    {
      var c = classes[i];
      if (c.match(/^tc-max-/i))
      {
        var limit = c.split('-');
        limit = limit[2];
      }
    }
    
    $(this).after(counter);
    $(this).limit(limit, '#'+spanID);
  });
  
  //datepicker
  $('form input.datepicker').datepicker(
  {
    dateFormat: 'dd/mm/yy',
    numberOfMonths: 2
  });
  
  $('form.ajax').each(function()
  {
    var form = $(this);
    $(this).ajaxForm(
    {
      beforeSubmit: function()
      {
        if (jQuery.browser.msie && ie6)
        {
          $('select').css('visibility', 'hidden');
        }
        
        $('body').append('<div id="ajax-loading-dialog" title="Submitting form"><p>Please wait while we submit your form...</p></div>');
        var loadingDialog = $('#ajax-loading-dialog');
        loadingDialog.dialog(
        {
          buttons: { },
          closeOnEscape: false,
          draggable: false,
          modal: true,
          resizable: false
        });
      },
      success: function(responseText, statusText)
      {
        $('#ajax-loading-dialog').dialog('close'); //close loading message
        $('#ajax-loading-dialog').remove();
        var callback = form.attr('name') + 'Callback';
        window[callback](form, responseText, statusText);
      }
    });
  });
    
  $('div[class$="list-page"] div.list div.item').click(function()
  {
    var href = $(this).find('.title a').attr('href');
    
    window.location = href;
  });
  
  $('div[class$="list-page"] div.list div.item div.info a').click(function(e)
  {
    e.stopPropagation();
  });
  
  //Print Detail page
  $('ul.actions li a.print[href="#"]').click(function()
  {
    var rel = $(this).attr('rel');
    if (rel != '')
    {
      var printPage = window.open('print.php?id='+rel, printPage, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=550,left = 50,top = 50', false);
    }
    return false;
  });
  
  $('.special-offer a').click(function()
  {
    var printPage = window.open($(this).attr('href'), printPage, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=550,left = 50,top = 50', false);
    return false;
  });
  
  setTimeout(function() {
    $('form select[name="location"]').each(function()
    {
      var categorySiblingVenue = $(this).parents('form').find('select[name="venue_type"]');
      var categorySiblingCategory = $(this).parents('form').find('select[name="category_id"]');
      
      if (categorySiblingVenue.length > 0 || categorySiblingCategory.length > 0)
      {
        $(this).change(function()
        {
          var categorySibling = null;
          if (categorySiblingVenue.length > 0)
          {
            categorySibling = categorySiblingVenue[0];
          }
          else if (categorySiblingCategory.length > 0)
          {
            categorySibling = categorySiblingCategory[0];
          }
          
          //fire off ajax with categorySibling as the target of any changes..!
          var location = $(this).val();
          var pcid = getPCID($(categorySibling).attr('class'));
          
          $(categorySibling).attr('disabled', true);
          
          if ($(categorySibling).is(":visible"))
          {
            addOverlayLoadingMessage(categorySibling, 'Loading categories');
          }
          
          var url = BASE + '/ajax/categorieswithlistings.php?location='+location+'&pcid='+pcid;
          $.getJSON(url, function(response, status)
          {
            if (response.success && !response.error)
            {
              if (response.categories.length > 0)
              {
                //clear out the current options in categorySibling, while keeping the first one
                var firstChild = $(categorySibling).children(':first');
                var selectedChild = $(categorySibling).children(':selected');
                $(categorySibling).children().remove();
                $(categorySibling).append(firstChild);
                
                $(response.categories).each(function(index, element)
                {
                  var id = element.id;
                  var title = element.title;
                  //TO DO: Create the option and append it to categorySibling
                  var option = $("<option></option>");
                  option.val(id);
                  option.text(title);
                  
                  if (selectedChild.length)
                  {
                    if (title == $(selectedChild).text())
                    {
                      option.selected(true);
                    }
                  }
                  
                  $(categorySibling).append(option);
                });
              }
            }
            else
            {
              alert('An error occured while retrieving the category list for this location.');
            }
            
            $(categorySibling).attr('disabled', false);
            removeOverlayLoadingMessage(categorySibling);
          });
        });
      }
      
      if ($(this).val() != '')
      {
        $(this).trigger('change');
      }
      
    });
  }, 100);
  
  $('input.autocomplete').each(function()
  {
    var acTable = getACTable($(this).attr('class'));
    var field = $(this).attr('name');
    
    var source = BASE+'/ajax/autocomplete.php?table='+acTable+'&field='+field;
    //alert(source);
    
    $(this).autocomplete({
      'source': source,
      'minLength': 2
    });

  });
  
});

function getPCID(classStr)
{
  classStr = classStr.split(' ');
  for (c in classStr)
  {
    c = classStr[c];
    var explode = c.split('-');
    if (explode[0] == 'pcid')
    {
      return explode[1];
    }
  }
  return false;
}

function getACTable(classStr)
{
  classStr = classStr.split(' ');
  for (c in classStr)
  {
    c = classStr[c];
    var explode = c.split('-');
    if (explode[0] == 'ac')
    {
      return explode[1];
    }
  }
  return false;
}

function addOverlayLoadingMessage(element, message)
{
  var position = $(element).position();
  var top = position.top;
  var left = position.left;
  var height = $(element).height();
  var width = $(element).width();
  
  var messageE = $('<div class="overlayLoadingMessage">'+message+'</div>');
  messageE.attr('element', $(element).attr('name'));
  
  messageE.css(
  {
    'display': 'none',
    'position': 'absolute',
    'top': (top-1)+'px',
    'left': (left-1)+'px',
    'height': (height-4)+'px',
    'width': (width-5)+'px',
    'border': '1px solid black',
    'background': 'white',
    'padding': '3px 2px 1px 2px',
    'color': '#666',
    'zIndex': '1000'
  });
  
  $('body').append(messageE);
  messageE.slideDown(200);
}

function removeOverlayLoadingMessage(element)
{
  $('.overlayLoadingMessage[element="'+$(element).attr('name')+'"]').slideUp(200, function() { $('#overlayLoadingMessage').remove(); });
}
