/*
Drupal.behaviors.ami_get_login_nav = function (context) {
	$.getJSON(Drupal.settings.ajax_domain+'/radaronline_general_primary_menu_ajax?callback=?',
		function(data){
			if (data.output == 1) {
		        $('ul.primary-links').append('<li class="menu-4"><span class="gradient_ff0065_ffa800"><a href="/logout" title="Logout of your account">LOGOUT</a></span></li>');
		        $('ul.primary-links').append('<li class="menu-21 last"><span class="gradient_ff0065_ffa800"><a href="/user" title="">MY ACCOUNT</a></span></li>');         
		      } 
		      else {
		        $('ul.primary-links').append('<li class="menu-326"><span class="gradient_ff0065_ffa800"><a href="/user/login" title="">LOGIN</a></span></li>');
		        $('ul.primary-links').append('<li class="menu-544 last"><span class="gradient_ff0065_ffa800"><a href="/user/register" title="">REGISTER</a></span></li>'); 
		      }       
		      gradientText.set();
		}
	);
};
*/
Drupal.behaviors.ami_get_login_nav = function (context) {
  $user_uid = $.cookie('radaronline_uid');
  if ($user_uid && $user_uid > 0) {
	  $('ul.primary-links').append('<li class="menu-4"><span class="gradient_ff0065_ffa800"><a href="/logout" title="Logout of your account">LOGOUT</a></span></li>');
      $('ul.primary-links').append('<li class="menu-21 last"><span class="gradient_ff0065_ffa800"><a href="/user" title="">MY ACCOUNT</a></span></li>'); 
  }else{
	  $('ul.primary-links').append('<li class="menu-326"><span class="gradient_ff0065_ffa800"><a href="/user/login" title="">LOGIN</a></span></li>');
      $('ul.primary-links').append('<li class="menu-544 last"><span class="gradient_ff0065_ffa800"><a href="/user/register" title="">REGISTER</a></span></li>'); 
  }
  gradientText.set();
};

Drupal.behaviors.ami_other_sites_ticker = function (context) {
  $('.other-sites-ticker-mid .carousel').jCarouselLite({
	  btnNext: ".other-sites-ticker-mid .button-next",
	  btnPrev: ".other-sites-ticker-mid .button-prev",
	  visible:4,
	  circular: false,
	  scroll:1
  });
}

Drupal.behaviors.ami_ajax_comments = function(context) {  
  if (Drupal.settings.nid) {
    if ($('#comments').length == 0) {
      $('.bg_left_mid').append('<div id="comments"></div>');
    }

    $.getJSON(Drupal.settings.ajax_domain+'/radaronline_general_comment_form_ajax?callback=?', {
        nid: Drupal.settings.nid
      },
      function(data) {
        // There are some params that come back in our data object:
        //    status - Only set to TRUE if the user authenticated.
        //    output - The comment form HTML
        //    comment_ids - Comma sperated list of comment ids this user owns.
        // Handle the comment IDs for this current user. We need to "explode" the
        // data.comment_ids value from the comma delimiter. Each ID is used to
        // allow controller links on each comment the user owns. So, we split
        // the ids out and then iterate through them, targeting each comment and
        // adding edit and delete buttons as needed.
        $('.comment_bottom li').hide();
        if (data.comment_ids != '') {
          var cids = data.comment_ids;
          if (cids.length) {
            var cidsArray = cids.split(",");
            for(var i=0; i<cidsArray.length; i++){
              // Now, we are iterating through all of the comment ids that have
              // been returned for this user. Each comment id can be accessed in
              // the cidsArray[i] array. We want to make sure that the value is an
              // integer, then see if we can find it in the DOM. If we do, we
              // add some extra links (edit and delete) to the comment.
              if (data.administer_comments == 1) {
                $('#comment-' + cidsArray[i]).next().find('.comment_bottom .comment_report ul').append('<li class="comment-actions-show"><a href="/comment/delete/' + cidsArray[i] +'">delete</a></li>');
              }
            }
          }
        }

        // Handle only showing the edit links on comments the user is allowed
        // to edit. These IDs can be found in the comment_edit_ids obj.
        if (data.comment_edit_ids != '') {
          var edit_cids = data.comment_edit_ids;
          if (edit_cids.length) {
            var edit_cids_array = edit_cids.split(",");
            for(var i=0; i<edit_cids_array.length; i++){
              $('#comment-' + edit_cids_array[i]).next().find('.comment_bottom .comment_report ul').append('<li class="comment-actions-show"><a href="/comment/edit/' + edit_cids_array[i] +'">edit</a></li>');
            }
          }
        }

        // Check to see if there is output. If there is, then we need to write
        // the form to the page.        
        if (data.output) {
          // We want to show the comments title here since we hid it in the CSS
          $('#comments h2').show();
          // Now we want to grab the node id for the page we are on and then go
          // insert all of the control links (reply, report abuse) for each
          // comment here.
          var nid = Drupal.settings.nid;
          if (data.abuse_ids != '') {
            var abuseArray = data.abuse_ids.split(",");
          }
          $('#comments .comment_report ul').each(function() {
            // Here we reach backwars and grab the id from the <a> tag that sits
            // above each comment. This id looks like comment-[comment_id] where
            // [comment_id] is the id for the current comment.
            var commentIdReg = $(this).parent().parent().parent().prev().attr('id');
            var commentId = commentIdReg.split("-");
            $(this).append('<li class="comment-actions-show"><a href="/comment/reply/' + nid + '/' + commentId[1] +'">reply</a></li>');
            // Users can not report abuse on comments that they own or on comments
            // that they've already abused. These IDs are in the data.abuse_ids obj
            // and need to be checked here before we write the link to the page.
            if (data.abuse_ids != '') {
              if (data.abuse_ids.indexOf(commentId[1]) === -1) {
                $(this).append('<li class="comment-actions-show"><a href="/abuse/report/comment/' + commentId[1] +'">Report abuse</a></li>');
              }
            }
            else {
              $(this).append('<li class="comment-actions-show"><a href="/abuse/report/comment/' + commentId[1] +'">Report abuse</a></li>');
            }
          });

          // Now we want to append the comment form to the comments id so that
          // the user can add comments to the node we are on.
          $('#comments').append(data.output);
          // Lets do a change on the form action for the comment-form so we can
          // take more control of that form.
          //$('#comment-form').attr("action", "/radaronline_general/comments-ajax-post");
          $('#comment-form').submit(function() {
            // Steps that need to be taken when subitted:
            //    Call the .sjaxSubmit which will call the form action and
            //    submit the form to that URL. We have overridden that URL
            //    locally so we can control some settings on the submit.
            $(this).ajaxSubmit({
              data: {op: 'Save'},
              beforeSubmit: function(formData, jqForm, options) {
                var filename = '/sites/radaronline.com/themes/radaronline/images/ajax-loader.gif';
                $(jqForm).find('#edit-submit').before('<img src="' + filename + '" class="spinner"></div>');
                return true;
              },
              success: function(responseText, statusText, xhr, form) {                
                var commentField = $(form).find('.form-textarea');
                if (commentField.val() == '') {
                  var message = {
                    text: 'Comment field is required.',
                    isError: true
                  };
                }
                else if (commentField.val().length > 250) {
                  var message = {
                    text: 'Your comment is too long. Comments are limited to a maximum of characters.',
                    isError: true
                  };
                }
                else {
                  var message = {
                    text: 'Your comment has been received and is in preview mode.\n\
                      Please allow up to 15 minutes to see your comments during high traffic hours.',
                    isGood: true
                  };

                  if ($('#comments div.comment-outer-wrapper:first').length > 0) {
                    $('#comments div.comment-outer-wrapper:first').clone().prependTo('#comments').find('.blurb').empty().append('<p>' + commentField.val() + '</p>');
                  }
                  else {
                    var comment_html = '\n\
                      <div class="comment-outer-wrapper">\n\
                        <div class="comment comment-new">\n\
                          <div class="comment_wrapper_bl">\n\
                            <div class="comment_wrapper_br">\n\
                              <div class="comment_innerwrapper">\n\
                                <div class="comment_wrapper_tl">\n\
                                  <div class="comment_wrapper_tr">\n\
                                    <div class="blurb"><p>' + commentField.val() + '</p></div>\n\
                                  </div>\n\
                                </div>\n\
                              </div>\n\
                            </div>\n\
                          </div>\n\
                        </div>\n\
                        <div class="comment_bottom clearfix">\n\
                          <div class="comment_meta">\n\
                            <span class="comment_name"></span><br />\n\
                            <span class="comment_date"></span>\n\
                          </div>\n\
                          <div class="comment_report"></div>\n\
                        </div>\n\
                      </div>';

                    $('#comments').prepend(comment_html);
                  }
                  var newComment = $('#comments div.comment-outer-wrapper:first');
                  /*var userName = form.find('a[title="View user profile."]').clone();
                  if (userName.length) {
                    newComment.find('.comment_name').empty().append('by ').append(userName);
                  }
                  else {
                    newComment.find('.comment_name').empty().append('by Anonymous');
                  }*/
                  newComment.find('.comment_name').empty().append('<span class="comment-preview-text status">This comment is in preview mode. It will be published to the site shortly. Please check back in a few minutes.</span>');

                  // Format the date of the new comment
                  var d = new Date();
                  var dayNames = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
                  var dayOfTheWeek = dayNames[d.getDay()];
                  var curr_day = ("0" + d.getDate()).slice(-2);
                  var curr_month = ("0" + (d.getMonth() + 1)).slice(-2);
                  var curr_year = d.getFullYear();
                  var curr_hour = ("0" + d.getHours()).slice(-2);
                  var curr_min = d.getMinutes();
                  var ampm = (curr_hour >= 12) ? 'pm' : 'am';
                  if (curr_hour == 0) {
                    curr_hour = '12';
                  }
                  else if (curr_hour > 12) {
                    curr_hour = curr_hour - 12;
                  }
                  curr_hour = ("0" + curr_hour).slice(-2);
                  var dateString = dayOfTheWeek + ', ' + curr_month + '/' + curr_day + '/' + curr_year + ' - ' + curr_hour + ":" + curr_min + ampm;
                  newComment.find('.comment_date').empty().append('Posted ' + dateString); // e.g. Thu, 01/20/2011 - 3:51pm
                  commentField.val('');
                  newComment.find('.comment_report').empty().append('');
                }

                $(form).parent().find('div.messages').remove();
                var messages = $('<div class="messages status comment-preview-text">' + message.text + '</div>');
                if (message.isError) {
                  messages.addClass('error');
                }
                if (message.isGood) {
                  messages.addClass('status');
                }
                $(form).prepend(messages);

                // Remove the loading indicator
                $(form).find('img.spinner').remove();
              }
            });
            return false;
          });
        }
        else {
          var comment_sign_in = '<div id="comment_sign_in">\n\
            <div id="normal_sign_in">\n\
              <h2><a class="popups thickbox" title="Sign in" href="/user/login?destination=' + window.location.pathname.substr(1) + '">Sign in</a> to post a comment here.</h2>\n\
            </div>\n\
          </div>';
          $('div#comments').append(comment_sign_in);
        }
      }
    );
  }

  // Add some default messaging to the user when they are replying on a comment.
  if (window.location.pathname.substr(1, 13) == 'comment/reply') {
    var message = $('<div class="messages status">During high traffic hours it may take up to 15 minutes for your reply to be visible on the site. <br />Thank you for your patience.</div>');
    $('#comment-form').prepend(message);
  }
  // Add some default messaging to the user when they are editing a comment.
  if (window.location.pathname.substr(1, 12) == 'comment/edit') {
    var message = $('<div class="messages status">During high traffic hours it may take up to 15 minutes for your changes to be visible on the site. <br />Thank you for your patience.</div>');
    $('#comment-form .comment-form-prefix').prepend(message);
  }
}

