$(function() {
  
  if($.browser.msie && $.browser.version == '6.0') {
    $('#content').before('<div>Sorry, ScholarlyMinds no longer supports the browser you are using. To view the site, please upgrade to a modern browser such as <a href="http://www.mozilla.com/firefox/">Firefox</a>.</div>').prev().addClass('warning');
    $('#content, #sidebar, #options').remove();
  }

  $.ajaxSetup({
    cache: false
  });
  $(".opaque").show().animate({
    opacity: 1
  });

  //  $('body.user.profile .panel > h2').css('cursor','pointer').click(function() {
  //    if(jQuery.browser.msie)
  //      $(this).next().toggle();
  //    else
  //      $(this).next().slideToggle('fast');
  //  });
  //  $('body.user.profile .panel > h2:lt(2)').click();

  $("a[href^=http]").attr('target','_blank');

  $('div.position .title a.more').toggle(function() {
    $(this).nextALL('.desc:first').slideDown();
    $(this).text('Read less');
  }, function() {
    $(this).nextALL('.desc:first').slideUp();
    $(this).text('Read more');
  });


  ///// sidebar behaviour //////
  

  $('#sidebar .addable + input, #sidebar .editable + input').each(function() {
    var input = this;
    var message = $(this).prev()[0];
    $(message).click(function() {
      $(message).hide();
      $(input).show().focus();
    });
  });

  $('.location, .interest','#sidebar').click(function() {
    $(this).remove()
    $('form','#sidebar').submit();
  }).addClass('removeable');

  $('#sidebar input[name=locations[]], input[name=job_location\\[name\\]], input[name=course_location\\[name\\]], input[name=funding_location\\[name\\]], input[name=event_location\\[name\\]]').each(function() {
    var input = this
    $(input).autocomplete({
      url: '/search/locations',
      adviceMessage: 'Start typing the name of a university, other academic institution, city of country.',
      submitOnEnter: true,
      onSelect: function(result) {        
        $(input).val(result.label);
        $(input.form).submit();
      }
    });
  });

  $('#sidebar input[name=interests[]], input[name=job_interest\\[name\\]], input[name=course_interest\\[name\\]], input[name=funding_interest\\[name\\]], input[name=event_interest\\[name\\]]').each(function() {
    var input = this
    $(input).autocomplete({
      url: '/search/interests',
      adviceMessage: 'Start typing the name of an academic interest',
      submitOnEnter: true,
      onSelect: function(result) {
        $(input).val(result.label);
        $(input.form).submit();
      }
    });
  });
  
  $('input[type=checkbox], select','#sidebar').change(function() {
    $(this.form).submit();
  });
  $('input[type=text]','#sidebar').focus(function() {
    if(!$(this).parent().find(':last').is('input[type=submit]'))
      $(this).parent().append('<input type="submit" value="Go" />');
  });  

  ///// locking and autocomplete /////

  $('input[name=institution] + input[name=department]').livequery(function() {
    var department = this;
    var institution = $(department).prev()[0];

    $(institution).lockable({
      value: function(result) {
        return result.label;
      },
      afterLock: function() {
        $(department).focus();
      },
      afterUnlock: function() {
        $(department).prevALL('.lockable').empty().hide();
        $(department).attr('disabled',false).val('').show();
      }
    }).autocomplete({
      url: '/search/institutions',
      adviceMessage: 'Start typing the name of a university or other academic institution',
      onSelect: function(result) {
        $(institution).trigger('lock',result);
      }
    });

    $(department).lockable({
      value: function(result) {
        return result.label;
      },
      afterLock: function() {
        $(department).nextALL(':input:first').focus();
      }
    }).autocomplete({
      url: '/search/departments',
      adviceMessage: 'Start typing the name of a faculty or department at this institution',
      cancelMessage: 'The faculty or department at this institution',
      extraParams: function() {
        return 'i='+$(institution).prevALL('.lockable').find('input:hidden').val()
      },
      cancelSearch: function() {
        return !$(institution).prevALL('.lockable').find('input:hidden').val()
      },
      onSelect: function(result) {
        $(department).trigger('lock',result);
      }
    });

  });


  ///// everything else /////

  $('select[name=order]').change(function() { 
    location.href = this.form.action + '&order=' + $(this).val();
  });

  $('a.modal.form').each(function() {
    var a = this;        
    $(a).click(function() {
      var div = $('<div></div>')[0];
      $(div).attr('title',a.title).load(a.href, function() {
        var form = $('form',div)[0];
        $(form).submit(function() { return false; });
        $(div).dialog({
          position: 'center',
          width: $(a).attr('modalwidth') || 600,
          height: $(a).attr('modalheight'),
          minHeight: 0,          
          buttons: {
            'Cancel': function() {
              $(this).dialog('close');
            },
            'Save': function() {              
              $.ajax({
                url: form.action,
                type: form.method || 'post',
                data: $(form).serialize(),
                success: function() {
                  location.reload();
                },
                error: function(data) {
                  $(div).html(data.responseText);
                }
              });
            }
          }
        });        
      });
      return false;
    });
  });

  $('a.modal.upload').each(function() {
    var a = this;
    $(a).click(function() {
      var div = $('<div></div>')[0];
      $(div).attr('title',a.title).load(a.href, function() {
        $(div).dialog({
          position: 'center',
          width: 600,
          minHeight: 0
        });
      });
      return false;
    });
  });


  $('[tip]').each(function() {
    $(this).simpletip($(this).attr('tip'),{
      showOn: 'focus',
      hideOn: 'blur',
      stem: {
        corner: 'leftTop',
        color: '#FFED9A'
      },
      hook: {
        target: 'rightMiddle'
      }
    });
  });

  $('[hint]').livequery(function() {
    var input = this;
    if ($(input).attr('hint') && ($.trim($(input).val()).length == 0 || $(input).val() == $(input).attr('hint'))) {
      $(input).addClass('hint');
      $(input).val($(input).attr('hint'));
      $(input).one('focus', function() {
        $(input).removeClass('hint');
        $(input).val('');
      });
      $(input.form).submit(function() {
        if ($(input).val() == $(input).attr('hint'))
          $(input).val('');
      });
    }
  });


  
  $('body.messages.compose input[name=recipients[]]').each(function() {
    var input = this;
    $(input).boxable({}).autocomplete({
      url: '/messages/recipients',
      adviceMessage: 'Start typing the name of a contact',
      selectFirst: true,
      onSelect: function(result) {
        $(input).trigger('box',result);
        $(input).val('');
      }
    });
  });

  $('a[href$=suggest]').each(function() {
    var a = this;    
    $(a).click(function() {
      var div = $('<div></div>')[0];
      $(div).attr('title','Refer to contacts').load(a.href, function() {
        $(div).dialog({
          position: 'center',
          width: 600,
          minHeight: 0,
          buttons: {
            'Cancel': function() {
              $(this).dialog('close');
            },
            'Send': function() {
              var form = $('form',div)[0];
              $.ajax({
                url: form.action,
                type: form.method || 'post',
                data: $(form).serialize(),
                success: function(data) {                  
                  $(div).dialog('close');
                }
              });
            }
          }
        });
      });
      return false;
    });
  });

  $('a[href$=apply]').each(function() {
    $(this).click(function() {
      var div = $('<div></div>')[0];
      $(div).attr('title','Apply').load(this.href, function() {
        $(div).dialog({
          position: 'center',
          width: 600,
          height: 500,
          buttons: {
            'Cancel': function() {
              $(this).dialog('close');
            },
            'Send': function() {
              var form = $('form',div)[0];
/*             $.ajax({
                url: form.action,
                type: form.method || 'post',
                data: $(form).serialize(),
                success: function(data) {                  
                  $(div).dialog('close');
                }
              })*/
              $(form).submit()
            }
          }
        })
      })
      return false
    })
  })

  $('form[action$=suggest] input[type=text][name=recipients[]]').livequery(function() {
    var input = this;

    $(input).boxable({}).autocomplete({
      url: '/messages/recipients',
      onSelect: function(result) {
        $(input).trigger('box',result);
        $(input).val('');
      }
    }).keydown(function(e) {
      if (e.which == 188)
        $(input).trigger('box',{
          label: input.value,
          value: input.value
        })
    }).keyup(function(e) {
      if (e.which == 188)
        $(input).val('').blur().focus();
    });

  });


  $('.datepicker').datepicker({
    dateFormat: $.datepicker.RFC_2822,
    duration: '',
    yearRange: '1920:2020',
    changeMonth: true,
    changeYear: true
  });

  $('a[href$=autotag]').click(function() {
    var a = this;
    $.getJSON(a.href + '?' +$(a).closest('form').find('textarea[name=description]').serialize(), function(results) {
      $.each(results,function() {        
        $('input[name=tags[]]').val(this).trigger('box', { label: this+'' }).val('');
      });
    });
    return false;
  });
  
  // Some JS & CSS fooling around to get nice, working layout with disabled JS
  // only to find out later that we actually require JS to be enabled :)
  $('span.new_tag').hide();
  $('a.new_tag').show();
  
  $('a.new_tag').click(function(event) {
    if ($('span#' + event.target.id + '_form').is(":visible"))
      $('span#' + event.target.id + '_form').hide();
    else
      $('span#' + event.target.id + '_form').show();
    return false;
  });

  function ajax_post_and_hide(form){
    $.post($(form).attr('action'), $(form).serialize(), function(data){
      $(form).parent().parent().children('span.tags').html(data);
   }, "text");
    $(form).children('input#new_tag_name').val('');    
    $(form).parent().hide();
  };

  //Unobtrusive way sending tags suggestion
  $('span.new_tag form').submit(function() {
    ajax_post_and_hide($(this));
    return false;
  });
  
  //$("#tabs").tabs();  //disabled because you don't see errors when you send form inside tab

  if ($('#random_item').length > 0) {
    get_random_item()
    window.setInterval(get_random_item, 5000);
  }
  $('a[href$=answer]').each(function() {
    $(this).click(function() {
      var div = $('<div id="feedback_dialog"></div>')[0];
      $(div).attr('title','Feedback').load(this.href, function() {
        $(div).dialog({
          position: 'center',
          resizable: 'false',
          width: 640,
          height: 480,
          buttons: {
            'Cancel': function() {
              $(this).dialog('close');
            },
            'Send': function() {
              var form = $('form',div)[0];
              $.ajax({
                url: form.action,
                type: form.method || 'post',
                data: $(form).serialize(),
                success: function(data) {
                  $(div).html(data);                  
                  //$(div).dialog('close');
                }
              })
//              $(form).submit()
            }
          }
        })
      })
      return false
    })
  })

  // search for users to change permissions
  $('input[name=users[]]').each(function() {
    var input = this
    $(input).autocomplete({
      url: '/search/users',
      adviceMessage: 'Start typing the name of a user or his email.',
      submitOnEnter: true,
      onSelect: function(result) {        
        $(input).val(result.label);
        $(input.form).submit();
        //alert('User id:'+result.id);
        $.get('/permissions/'+result.id+'/save',function(data){
          $('#permissions_form').html(data);
        },null,'text');
      }
    });
  });
});

function get_random_item() {
  $.get('search/random', function(data) {
    $('#random_item').html(data);
  })
}

/* Submits the put/delete form for marking an item as featured or not */
$(document).ready(function(){
  $('form.featured a').click(function(){
    $(this).closest('form').submit()
    return false
  })
})

/* Highlights the button in the top left corner when hovering over it */
$(document).ready(function() {
  $('#corner_area').mouseenter(function() {
    $('img', $(this).closest('div')).each(function() {
      old_url = $(this).attr('src').split('.')
      $(this).attr('src', old_url[0] + '_active.' + old_url[1])
    })
  })

  $('#corner_area').mouseleave(function() {
    $('img', $(this).closest('div')).each(function() {
      old_url = $(this).attr('src')
      $(this).attr('src', old_url.replace('_active', ''))
    })
  })
})

/* Submits the feedback message via ajax*/
$(document).ready(function(){
  var new_feedback_message = $('div.contact').html();
  $('form#new_feedback_message').live('submit',function(){
    if (recaptcha.create('recaptcha')){          // param - div id, you whan to create recaptcha fields
      return false;
    } else {
      $.post($(this).attr('action'), $(this).serialize(), function(data){
        if (data.status == "error") {
          alert(data.message);
        } else {
          //recaptcha.destroy();
          $('div.contact').html(new_feedback_message);
          reset_forms();
          alert(data.message);
        }
      }, "json");
    }
  return false
  })
})

$(document).ready(function() {
  $('form input[type=image].hover_animated, a.hover_animated img').mouseenter(function() {
    old_url = $(this).attr('src').split('.')
    $(this).attr('src', old_url[0] + '-hover.' + old_url[1])
  })
  $('form input[type=image].hover_animated, a.hover_animated img').mouseleave(function() {
    old_url = $(this).attr('src')
    $(this).attr('src', old_url.replace('-hover', ''))
  })
})

