// turn off in_line_editor highlighting
Ajax.InPlaceEditor.DefaultOptions.highlightColor = "#dae9f1";
Ajax.InPlaceEditor.DefaultOptions.highlightEndColor = "#F1EDE0";

var $j = jQuery.noConflict();

function displayNotice(notice, duration) {
    $("notice").update("<p>"+notice+"</span>");
    $("notice").show();
    new Effect.Fade("notice", {duration: 0.8, delay: (duration || 5)});
}

function showTagEdit() {
    $('currentTags').hide();
    $('editTags').show();
    $('peep_tag_list').focus();  
} 

function hideTagEdit() {
    $('currentTags').show();
    $('editTags').hide();
} 

function buildTagList(tag) {
    var selected_tags = [];
    $$('.selectedTag').each(function(tagElem) {
        //there will be at least a single space if the user happened to backspace out the fields,
        //which throws things off since it'll end joining further down and appending a comma if
        //they try to add tags again by clicking on them, so check that we don't have an empty one- rreumann
        if( tagElem.innerHTML.strip().length > 0 ) {
            selected_tags.push(tagElem.innerHTML);
        }
    });
    if (tag) {
        if (selected_tags.indexOf(tag) === -1) {
            selected_tags.push(tag);
        } else {
            selected_tags = selected_tags.without(tag);
        }
    }
    selected_tags = selected_tags.join(',');
    return selected_tags;
}

function selectTag(tagElem) {
    updateTagList($('peep_tag_list').value);
    Element.toggleClassName(tagElem, 'selectedTag');
    var selected_tags = buildTagList();
    $('peep_tag_list').value = selected_tags;
    $('peep_tag_list').focus();
}

function updateTagList(selected_tags) {   
    selected_tags = selected_tags.split(',');
    var tags = $H();
    $$('.tag').each(function(tag) { 
        tags.set(tag.innerHTML, tag);
        tag.removeClassName("selectedTag");
    });
    selected_tags.each(function(tagName) {
        tagName = tagName.strip();
        var tag = tags.get(tagName);
        if (tag) {
            tag.addClassName("selectedTag");
        } else {
            $('allTags').insert('<div class="tag selectedTag" onclick="selectTag(this);">'+tagName+'</div>');
        } 
    }); 
}

function toggleTag(tag, params) {
    var selected_tags = buildTagList(tag);
    // if a page number was added to the path, then remove it to start at
    // page 1
    var path = window.location.pathname.split('/');
    if (path.size() === 4) {
        path.pop();
    }
    path = path.join('/');
    redirect_to = window.location.protocol + "//" + window.location.host + path + "?selected_tags=" + selected_tags;
    if (params) {
	    redirect_to += '&' + params
    }
    window.location.href = redirect_to;
}

function toggleFeedback() {
    if ($('overlayWindow').style.left === "0px") {
        new Effect.Move('overlayWindow', {
            x: -432, y: 10,
            mode: 'absolute',
            transition: Effect.Transitions.linear, 
            duration: 0.75,
            afterFinish: function(){$('overlayScreen').hide();}
            });
    } else {
        new Effect.Move('overlayWindow', { 
            x: 0,  y: 10,
            mode: 'absolute',
            transition: Effect.Transitions.linear,
            duration: 0.75,
            beforeStart: function(){$('overlayScreen').show();}
        });
    }
}
  
jQuery(document).ready(function() {
    jQuery.fn.qtip.styles.peepcodeblue = {  
        padding: '4px 4px', 
        color:'#466578',
        background:'#c5d6df', 
        border: {
            color: '#c5d6df',
            width: 4,
            radius: 5
        },
        tip: true
    }
		jQuery('#show_twitter_list_dialog').click(function() {
			showTwitterListDialog();
			return false;
		});
		jQuery('.cancel-dialog').live('click', function() {
			jQuery('.simplemodal-close').trigger('click');
			return false;
		});
		jQuery('#export_twitter_list_link').live('click', function() {
			createTwitterList();
			return false;
		});
})

function checkImportStatus() {
	//get current_peep_count from cookie, set when peep index page loads
	var COOKIE_NAME = 'current_peep_count';
	current_peep_count = jQuery.cookie(COOKIE_NAME);
	jQuery.noConflict();
	jQuery.ajax({
	  url: '/peeps/import_status.xml',
	  dataType: "xml",
	  cache: false,
	  success: function(xml){
	  	jQuery(xml).find('import_status').each(function() {
				var status_desc = jQuery(this).attr('sync_status_desc');
				var status_id = jQuery(this).attr('sync_status_id');
				var total_peeps = parseInt(jQuery(this).attr('total_peeps'));
				var peep_sync_count = parseInt(jQuery(this).attr('peep_sync_count'));
				jQuery('div#import_status').html(status_desc);
				if (total_peeps > 15 && current_peep_count == 0) {
					location.reload(true);
				}
				if (handleImportStatus(status_id, status_desc, total_peeps)) {
					setTimeout('checkImportStatus()', 10000);
				}
			})
	  }
	});
}

function handleImportStatus(import_status, status_desc, total_peeps) {
	
	if (import_status == null ) {
	  jQuery('#import_status').css('display','none');
	  jQuery('#resync_link').css('display','inline');
	  return false;
  } else if (import_status == '6' ) {
	  displayNotice(status_desc,6);
	  jQuery('#import_status').css('display','none');
	  jQuery('#resync_link').css('display','none');
	  return false;
  } else if (import_status == '5' ) {
	  displayNotice("The import from Twitter failed. Twitter may be down. Please try again later.",6);
	  jQuery('#import_status').css('display','none');
	  jQuery('#resync_link').css('display','inline');
	  return false;
  } else if ( import_status == '4' ) {
	  displayNotice("Your Peeps have been imported from Twitter. You may want to reload to see fresh data.",6);
	  jQuery('#import_status').css('display','none');
	  jQuery('#resync_link').css('display','inline');
	  if(total_peeps) {
	    jQuery('div.peeplinks').html("You currently have<br><strong>" + total_peeps + "</strong> peeps imported.");
		  jQuery('div.peeplinks').css('display','block');
	  }
	  return false;
  } else if ( import_status == '7' ) {
	  jQuery('#import_status').css('display','none');
  	jQuery('#resync_link').css('display','none');
	  return false;
  } else {
	  jQuery('#import_status').css('display','inline');
	  jQuery('#resync_link').css('display','none');
	  return true;
  }
}

function setNoteObservers() {
	$$("#notes_body blockquote").each(function(note) {
    Event.observe(note, "mouseover", note.setStyle.bind(note, {backgroundColor: "#dae9f1"}));
    Event.observe(note, "mouseout", note.setStyle.bind(note, {backgroundColor: ""}));
  });
}

function hideAnnouncement(id) {
	var COOKIE_NAME = 'announce-' + id;
	jQuery.cookie(COOKIE_NAME, 'hide', { path: '/', expires: 14 });
	$('site_news').style.display = 'none';
}

function showAnnouncement(id) {
	var COOKIE_NAME = 'announce-' + id;
	return jQuery.cookie(COOKIE_NAME);
}

function remove_item(element) {
    $(element).up('.vcard_item').remove();
}

function mark_item_for_destroy(element) {
    $(element).next('.should_destroy').value = 1;
    $(element).up('.vcard_item').hide();
}

function showTwitterListDialog() {
	jQuery("#export_twitter_list").modal({
		opacity: 90,
		onOpen: function (dialog) {
			dialog.overlay.slideDown('slow', function () {
				dialog.data.hide();
				dialog.container.fadeIn('fast', function () {
					dialog.data.fadeIn();
				});
			});
		},
		onClose: function (dialog) {
			dialog.data.fadeOut('fast', function () {
				dialog.container.fadeOut('fast', function () {
					dialog.overlay.slideUp('slow', function () {
						jQuery.modal.close();
					});
				});
			});
		}
	});
}

function createTwitterList() {
	var filters = location.search;
	var listName = '&list_name='+jQuery('#list_name').val();
	var listPrivacyBox = jQuery('#list_privacy_private'), listPrivacy = '&list_privacy=';
	listPrivacy += (listPrivacyBox.length > 0 && listPrivacyBox[0].checked) ? 'private' : 'public';
	var overwriteListBox = jQuery('#overwrite_list'), overwriteList = '&overwrite_list=';
	overwriteList += (overwriteListBox.length > 0 && overwriteListBox[0].checked) ? 'true' : 'false';
	jQuery.get('/peeps/export_twitter_list'+filters+listName+overwriteList+listPrivacy, function(html) {
		jQuery('#export_twitter_list').replaceWith(html);
		if (jQuery('#overwrite_list').length > 0) { jQuery('#simplemodal-container').css('height', '330px'); }
		jQuery('#export_twitter_list').show();
	});
}