// setup config vars (tried adding them to top of template but vars from config class weren't working...)
var domain_collections = "http://snapza.com/collection";
var domain_base = "http://snapza.com";
var domain_items = "http://snapza.com/items";
var domain_login = "http://snapza.com/login";


// -------- PICTURE TAKING/UPLOAD RELATED FUNCTIONS ---------- //

function take_picture_nav(section){
	resetTakePictureControls();
	$('#take_picture_nav').find('a').removeClass('selected');
	switch(section){
		case 'webcam':
			$('#take_picture_nav').find('a.webcam').addClass('selected');
			$('#left_take_picture').show();
			$('#left_upload_picture').hide();
			$('#right_take_picture').show();
			$('#email_picture').hide();
			break;
		case 'upload':
			$('#take_picture_nav').find('a.upload').addClass('selected');
			$('#left_upload_picture').show();
			$('#right_take_picture').show();
			$('#left_take_picture').hide();
			$('#email_picture').hide();
			break;
		case 'email':
			$('#take_picture_nav').find('a.email').addClass('selected');
			$('#left_upload_picture').hide();
			$('#left_take_picture').hide();
			$('#right_take_picture').hide();
			$('#email_picture').show();
			break;
	}
}

// ------ JPEGCAM ------- //

var image_filename; 

function my_load_handler() {
	webcam.set_hook( 'onComplete', 'my_completion_handler' );
	if (is_new_user()) {
    	webcam.configure( 'privacy' );
	}
}

function delay_take_snapshot(second) {
	if (second == 0) {
		take_snapshot();
		$('#delay_button').val('3 second delay');
		return;
	}
	$('#delay_button').val(second);
	var second = second - 1;
	setTimeout(function(){delay_take_snapshot(second);},1000);
}


function take_snapshot() {
	// take snapshot and upload to server
	webcam.freeze();
	showConfirmation();
	//webcam.snap();
}

function showConfirmation(){
	$('#picture_controls').hide();
	$('#picture_confirmation').show();
	$('#confirm_message').show();
//	$('#right_take_picture').show();
}

function takeNewPicture(){
	resetTakePictureControls();
	webcam.reset();
}

function resetTakePictureControls(){
	$('#picture_controls').show();
	$('#picture_confirmation').hide();
	$('#confirm_message').hide();
}

function postPic(){
	$('#loading_message').css('display','inherit');
	var message = $('#message').val();
	if($('#twitter_autopost:checked').val() != null){
		var twitter_autopost = 1;
	}else{
		var twitter_autopost = 0;
	}
	

	var reply_to = $('input#reply_to').val()

	message = escape(message);
	
	webcam.set_api_url( '/items/additem?reply_to='+reply_to+'&twitter_autopost='+twitter_autopost+'&message='+message);
	webcam.upload();
}

function my_completion_handler(msg) {
	window.location = 'http://snapza.com/user';
}

function is_new_user(){
	if(readCookie('new_user')){
		return false;
	}else{
		document.cookie = 'new_user=1; expires=Thu, 2 Aug 2041 20:47:11 UTC; path=/';
		return true;
	}
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function my_error_handler(error){
	take_picture_nav('upload');
	if(error == 'No camera was detected.'){
		$('#picture_holder').html('<div style="margin: 10px 0 0 10px; width:340px; color:#F0511A; font-size:16px;">It appears that you do not have a webcam attached to your computer. Try upload a photo from your computer.</div>');
		$('#picture_controls').hide();
	}else{
		alert(error);
	}
}

function showTakePicture(action){
	hide_reply();
	
	if(action == 'show'){
		$('#take_picture').show();
	}else if(action == 'hide'){
		$('#take_picture').hide();
	}else{
		$('#take_picture').toggle();
	}
	
	if ( $('#take_picture').is(':visible') ) {
	   	webcam.set_hook( 'onError', 'my_error_handler' );
		webcam.set_hook( 'onLoad', 'my_load_handler' );
		webcam.set_quality( 100 ); // JPEG quality (1 - 100)
		webcam.set_shutter_sound( false ); // play shutter click sound
		$('#picture_holder').html(webcam.get_html(400, 300));
		
	}

}

// ------ END - JPEGCAM ------- //


var jcrop_target;
var jcrop_image_id;
var jcrop_image_width;
var jcrop_image_height;

function cancelSetProfilePic(item_number){
	$('#thumb_preview_'+item_number).css('display','none');
	$('#image_info_'+item_number).css('display','inherit');
	//var jcrop_api = $.Jcrop($('#image_'+item_number).find('img:first'));
	jcrop_target.destroy();
}

function setProfilePic(item_number,image_width,image_height){
	jcrop_image_width = image_width;
	jcrop_image_height = image_height;
	//$('#marker'+item_number).find('.image:first').find('img:first').after('<div id="preview"></div>');
	jcrop_image_id = item_number;
	$('#thumb_preview_'+item_number).css('display','inline');
	$('#image_info_'+item_number).css('display','none');
	jcrop_target = $.Jcrop($('#image_'+item_number).find('img:first'),{
		onChange: showPreview,
		onSelect: showPreview,
		aspectRatio: 1,
		bgColor: 'white',
		bgOpacity: .3
	});
	jcrop_target.setSelect([ 75,20,280,280 ]);
}

function showPreview(coords)
{
	var rx = 120 / coords.w;
	var ry = 120 / coords.h;

	$('#preview_'+jcrop_image_id).css({
		width: Math.round(rx * jcrop_image_width) + 'px',
		height: Math.round(ry * jcrop_image_height) + 'px',
		marginLeft: '-' + Math.round(rx * coords.x) + 'px',
		marginTop: '-' + Math.round(ry * coords.y) + 'px'
	});
	
	$('#thumb_preview_'+jcrop_image_id).find('#x').val(coords.x);
	$('#thumb_preview_'+jcrop_image_id).find('#y').val(coords.y);		
	$('#thumb_preview_'+jcrop_image_id).find('#w').val(coords.w);
	$('#thumb_preview_'+jcrop_image_id).find('#h').val(coords.h);
};

function processSetProfilePic(item_id){
	var x = $('#thumb_preview_'+item_id).find('#x').val();
	var y = $('#thumb_preview_'+item_id).find('#y').val();
	var w = $('#thumb_preview_'+item_id).find('#w').val();
	var h = $('#thumb_preview_'+item_id).find('#h').val();
	var full_image = $('#preview_'+jcrop_image_id).attr('src');
	$.ajax({
	    url: '/items/crop_profile_pic',
	    type: 'POST',
		data: 'full_image='+full_image+'&x='+x+'&y='+y+'&h='+h+'&w='+w,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			window.location = window.location.href;
	    }
	});
}


function hide_reply(){
	$('#reply_to_picture').hide();
}


function reply(link,item_id){
	$('#reply_to_picture').find('.reply_content').html('');
	
	var userlink = $('#image_info_'+item_id).find('.userlink:first').html();
	var image = $('#image_'+item_id).find('img:first');
	var message = $('#image_info_'+item_id).find('.message_text:first').text(); // text() removes html so we can trancate safely
	if (message.length > 60){
		message = message.substr(0,60)+'...';
	}
	
	var img_src = $(image).attr('src');
	var url_index = img_src.indexOf('image_cache/') + 12;
	var thumb = img_src.substr(0,url_index) + '100_' + img_src.substr(url_index,img_src.length);
	
//	$(image).attr('src',thumb);

	
	$('#reply_to_picture').find('#reply_thumb').append('<img src="'+thumb+'" />');
	
	
	$('#reply_to_picture').find('#reply_info').append(userlink);
	$('#reply_to_picture').find('#reply_info').append('<div style="margin-top:10px">'+message+'</div>');
	

	showTakePicture('show');	
	resetTakePictureControls();
	
	$('#reply_to_picture').show();
	
	$("input#reply_to").attr('value',item_id);
	
}


$(function() {
	

	
//	$("img").lazyload({ threshold : 200 });

	$(".followingthumb img").lazyload({ 
	    event : "loadFollowingThumbs" 
	});
	
	$(".followerthumb img").lazyload({ 
	    event : "loadFollowerThumbs" 
	});

	
	// verticle align function
	/*$.fn.vAlign = function() {
		return this.each(function(i){
			var image = this;
			//$(this).children('a').children('img').load(function(){
				alignimage(image);
			//});
		});
	};
	
	function alignimage(image){
		var ah = $(image).height();
		var ph = $(image).parent().height();
		var mh = (ph - ah) / 2;
		$(image).css('margin-top', mh);
	}
	
	$('.thumb').vAlign();
	
	//verticle align thumbnails (thumbs view)
	function valign_thumbs(iteration){
		iteration++;
		if (iteration < 100){
			$('.thumb').vAlign();
			setTimeout(function(){valign_thumbs(iteration);},50);
			//alert("helloo");
		}
	}

	valign_thumbs(1);*/
	
	
	
	function removeimage(id,collection_id){
		var url = domain_base + "/items/removeimage";
		//alert("id: "+id+" / collectionid: "+collection_id);
		$.ajax({
		    url: url,
		    type: 'POST',
			data: 'id='+id+'&collection_id='+collection_id,
		    dataType: 'html',
		    timeout: 7000,
		    error: function(){
		        //alert('Error loading XML document');
		    },
		    success: function(response){

		    }
		});
	}
	
	
	
	
	
	$('.flagimage a').hover(
	    function(event){
			$(this).siblings('.flagtip').css('display','inline');
	   	},
		function(event){
			$(this).siblings('.flagtip').css('display','none');
		}

	);
	
	$('body').click(
	    function(){
			collapse_menu();
	    }
	);
	
/*$('.fave_btn_container div').hover(
    function(){
		if ($(this).attr('class') != 'fave_btn_div_clicked'){
         	$(this).removeClass('fave_btn_div').addClass('fave_btn_div_hover');
		}
    },
    function(){
		if ($(this).attr('class') != 'fave_btn_div_clicked'){
			$(this).removeClass('fave_btn_div_hover').addClass('fave_btn_div');
		}
    }
);*/
	
	
	

	
	$('.fave_button').click(
	    function(event){
			var imageid = $(this).parents('.image_info:eq(0)').attr('imageid');
			//var image = $(this).parents('.image_info:eq(0)').attr('cached_image');
			//var loggedinuser = $(this).parents('.image_info:eq(0)').attr('loggedinuser'); // very hack
	//callPublish('added to my imgfave',{'media':[{'type':'image','src':'http://imgfave.com/image_cache/'+image,'href':'http://imgfave.com/view/'+imageid}]},'');
			favebtn_state_change(imageid);
			addtofavorites(imageid);
			event.stopPropagation();
			return false;
	    }	
	);
	
	

	$('.image_info .menu_arrow').hover(
    	function(){
			$('.fave_btn_container div').removeClass('fave_btn_div_clicked').addClass('fave_btn_div');
			$('.item_menu').css('display','none');
			$('#item_menu_'+this.id).css('display','block'); // don't use an id here, make it relative, that way if their are dupes on a page it doesn't activate the firsty dupes menu
			$(this).parent().removeClass('fave_btn_div');
			$(this).parent().removeClass('fave_btn_div_hover').addClass('fave_btn_div_clicked');
	  		//event.stopPropagation();
	
			// preload the collection arrow and new icons
			collection_arrow = new Image();
			collection_arrow.src = "/img/bullet_go.png";
			collection_new = new Image();
			collection_new.src = "/img/add.png";

    	},
		function(){
			// don't do anything when mouse moves off
		}
	);


	$('.collection_btn').click(
	    function(event){
			var id = $(this).parents('.image_info:eq(0)').attr('imageid');
			if($("#collections_container_"+id).html() == ''){
				getCollections(id);
			}else{
				$("#collections_container_"+id).html(''); // hide collections
				toggleCollectionForm(id,'hide');
			}	
			event.stopPropagation();
			return false;
	    }	
	);
	
	
	$('.remove_btn').click(
		function(event){
			var id = $(this).parents('.image_info:eq(0)').attr('imageid');
			//var faveid = $(this).parents('.image_info:eq(0)').attr('imageid');
			var collection_id = $(this).parents('.image_info:eq(0)').attr('collectionid');
			$(this).parents('.image_container:eq(0)').hide();	
			//$(this).parents('.image_container:eq(0)').fadeOut(150);	
			removeimage(id,collection_id);
			return false;
		}
	
	);
	
	
	
	$('.item_menu').click(
	    function(event){
			event.stopPropagation();
	    }	
	);
	
	// preload the menu item icons)
	/*image1 = new Image();
	image1.src = "/img/color_swatch.png";
	
	image2 = new Image();
	image2.src = "/img/cross.png";*/
	
	
	// we don't put this in the setupcollection events function because its already in the DOM (otherwise we end up binding multiple click events each time we close/open the collections menu)
	$('.create_collection').click(
		function(event){
			var imageid = $(this).parents('.image_info:eq(0)').attr('imageid');
			var collection_privacy = $(this).parents('.collection_additem_form:eq(0)').children('.setprivacy_container').children('.setprivacy').attr('checked');
			var collection_name = $(this).parents('.collection_additem_form:eq(0)').children('.collection_name').attr('value');
			if (!collection_name.match(/(?=^.*[^\W_])[\w ]*$/)){
				alert('Collection names can only contain letters, numbers, spaces, and underscores. They must contain at least one number or letter.');
				event.stopPropagation()
				return false;
			}
			if (collection_name){
				createCollection(collection_name,collection_privacy,imageid);
				clicky.log('action/createcollection','created a collection');
			}
			return false;
		}
	
	);
	


});


function fave(imageid){
	$('#image_info_'+imageid).find('.like_button').addClass('half').removeAttr('onclick').removeAttr('href');
	var fave_count = $('#image_info_'+imageid).find('.like_count');
	$(fave_count).show().removeAttr('onclick').removeAttr('href');
	$(fave_count).html(parseInt($(fave_count).html())+1);
	
	addtofavorites(imageid);
}

// fave button changes when clicked (called from space key press, so we removed style changes from the link onclick event)
function favebtn_state_change(imageid){
	$("#fave_item_"+imageid).css('background', 'url(/img/heart_clicked.jpg) no-repeat');
	$("#fave_item_"+imageid).css('background-position', '0px 8px');
	$("#fave_item_"+imageid+" a.fave_btn").html('faved');
	$("#fave_item_"+imageid+" a.fave_btn").css('color', 'red');
	$("#fave_item_"+imageid).css('width', '74px');
}

function collapse_menu(){
	/*change: $('.item_menu').css('display','none'); */
	$('.fave_btn_container div').removeClass('fave_btn_div_clicked').addClass('fave_btn_div');
	$(".collections_container").html(''); // hide collections
	toggleCollectionForm(null,'hide');
}

function removeimage(id,button){
	$(button).parents('.image_container:eq(0)').hide();
	var url = domain_base + "/items/removeimage";
	//alert("id: "+id+" / collectionid: "+collection_id);
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'id='+id,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			
	    }
	});
}

function frontremove(id){
	$("#item_menu_"+id).parents('.image_container:eq(0)').fadeOut(150);	
	var url = domain_base + "/items/frontremove";
	//alert("id: "+id+" / collectionid: "+collection_id);
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'id='+id,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			
	    }
	});
}

function permdelete(id){
	$("#item_menu_"+id).parents('.image_container:eq(0)').fadeOut(150);	
	var url = domain_base + "/items/permdelete";
	//alert("id: "+id+" / collectionid: "+collection_id);
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'id='+id,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			
	    }
	});
}

function flag(id,problem){
	$("#item_menu_"+id).parents('.image_container:eq(0)').children('.image_title').html('<div style="background:red;color:#fff;padding:5px; width:200px;">Flagged for Nudity</div>');
	var url = domain_base + "/items/flag";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'id='+id+'&problem='+problem,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			
	    }
	});
}

function makepopular(id){
	$("#item_menu_"+id).parents('.image_container:eq(0)').children('.image_title').html('<div style="background:yellow;color:#000;padding:5px; width:200px;">Made Popular</div>');
	var url = domain_base + "/items/makepopular";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'id='+id,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(response){
	        alert('Error loading XML document');
	    },
	    success: function(response){
			
	    }
	});
}





// id is just the number assigned to the image div (it will be the imageid or faveid) -- we need to know which image to update with the success message
function addtofavorites(imageid,collectionid){	
	var url = domain_base + "/items/addtofaves";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'imageid='+imageid+'&collectionid='+collectionid,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			if (response == "not logged in"){ 
				window.location = domain_login;
			}else{
				// Log the action in Clicky Analytics
				if(collectionid > 0){
					clicky.log('action/addtocollection','added to collection');
				}else{
					clicky.log('action/addtofaves','added to favorites');
				}
			}
			
	    }
	}); 

	
	 
}

function profile_showcollections(collections_id_string){ //returns collections to show in the user profile
	if ($("#collections_holder").css('display') == "block"){
		$("#collections_holder").css('display','none');
	}else{
		profile_hideuserlinks();
		$("#collections_holder").css('display','block');
		
		if ($("#collections_holder").html() == ""){
			$("#collections_loading").css('display','inline');
			var url = domain_base + "/items/minicollections/"+collections_id_string;
			$.ajax({
	   			url: url,
	    		type: 'GET',
				//data: "id="+id,
	    		dataType: 'html',
	    		timeout: 20000,
	    		error: function(error){
	       			//alert('Error loading XML document');
					clicky.log('action/timeout_showcollections','timed out loading collections');
	    		},
	    		success: function(response){
					$("#collections_holder").html(response);
					$("#collections_loading").css('display','none');
					clicky.log('action/showcollections','show collections on a profile');
	    		}
			});
		}
	}
}

function profile_hideuserlinks(){
	$("#collections_holder").css('display','none');
	$("#following_container").css('display','none');
	$("#followers_container").css('display','none');
}

function profile_showfollowing(){
	$("#collections_holder").css('display','none');
	if ($("#following_container").css('display') == 'block'){
		$("#following_container").css('display','none');
	}else{
		$(".followingthumb img").trigger("loadFollowingThumbs");
		$("#followers_container").css('display','none');
		$("#following_container").css('display','block');
	}
}


function profile_showfollowers(){
	$("#collections_holder").css('display','none');
	if ($("#followers_container").css('display') == 'block'){
		$("#followers_container").css('display','none');
	}else{
		$(".followerthumb img").trigger("loadFollowerThumbs");
		$("#following_container").css('display','none');
		$("#followers_container").css('display','block');
	}
}

function getCollections(id){ // returns collections for the image menu
	var url = domain_base + "/collections/get/";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: "id="+id,
	    dataType: 'html',
	    timeout: 30000,
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			if (response == "not logged in"){
				window.location = domain_login;
			}else if (response == "no collections"){
				toggleCollectionForm(id,'show');
			}else{
				$("#collections_container_"+id).html(response);
				setupCollectionEvents(); // add the onclick events to the new collection items that have been added to the DOM
			}
	    }
	});
}


function createCollection(name,private,imageid){
	var url = domain_base + "/collections/create/";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: "name="+name+"&private="+private,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			var collection_id = response;
			collapse_menu();
			addedtocollection_message(imageid,collection_id,name);
			addtocollection(imageid,collection_id);
	    }
	});
}

function deleteCollection(id){
	var answer = confirm("Are you sure you want to delete this collection?");
		if (answer){
		
		}else{
			return;
		}
	
	var url = domain_base + "/collections/delete/";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: "id="+id,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			window.location = domain_base+"/user";
	    }
	});
}


function toggleCollectionForm(id,toggle){
	if (toggle == 'show'){
		$('#collection_additem_form_'+id).css('display','block'); 
		$('#collection_additem_form_'+id+' input:first').focus();
	}else{
		if (id == null){
			var target = '.collection_additem_form';
			$(target).css('display','none'); 
		}else{
			var target = '#collection_additem_form_'+id;
			$(target).css('display','none'); 
		}
		$(target+' input:first').attr("value", ""); 
	}
}

function setupCollectionEvents(){
	$('.newcollection_btn').click(
	    function(event){
			var id = $(this).parents('.image_info:eq(0)').attr('imageid');
			$('#collection_additem_form_'+id).css('display','block');
			$('#collection_additem_form_'+id+' input:first').focus();$('#collection_additem_div_'+id).css('display','none');
			event.stopPropagation();
			return false;
	    }
	
	);
	
	$('.collection_item_div').click(
		function(event){
			var id = $(this).parents('.image_info:eq(0)').attr('imageid');
			var collection_id = $(this).attr('collection_id');
			
			var name = $(this).children('a:first').html();
			addedtocollection_message(id,collection_id,name);
			
			collapse_menu();
			
			addtocollection(id,collection_id, this);
			
			return false;
		}
	
	);

}

function addtocollection(id,collection_id, object_clicked){
	/*$(object_clicked).css('background-image','url(/img/added.png)');
	$(object_clicked).css('padding-left','52px');*/
	
	if(object_clicked){
		/*var added_message = '<div style="display: inline; background: blue; padding: 2px 4px 2px 4px; margin: 0 4px 0 0; color: #fff;">added</div>';
		$(object_clicked).html(added_message+$(object_clicked).html());
		$(object_clicked).css('background-image','none');
		$(object_clicked).css('padding-left','5px');*/
		//$(object_clicked).html($(object_clicked).html()+' (<a href="">go there now</a>)');
	}
	addtofavorites(id,collection_id);
	
	return false;
}

function addedtocollection_message(id,collection_id,name){
	$('#addedtocollection_message_'+id).css('display','block');
	$('#addedtocollection_message_'+id).html('added to <a href="'+domain_collections+'/'+collection_id+'">'+name+'</a>');
}

function saveCollectionOrder(id,order){
	var url = domain_base+"/collection/"+id;
	$.ajax({
	    url: url,
	    type: 'POST',
		data: order,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
		//	$("#collections_container_"+id).html(response);
			//setupmenu(id);
	    }
	});

}

function followuser(userid,unfollow){
	if(unfollow){
		$("#followbtn a").html('Follow');
		$("#followbtn a").unbind('click');
		$('#followbtn a').attr("onclick", "");
		$("#followbtn a").click(function(event){followuser(userid);return false;});
		$('#followbtn a').css("background-color", "#62CF40");
	//	clicky.log('action/unfollowuser','unfollow user');
	}else{
		$("#followbtn a").html('Following');
		$("#followbtn a").unbind('click');
		$('#followbtn a').attr("onclick", "");
		$("#followbtn a").click(function(event){followuser(userid,true);return false;});
		$('#followbtn a').css("background-color", "#CFCFCF");
	
		/*$('#nav_views').find('li.friends').find('a').css("background-color", "#62CF40");
		$('#nav_views').find('li.friends').find('a').css("color", "#fff");*/
	
		
		//Fade back to original color
	//	clicky.log('action/followuser','follow user');
	}
	
	if (unfollow){
		var url = domain_base+"/subscriptions/unfollow";
	}else{
		var url = domain_base+"/subscriptions/follow";
	}
	$.ajax({
	    url: url,
	    type: 'POST',
		data: "userid="+userid,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			
	    }
	});	
}

function toggleFollowers(show){
	if(show == 'following'){
		$('#follow_nav #followingbtn').addClass('selected');
		$('#follow_nav #followersbtn').removeClass('selected');
		$('#follow_holder #following').css('display','block');
		$('#follow_holder #followers').css('display','none');
	}else{
		$('#follow_nav #followersbtn').addClass('selected');
		$('#follow_nav #followingbtn').removeClass('selected');
		$('#follow_holder #following').css('display','none');
		$('#follow_holder #followers').css('display','block');
	}
}
function fb_login(bookmarklet){
	var fb_uid = FB.Facebook.apiClient.get_session().uid;
	FB.Facebook.apiClient.users_getInfo(fb_uid,'name,current_location',function(result, ex) {
		var fb_fullname = result[0]['name'];
		/*var fb_location = result[0]['current_location'];
		if (fb_location['city'] && fb_location['state']){
			fb_location = fb_location['city']+", "+fb_location['state'];
		}else if (fb_location['city']){
			fb_location = fb_location['city'];
		}else if (fb_location['state']){
			fb_location = fb_location['state'];
		}*/

		$("#login").html("loading...");
		var url = domain_base + "/register/";
		$.ajax({
		    url: url,
		    type: 'POST',
			data: "fb_login=true&fb_uid="+fb_uid+"&fb_fullname="+fb_fullname,
		    dataType: 'html',
		    timeout: 7000,
		    error: function(error){
		        //alert('Error loading XML document');
		    },
		    success: function(response){
				if(bookmarklet){
					window.location = window.location.href;
					return;
				}
				if(response=="register"){
					window.location = domain_base+'/user';
				}else{
					window.location = domain_items;
				}	
		    }
		});


	});

}

function usefbavatar(){
	var fb_uid = FB.Facebook.apiClient.get_session().uid;
	var url = domain_base + "/users/fbavatar/";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: "fb_uid="+fb_uid,
	    dataType: 'html',
	    timeout: 7000,
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    success: function(response){
			clicky.log('action/usefbavatar','imported facebook avatar');
			window.location = window.location;
	    }
	});

}

function snapaddimage(image){
	var url = domain_base+"/items/additem";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'image='+image,
	    dataType: 'html',
	    timeout: 30000, // 1 sec timeout, return success even if it times out (just want success dom change instantly, wasnt working outside of the ajax call, maybe not enough time to loud jquery)
	    error: function(error){
	        //alert('Error loading XML document');

			window.location = window.location.href;
	    },
	    success: function(response){
		alert(response);
		//	alert("SUCCESS");
			//window.location = window.location.href;
			//clicky.log('action/postimage','added new image');
	 	}
	});

}

function addimage(image,source_url,title,nudity){
	var url = domain_base+"/items/additem";
	$.ajax({
	    url: url,
	    type: 'POST',
		data: 'i='+image+'&t='+title+'&u='+source_url+'&n='+nudity,
	    dataType: 'html',
	    timeout: 1000, // 1 sec timeout, return success even if it times out (just want success dom change instantly, wasnt working outside of the ajax call, maybe not enough time to loud jquery)
	    error: function(error){
	        //alert('Error loading XML document');
			$("#status").html('added<br /><span style="font-size:12px;"><a href="'+domain_base+'/user" target="_parent">go to my imgfave</a></span>');
			clicky.log('action/postimage','added new image');
	    },
	    success: function(response){
		//alert(response);
			$("#status").html('added<br /><span style="font-size:12px;"><a href="'+domain_base+'/user" target="_parent">go to my imgfave</a></span>');
			clicky.log('action/postimage','added new image');
	 	}
	});

}

function fbs_click_custom(url,collection) {
	if(url){
		u=url;
	}else{
		u=location.href;
	}
	t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	if(collection){
		clicky.log('action/fbshare_collection','facebook collection share');
	}else{
		clicky.log('action/fbshare','facebook share');
	}
	return false;
}



function callPublish(msg, attachment, prompt) {
  FB.ensureInit(function () {
    FB.Connect.streamPublish(msg, attachment, null, null, prompt);
  });
}


