/* all our favorite JS */
/* mostly by jamiew */

/* firebug override */
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {};
}



// initialize DOM
$(document).ready(function() {  
  
  /* ajax indicators */
  $("#loading").ajaxStart(function(){
    $(this).show();
  }).ajaxStop(function(){
    $(this).hide();
  });
  
  /* tabbed interfaces */
  $('.tabs').tabs();
  
  
  /* hijax togglables */
  var topMargin = 10;
  $('a.togglable-link').each(function(){

    var target = '#'+$(this).attr('id').replace('-link', ''); // what said link is referring to
    $(target).hide(); // hide it unobtrusively

    // add a close button (w/ div for text-indent) -- append due to tab weirdness; use abs positioning to locate anyway
    $(target).append('<a class="close" href="javascript:void(0);" title="Close this window">&nbsp;</a>'); // FIXME; no text, use div wrappers w/ text-indent
    $(target).children('.close').click(function(){
      console.log("close button: hide!");
      $(this).parent().hide();
    }); 
    
    // toggle about when click'd
    $(this).click(function(event){ // when said link is clicked...
      console.log("link click!");
      // if(!$(target).is(':visible')) // reposition if it was hidden
      $(".togglable:visible").not($(target)).hide(); // hide other visible hides w/ animation
      $(target).css('top', event.pageY + topMargin).css('left', event.pageX - $(target).width()/2 /* center it */);
      $(target).slideToggle('fast'); // show this one (for reals)
      return false;
    });
    
  });
  
  /* hijax forms (e.g. share-this-email) */
  $('form.hijax').ajaxForm(); // generic, no callbacks etc.
  
  // catch some keys -- esc closes visible togglables
	$(window).keydown(function(event){
	  switch (event.keyCode) {
			// escape, in FF at least
			case 27: 
  			$('.togglable:visible').fadeOut('fast'); // with efx wordup
  			break;
	  }
	});
  
  // comment link
  $('a#comment_link').bind('click.comments', function(){ 
    openWindow($(this).attr('href'), 'Rocketboom Comments');
    // var href = $(this).attr('href');
    // $('#ajax-comments').show().load(href);
    return false;
  });

  // form niceness
  var empty_input_value = "name@example.com";
  $('input.email').focus(function(){
    $(this).attr('val_backup', $(this).val()).val('');
  }).blur(function(){
    // $(this).val(empty_input_value);
  });
  
  
});

function init_login_box(opts) {

  // console.log('init_login_box');
  
  // tabbify login/register/password reset
  // var opts = { fxFade: true, fxSpeed: 'fast' }
  var tabopts = { };
  $('#login_tabs').tabs(tabopts);

  
  // thickbox init
 	var link = $('#login-link');
  link.click(function(){
    // $('#tb-modal').css('left', $(window).width() - $('#tb-modal').width());
  });

  if(link.length > 0) {
    var left = $(window).width() - 300 - 20;
    var top = 60; // below flashing...
    // , animate: { opacity: 'show' }, speed: 1000} }
    link.thickbox( { top: ''+top, left: ''+left, height: 140, width: 300 } );  
  }

}

// helpers
function flash(msg, type, target, timeout) {
  
  // console.log("flashing: "+msg);
  type = type ? type : 'error';
  target = target ? target : '#flash';
  

  // just move it, don't bother checking (optimize?)
  if(target == '#flash')
    $('#flash').css('top', $(window).scrollTop());
  timeout = timeout ? timeout : 5000;
  var elem = $(target);
  elem.html(msg);
  elem.fadeIn('fast');
  elem.css('background-color', (type == 'info' ? '#9d9' : '#d99'));
  elem.css('border-color', (type == 'info' ? '#1b1' : '#b11'));
  setTimeout(function(){ elem.fadeOut('slow'); }, timeout);
}


// refresh
function refresh(location) // location is just a suggestion, really.
{ 
  // change to true? forget what that does.
  // window.location.reload( true );
  window.location.href = window.location.href; // clears POST data
}

// login_request handled by hijax'd form
function login(vars) { 
  $.thickbox.hide();  // could simulate click, too; modded thickbox to publicize this func
  $('#login-info').hide();
  $('#logout-info').slideToggle('fast');
  flash("Logged you in!", 'info');
  update_page(); // update story details, etc. w/ new voting links...
  $('#username-display').html(''+vars.split(',')[0]); // replace username display
  $('input[name=user_id]').val(vars.split(',')[1]); // replace any input fields w/ new user_id
  $('.anonymous_details').hide(); // hide anonymous details

  // refresh anything inside pligg-bridge (e.g. comments pages)
  // if(document.location.href.match(/pligg\-bridge/)) {
  //   console.log("login: matched pligg-bridge, REFRESHING");
  //   refresh();
  // }
}

function logout_request(url) {
  $("#flash").load(url, {}, logout);
  $('.anonymous_details').show();
}

function logout(url) {
  // main + for index page
  flash("Logged you out.", 'info');
  $('#logout-info').hide();
  $('#login-info').slideToggle('fast');
  update_page();  
  $('#username-display').html(''); // replace username display
  $('input[name=user_id]').val(''); // replace any input fields w/ new user_id  
  $('.anonymous_details').show();
  
  // see note above  
  // if(document.location.href.match(/pligg\-bridge/)) {
    // console.log("logout: matched pligg-bridge, REFRESHING");
    // refresh();
  // }
}

function update_page() {
  // $('#story-details').load(safe_location_all()+'&update_storydetails=1', {}, function() {  } );
  // $('#login-invite').load(safe_location_all()+'&update_logininvite=1;', {}, function() {  } );

}

// strip location
function safe_location() {
  var url = document.location.href;
  url = url.replace(/\?.*/,'');
  url = url.replace(/\#.*/,'');
  return url;
}

// returns current URI w/ a ?true=1 appended if there are no current 
function safe_location_all() {

    // cleanup, but pass day GET
    var day = '';
    if(gup('day').length > 0) {
      day = '?day='.gup('day');
    }
    else {
      day = '?filler=1';
    }
    
    return safe_location()+day;
}

// gives a value of a GET variable
function gup( name ) {
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}



/************ rb-specific ***********/

// RB comment window opener
function openWindow(url, title, width, height, opts) {
  title = title || 'Rocketboom Comments';
  width = width || 540;
  height = height || 580;
  opts = opts || 'scrollbars=yes,status=yes,resizable=yes';
  newwindow = window.open(url, title, 'width='+width+',height='+height+','+opts);
  if (window.focus) { newwindow.focus(); }  // focus the window please
}


/* formerly sendmailto.js */

function sendMailTo(name, company, domain) {
      locationstring = 'mai' + 'lto:' + name + '@' + 'rocketboom.com';
      window.location.replace(locationstring);
   }
