var rmxUsername = null;
function highlightIdeaBrief(ev){  // this.style.textDecoration = 'underline';
}

function browserString(default_string) {
  var B = Prototype.Browser;
  if (B.IE)           return "ie";
  if (B.Opera)        return "opera";
  if (B.Gecko)        return "safari";
  if (B.WebKit) {
    return (((navigator.userAgent.indexOf('Chrome') > -1) && "chrome") || "safari");
  }
  if (B.MobileSafari) return "mobilesafari";

  return default_string;
}
function revertIdeaBrief(ev){
  // this.style.textDecoration = 'none';
}

function toggleButton(cur,valueField,all) {
  $A(all).each(function(a){$(a+'Toggle').removeClassName('toggleOn');});
  $(cur+'Toggle').addClassName('toggleOn');
  $(valueField).value = cur;
}

var pre_login_step = null;
function fn_login_then_call(fn,msg) {
  return function() {
    if(!rmxUsername) {
      pre_login_step = fn;
      showLoginDialog(msg);
    } else {
      fn();
    }
  }.bind(this);
}

function goToUrl(url) {
  location.href = url;
}

function fn_login_then_goto(url,msg) {
  fn = goToUrl.curry(url);
  return fn_login_then_call(fn, msg);
}

function loggedIn(req) {
  if( req ) {
    if( pre_login_step ) {
      pre_login_step();
    }
    if(window.refresh_after_login) {
      window.location.reload();
    } else {
      cancelPopup(false);
      out = req.responseText.evalJSON();
      //set the username
      rmxUsername = out[0];
      //update the header
      var all = $('all');
      all.addClassName('auth');
      all.removeClassName('anon');
      $('session').replace(out[1]);
      $('message').hide();
    }
  }
}

function cancelPopup(leaveCurtain) {
  if(rmxPoppedUp) rmxPoppedUp.hide();
  var msg = rmxPoppedUp.down('#popupMessage');
  if(msg) msg.innerHTML='';
  rmxPoppedUp = null;
  if(!leaveCurtain) $('curtain').hide();
  if(window.after_cancel_fn) {
    window.after_cancel_fn();
    window.after_cancel_popup = null;
  }
}

function showLoginDialog(msg) {
  var offset=window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop;
  rmxPoppedUp = $('loginPopup');
  rmxPoppedUp.down('#popupMessage').innerHTML = msg ? msg : '';
  $('curtain').show();
  rmxPoppedUp.style.top = 40 + offset + 'px';
  rmxPoppedUp.show();
}

function rotateToggle(eid, bid, fid, force) {
  var args = {duration:0.15};
  var worker = null;
  if(force == 'open') {
    worker = function() {
      Effect.Appear(eid, args);
      $(bid).removeClassName('closed');
    };
  } else if (force == 'closed') {
    worker = function() {
      Effect.Fade(eid, args);
      $(bid).addClassName('closed');
    };
  } else {
    worker = function() {
      Effect.toggle(eid, 'appear', args);
      $(bid).toggleClassName('closed');
    };
  }
  setTimeout(worker, 100);
  if(fid) setTimeout(function(){$(fid).activate()}, 200);
}

function catchKey(ev, key, fn) {
  if(ev.keyCode==key) {
    if(fn) fn();
    ev.stop();
  }
}

function lightsOut(excepted) {
  $('curtain').show();
  $$(excepted).each(function(e){
    e.oldZ = e.style.zIndex;
    e.style.zIndex = 10000 + parseInt(e.old,10);
  });
}

function lightsOn(excepted) {
  $$(excepted).each(function(e){e.style.zIndex = e.oldZ;});
  $('curtain').hide();
}

displayErrors = function(response, targetEl) {
  targetEl = $(targetEl);
  if(response.responseText) response = response.responseText;
  if(response.isJSON()) {
    var errors = response.evalJSON();
    var listEl = new Element('div');
    errors.each(function(e) {
      var english_field = e[0].replace('_', ' ');
      if (e[0] == 'base') {
        listEl.appendChild(new Element('div').addClassName('formError').update(e[1])); // only display the msg
      } else {
        listEl.appendChild(new Element('div').addClassName('formError').update(english_field + " " + e[1])); // display it "as is"
      }
    });
    targetEl.update(listEl);
  } else {
    targetEl.update('An error occurred while processing your request.');
  }
  targetEl.show();
  new Effect.Highlight(targetEl);
}

function focusSearch(s) {
  s.style.backgroundColor='white';
  s.style.color="#29AAE2";
  if(s.value=='search') {
    s.value='';
  }
  s.focus();
}

function blurSearch(s,clicked) {
  if(!clicked && s.value=='') {
    s.style.color=s.style.backgroundColor=null;
    s.value='search';
    var ab = $('alternativeButton');
    if(ab) ab.focus();
  }
}

function showFeedForm() {
  $('addFeedButton').hide();
  $('addFeedFields').blindDown({duration:0.25});
}
function hideFeedForm() {
  $('addFeedFields').blindUp({duration:0.1,
                              afterFinish:Element.show.curry($('addFeedButton'))});
}
function loadFeed(id) {
  new Ajax.Request( "/load_feed/THEID".replace("THEID", id), {
    evalJSON:false,
    asynchronous:true,
    onSuccess:function(xhr) {
      $('feedItems'+id).update(xhr.responseText);
    }.bind(this)
  });
}
function deleteFeed(oid,fid) {
  new Ajax.Request
  ( "/delete_feed/THEID".replace("THEID", oid),
      {evalJSON:false,
       asynchronous:true,
       onSuccess:Element.fade.curry($('feed'+fid)) });
}
function prependNewFeed(resText) {
  new Insertion.Top('feedList', resText);
  $$('#feedList .noFeedsMessage').first().remove();
  hideFeedForm();
}

function toggleInviteReaderForm() {
  $('inviteReaderForm').toggle('blindDown');
}
function showInviteReaderForm() {
  var f = $('inviteReaderForm');
  if(!f.visible()) f.blindDown({duration:0.25});
}
function hideInviteReaderForm() {
  var f=$('inviteReaderForm');
  if(f.visible()) f.blindUp({duration:0.1});
}
function readerInvited(resText) {
  hideInviteReaderForm();
  $('invite_email').value='';
  $('invite_message').value='';
  var im = $('inviteMessage');
  im.innerHTML = 'invitation sent';
  im.show();
  setTimeout(Element.fade.curry('inviteMessage'), 3000);
}

function hoverOver(i)   {var img=i.getAttribute('over');   if(img) i.src=img;}
function hoverNormal(i) {var img=i.getAttribute('normal'); if(img) i.src=img;}
function hoverSelect(i) {var img=i.getAttribute('sel');    if(img) i.src=img;}
function instrumentHoverImages(parent) {
  var p = parent ? $(parent) : document;
  
  Selector.findChildElements(p, $A('IMG.hasOver')).each(function(i) {
    i.stopObserving('mouseover', hoverOver);   i.observe('mouseover', hoverOver.curry(i));
    i.stopObserving('mouseout',  hoverNormal); i.observe('mouseout',  hoverNormal.curry(i));
    i.stopObserving('click',     hoverSelect); i.observe('click',     hoverSelect.curry(i));
  });
}

document.EMPTY_SCRIBBLER = 'discover new ideas...';
function clearScribbler() {
  var ta = $$('#scribbler TEXTAREA,#scribbler INPUT').first();
  ta.value = '';
  resetScribblerIfEmpty(ta);
  new Ajax.Request('http://socialfact.com/search/forget');
}
var composingScribble = false;
function composeScribble() {
  composingScribble = true;
  var el =  $$('#scribbler TEXTAREA','#scribbler INPUT').first();
  if(el.value == document.EMPTY_SCRIBBLER) {
    el.value = '';
  }
  window.location.href = "http://socialfact.com/quick?question="+el.value;
}
function focusScribbler(ev) {
  var el = ev.element();
  if(el.value == document.EMPTY_SCRIBBLER) {
    el.value = '';
  }
  $('scribbler').addClassName('active');
  el.focus();
  if(el.value != '') document.scribbleCompleter.activate();
}
function blurScribbler(ev) {
  setTimeout(resetScribblerIfEmpty, 300);
}
function resetScribblerIfEmpty(ta) {
  if(composingScribble) {
    composingScribble = false;
    return;
  }
  var el = ta || $$('#scribbler TEXTAREA, #scribbler INPUT').first();
  if(el.value == '') {
    new Ajax.Request('http://socialfact.com/search/forget');
    $('scribbler').removeClassName('active');
    el.value = document.EMPTY_SCRIBBLER;
  }
}
function seeMore() {
  var qf = $('scribbleQuestion');
  document.location = 'http://socialfact.com/search/ideas?query=QQQ'.replace('QQQ', (qf ? qf.value : ''));
}

function incrementCount(el,incr) {
  var sum = 0;
  try {
    sum = parseInt(el.innerHTML,10);
    el.update((sum + incr)+"");
  } catch(e) {
  }
}
function subscribeIdea(elSpec,otherSpec,id,size)      {doSubscribe(elSpec,otherSpec,'http://socialfact.com/subscribe/idea/SUBJID',id,size);}
function subscribeGroup(elSpec,otherSpec,id,size)     {doSubscribe(elSpec,otherSpec,'http://socialfact.com/subscribe/theme/SUBJID',id,size);}
function subscribeQuestion(elSpec,otherSpec,id,size)  {doSubscribe(elSpec,otherSpec,'http://socialfact.com/subscribe/question/SUBJID',id,size);}
function subscribeUser(elSpec,otherSpec,id,size)      {doSubscribe(elSpec,otherSpec,'http://socialfact.com/subscribe/user/SUBJID',id,size);}
function unsubscribeIdea(elSpec,otherSpec,id,size)    {doSubscribe(elSpec,otherSpec,'http://socialfact.com/unsubscribe/idea/SUBJID',id,size);}
function unsubscribeGroup(elSpec,otherSpec,id,size)   {doSubscribe(elSpec,otherSpec,'http://socialfact.com/unsubscribe/theme/SUBJID',id,size);}
function unsubscribeQuestion(elSpec,otherSpec,id,size){doSubscribe(elSpec,otherSpec,'http://socialfact.com/unsubscribe/question/SUBJID',id,size);}
function unsubscribeUser(elSpec,otherSpec,id,size)    {doSubscribe(elSpec,otherSpec,'http://socialfact.com/unsubscribe/user/SUBJID',id,size);}
function doSubscribe(elSpec,otherSpec,url,id,size) {
  fn_login_then_call
  (function() {
    new Ajax.Request
     (url.replace('SUBJID', id), {
        method:'get',
        evalJSON:false,
        asynchronous:true,
        evalScripts:false,
        parameters:{size:size},
        onSuccess:function(req){
                    $$(elSpec).each(function(el){
            el.up().replace(req.responseText);
            el.removeAttribute('ajaxing');
          });
          setTimeout(function(){req.responseText.evalScripts();}, 100);
        }
      });
   }, "Sign in to track interesting ideas, authors and themes")();
}
function subClick(ev) {
  var el      = ev.element();
  var subd    = el.src.match(/following/);
  var small   = el.src.match(/small/);
  var sfun    = el.getAttribute('sfun');
  var sid     = el.getAttribute('sid');
  var sibid   = el.getAttribute('sibid');
  var elSpec  = '.'+(subd ? 'following' : 'follow')+'[sid='+sid+'][sfun='+sfun+']';
  var sibSpec = sibid ? '.'+(subd ? 'follow' : 'following')+'[sibid='+sibid+']' : '';
  if(!sfun) {
      } else {
    el.setAttribute('ajaxing','y');
    after_cancel_fn = setFollowButtonToOppositeStatus.curry(el);
    setFollowButtonToOppositeStatus(el);
    eval(sfun)(elSpec,sibSpec,sid,small);
  }
  ev.stop();
}
function setFollowButtonToOppositeStatus(img) {
  var following = img.src.match(/following/);
  var small     = img.src.match(/small/);
  var opposite  = (following ? 'follow' : 'following') + (small ? '_small' : '');
  img.src = '/images/'+opposite+'.png';
}
function setFollowButtonToNormalStatus(ev) {
  var img = ev.element();
  if(!img.getAttribute('ajaxing')) {
    var following = img.src.match(/following/);
    var small     = img.src.match(/small/);
    var status    = (following ? 'following' : 'follow') + (small ? '_small' : '');
    img.src = '/images/'+status+'.png';
  }
}
function setFollowButtonToOverStatus(ev) {
  var img       = ev.element();
  var following = img.src.match(/following/);
  var small     = img.src.match(/small/);
  var status    = (following ? 'following' : 'follow') + (small ? '_small' : '');
  img.src = '/images/'+status+'_over.png';
}
function saveInquiry() {
  $('saveInquiryForm').onsubmit();
}
function saveInquiryPrep() {
  $('saveInquiryQuestion').value = $F('inquirerQuestion');
}
function deleteInquiry(inquiryId) {
  new Ajax.Request( "http://socialfact.com/inquiry/THEID/delete".gsub('THEID', inquiryId), {
    onSuccess: function(res){$('inquiry'+inquiryId).up('LI').remove();},
    onFailure: handleInquiryFailure
  });
}
function clearInquiryErrors() {
  $('inquiryErrors').innerHTML = '';
}
function handleInquirySuccess(response) {
  clearInquiryErrors();
  new Insertion.Bottom('inquiryList', '<li>' + response + '</li>');
  $('inquirerQuestion').value = '';
  blurInquirer();
}

function handleInquirySuccess2(response) {
  clearInquiryErrors();
  new Insertion.Top('inquiryList', '<li>' + response + '</li>');
  $('inquiryList').scrollTo();
  $('questionText').value = '';
  $$('#inquiryList LI').first().highlight({endcolor:'#C4DDF5'});
}
function handleInquiryFailure(response) {
  clearInquiryErrors();
  displayErrors(response, 'inquiryErrors');
}
function clearAlternativeErrors() {
  $('alternativeErrors').innerHTML = '';
}
function handleAlternativeSuccess(response) {
  clearAlternativeErrors();
  if($$('#alternativeList LI').size() == 0) $('alternativeList').previous().show();
  new Insertion.Top('alternativeList', '<li>' + response + '</li>');
  $('alternativeText').value = '';
  $$('#alternativeList LI').first().highlight({endcolor:'#C4DDF5'});
  scrollTo($('alternativeList'));
}
function handleAlternativeFailure(response) {
  displayErrors(response, 'alternativeErrors');
}
function showPreds(el) {
  $(el).up('.listStats').next().toggle();
  $(el).up().toggleClassName('clicked');
}

function expandExplainerBar() {
  var bar = $('explainerBar');
  new Effect.BlindDown(bar.down('.content'), {afterFinish:
    function() { bar.addClassName('expanded'); }});
  pageTracker._trackPageview('/programmatic/explainerbar');
}
function collapseExplainerBar() {
  var bar = $('explainerBar');
  new Effect.BlindUp(bar.down('.content'), {afterFinish:
    function() { bar.removeClassName('expanded'); }}); 
}
function hideExplainerBar() {
  createCookie("NotANoob", "1", "365");
  $('explainerBarWrapper').hide();
}

var rmxPoppedUp = null;
document.observe('dom:loaded', function() {
  var c = $('curtain');
  if(c) c.observe('click', cancelPopup);

  var lefts = $$('.subnav .left');
  lefts.each(function(s) {
    s.observe('click', function(){
      lefts.each(function(l) {
        l.removeClassName('selected');
      });
      s.addClassName('selected')
    });
  });

  var s = $$('search INPUT').first();
  if(s) {
    var f = focusSearch.curry(s);
    s.observe('mouseover', f);
    s.observe('focus', f);
    s.observe('mouseout',  function() {
      blurSearch(s,this.clickedSearch);
    }.bind(this));
    s.observe('blur', function() {

      blurSearch(s,this.clickedSearch);
    }.bind(this));
    s.observe('click', function() {
      this.clickedSearch=true;
    }.bind(this));
  }

  instrumentHoverImages();

  $$('.hasHover').each(function(e) {
    var hi = e.down('.hoverInfo, .hoverInfoSpan'); if(hi) hi.style.visibility='hidden';
    e.observe('mouseover', function() {
      e.addClassName('hovered');
      var hi=this.select('.hoverInfo, .hoverInfoSpan').first();
      if(hi) {
        hi.style.visibility='visible';
        if(hi.hasClassName('hoverInfo')) e.addClassName('hoverShowBorder');
      }
      return true;
    });
    e.observe('mouseout',  function() {
      e.removeClassName('hovered');
      var hi=this.select('.hoverInfo, .hoverInfoSpan').first();
      if(hi) { hi.style.visibility='hidden'; e.removeClassName('hoverShowBorder'); }
      return true;
    });
  });

  document.onkeyup = function(ev) {
    if(ev == undefined) return; // IE7
    if((ev.keyCode && ev.keyCode===Event.KEY_ESC) ||
       (ev.which && ev.which===Event.KEY_ESC)) {
      var m = $('message');
      if(m.visible()) {
        m.hide();
        ev.stop();
      }
    }
  };
});


