$(document).ready(function(){
  layout();
  makepopups();
  forums();
  printpage();
  makeclickables();
  oneclick();
  tooltip();
  makeforms();
  modal();
  rating();
});

/* LAYOUT */
function layout() {
  if($('body#popup').length > 0) { self.focus(); }
  /* IF IE */
  if (jQuery.browser.msie) {
    /* IF IE6 */
    if(parseInt(jQuery.browser.version) == '6') {
      $('#ie6').addClass('js');    
      /* RESIZE */
      if ($('body').attr('id') == 'popup') { return; }
      window.onresize=function() {
        document.documentElement.offsetWidth <= 941
        ?  $('body').css({ width: '940px'})
        : $('body').css({ width: '95%'});
      }
    }
  }
  /* MOZ 1.0.2 (AOL) CLEARFIX */
  if ((jQuery.browser.mozilla) && (jQuery.browser.version == '1.0.2')) {
    $('*').each(function(){
      if(($(this).css('overflow') == 'hidden') && ($(this).attr('id') != 'nav')) {
        $(this).append('<br style="clear: both;" />');
      }
    });
  }
}

function textsize(s) {
  var opts = [['small-text','0.90em'],['medium-text','1.0em'],['large-text','1.15em']];
  $('#main, #contextual, #global').css({ fontSize: opts[s][1] });
  for(i=0;i<3;i++) {
    (s == i) ? $('#' + opts[i][0]).css({ textDecoration: 'none' }) : $('#' + opts[i][0]).css({ textDecoration: 'underline' });
  }
  set_cookie('rw_textsize', s, '', '/', '', '');
}

/* SHOW/HIDE */
function show_hide (v,id,tog,open,shut) {
  var p = tog.split('-');
  if (id == 'more-search' ) { $('#adv').attr({value: v}); }
  if(v==0) {
    $('#'+id).hide();
  } else {
    $('#'+id).fadeIn('slow', function() {
      if(!jQuery.support.cssFloat) {
        this.style.removeAttribute("filter");
      }
    });
  }
  $('#'+tog).html(v
  ? '<a href="#' + p[1] + '" class="no-nudge" onclick="show_hide(0,\'' + id + '\',\'' + tog + '\',\'' + open + '\',\'' + shut + '\');">' + shut + '</a>'
  : '<a href="" class="nudge-top" onclick="show_hide(1,\'' + id + '\',\'' + tog + '\',\'' + open + '\',\'' + shut + '\'); return false;">' + open + '</a>'
  );
}

function HTMLEncode(text) {
  text = text.replace(/&/,"&amp;"); text = text.replace(/</,"&lt;"); text = text.replace(/>/,"&gt;");
  return (text);
}

function forums(){
  $('#close-search').click(function(){ $('#inline-search').fadeOut('normal'); return false; });
  $('a#do-search').click(function(){ $('#inline-search').fadeIn('normal'); return false; });
}

function printpage(){
  $('.printpage').wrapInner('<a href="" onclick="window.print(); return false;"></a>');
}

function oneclick(){
  $('form.oneclick').submit(function(){
    $(this).children('input[type="submit"]').attr({
      disabled: 'disabled', value: 'Processing...'
    });
    var n = $(this).children('input[type="submit"]').attr('name');
    $(this).append('<input type="hidden" name="' + n + '" value="' + n + '" />');
  });
}

/* POPUPS */
function makepopups() {
  var defs = 'directories=no,resizable=yes,toolbar=no,menubar=no,location=no,scrollbars=yes';
  $('a.popup-link').click(function(event) {
    var u = $(this).attr('href');
    if(u.indexOf('#') > -1 ) {
      u = u.split('#');
      var a = '#' + u[1];
      u = u[0]; 
    }
    var r = $(this).attr('rel');
    if(!r){
      f = 'width=450,height=300,' + defs;
      popup($(this).attr('href'),'popup',f);
      return false;
    } else {
      r = $(this).attr('rel').split(' ');
      n = r[0];
      f = 'width=' + r[1] + ', height=' + r[2] + ',' + defs;
      if(r[0]=='rw_page'){
        var q = (u.indexOf('?') > -1) ? '&popup=1' : '?popup=1';
        u = u + q;
      }
      if(a) { u = u+a; }
      popup(u,n,f);
      return false;
    }
  });
  $('#exch-matrix-partial').click(function(event) {
    popup($(this).find('a').attr('href') + '?popup=1','matrix','width=700,height=550' + defs);
  });
  $('form#sug').submit(function(event) { popup('','sb','width=300,height=150' + defs); });
}

function popup(u,n,f) { var newwin = window.open(u,n,f); newwin.focus(); }

function set_cookie (name, value, expires, path, domain, secure) {
  document.cookie= name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

function get_cookie (name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else {
    begin += 2;
  }
  var end = document.cookie.indexOf(";", begin);
  if (end == -1) {
    end = dc.length;
  }
  return unescape(dc.substring(begin + prefix.length, end));
}

function delete_cookie(name, path, domain) {
  if (! get_cookie(name)) return;

  document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

/* SUGGESTION BOX */
function suggestion (v) { $('#feed').css({ height: v ? '20px' : '60px' }); }

function clearit (id) { document['sug'].reset(); $('#confirm').text('Your message has been sent. Thank you.'); }

/* TARGET PARENT CLOSE SELF */
function tpcs(href) { window.opener.location = href; self.close(); }

function makeclickables(){
  $('a.sign + .box').each(function() {
    if($(this).prev('a').attr('href') != undefined) {
      clickable($(this),$(this).prev('a').attr('href'),$(this).prev('a').attr('title'));
    }
  });
  $('table.postings tr').each(function(){
    if(undefined != $(this).find('a.view-lnk').attr('href')) {
      var t;
      $(this).children('td').children('span.tooltip').length > 0 ? t = '' : t = $(this).children('td').children('a.view-lnk').attr('title');
      clickable($(this),$(this).find('a.view-lnk').attr('href'),t);
    }
  });
  $('div.post-box').each(function(){
    if($(this).find('a.contact-owner').attr('href') != undefined) {
      clickable($(this),$(this).find('a.contact-owner').attr('href'),$(this).find('a.contact-owner').attr('title'));
    }
  });
  $('div.sixty.float_left p').each(function() {
    if($(this).children('a').attr('href') != undefined) {
      clickable($(this),$(this).children('a').attr('href'),$(this).children('a').attr('title'));
    }
  });
  $('div.box.esc').each(function() {
    if($(this).children('p').children('a').attr('href') != undefined) {
      clickable($(this),$(this).children('p').children('a').attr('href'),$(this).children('p').children('a').attr('title'));
    }
  });
  $('#main div.post-ads p').each(function(){
    if(undefined != $(this).prev('strong').prev('a').attr('href')) {
      clickable($(this),$(this).prev('strong').children('a.').attr('href'),$(this).prev('strong').prev('a').attr('title'));
    }
  });
  $('#featured p.entry').each(function(){
    if(undefined != $(this).children('a.entry-link').attr('href')) {
      clickable($(this),$(this).children('a.entry-link').attr('href'),$(this).children('a.entry-link').attr('title'));
    }
  });
  $('#exchange-inventory #resort-listings li.resort').each(function(){
    if(undefined != $(this).find('a').attr('href')) {
      clickable($(this),$(this).find('a').attr('href'),$(this).find('a').attr('title'));
    }
  });
  $('.featured-exchange').each(function(){
    if(undefined != $(this).find('a').attr('href')) {
      clickable($(this),$(this).find('a').attr('href'),$(this).find('a').attr('title'));
    }
  });
}

function clickable(e,h,t) {
  $(e)
  .mouseover(function(){
    window.status = t;
    $(this).addClass('clickable').attr({ title: t });
  })
  .mouseout(function(){
    window.status = '';
    $(this).removeClass('clickable');
  })
  .bind('click',function(){
    window.location = h;
  })
}

this.tooltip = function(){
  var x = 10;
  var y = 20;
  $('.tooltip').hover(function(e){
    this.t = $(this).text();
    this.d = this.title;
    this.title = '';
    $('body').append('<dl id="tooltip"><dt>'+ this.t +'</dt><dd>' + this.d + '</dd></dl>');
    $('#tooltip').css('top',(e.pageY - x) + 'px').css('left',(e.pageX + y) + 'px').fadeIn('slow');
  },
  function(){
    this.title = this.d;
    $('#tooltip').remove();
  });
  $('.tooltip').mousemove(function(e){
    $('#tooltip').css('top',(e.pageY - x) + 'px').css('left',(e.pageX + y) + 'px');
  });
};
function makeforms() {
  if(($('#mess').length > 0) && ($('#contact').length > 0)) {
    if($('#mess').text() != '') {
      $('#mess').focus();
      $('#mess').text('\r\r' + $('#mess').text());
      setSelRange(document.contact.mess, 0, 0)
    }
  }
  if($('input.checkall').length > 0 ) {
    var e = $('input.checkall').parents('table').find(':checkbox');
    $(e).click(function() {
      if($(this).attr('className') == 'checkall') {
        $(this).attr('checked') ? $(e).attr({ checked: 'checked' }) : $(e).attr({ checked: '' });
      } else {
        $('input.checkall').attr({ checked: '' });
      }
    });
  }
  $('input[name="do_refresh"]').click(function() {
    $(this).parents('form').find(':checkbox').attr({ checked: '' });
  });
  $('input[name="do_delete"]').click(function() {
    var e = $(this).parents('form').find('input:checked[type="checkbox"][@name^="delete"]');
    if($(e).length > 0) {
    var msg = "Are you sure you want to delete the message(s)?";
    return confirm(msg);
    } else {
      var msg ="No messages were selected for deletion.";
      alert(msg);
      return false;
    }
  });
}

function setSelRange(inputEl, selStart, selEnd) { 
 if (inputEl.setSelectionRange) { 
  inputEl.focus(); 
  inputEl.setSelectionRange(selStart, selEnd); 
 } else if (inputEl.createTextRange) { 
  var range = inputEl.createTextRange(); 
  range.collapse(true); 
  range.moveEnd('character', selEnd); 
  range.moveStart('character', selStart); 
  range.select(); 
 } 
}

var showModal = function(hash) {
  var err = '<div class="flash error">An error has occurred, please try your request again. <a href="/contact_us" title="Contact Customer Support">Contact us</a> if this error persists.<img src="/beacon?type=ajax&error=Modal+got+no+responsefrom+server+script" width="1" height="1" alt="" /></div>';
  $('#modal-content').ajaxStart(function(){
    var spin = '<img src="/images/elements/progress-spinner.gif" width="16" height="16" alt="Loading&#8230;" id="spinner" />';
    if($(this).html() == '') {
      $(this).html(spin);
    } else {
      if($('#spinner').length < 1 ) { $(this).prepend(spin); }
    }
  });
  var $t = $(hash.t);
  var $u = $t.attr('href');
  var $r = $t.attr('rel');
  if($r) {
    $r = $t.attr('rel').split(' ');
    $l = $u + ' #' + $r[0];
    $f = $r[1];
  } else {
    $l = $u;
  }
  $(hash.w).css('opacity',100).show();
  $('#modal-content').load($l).ajaxStop(function() {
    if($f){ $(window).trigger($f); }
    if(($t).hasClass('nojson')) { return true; }
    if ($(this).children('form').length > 0 ) {
      $('form :input:visible:enabled:first').focus();
      $(this).children('form').submit(function() {
        var $s = $(this).serialize();
        var $submit = $('input[type="submit"]').attr('name');
        $s += '&' + $submit + '=' + $submit;
        $.ajax({
          cache: false,
          data: $s,
          dataType: 'json',
          success: function(data) {
            if(data.json) {
              if(data.flash) {
                $('#spinner').remove();
                if(data.flash.classname != 'error') { $('#modal-content').html(''); }
                if($('div.flash').length < 1 ) { $('#modal-content').prepend('<div class="flash"></div>'); }
                $('div.flash').addClass(data.flash.classname).html(data.flash.message);
              }
              if(data.message) { $('#modal-content').append(data.message); }
              if(data.refresh) { window.location.reload(); }
            } else {
              $('#modal-content').html(err);
            }
          },
          type: 'POST',
          url: $(this).attr('action')
        });
        return false;
      });
    }
  }).ajaxError(function(event, request, setting) {
    $(this).html(request.responseText);
  });
}
function modal() {
  if(($('a.modal-link').length > 0) && $($('#dialog').length < 1)) {
    $('#content').after('<div class="jqmWindow" id="dialog"><h4 id="modal-head"><a href="" class="modal-close" title="Close this Window">Close</a></h4><div id="modal-content"></div><a href="#" id="modal-foot" class="modal-close">Close</a></div>');
    $('#dialog').jqm(
      {
        overlayClass: 'modal-dimmer',
        closeClass: 'modal-close',
        trigger: 'a.modal-link',
        toTop: true,
        onShow: showModal,
        onHide: function(h) {
          $(h.w).hide().children('#modal-content').html('');
          $(h.o).remove();
        }
      }
    );
  }
}

function rating(){
  $('select.star-rating').each(function(){
    var stars = '';
    var selected = $('option:selected').val() || '';
    $(this).before('<input type="hidden" name="rating" id="the-rating" value="' + selected +'" />').hide().children('option[value!=""]').each(function(){
      selected >= $(this).attr('value') ? c = 'star star_selected' : c = 'star';

      stars += '<a href="" id="star' + $(this).val() + '" class="' + c + '" title="' + $(this).text()  + '">' + $(this).val() + '</a>';
    }).end().remove();
    $('#the-rating').after(stars + '<span class="note">&nbsp;(click appropriate star to indicate rating)</span>');
  });
  var r = $('#the-rating');
  $('a.star').click(function(){
    $(r).val($(this).text());
    $('a.star:gt(' + ($("a.star").index(this)-1) + ')').removeClass('star_selected').triggerHandler('mouseout');
    return false;
  })
  .hover(
    function() {
      $('a.star:lt(' + ($("a.star").index(this)+1) + ')').addClass('star_hover');
      $(this).nextAll('a').removeClass('star_selected');
    },
    function() {
      $(this).prevAll('a.star').andSelf().removeClass('star_hover');
      $('#star' + $(r).val()).prevAll('a.star').andSelf().addClass('star_selected');
    }
  );
}

/* OVERLABEL Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net) */
(function($){
  $.fn.overlabel = function() {
    this.each(function() {
      var $label = $(this), $input = $('#' + $label.attr('for'));
      $label
      .addClass('overlabel-apply')
      .bind('click', function(event) {
        $input.focus();
      });
      $input
      .bind('focus blur', function(event) {
        $label.css('display', (event.type == 'blur' && !$input.val() ? '' : 'none'));
      }).trigger('blur');
    });
  };
})(jQuery);

