
/*--------------------------------------------
         =Call Out
--------------------------------------------*/
$(function () {
  function dropShadow(shadow,shade,offset,type){

    var color = [getStyle(shadow,"background-color"),getStyle(shadow,"color"),shade];
    var container = (type=="box") ? document.createElement("div") : document.createElement("span");
    var els = [container,shadow];
    var content = shadow.childNodes;

    switch(type){
     case "box":
      container.appendChild(shadow.cloneNode(true));
      for(x=0;content.length>x;x++){
       shadow.removeChild(shadow.childNodes[x]);
      }	
      for(x=0;els.length>x;x++){
       els[x].style.color = color[1];
       els[x].style.position = "relative";
       if(x==0){
        els[x].style.width = getStyle(shadow,"width");
        els[x].style.backgroundColor = color[0];
       } else {	
        els[x].style.margin = offset[0]+"px "+offset[1]+"px";
        els[x].style.backgroundColor = color[2];
       }
      }
      break;
     case "text":	
      for(x=0;content.length>x;x++){
       deep = (content[x].childNodes) ? true : false;
       container.appendChild(content[x].cloneNode(deep));
      }
      for(x=0;els.length>x;x++){
       els[x].style.position = (x==0) ? "absolute" : "relative";
       els[x].style.color = color[x+1];    
      }
      break;
    }

    for(x=0;els.length>x;x++){
     els[x].style.top = (x==0) ? (offset[0]*-1)+"px" : offset[0]+"px";
     els[x].style.left = (x==0) ? (offset[1]*-1)+"px" : offset[1]+"px";
    }
    shadow.appendChild(container);
    $(shadow).after("<span class='space'></span>");

    function getStyle(obj,style){
     if(obj.currentStyle){
      return obj.currentStyle[style];
     } else if(window.getComputedStyle) {
      return document.defaultView.getComputedStyle(obj,null).getPropertyValue(style);
     }	
    }
  }

  $("p.callout").each(function() {
    dropShadow(this,"#CCC",[4,4],"box");
  });

  $("p.callout-narrow").each(function() {
    dropShadow(this,"#CCC",[4,4],"box");
  });

});


/*--------------------------------------------
         =Login
--------------------------------------------*/
function adjustForLoggedin() {
  $('li.guest').hide();
  $('li.loggedin').show();
  $('li.loggedin .member-name').text($.cookie('member-name'));
  FB.ensureInit(function() {
    FB.Connect.get_status().waitUntilReady(function(status) {
      if(status == FB.ConnectState.connected) { 
        $('li.loggedin').addClass('facebook');
        $('#member_name_display').attr('title', 'To see which of you Facebook friends are on VibrantNation.com, click the "my VN" link to your right.');
      }
    });
  });

  $('li.loggedin .member-view').attr('href', $.cookie('member-uri'));
  //Handle any forms that require a login
  $('input[name="member_uri"]').val($.cookie('member-uri'));
  $('form:has(input[name="member_uri"])').each(function(){
    if($(this).data('pendingSubmit')) {
      $(this).submit();
    }
  });   
}

function showLoginBox(e, target) {
  var cursorX = e.pageX - 130;
  var cursorY = e.pageY;
  $('body').prepend('<div id="login"></div>');
  $("div#login").load($("a.login").attr("href") + '?target=' + target);
  document.getElementById('login').style.left = cursorX + "px";
  document.getElementById('login').style.top = cursorY + "px";
  return false;
}

function adjustForNotLoggedin() {
  $('li.guest').show();
  $('li.loggedin').hide();
  $('li.loggedin').removeClass('facebook');
  $('a.login').click(showLoginBox);
  $('input[name="member_uri"]').val('');

  $('form:has(input[name="member_uri"]) input[type="image"], form:has(input[name="member_uri"]) input[type="submit"]').click(function(e) {
    if($.cookie('member-uri') == null) {
      $(this).parents('form').data('pendingSubmit', true);
      return showLoginBox(e, $(this).parents('form').attr('action'));
    } else {
      $('input[name="member_uri"]').val($.cookie('member-uri'));
      return true;
    }
  });
}

function successfulLogin(data) {
  var data = $(data);
  $.cookie('member-uri', data.find('a.member-uri').attr('href'), {path: '/'});
  $.cookie('member-name', data.find('.member-name').text(), {path: '/'});
  $.cookie('member-first-last', data.find('.member-first-last').text(), {path: '/'});
  $.cookie('subscriptions', data.find('.member-subscriptions').text(), {path: '/'});
  adjustForLoggedin();
  $('#login').remove();
}

function loginViaFacebook() {
  $.post('/members/new/link_user_accounts', {}, facebookLoginResult);
}

function facebookLoginResult(data) { 
  if($(data).find('a.member-uri').length > 0) {
    successfulLogin(data);
  } else {
    $('#login form').replaceWith($(data).find('#contentColumn form'));
    $('#login form').submit(facebookLoginSubmit);
  } 
}

function facebookLoginSubmit() {
  var form = $('#login form');
  $.ajax({
    type: "POST",
    url: form.attr('action'),
    data: form.serialize(),
    success: facebookLoginResult,
    error: function() {
      $('#login').remove();
    }
  });
  return false;
}

function vnAdjustForSignInState(){
  if($.cookie('member-uri')) {
    adjustForLoggedin();
  } else {
    adjustForNotLoggedin();
  }
}

$(function(){
  vnAdjustForSignInState();

  $('.logout').click(function() {
    $.cookie('member-uri', null, {path: '/'});
    $.cookie('member-name', null, {path: '/'});
    $.cookie('member-first-last', null, {path: '/'});
    $.cookie('subscriptions', null, {path: '/'});
    FB.Connect.logout(function(){});
    $.cookie('_radiant_session', null, {path: '/'});
    adjustForNotLoggedin();
    return false;
  });
});


/*--------------------------------------------
         =Rotate Features
--------------------------------------------*/
$(function(){
  $('.feature-list').each(function() {
    var features = $(this).find('.feature-holder');
    var selected = Math.floor(Math.random()*features.length);
    features.each(function(i) {
      if(selected == i) {
        $(this).show();
      } else {
        $(this).hide();
      }
    });
  });
});


/*--------------------------------------------
         =Style Switch
--------------------------------------------*/
$(function(){
  function switchStyle(styleName) {
    $('link[@rel*=style][@title]').each(function() {
      this.disabled = true;
      if (this.getAttribute('title') == styleName) this.disabled = false;
    });
    $('.styleswitch').removeClass('active').filter('[rel='+ styleName +']').addClass('active');
    $.cookie('style', styleName, {path: '/'});
  }
      
  $('.styleswitch').click(function() {
    switchStyle(this.getAttribute("rel"));
    return false;
  });
  if($.cookie('style')) switchStyle($.cookie('style'));
});


/*--------------------------------------------
         =External Links
--------------------------------------------*/
$(function(){
  $('a[href^=http]').not('a[href^=http://openx.vibrantnation.com]').not('a[href^=http://www.vibrantnation.com]').not('a[href^=http://d27mdn6ve8d84q.cloudfront.net]').click(function() {
    window.open($(this).attr('href'));
    return false;
  });
});



/*--------------------------------------------
         =Pretty Date
--------------------------------------------*/
$(function(){
  $('.pretty-date').prettyDate('%m/%d/%Y, %I:%M%p');

});



/*--------------------------------------------
         =Talk Navigation
--------------------------------------------*/
$(function(){
  $('#talk_nav').hover(function() {
    $(this).addClass('hover');
  },function() {
    $(this).removeClass('hover');
  });
  
  $("#talk-dropdown").change(function() {      
    window.location = $("#talk-dropdown option:selected").attr("value");
  });
});


/*--------------------------------------------
         =Nested Replies
--------------------------------------------*/
$(function(){
  $('#reply_form, form.ugc-wide, form.UGC').submit(function(){
    $('input[type=image]', this).attr('disabled', 'disabled');
    return true;
  });

  $('#reply-link').click(function(e){
    $(this).hide();
    $('#reply_form').show('normal', function(){
      tinymce.EditorManager.get('reply_entry').focus();
    });
    return false;
  });
  if(/#reply-link/.test(window.location.hash)) {
    $('#reply-link').click();
  }
  
  $('a.comment-reply').click(function(e){
    $(this).hide();
    var textareaId = ('' + Math.random()).replace('0.', '');
    var form = $('<form action="/replies" method="post">' +
                 '  <fieldset>' +
                 '  <label for="reply_entry">your response</label>' +
                 '  <textarea id="' +  textareaId + '" name="body" cols="40" rows="5" style="width: 100%;"></textarea>' +
                 '  <input type="hidden" name="member_uri"/>' +
                 '  <input type="hidden" name="page_uri" value="' + window.location.pathname + '"/>' +
                 '  <input type="hidden" name="parent_id" value="' + $(this).parents('.post').attr('id').replace(/reply-/, '')+ '"/>' +
                 '  <input type="submit" id="submitQuery" value="" />  </fieldset>' +
                 '</form>');
    var featuredActions = $(this).parents('div.featuredActions');
    featuredActions.before(form);
    $('form', featuredActions.parent()).submit(function(){
      $('input[type=submit]', this).attr('disabled', 'disabled');
      return true;
    });
    BASE_TINYMCE_SETTINGS['oninit']='';
    BASE_TINYMCE_SETTINGS['mode']='exact';  
    BASE_TINYMCE_SETTINGS['auto_focus']=textareaId;  
    BASE_TINYMCE_SETTINGS['elements']=textareaId;
    BASE_TINYMCE_SETTINGS['setup']=function(editor){
      vnAdjustForSignInState();
    };
    tinyMCE.init(BASE_TINYMCE_SETTINGS);
    return false;
  });
});


/*--------------------------------------------
         =Follow Post
--------------------------------------------*/
function setFollowActive() {
  $("label[for=followPostCheckbox] span").html("following this post").addClass("active");
  $('#followPostCheckbox').val(['followed']);
}

$(function(){
$('form.subscribe').submit(function() {
  if($("input[name='followPost']").is(":checked") == true)
  {
     $.ajax({
       url: $(this).attr('action'),
       data: $(this).serialize(),
       type: 'POST',
       complete: function(xhr) {
         if(xhr.status == 201) {
           $.cookie('subscriptions', $.cookie('subscriptions') + xhr.getResponseHeader('Location') + ',', {path: '/'})
         }
       }
     });
     setFollowActive();
  }
  else
  {
     var subscriptionUri = $('form.subscribe').attr('action');
     $.ajax({
       url: $.cookie('subscriptions').match(new RegExp('('+subscriptionUri+'/[^,]+),'))[1],
       data: $(this).serialize(),
       type: 'DELETE',
       success: function() {
         $.cookie('subscriptions', $.cookie('subscriptions').replace(new RegExp(subscriptionUri+'/[^,]+,', 'g'), ''), {path: '/'})
       }
     });
     $("label[for=followPostCheckbox] span").html("follow this post").removeClass("active");
  }
  return false;
});

$("input[name='followPost']").click(function(e) {
  var form = $(this).parents('form');
  if($.cookie('member-uri') == null) {
    form.data('pendingSubmit', true);
    showLoginBox(e, form.attr('action'));
  } else {
    form.submit();
  }
});

});


/*--------------------------------------------
         =Facebook
--------------------------------------------*/
function facebookPublishFeedStory(formBundleId, templateData, callback) {
  FB.ensureInit(function() {
    FB.Connect.showFeedDialog(formBundleId, templateData, null, null, null, FB.RequireConnect.promptConnect, callback);
  });
}


/*--------------------------------------------
         =New Reply
--------------------------------------------*/
$(function () {  
  //poppycock promotion
  if(/35615-.+#replied/.test(window.location.href)) {
    window.location = '/promo/2009/12/03/poppycock-gourmet-popcorn-giveaway';
  }
  if(/#replied/.test(window.location.hash)) {
    FB.ensureInit(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
        if(status == FB.ConnectState.connected) {
          facebookPublishFeedStory(91333436127, {
            'href': window.location.pathname + window.location.hash.replace('replied', 'reply'),
            'post': $('.post-subject').text()
          }, function() {
            window.location.hash = window.location.hash.replace('replied', 'reply');      
          });
        } else {
          window.location.hash = window.location.hash.replace('replied', 'reply');
        }
      });
    });
    setFollowActive();
    $.get($.cookie('member-uri'), function(data){
      $.cookie('subscriptions', $(data).find('.member-subscriptions').text(), {path: '/'});
    });
  }
});


/*--------------------------------------------
         =Edit Message
--------------------------------------------*/
$(function(){
  function showEditMessageForm() {
    var contentDiv = $(this).parent().parent().find('.message-content')
    var messageForm = $('' +
    '<form action="" method="post" class="edit-message-form">' +
      '<fieldset>' +
        '<textarea name="body" cols="40" rows="5" style="width: 85%;" class="edit-message-textarea"></textarea>' +
        '<input name="_method" type="hidden" value="put" />' +
        '<input type="hidden" name="member_uri"/>' +
        '<input type="image" id="submitQuery" src="/images/submit_your_response_btn.jpg" />' +
      '</fieldset>' +
    '</form>');
    messageForm.find('textarea').text(contentDiv.html());
    messageForm.attr('action', $(this).attr('href'));
    messageForm.find('input[name=member_uri]').val($.cookie('member-uri'));
    contentDiv.replaceWith(messageForm); 
    tinyMCE.init({
	mode : "specific_textareas",
	editor_selector : "edit-message-textarea",
        theme : "advanced",
        convert_urls : false,
        theme_advanced_buttons1 : "bold,italic,separator,bullist,numlist,link,unlink,spellchecker",
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_toolbar_location : "bottom",
        theme_advanced_toolbar_align : "left",
        init_instance_callback : "correctHeight",
        plugins : "spellchecker",
        spellchecker_languages : "+English=en",
        spellchecker_rpc_url : "/spellcheck"
    });

    $(this).hide();
    return false;   
  }

  var now = new Date().deskew();
  $('a.authorLink').each(function(){
    if($(this).attr('title') == $.cookie('member-name')) {
      var message = $(this).parent().parent();
      var message_date = new Date(message.find('.pretty-date').attr('title').replace(/-/g,"/").replace(/[TZ]/g," "));
      var minutes_ago = Math.floor((now - message_date)/(60000));
      if(minutes_ago < 16) {
        var editMessageTimer = message.find('.edit-message-timer');
        editMessageTimer.text(15 - minutes_ago);
        message.find('.edit-message').show().click(showEditMessageForm);

        function decrementTimer(){
          var timeLeft = parseInt(editMessageTimer.text())-1;
          if(timeLeft > 0) {
            editMessageTimer.text(timeLeft);
          } else {
            editMessageTimer.parent().hide();
          }
          setTimeout(decrementTimer, 60000);
        }
        setTimeout(decrementTimer, 60000);
      }
    }
  });

  now = new Date();
  if(/our-blog-circle/.test(window.location.href)) {
    if($('.by-line a').text() == $.cookie('member-name')) {
      var message_date = new Date($('.posted-on').attr('title').replace(/-/g,"/").replace(/[TZ]/g," "));
      var minutes_ago = Math.floor((now - message_date)/(60000));
      if(minutes_ago < 16) {
        var editMessageTimer = $('.edit-page-timer');
        editMessageTimer.text(15 - minutes_ago);
        $('.edit-page').show();

        function decrementTimer(){
          var timeLeft = parseInt(editMessageTimer.text())-1;
          if(timeLeft > 0) {
            editMessageTimer.text(timeLeft);
          } else {
            editMessageTimer.parent().hide();
          }
          setTimeout(decrementTimer, 60000);
        }
        setTimeout(decrementTimer, 60000);
      }
    }  
  }
});


/*--------------------------------------------
         =Report Abuse
--------------------------------------------*/
$(function(){
  $('.featuredPost li.report a').click(function(){
    $(this).parents('div.featuredActions').find('form.report-form input[type="submit"]').click();
    return false;
  });

  $('.post li.report a').click(function(){
    var form = $('<form style="display:none" action="/abuse_reports" method="post">' +
                 '  <input type="hidden" name="member_uri"/>' +
                 '  <input type="hidden" name="message_id" value="' + $(this).parents('.post').attr('id').replace(/reply-/, '')+ '"/>' +
                 '  <input type="submit" id="submitQuery" value="" />' +
                 '</form>');
    $(this).after(form);
    vnAdjustForSignInState();
    $('input[type="submit"]', form).click();
    return false;
  });
});


/*--------------------------------------------
         =Love
--------------------------------------------*/
$(function(){
  function loveFormSubmit(){
    var message = $(this).parents('.featuredInformation, .postDetails, .editorial-featured-actions');
    $.ajax({
      url: $(this).attr('action'),
      data: $(this).serialize(),
      type: 'POST',
      success: function(){
        $('.love-message', message).show();
        var count = $('.love-count', message);
        $('.love-message', message).css('height', $('.love-message').css('height'));
        $('.love-message', message).animate( { fontSize:"50%" } , 500, function(){
          count.text(parseInt(count.text()) + 1);
          if(parseInt(count.text()) == 2) {
            $('.love-subject-verb').text('members love');
          }
        }).animate( { fontSize:"100%" } , 500 );
      }});
    return false;
  }
  $('form.love-form').submit(loveFormSubmit);
  $('.featuredPost li.love a, .editorial-featured-actions li.love a').click(function(){
    if($.cookie('member-uri')) {
      $(this).parents('div.featuredActions').find('form.love-form').submit();
    } else {
      $(this).parents('div.featuredActions').find('form.love-form input[type="submit"]').click();
    }
    return false;
  });

  $('.post li.love a').click(function(){
    var form = $('<form style="display:none" action="/loves" method="post">' +
                 '  <input type="hidden" name="member_uri"/>' +
                 '  <input type="hidden" name="message_id" value="' + $(this).parents('.post').attr('id').replace(/reply-/, '')+ '"/>' +
                 '  <input type="submit" id="submitQuery" value="" />' +
                 '</form>');
    $(this).after(form);
    vnAdjustForSignInState();
    form.submit(loveFormSubmit);
    if($.cookie('member-uri')) {
      form.submit();
    } else {
      $('input[type="submit"]', form).click();
    }
    return false;
  });
});



/*--------------------------------------------
         =Share
--------------------------------------------*/
$(function(){
  $('a.share-link').click(function(){
    var share = SHARETHIS.addEntry({
      url: 'http://' + window.location.host + $(this).attr('href')},
      {button:false});
    share.attachButton($(this)[0]);
    share.popup();
    return false; 
  });
});


/*--------------------------------------------
         =New Status
--------------------------------------------*/
$(function(){
  $('.featuredInformation .pretty-date, .postDetails .pretty-date').each(function(){
    var date = new Date($(this).attr('title').replace(/-/g,"/").replace(/[TZ]/g," "));
    var diff = (((new Date()).getTime() - date.getTime()) / 1000) + (date.getTimezoneOffset()*60);
    if(diff < 86400) {
      $(this).siblings('.new').show();
    }
  });
});


