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

jQuery(document).ready(function()
{
  jQuery('#global_search_form, #find-a form, #searchBox form').submit(function() {
      jQuery('#global_search_dialog').dialog('open');
  });

  jQuery('#global_search_form li.button a').click(function()
  {
    jQuery(this).parents('form').submit();
    return false;
  });

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

  jQuery('.top .search input[title!=""], #searchBox ul li.field input[title!=""]').each(function()
  {
    var example = jQuery(this).attr('title');
    jQuery(this).example(example);
  });
  
    jQuery('.widget input').each(function()
    {
        if(jQuery(this).attr('type') != "submit") {
            var value = jQuery(this).val();
            jQuery(this).val('');
            jQuery(this).example(value);
        }
    });

  jQuery('#searchInputs input').each(function()
  {
    var v = jQuery(this).val();

    if( v == 'Venue Name' || v == 'Suburb')
    {
		jQuery(this).val('');
		jQuery(this).example(v);
	}
  });

  jQuery('.panes .pane input').each(function()
  {
    var v = jQuery(this).val();

    if( v == 'Restaurant Name' || v == 'Bar Name' || v == 'Hotel Name' || v == 'Suburb')
    {
		jQuery(this).val('');
		jQuery(this).example(v);
	}
  });
  
  jQuery('.widget form ul li a[href="#"], .left-col form ul li a[href="#"]:not("no-auto-submit"), .competition-enter-details form ul li.button a').live('click', function()
  {
    jQuery(this).parents('form').each(function()
    {
      jQuery(this).submit();
    });
    return false;
  });

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

  jQuery('.images .thumbnail img').each(function()
  {
    jQuery(this).click(function()
    {
      var id = jQuery(this).attr('id');
      id = id.split('thumbnail-');
      id = id[1];

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

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

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

  jQuery('select.state-change').change(function()
  {
    var parentForm = jQuery(this).parents('form');
    parentForm.attr('action', '');
    parentForm.attr('method', 'post');
    parentForm.submit();
  });

  jQuery('form a.go-button[href="#"]').click(function()
  {
    jQuery(this).parents('form').submit();
    return false;
  });

  //textarea limiting and character counting
  jQuery('form textarea.textCounter').each(function()
  {
    var name = jQuery(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 = jQuery(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];
      }
    }
    
    jQuery(this).after(counter);
    jQuery(this).limit(limit, '#'+spanID);
  });
  
  //datepicker
  /*
  jQuery('form input.datepicker').datepicker(
  {
    dateFormat: 'dd/mm/yy',
    numberOfMonths: 2
  });
  */
  
  jQuery('form.ajax').each(function()
  {
    var form = jQuery(this);
    jQuery(this).ajaxForm(
    {
      beforeSubmit: function()
      {
        if (jQuery.browser.msie && ie6)
        {
          jQuery('select').css('visibility', 'hidden');
        }
        
        jQuery('body').append('<div id="ajax-loading-dialog" title="Submitting form"><p>Please wait while we submit your form...</p></div>');
        var loadingDialog = jQuery('#ajax-loading-dialog');
        loadingDialog.dialog(
        {
          buttons: { },
          closeOnEscape: false,
          draggable: false,
          modal: true,
          resizable: false
        });
      },
      success: function(responseText, statusText)
      {
        jQuery('#ajax-loading-dialog').dialog('close'); //close loading message
        jQuery('#ajax-loading-dialog').remove();
        var callback = form.attr('name') + 'Callback';
        window[callback](form, responseText, statusText);
      }
    });
  });
    
  jQuery('div[class$="list-page"] div.list div.item').click(function()
  {
    var href = jQuery(this).find('.title a').attr('href');
    
    window.location = href;
  });
  
  jQuery('div[class$="list-page"] div.list div.item div.info a').click(function(e)
  {
    e.stopPropagation();
  });
  
  //Print Detail page
  jQuery('ul.actions li a.print').click(function(e)
  {
    var rel = jQuery(this).attr('rel');
    var href = jQuery(this).attr('href');
    if (rel != '')
    {
        var url = (href == '#') ? 'print.php?id='+rel : href;
        var printPage = window.open(url, printPage, 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=700,height=550,left = 50,top = 50', false);
    }
    e.preventDefault();
  });
  
  jQuery('.special-offer a').click(function()
  {
    var printPage = window.open(jQuery(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;
  });
  


  /* recommend a venue */
  jQuery('.widget #recommend-a-listing li a').click(function()
  {
    var form = jQuery(this).parents('form');
    var name = form.find('input[name="recommend[name]"]');
    if (jQuery(name).hasClass('example'))
    {
      name = '';
    }
    else
    {
      name = jQuery(name).val();
    }
    var location = form.find('input[name="recommend[location]"]');
    if (jQuery(location).hasClass('example'))
    {
      location = '';
    }
    else
    {
      location = jQuery(location).val();
    }
    var why = form.find('input[name="recommend[why]"]');
    if (jQuery(why).hasClass('example'))
    {
      why = '';
    }
    else
    {
      why = jQuery(why).val();
    }
    var reviewer = form.find('input[name="recommend[reviewer]"]');
    if (jQuery(reviewer).hasClass('example'))
    {
      reviewer = '';
    }
    else
    {
      reviewer = jQuery(reviewer).val();
    }
    
    var errorMessage = '';
    if (reviewer == '')
    {
      errorMessage = errorMessage + 'Please enter your name.<br />';
    }
    if (name == '')
    {
      errorMessage = errorMessage + 'Please enter the name of the venue.<br />';
    }
    if (why == '')
    {
      errorMessage = errorMessage + 'Please enter why you like the venue.<br />';
    }
    if (location == '')
    {
      errorMessage = errorMessage + 'Please enter the location of the venue.<br />';
    }

    
    if (errorMessage != '')
    {
      if (jQuery.browser.msie && ie6)
      {
        jQuery('select').css('visibility', 'hidden');
      }
      
      jQuery('body').append('<div id="error-dialog" title="Submitting form"><p>'+errorMessage+'</p></div>');
      var errorDialog = jQuery('#error-dialog');
      errorDialog.dialog(
      {
        buttons: { "OK": function() { jQuery(this).dialog("close"); } },
        draggable: false,
        modal: true,
        resizable: false,
        close: function(event, ui)
        {
          jQuery('select').css('visibility', 'visible');
          errorDialog.remove();
        }
      });
      
      return false;
    }
    else
    {
        jQuery(this).parents('form').each(function()
        {
            jQuery(this).submit();
        });

    }
    
//    var queryString = '';
//
//    queryString += 'subject=Suggest a venue&body=Hi,%0D%0AI think the following venue would be a great addition to FOOD WINE SLEEP:';
//    queryString += '%0D%0AVenue Name: '+name;
//    queryString += '%0D%0ALocation: '+location;
//    queryString += '%0D%0AWhy I like it: '+why;
//    queryString += '%0D%0AWebsite: ';
//
//    window.location = (jQuery(form).find('li a').attr('href')+'?'+queryString);
    
    return false;
  });

  
  jQuery('input.autocomplete').each(function()
  {
    var acTable = getACTable(jQuery(this).attr('class'));
    var field = jQuery(this).attr('name');
    
    var source = BASE+'/ajax/autocomplete.php?table='+acTable+'&field='+field;
    //alert(source);
    
    jQuery(this).autocomplete({
      'source': source,
      'minLength': 2
    });

  });
  
  
  
  setTimeout(function() {
    jQuery('form select[name="location"]').each(function()
    {
      if (!jQuery(this).hasClass('event-location'))
      {
        var categorySiblingVenue = jQuery(this).parents('form').find('select[name="venue_type"]');
        var categorySiblingCategory = jQuery(this).parents('form').find('select[name="category_id"]');
        
        if (categorySiblingVenue.length > 0 || categorySiblingCategory.length > 0)
        {
          jQuery(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 = jQuery(this).val();
            var pcid = getPCID(jQuery(categorySibling).attr('class'));
            
            jQuery(categorySibling).attr('disabled', true);
            
            if (jQuery(categorySibling).is(":visible"))
            {
              addOverlayLoadingMessage(categorySibling, 'Loading categories');
            }
            
            var url = BASE + '/ajax/categorieswithlistings.php?location='+location+'&pcid='+pcid;
            jQuery.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 = jQuery(categorySibling).children(':first');
                  var selectedChild = jQuery(categorySibling).children(':selected');
                  jQuery(categorySibling).children().remove();
                  jQuery(categorySibling).append(firstChild);
                  
                  jQuery(response.categories).each(function(index, element)
                  {
                    var id = element.id;
                    var title = element.title;
                    var option = jQuery("<option></option>");
                    option.val(id);
                    option.text(title);
                    if (element.classStr)
                    {
                      option.addClass(element.classStr);
                    }
                    
                    if (selectedChild.length)
                    {
                      if (id == jQuery(selectedChild).val())
                      {
                        option.selected(true);
                      }
                    }
                    
                    jQuery(categorySibling).append(option);
                    
                    jQuery(element.children).each(function(index, child)
                    {
                      var cid = child.id;
                      var ctitle = "&nbsp;&nbsp;"+child.title;
                      var coption = jQuery("<option></option>");
                      coption.val(cid);
                      coption.html(ctitle);
                      
                      if (child.classStr)
                      {
                        coption.addClass(child.classStr);
                      }
                      
                      if (selectedChild.length)
                      {
                        if (cid == jQuery(selectedChild).val())
                        {
                          coption.selected(true);
                        }
                      }
                      
                      jQuery(categorySibling).append(coption);
                    });
                  });
                }
              }
              else
              {
                alert('An error occured while retrieving the category list for this location.');
              }
              
              jQuery(categorySibling).attr('disabled', false);
              removeOverlayLoadingMessage(categorySibling);
            });
          });
        }
        
        if (jQuery(this).val() != '')
        {
          jQuery(this).trigger('change');
        }
      }
    });
  }, 100);
  
  
});

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

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

