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




$(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);
	
	
	$('.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_btn').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_div').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)').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;
		}
	
	);
	


});

// 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,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){
			
	    }
	});
}

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;});
		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;});
		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 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: 60000, // 60 sec timeout
	    error: function(error){
	        //alert('Error loading XML document');
	    },
	    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) {
	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');
	clicky.log('action/fbshare','facebook share');
	return false;
}



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


